//! `Buffer` (`MTLBuffer`) and `Device::new_buffer`. //! //! A buffer is a `VkBuffer` placed in the device's sub-allocator (one [`MemoryClass`] per storage //! mode, `Shared`'s by its CPU cache mode, [`buffer_class`]; at a multiple of //! [`LINEAR_IMAGE_ALIGNMENT`]), or in the caller's host memory for a no-copy buffer (step 4, //! `host_memory.rs`), and a range of the device's Metal address space, which `gpu_address` //! answers. The `VkBuffer` is the length rounded up to 16 bytes (the binder's //! padding contract), and has a Vulkan device address where the device enables //! `bufferDeviceAddress`: a placed buffer its block's (`memory.rs`, `memory::allocate_addressed`; //! made without the device-address usage itself, so the driver counts no addressable buffer per //! program buffer), any other its own. Every new buffer the runtime allocates reads zero, as Metal's do: memory //! the host reaches is cleared through its mapping, the rest by a fill on the device before //! `new_buffer` returns. //! //! Step 1 makes `Shared` and `Private` buffers, step 2 `Managed` ones (host-coherent memory, //! cached where the device has it, and on a device without unified memory a device-local copy //! with such a host copy, [`Mirror`]: `managed.rs`; a `Managed` no-copy buffer there has the //! caller's pages as its host copy, `managed_copy.rs`), step 4 buffers over host memory and from bytes //! (`buffer_descriptor.rs`), labels and purgeable state (`attributes.rs`); `Memoryless` is not a //! buffer's storage mode in Metal (refused `Invalid`). Step 7 places buffers in heaps //! (`heap.rs`): such a buffer is bytes of its heap's own buffer, from its offset there //! ([`Bytes::Heap`]), so it has no `VkBuffer`, memory or address range of its own. use super::address::{AddressPlacement, GpuAddress, Held, KeptToken, Place, RangeToken}; use super::attributes::ResourceAttributes; use super::buffer_texture::TexelViews; use super::churn_counts::Recycled; use super::degradation::{Degradation, NoticesFor}; use super::device::carry::{CallHold, Contents, Left, LostParts, MadeOn, PartsCalls}; use super::device::{lock, DeviceShared}; use super::dirty_pages::{DirtySource, PagesLog}; use super::error::{internal, invalid, nil, vulkan, Error, Problem}; use super::exit_guard; 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, HostParts, KeepAlive, Release}; use super::host_ram::RamOnDevice; #[cfg(unix)] use super::host_residency::{Again, Residency}; use super::managed_copy::{CallerCopy, SyncTarget}; use super::memory::{ BoundMemory, Holds, Mapped, MemoryClass, Placement, BLOCK_BYTES, FD_BLOCKS_HANDLE, HOST_PAGES_HANDLE, }; use super::program_objects::ProgramObject; use super::rebind::{ImportHold, Unexact}; use super::recycle::{self, BufferMaking}; use super::resource::{Identity, ObjectId, ResourceKey}; use super::retained::HeldBy; use super::texture::first_move::{Filled, Mine}; use super::values::{CpuCacheMode, HazardTrackingMode, ResourceOptions, StorageMode}; use super::Device; use crate::release; use ash::vk; use metal2vulkan::bind::ResidentRange; use std::any::Any; use std::mem::ManuallyDrop; use std::ops::Range; use std::ptr::NonNull; use std::sync::atomic::{AtomicBool, AtomicU16, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError, Weak}; use std::time::Instant; /// A Metal buffer (`MTLBuffer`). Cheap to clone (a retain); `Send + Sync`. Two handles are equal /// when they are the same buffer. #[derive(Clone)] pub struct Buffer(Arc); /// The distinct host imports a commit's count of them tells apart in place /// ([`Buffer::distinct_host_imports`]) before it lists them. const FEW_IMPORTS: usize = 16; /// A buffer held without keeping it (`used_resources.rs`). #[derive(Clone)] pub(super) struct WeakBuffer(Weak); impl WeakBuffer { /// The buffer, while it lives. pub(super) fn upgrade(&self) -> Option { self.0.upgrade().map(Buffer) } /// Whether the buffer lives. pub(super) fn lives(&self) -> bool { self.0.strong_count() > 0 } } struct BufferShared { /// Its generation of the device: let go of once the buffer was carried to the next one and its /// parts there went (`device/carry.rs`). device: MadeOn, /// The address of its generation's `DeviceShared`, which a command buffer's work names /// (`Buffer::carried`), read without the device. generation: usize, /// Its identity (`object_id`). object_id: ObjectId, length: u64, /// The options with the hazard tracking mode resolved, as `resourceOptions` reports them. options: ResourceOptions, address: GpuAddress, attributes: ResourceAttributes, bytes: Bytes, /// The encoder core that holds it from an argument table's retain (`retained::HeldBy`). held_by: HeldBy, /// Its `VkBuffer` was handed out (`Buffer::vk_buffer`): the caller's own work may write its /// bytes, so no shadow over them keeps a standing across command buffers /// (`shadow_standing.rs`). handed_out: Arc, /// Its maker declared that nothing reads the bytes between a texture's rows and slices over /// it (`BufferDescriptor::padding_unobserved`), set as it is made: an image over such a /// texture's memory may hold them (`linear_plan::holding`). padding_unobserved: AtomicBool, /// Work staged for the device's next submission holds what it reads for this buffer: a /// staging buffer (`Buffer::fill_first_from`) or its host copy (`Buffer::upload`), each /// holding the device. Its drop lets that work go with it (`FirstMoves::forget`). staged: AtomicBool, /// The buffer's parts on its device's next generation, where its device's recovery carried it /// (`device/carry.rs`): the same buffer there, its identity, address, range and range token /// this one's, its own parts that generation's (`Buffer::s`). Set once; held by this one /// alone, which the program's handles are. next: OnceLock, /// `next` is set: read at one relaxed load where nothing was carried ([`Buffer::s`]), `next` /// with its own ordering where it was. carried: AtomicBool, /// The calls outside a command buffer's work under way on these parts ([`Buffer::held_parts`]). calls: PartsCalls, } /// Where a buffer's bytes are. enum Bytes { /// Its own: a `VkBuffer`, memory and a range of the address space, released with it. Own(OwnBytes), /// Its heap's (`heap.rs`). Heap(HeapBytes), } /// A buffer's own bytes. struct OwnBytes { /// Where they lie: for good, or a no-copy buffer's host pages, which a rebind replaces /// (`rebind.rs`). lie: Lie, /// The bytes of the Metal address space the buffer holds. reserved: Held, identity: Identity, owner: Owner, /// A `Managed` buffer's host copy on a device without unified memory: its `VkBuffer` is then /// in device-local memory, and `contents` maps the copy ([`HostCopy`]). Shared with the /// submissions that upload from it. mirror: Option, /// The caller's token for the buffer's range (a buffer's `range_token`, or its heap's when /// the buffer is a heap's own), set once as it is made: dropped right after the range is /// free and the buffer's teardown leaves its exit section, no runtime lock held, on the /// thread that drops the buffer's last holder, as the program's code (`exit_guard::program`); /// left to the process's exit with the buffer where the runtime leaves the buffer to it /// (`BufferShared`'s drop). range_token: KeptToken, } /// Where a buffer of its own lies: its `VkBuffer` in its memory. pub(super) struct Pages { raw: vk::Buffer, memory: Bound, /// Where the buffer's bytes start in its placement: a no-copy buffer's offset in its pages. offset: u64, /// Where the buffer's byte 0 lies in `raw`: 0, but for a no-copy buffer whose pointer misses /// the buffer's memory alignment, bound that many bytes below it. base: u64, /// The bytes from byte 0 a copy reads ([`Buffer::copy_reach`]). reach: u64, } /// Where a buffer of its own lies, for good or until a rebind. enum Lie { /// The runtime's memory, or the caller's `VkBuffer`. Fixed(Arc), /// A no-copy buffer's host pages: the pages it lies in now, which a rebind replaces. Host(Arc), } /// A no-copy buffer's (or a no-copy heap's own buffer's) hold on its host pages, which /// `rebind_bytes_no_copy` replaces (`rebind.rs`) and `detach_backing` lets go of (`detach.rs`). pub(super) struct HostCell { pages: Mutex, /// The texel buffer views of the textures over the buffer's bytes (a no-copy heap's: over /// its buffers'), which view its pages: a rebind empties them. texels: Mutex>>, /// The images of the textures over the buffer's bytes (a no-copy heap's: over its buffers' /// and in it), which a detach makes present stand-ins (`detach.rs`), and the textures being /// made over them, which a detach refuses while one is. textures: Mutex, /// The images in place over the buffer's bytes (a no-copy heap's: over its buffers'), which a /// rebind makes again over its new pages (`texture/in_place_image.rs`). in_place: Mutex>, /// The reasons the buffer's Metal address was handed out for (`Buffer::gpu_address`, /// `Buffer::exposed_address`), a bit each ([`ReadApart`]): once any is, its import is kept /// imported for good (`host_residency.rs`), and a call for a reason noted need not look /// again. exposed: AtomicU16, /// The device whose work counts each look at its pages adds to /// (`WorkCounts::no_copy_lies_read`): its generation, let go of once the buffer was carried /// to the next one and its pages there went (`device/carry.rs`). device: MadeOn, /// Its pages on its lost generation were marked let go of, the buffer carried to the next one /// and that generation at rest ([`LostHost`]): no call takes them from now on /// (`Buffer::held_parts`). released: AtomicBool, /// They went ([`LostHost`]): it lies in none ([`Lying::Gone`]). freed: AtomicBool, /// The GPU's writes to the buffer are dropped, as Metal's private option bit 24 drops them: /// its pages are imported through a read-only view of them (`read_only_view.rs`), or copied, /// the copy's GPU writes never written back (`copied.rs`), and a rebind's are too. drops_writes: bool, /// The deallocator of the pages its last detach let go of (`detach.rs`), held back until its /// next rebind or its release, as Metal runs it then ([`Release::hold_back`]). held_back: Mutex>>, } /// An image in place over a buffer's host pages ([`HostCell`], `texture/in_place_image.rs`), /// which a rebind makes again over the new pages: the image (`texture.rs`'s `Image`), held weakly /// and by type erased as [`NotedTexture`] holds it, where its texels lie in bytes from the pages' /// first byte, how Metal lays them out from there, whether their rows' padding is the buffer's /// own (`in_place::Padding`), and the bytes of one texel (whose width picks the check of a /// shader's writes, `in_place::Access::written`). #[derive(Clone)] pub(super) struct InPlaceWatch { pub(super) image: Weak, pub(super) from_base: u64, pub(super) layout: crate::linear_plan::BufferLayout, pub(super) padding_owned: bool, pub(super) texel: u64, } impl InPlaceWatch { /// Whether the image lives. fn lives(&self) -> bool { self.image.strong_count() > 0 } } /// The textures over a buffer's host pages ([`HostCell`]): their images, which a detach makes /// present stand-ins, and how many are being made, which a detach refuses while any is /// (`detach.rs`). #[derive(Default)] pub(super) struct TexturesOver { /// The textures made over them, each its own entry (a view's too). noted: Vec, /// How many are being made now ([`TextureMaking`]). making: u32, } /// A texture over a buffer's host pages (`TexturesOver`): the texture and its image /// (`texture.rs`'s `TextureShared` and `Image`), held weakly and by type erased: each holds its /// device, so naming their types here would make the buffer's types recursive through them, /// which rustdoc's search for their auto traits overflows on. pub(super) struct NotedTexture { texture: Weak, image: Weak, /// The texture's `ObjectId`. pub(super) id: ObjectId, /// Whether a stand-in of zero bytes presents its image exactly: not for an image of texels /// its copies convert from the bytes (`texture/stand_in.rs`). exact: bool, /// Whether its image's stand-in has a sink (its plan has `STORAGE` usage): a read through a /// storage-class element there reads what an unnamed write left (`Device::note_stale`). sink: bool, /// Whether its image keeps its own texels while the bytes are detached, presenting no /// stand-in: a tiled texture's, a copy of the bytes taken at use (`shadow.rs`). keeps: bool, } impl NotedTexture { /// `texture`, whose image is `image`, of object `id`; `exact`, `sink` and `keeps` as the /// fields say. pub(super) fn new( texture: Weak, image: Weak, id: ObjectId, (exact, sink, keeps): (bool, bool, bool), ) -> NotedTexture { NotedTexture { texture, image, id, exact, sink, keeps, } } /// Whether its image's stand-in has a sink (`NotedTexture::sink`). pub(super) fn sink(&self) -> bool { self.sink } /// Whether its image keeps its own texels while the bytes are detached /// (`NotedTexture::keeps`). pub(super) fn keeps(&self) -> bool { self.keeps } /// Whether the texture lives. fn lives(&self) -> bool { self.texture.strong_count() > 0 } /// The texture, by type erased, while it lives. pub(super) fn texture(&self) -> Weak { Weak::clone(&self.texture) } } impl TexturesOver { /// The images of the live textures that present stand-ins while the bytes are detached (all /// but those that keep their own, `NotedTexture::keeps`), each once, by type erased; and /// whether a stand-in of zero bytes presents each exactly (`NotedTexture::exact`). pub(super) fn images(&self) -> (Vec>, bool) { let mut images: Vec> = Vec::new(); let mut exact = true; for noted in self.textures().filter(|noted| !noted.keeps) { let Some(image) = noted.image.upgrade() else { continue; }; exact &= noted.exact; if !images.iter().any(|held| Arc::ptr_eq(held, &image)) { images.push(image); } } (images, exact) } /// The live textures. pub(super) fn textures(&self) -> impl Iterator { self.noted.iter().filter(|noted| noted.lives()) } } /// How many times a no-copy buffer of the process (or a no-copy heap's own buffer) came to lie /// elsewhere ([`HostCell::replace`]: rebound or detached). static HOST_CELLS_MOVED: AtomicU64 = AtomicU64::new(0); /// The count of the times a no-copy buffer of the process came to lie elsewhere (rebound or /// detached) so far: while it holds, every buffer's binding is what it was (its base, its /// addresses), which is what an encoder's kept bind state reads of them (`live_bind.rs`). pub(super) fn host_cells_moved() -> u64 { HOST_CELLS_MOVED.load(Ordering::Acquire) } /// The most buffers over host pages a [`KeptSpaces`] keeps where they lie. const KEPT_SPACES: usize = 4; /// Where buffers over host pages (no-copy buffers, and no-copy heaps' own buffers, which their /// placed buffers lie in) lay as an encoder's binds last read them ([`Buffer::space_kept`]): a /// bind reads where a buffer lies at each draw (`binding::rebind_into`), which for one over host /// pages locks its pages and takes a hold of them, and a heap's own buffer is one every encoder /// of its device's threads reads, as the consumer binds its draws' bytes in a heap over the guest's /// RAM. Each is kept while no no-copy buffer of the process moved since ([`host_cells_moved`]): a /// buffer lies where it lay until one moves (`HostCell::replace`), and its import, read for a /// binding once, stays imported (`HostImport::pages`). A buffer is kept by its cell's address, /// held weakly: a cell that goes leaves its allocation, and so its address, to its weak handles, so /// no other cell is at the address while it is kept. #[derive(Default)] pub(super) struct KeptSpaces { kept: Vec, /// The entry the next buffer kept takes once every one is taken. next: usize, } /// A buffer over host pages a [`KeptSpaces`] keeps: its cell, the count of moves it was read /// under, and what [`HostCell::binding_pages`] read. struct KeptSpace { cell: Weak, moved: u64, pages: (vk::Buffer, u64, u64), } impl KeptSpaces { /// [`HostCell::binding_pages`] of `cell`, kept or read and kept. fn of(&mut self, cell: &Arc) -> (vk::Buffer, u64, u64) { // Read before the cell: a move after it makes the next look read the cell again. let moved = host_cells_moved(); let at = Arc::as_ptr(cell); let found = (self.kept.iter()).find(|kept| kept.moved == moved && kept.cell.as_ptr() == at); if let Some(kept) = found { #[cfg(debug_assertions)] assert_eq!( kept.pages, cell.binding_pages(), "a buffer kept where it no longer lies" ); return kept.pages; } let pages = cell.binding_pages(); let entry = KeptSpace { cell: Arc::downgrade(cell), moved, pages, }; // A stale entry or this cell's goes first; else the entries in turn. let stale = (self.kept.iter()).position(|kept| kept.moved != moved || kept.cell.as_ptr() == at); match stale { Some(index) => self.kept[index] = entry, None if self.kept.len() < KEPT_SPACES => self.kept.push(entry), None => { self.kept[self.next] = entry; self.next = (self.next + 1) % KEPT_SPACES; } } pages } } /// A texture being made over a buffer's host pages ([`Buffer::making_texture`]): a detach /// refuses until it goes, once the texture is noted (`Buffer::note_texture`) or its making /// failed. pub(super) struct TextureMaking(Arc); impl Drop for TextureMaking { fn drop(&mut self) { let mut textures = lock(&self.0.textures); textures.making = textures.making.saturating_sub(1); } } /// Where a no-copy buffer (or a no-copy heap's own buffer) lies: in host pages, or detached /// from them (`detach.rs`). #[derive(Clone)] pub(super) enum Lying { /// The host pages it lies in. In(Arc), /// Detached: in no pages. Detached(Arc), /// Its pages on a lost generation went at the generation's rest, the buffer carried to the /// next one ([`LostHost`], `device/carry.rs`), where they lay as the [`Shape`] says: no work /// of the generation reads them from then on, and every other reach of the buffer goes to /// where it was carried. Gone(Shape), } /// A read of a carried no-copy buffer's pages on its lost generation after the generation's rest /// ([`Lying::Gone`]), which no work makes: none of its command buffers records, and a call that /// held them keeps them until it ends (`Buffer::held_parts`). pub(super) fn read_gone() -> ! { unreachable!("a carried no-copy buffer's pages read on its lost generation after its rest") } /// What a detached no-copy buffer's commands take of it while it is detached (`detach.rs`): the /// device's stand-in's `VkBuffer`, at the place the buffer's bytes had in the pages it was detached /// from (their offset, base and reach), and the stand-in's memory. No command that takes it runs: /// an encoder that names a detached buffer records nothing from that command on, and its submission /// fails (`EncoderCore::skips`). pub(super) struct Detached { /// The stand-in, a small buffer of the runtime's own, kept while a buffer is detached. _stand_in: Buffer, pages: Pages, /// The host address of the first page of the pages it was detached from, the caller's, /// whose pointer `contents` answers meanwhile (at `pages.offset`); nothing of the runtime's /// reads or writes through it. last: Option, /// The index of the memory type of the pages it was detached from: a texture made over the /// bytes meanwhile takes the route it would over them (`texture/heap.rs`). type_index: u32, /// Whether the pages it was detached from were imported as dma-bufs, for the same. over_dma_buf: bool, } impl Detached { /// What a buffer detached from `from` takes: `stand_in`'s `VkBuffer` and memory, at the /// place its bytes had in `from`. No memory is placed for it: the placement names the /// stand-in's, unmapped and freed by none, so the runtime maps nothing of it while it is /// detached (`Buffer::mapped_contents`); `contents` answers `from`'s pointer. /// Refused (an internal error) for a stand-in placed in a heap. pub(super) fn new(stand_in: Buffer, from: &HostPages) -> Result { let Bytes::Own(own) = &stand_in.0.bytes else { return Err(internal("a detached buffer's stand-in placed in a heap")); }; let old = from.import.shape; let pages = own.with(ReadApart::Binding, |pages| { let placement = &pages.memory.placement; Pages { raw: pages.raw, memory: Bound { placement: Placement::caller( placement.memory, placement.offset, placement.size(), placement.type_index(), None, ), device_address: pages.memory.device_address, }, offset: old.offset, base: old.base, reach: old.reach, } }); Ok(Detached { _stand_in: stand_in, pages, last: old.mapped, type_index: from.type_index(), over_dma_buf: from.over_dma_buf(), }) } } impl HostCell { /// Whether the GPU's writes to the buffer are dropped (`read_only_view.rs`, `copied.rs`). pub(super) fn drops_writes(&self) -> bool { self.drops_writes } /// The pages the buffer lies in now; `None` while it is detached. pub(super) fn current(&self) -> Option> { self.device.shared().counts.thread().no_copy_lie_read(); match &*lock(&self.pages) { Lying::In(pages) => Some(Arc::clone(pages)), Lying::Detached(_) | Lying::Gone(_) => None, } } /// Where the buffer lies now. pub(super) fn lying(&self) -> Lying { self.device.shared().counts.thread().no_copy_lie_read(); lock(&self.pages).clone() } /// The `VkBuffer` its bytes lie in now, where its byte 0 lies there (`Pages::base`), and /// where they start in their first page (`Shape::base`), read for a binding /// (`ReadApart::Binding`): what [`Buffer::space`] and [`Buffer::at_for`] read of it. fn binding_pages(&self) -> (vk::Buffer, u64, u64) { match self.lying() { Lying::In(pages) => { let read = pages.import.pages(ReadApart::Binding); (read.raw, read.base, pages.import.shape.base) } Lying::Detached(detached) => { let pages = &detached.pages; (pages.raw, pages.base, Shape::of(pages).base) } Lying::Gone(_) => read_gone(), } } /// The host addresses of the buffer's bytes, from its byte 0 over the bytes a copy reads, /// where it lies in host pages now; `None` while it is detached. pub(super) fn host_range(&self) -> Option> { match self.lying() { Lying::In(pages) => { let shape = pages.import.shape; let mapped = shape.mapped?; let start = (mapped.as_ptr() as usize).checked_add(shape.offset as usize)?; Some(start..start.checked_add(shape.reach as usize)?) } Lying::Detached(_) | Lying::Gone(_) => None, } } /// The `N` bytes at `offset` of the buffer's bytes, as the host reads them now through the /// pages they lie in, which are held while they are read: a detach and a rebind meanwhile let /// none of them go under the read (their deallocator waits for them, `HeldBack`). `None` while /// it is detached. The caller holds `offset + N` inside the buffer's length. fn read(&self, offset: u64) -> Option<[u8; N]> { let pages = self.current()?; let shape = pages.import.shape; let start = shape.mapped?.as_ptr().wrapping_add(shape.offset as usize); let mut bytes = [0u8; N]; // SAFETY: the pages map the buffer's bytes from `start`, and the caller holds the `N` // bytes at `offset` inside its length; `pages` keeps them mapped until the copy ends. A // write to them meanwhile races, as a read of `contents` does on Metal. unsafe { let at = start.wrapping_add(offset as usize); std::ptr::copy_nonoverlapping(at, bytes.as_mut_ptr(), N); } drop(pages); Some(bytes) } /// The caller's pointer of the pages the buffer was detached from, while it is detached. fn detached_pointer(&self) -> Option> { match &*lock(&self.pages) { Lying::Detached(detached) => (detached.last).and_then(|mapped| { NonNull::new(mapped.as_ptr().wrapping_add(detached.pages.offset as usize)) }), Lying::In(_) | Lying::Gone(_) => None, } } /// Whether the buffer is detached. pub(super) fn detached(&self) -> bool { matches!(*lock(&self.pages), Lying::Detached(_)) } /// Where the bytes start in their first page: the pages', or those it was detached from. pub(super) fn offset(&self) -> u64 { match &*lock(&self.pages) { Lying::In(pages) => pages.offset(), Lying::Detached(detached) => detached.pages.offset, Lying::Gone(shape) => shape.offset, } } /// Lie `lying` from now on: where the buffer lay, which the caller lets go of. Counted in /// [`host_cells_moved`]: a buffer binding that reads where it lies (its base, its device /// address) may change. pub(super) fn replace(&self, lying: Lying) -> Lying { let lay = { let mut pages = lock(&self.pages); let lay = std::mem::replace(&mut *pages, lying); HOST_CELLS_MOVED.fetch_add(1, Ordering::AcqRel); lay }; lay } /// A detach let go of `pages`: their deallocator is held back until the buffer's next rebind /// or its release ([`HostCell::release_held_back`]), as Metal never runs it at a detach. pub(super) fn hold_back(&self, pages: &HostPages) { let Some(held) = pages.release.get().and_then(Release::hold_back) else { return; }; let earlier = lock(&self.held_back).replace(held); // Never so: a detached buffer is detached again by no detach, and a rebind runs what // was held back first. Were it to be, the earlier one is due now. if let Some(earlier) = earlier { self.held_back_due(&earlier); } } /// The buffer's next rebind (inside the call, once its new pages are in place) or its release /// came: the deallocator its last detach held back runs now, on this thread, as Metal runs it /// there, or, where the pages it let go of are still imported (a texture's image over them /// waits for a command buffer that may read it) and no keep-alive keeps them mapped, once /// their import is freed, announced (`host-deallocator-delayed`). pub(super) fn release_held_back(&self) { let held = lock(&self.held_back).take(); if let Some(held) = held { self.held_back_due(&held); } } /// `held` is due ([`HostCell::release_held_back`]). fn held_back_due(&self, held: &HeldBack) { if !held.due() { return; } let device = &self.device; device.shared().counts.host_deallocator_delayed(); device.degrade_once(Degradation::HostDeallocatorDelayed, || { ( "a detached no-copy buffer".to_owned(), "the pages its detach let go of are still imported as it is rebound or released \ (a texture's image over them may still be read through its resource ID by a \ command buffer), and the caller gave no keep-alive: its deallocator runs once \ their import is freed" .to_owned(), ) }); } /// Note `noted`, a texture over the buffer's bytes (`TexturesOver`), forgetting those /// gone. fn watch_texture(&self, noted: NotedTexture) { let mut textures = lock(&self.textures); textures.noted.retain(NotedTexture::lives); textures.noted.push(noted); } /// Note `watch`, an image in place over the buffer's bytes, forgetting those gone. fn watch_in_place(&self, watch: InPlaceWatch) { let mut in_place = lock(&self.in_place); in_place.retain(InPlaceWatch::lives); in_place.push(watch); } /// The live images in place over the buffer's bytes, which a rebind makes again. pub(super) fn in_place_images(&self) -> Vec { let mut in_place = lock(&self.in_place); in_place.retain(InPlaceWatch::lives); in_place.clone() } /// The textures over the buffer's bytes, locked, where none is being made: none is made /// while it is held (`Buffer::making_texture`). `None` where one is. pub(super) fn settled(&self) -> Option> { let textures = lock(&self.textures); (textures.making == 0).then_some(textures) } /// The texel views of the live textures over the buffer's bytes. pub(super) fn texels(&self) -> Vec> { lock(&self.texels) .iter() .filter_map(Weak::upgrade) .collect() } /// Note `views`, a texture's over the buffer's bytes, forgetting those gone. fn watch(&self, views: &Arc) { let mut texels = lock(&self.texels); texels.retain(|views| views.strong_count() > 0); texels.push(Arc::downgrade(views)); } } /// A hold on the pages a buffer of its own lies in (`Buffer::resident`), kept and never read: /// they stay while it lives. #[derive(Clone)] pub(super) enum PagesHold { Fixed { _pages: Arc }, Host { _pages: ListedPages }, } /// A live buffers' table's hold on host pages (`PagesHold::Host`), counted /// (`HostPages::listed`): one left as the buffer is released is a table a command buffer that may /// reach the pages unnamed holds, past Metal's release (`HostPages::released_listed`). pub(super) struct ListedPages(Arc); impl ListedPages { fn new(pages: Arc) -> ListedPages { pages.listed.fetch_add(1, Ordering::AcqRel); pages.import.note_listed(); ListedPages(pages) } } impl Clone for ListedPages { fn clone(&self) -> ListedPages { ListedPages::new(Arc::clone(&self.0)) } } impl Drop for ListedPages { fn drop(&mut self) { self.0.listed.fetch_sub(1, Ordering::AcqRel); } } /// A hold on the memory a buffer's bytes lie in now, and on nothing else of the buffer /// (`Buffer::memory_hold`), kept and never read: an image bound to them (a texture's over the /// buffer, a heap's texture's) keeps it while a command buffer may still reach the image, past the /// buffer and texture objects. Metal frees those at their release: the buffer's range of the /// address space and its range token go with the buffer, and a no-copy buffer's deallocator runs as /// its pages go; only the `VkBuffer` and its memory, or host pages' import, stay. #[derive(Clone)] pub(super) enum MemoryHold { Fixed { _pages: Arc }, Host { _import: Arc }, } /// The pages a buffer of its own lies in for good: its `VkBuffer` and its placement. Held by the /// buffer, and by each command buffer whose resident set lists them until it completed /// (`live_buffers.rs`): the last lets go, which parks the `VkBuffer` and its placement for the /// next buffer of the same making where the recycler noted them (`recycle.rs`), else destroys the /// `VkBuffer` (unless it is the caller's, `Owner::Vulkan`) and frees the placement. pub(super) struct FixedPages { /// Its generation of the device: let go of with the pages on a lost generation /// ([`FixedPages::release_lost`]). device: MadeOn, pages: Pages, /// The `VkBuffer` is the runtime's to destroy. owned: bool, /// Its `VkBuffer` and memory are let go of on its lost generation, its buffer carried to the /// next one ([`LostBuffer`]): no work meets them from now on. released: AtomicBool, /// They went ([`FixedPages::release_lost`]): its drop lets go of nothing. freed: AtomicBool, } impl FixedPages { /// Destroy the `VkBuffer` and free the memory of the pages of a buffer its device's recovery /// carried to the next generation, on the lost one at rest, marked let go of /// ([`LostBuffer`]), and let go of its handle of that generation (`device/carry.rs`). Vulkan /// leaves a lost device's objects to the program to destroy: "When a device is lost, its /// child objects are not implicitly destroyed and their handles are still valid. Those /// objects must still be destroyed before their parents or the device can be destroyed" /// (vkspec 5.2.3). Nothing recycles them. Left to the process's end while it exits. fn release_lost(&self) { let Some(busy) = exit_guard::enter() else { return; }; let shared = self.device.shared(); if self.owned { // SAFETY: none of the lost generation's command buffers records or is pending, and // every later one's work reaches the carried buffer's own pages. unsafe { release::object(shared.vk(), self.pages.raw) }; } lock(&shared.memory).free(shared.vk(), &self.pages.memory.placement); self.freed.store(true, Ordering::Release); drop(busy); // SAFETY: as above; the pages' drop reads nothing once they went. unsafe { self.device.let_go() }; } } /// A carried buffer's parts on its device's lost generation (`device/carry.rs`): its pages, held /// until they go whether the program keeps the buffer or not, and its handle of the generation. struct LostBuffer { pages: Arc, buffer: Weak, } impl LostParts for LostBuffer { fn mark(&self) { self.pages.released.store(true, Ordering::Release); } fn release(self: Box) { let Some(buffer) = self.buffer.upgrade() else { // The buffer went, and with it every call on its parts. self.pages.release_lost(); return; }; // The last call under way on them lets them go (`Buffer::held_parts`). if let Some(lost) = buffer.calls.unless_held(self) { (*lost).release_now(&buffer); } } } impl LostBuffer { /// Let the parts go, no call on them under way, and the buffer's handle of their generation: /// but where their `VkBuffer` or memory was handed out (`Buffer::vk_buffer`, /// `Buffer::vk_host_memory`), which the caller may use while the buffer lives, so they go /// with the buffer, as a refused object's do. fn release_now(self, buffer: &BufferShared) { if buffer.handed_out.load(Ordering::Acquire) { return; } self.pages.release_lost(); // SAFETY: its parts on the generation went, no command buffer of the generation records, // no call under way reads them (`Buffer::held_parts`), and every other reach of the // buffer goes to where it was carried (`Buffer::carried`). unsafe { buffer.device.let_go() }; } } /// A carried heap buffer's parts on its device's lost generation (`Buffer::carry_placed`): no /// Vulkan object of their own (their bytes are their heap's own buffer's, which its carry carried /// apart), their entry among the generation's live buffers, and the buffer's handle of the /// generation, let go of once none of its command buffers may record. struct LostPlaced { buffer: Weak, } impl LostParts for LostPlaced { fn release(self: Box) { // The buffer went: its drop on the generation let go of everything there. let Some(buffer) = self.buffer.upgrade() else { return; }; // The last call under way on them lets them go (`Buffer::held_parts`). if buffer.calls.unless_held(self).is_none() { return; } let shared = buffer.device.shared(); (shared.live_buffers).forget(buffer.address.0, buffer.object_id); // SAFETY: no command buffer of the generation records, no call under way reads its parts // there (`Buffer::held_parts`), and every other reach of the buffer goes to where it was // carried (`Buffer::carried`). unsafe { buffer.device.let_go() }; } } /// A carried no-copy buffer's parts on a lost generation (`Buffer::carry`): its hold there on the /// caller's pages (`cell`, its pages' import among them) and the buffer's handle of the /// generation, let go of once none of the generation's command buffers may record, as a buffer of /// the generation's goes there: out of its live buffers and its registries of no-copy buffers, /// its pages let go of, whose release tells what waits for every import of them /// (`Release::carry_on`). struct LostHost { cell: Arc, buffer: Weak, } impl LostParts for LostHost { fn mark(&self) { self.cell.released.store(true, Ordering::Release); } fn release(self: Box) { // The buffer went: its drop on the generation let go of everything there. let Some(buffer) = self.buffer.upgrade() else { return; }; // The last call under way on them lets them go (`Buffer::held_parts`). if let Some(lost) = buffer.calls.unless_held(self) { (*lost).release_now(&buffer); } } } impl LostHost { /// Let the parts go, no call on them under way, as [`LostBuffer::release_now`] does. fn release_now(self, buffer: &BufferShared) { if buffer.handed_out.load(Ordering::Acquire) { return; } // The process is exiting: the parts are left to its end, as every buffer's. let Some(busy) = exit_guard::enter() else { return; }; let shared = buffer.device.shared(); shared .live_buffers .forget(buffer.address.0, buffer.object_id); if let Bytes::Own(own) = &buffer.bytes { shared.rebinds.forget(own.identity.key); shared.aliases.forget(own.identity.key); } drop(busy); let shape = match self.cell.lying() { Lying::In(pages) => pages.import.shape, Lying::Detached(detached) => Shape::of(&detached.pages), Lying::Gone(shape) => shape, }; let left = self.cell.replace(Lying::Gone(shape)); self.cell.freed.store(true, Ordering::Release); // The pages go where nothing else holds them, their import freed where none holds it: // their release tells what waits for every import of them. drop(left); // SAFETY: its parts on the generation went, no command buffer of the generation records, // no call under way reads them (`Buffer::held_parts`), its cell lies in none of them and // is read no more there (`Lying::Gone`), and every other reach of the buffer goes to // where it was carried (`Buffer::carried`). unsafe { self.cell.device.let_go(); buffer.device.let_go(); } } } /// A call outside a command buffer's work on a buffer's parts on one generation /// ([`Buffer::held_parts`]), until it goes: the parts stay while it lives (`PartsCalls`), and /// every read of the buffer's parts on this thread meanwhile answers them. pub(super) struct HeldParts<'a> { _call: CallHold<'a>, _scope: NoticesFor, } impl Drop for FixedPages { fn drop(&mut self) { // Let go of on its lost generation already (`FixedPages::release_lost`). if *self.freed.get_mut() { return; } // The Vulkan teardown is a section of the exit guard. let Some(busy) = exit_guard::enter() else { // The process is exiting: the buffer and its memory are left to its end. return; }; let shared = self.device.shared(); // No pending command buffer uses the pages: one whose commands used the buffer holds it, // and one whose resident set lists them holds them, until it completed. let placement = &self.pages.memory.placement; let parked = match self.owned { true => { let mut recycled = lock(&shared.recycled_buffers); let now = Instant::now(); let parked = recycled.park(self.pages.raw, placement.handed_over(), now); // Gone in time where no park or take comes (`idle_sweep.rs`). if let Some(due) = recycled.due() { shared.idle_sweep.by(due); } parked.ok() } false => None, }; match parked { Some(gone) => { shared.counts.churn.parked(Recycled::Buffer); self.device.let_go_parked_buffers(gone); } None => { if self.owned { // SAFETY: as above. unsafe { release::object(shared.vk(), self.pages.raw) }; } // The caller's `VkBuffer`'s placement returns nothing. lock(&shared.memory).free(shared.vk(), placement); } } drop(busy); } } /// Host pages a no-copy buffer lies in: its `VkBuffer` over them and their import /// (`HostImport`), the images a rebind parked, and their release. Held by the buffer while it /// lies in them and by each command buffer whose commands used them until it completed /// (`rebind.rs`); the last lets go: the parked images are destroyed, the import let go (destroyed /// where these pages held it last), and the deallocator run. /// /// The import may outlive them: a texture over the pages whose image a command buffer submitted /// before the texture's release may still read through its resource ID holds it (`heap_sets.rs`). /// Vulkan requires the pages to stay mapped while imported, so the deallocator runs as they go only /// where the caller's keep-alive keeps the pages mapped (the import keeps it until freed), or /// another buffer lies in the import, whose contract keeps them mapped; else it runs once the /// import is freed, at once where nothing else holds it, and announced where something does /// (`host-deallocator-delayed`). A keep-alive goes as they go where the import's pages stay mapped /// without it: another buffer lies in the import, or the import keeps another's keep-alive already /// (every buffer in it was made over the same bytes, `host_aliases.rs`). So an import keeps one /// keep-alive at most, however many buffers come and go over its bytes while it lives. pub(super) struct HostPages { /// The images and views over them a rebind or a detach replaced (a no-copy heap's textures', /// texel buffer views), which commands recorded before it may use: destroyed with them, /// first. parked: Mutex>>, /// Their `VkBuffer` and its memory, which no-copy buffers made over the same bytes share /// (`host_aliases.rs`). import: Arc, /// Their release to the caller's deallocator and keep-alive, set once they are the buffer's /// (a refused rebind drops its pages without it, and the deallocator unrun). release: OnceLock, /// The live buffers' tables' holds on them ([`ListedPages`]). listed: AtomicUsize, /// The caller's log of the writes to them, where it gave one with their memory /// (`HostMemory::with_dirty_pages`, `dirty_pages.rs`). dirty: OnceLock>, /// The guest RAM their caller resolved them to and the runs of it they are, in their byte /// order (`HostMemory::with_runs`, `host_ram.rs`), kept until the rebind or the release. ram_runs: OnceLock<(Arc, Box<[Range]>)>, /// The key they named to their copy, where they lie in one ([`HostPages::copied_as`]): its /// naming goes as they go. named: OnceLock, /// 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, } /// How new pages come to lie in an import ([`HostPages::new`]). #[derive(Clone, Copy, PartialEq, Eq)] pub(super) enum Joining { /// The import was made for them. First, /// A no-copy buffer's, made over the bytes the import's buffers were made over /// (`host_aliases.rs`): it reads the import as they do, through the import, so a releasable /// import stays releasable beside it (`host_residency.rs`). Buffer, /// A no-copy heap's own bytes, over the bytes the import's buffers were made over: its /// placed buffers' addresses are the heap's, handed out with no read of the import noted, so /// the import is kept imported for good. Heap, /// A rebound buffer's (`rebind.rs`): kept imported for good, as a rebind's own import is. Rebound, } impl HostPages { /// New pages lying in `import`, with no release yet, `joining` it so. fn new(import: Arc, joining: Joining) -> HostPages { let others = import.lying.fetch_add(1, Ordering::AcqRel) > 0; match (joining, others) { // Imported for good beside the others (`host_residency.rs`). (Joining::Heap, true) => { import.expose(ReadApart::Heap); } (Joining::Rebound, true) => { import.expose(ReadApart::Rebound); } (Joining::Buffer, true) => import.note_joined(), (Joining::First | Joining::Buffer | Joining::Heap | Joining::Rebound, _) => {} } HostPages { parked: Mutex::new(Vec::new()), import, release: OnceLock::new(), listed: AtomicUsize::new(0), dirty: OnceLock::new(), ram_runs: OnceLock::new(), named: OnceLock::new(), made_of: OnceLock::new(), } } /// 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) { let _kept = self.dirty.set(dirty); } /// Keep the logs of the writes to them (`dirty_pages::PagesLog`), with their import. pub(super) fn keep_log(&self, log: Arc) { self.import.keep_log(log); } /// The logs of the writes to them, where their memory came with one. pub(super) fn log(&self) -> Option<&Arc> { self.import.log.get() } /// Name `key`, a buffer's (or a heap's bytes') lying in them, to their copy, where they are /// one: its merges back compare the copy where a batch wrote that key (`copied.rs`), until /// they go. Once: a second call names nothing. pub(super) fn copied_as(&self, key: ResourceKey) { if let Some(copied) = self.import.copied.get() { if self.named.set(key).is_ok() { copied.name(key); } } } /// Report the GPU's writes through the uses of `key`, a buffer's (or a heap's bytes') lying /// in them, to their logs (`DirtyShadows::logged_in_place`), where they have one and lie in /// an import the GPU writes in place: a copy reports its merges back instead (`copied.rs`), /// and a read-only view takes no write. pub(super) fn logged_as(&self, key: ResourceKey) { let import = &self.import; if import.copied.get().is_some() || import.drops_writes() { return; } if let Some(log) = import.log.get() { import.device.shared().dirty.logged_in_place(key, log); } } /// 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, Box<[Range]>)) { let _kept = self.ram_runs.set(runs); } /// The caller's log of the writes to them, where it gave one. pub(super) fn dirty(&self) -> Option<&Arc> { self.dirty.get() } /// Keep `objects`, over these pages, until they go. pub(super) fn park(&self, objects: impl Any + Send + Sync) { lock(&self.parked).push(Box::new(objects)); } /// Their memory and where the bytes start in it (a heap's textures bind images there): a /// read that keeps the import imported for good (`host_residency.rs`). pub(super) fn memory(&self) -> (vk::DeviceMemory, u64) { let pages = self.import.pages(ReadApart::Texture); let placement = &pages.memory.placement; (placement.memory, placement.offset + pages.offset) } /// Where the bytes start in their first imported page. pub(super) fn offset(&self) -> u64 { self.import.shape.offset } /// Whether they lie in fresh pages the runtime mapped and imported (`fresh_pages.rs`): a copy /// of the caller's pages that images in place ride on (`Device::copied_pages`). pub(super) fn over_own_pages(&self) -> bool { let pages = self.import.pages(ReadApart::Texture); pages.memory.placement.over_own_pages() } /// The bytes of their memory from where the bytes start to the placement's end: the room an /// image bound at their bytes has. pub(super) fn room(&self) -> u64 { let pages = self.import.pages(ReadApart::Texture); pages.memory.placement.size().saturating_sub(pages.offset) } /// The index of their memory's type. pub(super) fn type_index(&self) -> u32 { self.import.shape.type_index } /// Whether they were imported as dma-bufs (`dma_buf.rs`), not by their pointer. pub(super) fn over_dma_buf(&self) -> bool { 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 byte `offset` of the bytes lying in them lies in their import's memory, for the /// caller ([`Buffer::vk_host_memory`](crate::Buffer::vk_host_memory)): read apart as the /// buffer's `VkBuffer` is (`ReadApart::VkBuffer`), which keeps a releasable import imported /// for good. `None` where that memory is not one import of the pages themselves by their /// pointer, alone or a guest RAM chunk's: a copy of them, imports of dma-bufs, an import of a /// read-only view of them, or the device's stand-in for an import it could not make again. fn in_import(&self, offset: u64) -> Option { let import = &self.import; if import.copied() || import.drops_writes() || import.shape.over_dma_buf { return None; } let pages = import.pages(ReadApart::VkBuffer); #[cfg(unix)] if matches!(pages, ImportPages::StandIn(_)) { return None; } let placement = &pages.memory.placement; if placement.over_dma_buf() || placement.over_read_only_view() || placement.over_own_pages() { return None; } let at = pages.offset + offset; Some(crate::VkHostMemory { memory: placement.memory, offset: placement.offset + at, size: placement.size().saturating_sub(at), type_index: placement.type_index(), handle_type: vk::ExternalMemoryHandleTypeFlags::HOST_ALLOCATION_EXT, }) } /// Whether they are bound in the device's import of a chunk of a guest RAM (`host_ram.rs`), /// with no import of their own. pub(super) fn in_ram_chunk(&self) -> bool { self.import.shape.in_ram_chunk } /// 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. Read as a blit reads /// them (`HostImport::blit_pages`): imported again where the device released them while /// idle, and left releasable, for an image over a dma-buf of its own pages /// (`Device::dma_buf_image`), which asks their source and binds none of their memory, so /// neither it nor a command that uses it holds their import (`host_residency.rs`). Refused /// where the device cannot import them again. #[cfg(unix)] pub(super) fn dma_buf( &self, ) -> Result, u64, u32)>, Error> { let (pages, _) = self.import.blit_pages()?; let placement = &pages.memory.placement; let (Some(imports), Some(mapped)) = (placement.dma_buf_pages(), placement.mapped) else { return Ok(None); }; let start = (mapped.as_ptr() as u64).checked_add(pages.offset); Ok(start.map(|start| { ( Arc::clone(imports), placement.dma_buf_address(start), placement.type_index(), ) })) } /// As the buffer that lies in them is released (`BufferShared`'s drop, a no-copy heap's own /// buffer's included), its listing let go of: a live buffers' table that still lists them is a /// command buffer's, one that may reach them unnamed (its first submission's, a host step's, /// or one a root table recorded before its first submission holds, `live_buffers.rs`), and /// the pages stay until it lets go of it. Where the caller gave a keep-alive, that keeps the /// pages mapped until the import is freed, so the deallocator runs here, at Metal's moment /// ([`HostPages::run_kept`]), and the import keeps the keep-alive unless it keeps another's. /// Else the deallocator waits for the pages to go, where Metal's runs at the release: /// announced once per device (`Degradation::HostDeallocatorDelayed`). fn released_listed(&self, device: &Device) { let Some(release) = self.release.get() else { return; }; if self.listed.load(Ordering::Acquire) == 0 { return; } // The exit guard runs no deallocator and drops no keep-alive: the pages' drop keeps them. let Some(busy) = exit_guard::enter() else { return; }; drop(busy); if let Some(keep_alive) = release.keep_alive() { // These pages still lie in the import, and another buffer lying there may have let go // of its keep-alive here too: only a keep-alive the import keeps covers this one. self.run_kept(release, keep_alive, false); return; } if !release.deallocates() { return; } device.shared().counts.host_deallocator_delayed(); let length = release.length(); device.degrade_once(Degradation::HostDeallocatorDelayed, || { ( format!("a no-copy buffer of {length} bytes"), "a command buffer that may reach its pages unnamed (a live buffers' table it \ holds lists them) holds them as it is released, and the caller gave no \ keep-alive" .to_owned(), ) }); } /// Run `release`'s deallocator now, at Metal's moment, the caller's `keep_alive` keeping the /// pages mapped until the import is freed: the import keeps it, unless it keeps another's /// already, or `others` (another buffer lies in the import, whose own contract keeps the same /// bytes mapped until it is freed); then it is dropped after the deallocator, which may read /// the bytes. fn run_kept(&self, release: &Release, keep_alive: ProgramObject, others: bool) { let counts = &self.import.device.shared().counts; let covered = { let mut kept = lock(&self.import.kept); match others || kept.is_some() { true => Some(keep_alive), false => { // Counted before the free can take it. counts.host_keep_alive_kept(); if self.import.held_inside() { counts.host_release_held_inside(); } *kept = Some(keep_alive); None } } }; release.run(); if let Some(keep_alive) = covered { counts.host_keep_alive_covered(); exit_guard::program_release(move || drop(keep_alive)); } } /// Release the pages to `release` when they go. pub(super) fn release_to(&self, release: Release) { // A refused set leaves the deallocator unrun, as a refused call does: never reached, // since each pages' release is set once, as they become a buffer's. let _ = self.release.set(release); } /// Hold back their release's deallocator and keep-alive for a recovery that carries their /// buffer to its device's next generation ([`Release::carry_on`]): `None` where it holds /// neither, or they have none. pub(super) fn carry_release(&self) -> Option> { self.release.get().and_then(Release::carry_on) } /// Their import, which a no-copy buffer made over the same bytes shares. pub(super) fn import(&self) -> &Arc { &self.import } } /// The import of host pages one or more no-copy buffers lie in: a `VkBuffer` over them and the /// memory imported from them. Every no-copy buffer made over the same bytes as a live one, of /// its memory class, lies in its import (`host_aliases.rs`): one resource to the driver, as one /// IOSurface's memory is to Metal. The last hold on it destroys the `VkBuffer` and frees the /// import (in the release, or on a handler thread where a keep-alive alone waits for the free), /// but for a releasable one's, which the command buffers that read them hold too /// (`host_residency.rs`). pub(super) struct HostImport { device: Device, /// Where the bytes lie in its `VkBuffer` and memory: the same in each import of them again. shape: Shape, /// Its `VkBuffer` and memory: taken as it goes, to be freed in the release or, where a /// keep-alive alone waits for the free, on a handler thread. objects: ManuallyDrop, /// The [`HostPages`] lying in it. lying: AtomicUsize, /// The buffers bound inside its memory now, each with no import of its own ([`Inside`]). inside: AtomicUsize, /// The reads other than a blit's that took it, a bit each ([`HostImport::note_read_apart`]): /// counted in `WorkCounts::host_imports_read_apart` and the gauge of each reason while it /// lives. read_apart: AtomicU16, /// Why the device never releases it while idle, for an import it keeps: counted in that /// reason's `WorkCounts` gauge while it lives. `None` for a releasable one. kept_because: Option, /// A rebind's import that no live buffers' table listed yet ([`ListedPages`]): counted in /// `WorkCounts::host_imports_rebound_unlisted` until one does or it goes. unlisted: AtomicBool, /// The keep-alive of the pages that went while it lived with none other lying in it, dropped /// once it is freed: it keeps the bytes mapped for every buffer made over them, since all were /// made over the same bytes, so a later one's keep-alive is dropped as its pages go /// ([`HostPages`]). kept: Mutex>>, /// The releases of pages that went while it lived with no keep-alive: their deallocators /// run once it is freed. after_free: Mutex>, /// 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, /// The logs of the writes to its pages, where their memory came with one /// (`dirty_pages::PagesLog`): every buffer lying in it shares them. log: OnceLock>, } /// Where a host import's bytes lie in its `VkBuffer` and memory, which reading needs no /// `VkBuffer`: the same in each import of them again (`host_residency.rs`). #[derive(Clone, Copy)] pub(super) struct Shape { /// Where the bytes start in the first imported page. pub(super) offset: u64, /// Where the buffer's byte 0 lies in its `VkBuffer`. pub(super) base: u64, /// The bytes from byte 0 a copy reads ([`Buffer::copy_reach`]). pub(super) reach: u64, /// The host address of the first imported byte. pub(super) mapped: Option, /// The index of the memory's type. pub(super) type_index: u32, /// The pages were imported as dma-bufs (`dma_buf.rs`), not by their pointer. pub(super) over_dma_buf: bool, /// The bytes are bound in the device's import of a chunk of a guest RAM (`host_ram.rs`), with /// no import of their own. pub(super) in_ram_chunk: bool, /// The pages were imported through a read-only view of them, which drops the GPU's writes /// (`read_only_view.rs`). pub(super) drops_writes: bool, } impl Shape { /// The shape of `pages`. pub(super) fn of(pages: &Pages) -> Shape { let placement = &pages.memory.placement; Shape { offset: pages.offset, base: pages.base, reach: pages.reach, mapped: placement.mapped, type_index: placement.type_index(), over_dma_buf: placement.over_dma_buf(), in_ram_chunk: placement.over_ram_chunk(), drops_writes: placement.over_read_only_view(), } } /// Whether `other` lays the bytes as this does: an import again of them as their first. pub(super) fn same(&self, other: &Shape) -> bool { let at = |shape: &Shape| shape.mapped.map(Mapped::as_ptr); ( self.offset, self.base, self.reach, self.type_index, self.over_dma_buf, self.in_ram_chunk, self.drops_writes, ) == ( other.offset, other.base, other.reach, other.type_index, other.over_dma_buf, other.in_ram_chunk, other.drops_writes, ) && at(self) == at(other) } } /// Why a read other than a blit's took a host import ([`HostImport::note_read_apart`]), each /// counted once per import in its `WorkCounts::host_imports_read_apart_*` gauge while the import /// lives. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum ReadApart { /// The buffer's Metal address handed out: `gpu_address`, or written for the caller. Address, /// The buffer's `VkBuffer` handed out (`Buffer::vk_buffer`). VkBuffer, /// A command's read other than a blit's copy: a binding, `use_resource`, or a copy of a /// texture over the bytes. Binding, /// A texture over the bytes: an image bound to the memory, or a texel view over the /// `VkBuffer`. Texture, /// A buffer bound inside its memory, with a `VkBuffer` of its own (`host_aliases.rs`, "One /// page, one import"). Inside, /// A buffer made to share its buffer's range (`BufferDescriptor::range_of`), its Metal /// address handed to that buffer. SharedRange, /// A no-copy heap's own bytes lying in it ([`Joining::Heap`]). Heap, /// A rebound buffer lying in it ([`Joining::Rebound`]). Rebound, /// No thread to release it while idle (`host_residency.rs`). Unreleased, } impl ReadApart { /// How many reasons there are. pub(crate) const COUNT: usize = 9; const ALL: [ReadApart; ReadApart::COUNT] = [ ReadApart::Address, ReadApart::VkBuffer, ReadApart::Binding, ReadApart::Texture, ReadApart::Inside, ReadApart::SharedRange, ReadApart::Heap, ReadApart::Rebound, ReadApart::Unreleased, ]; /// Its bit in [`HostImport::read_apart`]. fn bit(self) -> u16 { 1 << self as u16 } } /// Why the device keeps a host import imported whatever reads it, never releasing it while idle /// (`host_residency.rs`), each counted in its `WorkCounts::host_imports_kept_*` gauge while the /// import lives. Imports of dma-bufs kept as their descriptors did not fit count apart /// (`WorkCounts::host_imports_kept_for_fds`), as pointer imports here. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum KeptBecause { /// A heap's own import. Heap, /// A rebind's import (`rebind.rs`). Rebind, /// An import by pointer on a device whose submission checks did not find a held pointer /// import to cost every submission (`submit_check.rs`), or made before they answered, or off /// Unix. Pointer, /// No stand-in buffer for a read of a released one. NoStandIn, } impl KeptBecause { /// How many reasons there are. pub(crate) const COUNT: usize = 4; } /// A host import's `VkBuffer` and memory. enum Objects { /// Imported until the import goes. Fixed(Imported), /// Released while idle, and imported again at the next read (`host_residency.rs`). #[cfg(unix)] Releasable(Residency), } /// A host import's `VkBuffer` and memory as one read takes them: borrowed from an import that /// keeps them, or held, from one that may release them, for as long as the read lasts. pub(super) enum ImportPages<'a> { Fixed(&'a Pages), #[cfg(unix)] Held(Arc), /// The device's stand-in, which a read of a released import takes where the device cannot /// import it again ([`HostImport::pages`]). #[cfg(unix)] StandIn(Arc), } impl std::ops::Deref for ImportPages<'_> { type Target = Pages; fn deref(&self) -> &Pages { match self { ImportPages::Fixed(pages) => pages, #[cfg(unix)] ImportPages::Held(imported) => &imported.pages, #[cfg(unix)] ImportPages::StandIn(stand_in) => &stand_in.pages, } } } impl HostImport { /// The import of `pages`, no pages lying in it yet, which the device keeps imported for /// `because` (`None`: an import of dma-bufs whose descriptors did not fit, counted as such, /// or pages bound in a guest RAM's chunk imported as a dma-buf, which the RAM's use keeps). fn new(device: &Device, pages: Pages, because: Option) -> HostImport { if let Some(because) = because { device.shared().counts.host_import_kept(because, true); } let unlisted = because == Some(KeptBecause::Rebind); if unlisted { device.shared().counts.host_import_rebound_unlisted(true); } HostImport { device: device.clone(), shape: Shape::of(&pages), objects: ManuallyDrop::new(Objects::Fixed(Imported::new(device, pages))), lying: AtomicUsize::new(0), inside: AtomicUsize::new(0), read_apart: AtomicU16::new(0), kept_because: because, unlisted: AtomicBool::new(unlisted), kept: Mutex::new(None), after_free: Mutex::new(Vec::new()), copied: OnceLock::new(), log: OnceLock::new(), } } /// The import of `pages`, no pages lying in it yet, which the device releases while idle and /// `again` imports again (`host_residency.rs`). #[cfg(unix)] fn releasable( device: &Device, pages: Pages, again: Again, stand_in: Arc, ) -> HostImport { HostImport { device: device.clone(), shape: Shape::of(&pages), objects: ManuallyDrop::new(Objects::Releasable(Residency::new( device, pages, again, stand_in, ))), lying: AtomicUsize::new(0), inside: AtomicUsize::new(0), read_apart: AtomicU16::new(0), kept_because: None, unlisted: AtomicBool::new(false), kept: Mutex::new(None), after_free: Mutex::new(Vec::new()), copied: OnceLock::new(), log: OnceLock::new(), } } /// A live buffers' table listed pages lying in it ([`ListedPages`]): a rebind's import is /// listed from now on (`WorkCounts::host_imports_rebound_unlisted`). A load once listed. fn note_listed(&self) { if self.unlisted.load(Ordering::Relaxed) && self.unlisted.swap(false, Ordering::Relaxed) { (self.device.shared().counts).host_import_rebound_unlisted(false); } } /// Whether a buffer bound inside its memory lives now ([`Inside`]): it holds the import past /// the release of the pages lying in it. fn held_inside(&self) -> bool { self.inside.load(Ordering::Acquire) > 0 } /// 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 it is an import of dma-bufs of the pages (`dma_buf.rs`), not of their pointer nor /// a copy of them. pub(super) fn over_dma_buf(&self) -> bool { self.shape.over_dma_buf && !self.copied() } /// Whether its memory is a copy of the caller's pages that drops the GPU's writes, as the /// process cannot write them (`copied.rs`). pub(super) fn copy_drops_writes(&self) -> bool { self.copied .get() .is_some_and(|copied| copied.drops_writes()) } /// Where the bytes start in its first page: their offset in their host page for an import of /// them, 0 for a copied host buffer's copy, which lays them from its first byte. pub(super) fn offset(&self) -> u64 { self.shape.offset } /// Keep the logs of the writes to its pages (set once, as its first buffer is made), which /// its copy, where it is one, reports its merges back to (`copied.rs`). pub(super) fn keep_log(&self, log: Arc) { if let Some(copied) = self.copied.get() { copied.set_log(&log); } self.device.shared().dirty.note_logged(); let _ = self.log.set(log); } /// 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 { self.shape.drops_writes } /// Its residency, where the device may release it while idle. #[cfg(unix)] pub(super) fn residency(&self) -> Option<&Residency> { match &*self.objects { Objects::Fixed(_) => None, Objects::Releasable(residency) => Some(residency), } } /// Its `VkBuffer` and memory for a read other than a blit's, for `reason`, which keeps a /// releasable import imported for good from then on (`host_residency.rs`). Released, it is imported again /// first; where the device cannot, the device is lost (its work no longer runs) and the read /// takes the device's stand-in. pub(super) fn pages(&self, reason: ReadApart) -> ImportPages<'_> { self.note_read_apart(reason); match &*self.objects { Objects::Fixed(imported) => ImportPages::Fixed(&imported.pages), #[cfg(unix)] Objects::Releasable(residency) => match residency.exposed() { Some(held) => ImportPages::Held(held), None => { // No work that read it runs on a lost device. self.device.mark_lost(); self.device.shared().counts.host_import_lost(); ImportPages::StandIn(residency.stand_in()) } }, } } /// Its `VkBuffer` and memory for a blit's command (`Buffer::blit_at`), imported again where /// released, with what the command buffer holds of them (`rebind::ImportHold`): nothing of an /// import that keeps them. Refused where the device cannot import them again. pub(super) fn blit_pages(&self) -> Result<(ImportPages<'_>, Option), Error> { match &*self.objects { Objects::Fixed(imported) => Ok((ImportPages::Fixed(&imported.pages), None)), #[cfg(unix)] Objects::Releasable(residency) => { let held = residency.for_blit()?; let hold = ImportHold::Held(Arc::clone(&held)); Ok((ImportPages::Held(held), Some(hold))) } } } /// Its `VkBuffer` and memory for a live-table listing (`live_buffers.rs`), which reads them /// without exposing them: `None` while a releasable import is released. fn listing(&self) -> Option> { match &*self.objects { Objects::Fixed(imported) => Some(ImportPages::Fixed(&imported.pages)), #[cfg(unix)] Objects::Releasable(residency) => residency.listing().map(ImportPages::Held), } } /// Keep it imported for good from now on, for `reason` (`host_residency.rs`): whether it was /// ever released, so a range of it noted before may be stale. pub(super) fn expose(&self, reason: ReadApart) -> bool { self.note_read_apart(reason); match &*self.objects { Objects::Fixed(_) => false, #[cfg(unix)] Objects::Releasable(residency) => residency.expose(), } } /// Note a read other than a blit's, for `reason` ([`HostImport::pages`], /// [`HostImport::expose`]): the reads after which the device's residency keeps a releasable /// import for good (`host_residency.rs`), noted for an import of any kind, counted once while /// it lives (`WorkCounts::host_imports_read_apart`), and once for each reason. A load once /// noted. fn note_read_apart(&self, reason: ReadApart) { let bit = reason.bit(); if self.read_apart.load(Ordering::Relaxed) & bit != 0 { return; } let before = self.read_apart.fetch_or(bit, Ordering::Relaxed); if before & bit != 0 { return; } let counts = &self.device.shared().counts; if before == 0 { counts.host_import_read_apart(true); } counts.host_import_read_apart_for(reason, true); } /// A no-copy buffer made over its bytes came to lie in it beside another /// ([`Joining::Buffer`]): counted where it is releasable still, which it stays /// (`WorkCounts::host_imports_joined_releasable`, `host_residency.rs`). fn note_joined(&self) { #[cfg(unix)] if self.residency().is_some_and(Residency::releasable) { (self.device.shared().counts).host_import_joined_releasable(); } } } impl Device { /// On a device that keeps MoltenVK's residency set (`argument_buffers.rs`), a line to the /// device's message sink (`Verbose`, id name `metal2vulkan-host-import-freed`) for a host /// import of `bytes` freed: MoltenVK removes its buffer from the set and commits the set at /// once, with the submissions in flight on the device's queues it names. Elsewhere nothing, /// and nothing made where the sink hears no `Verbose` message /// (`MessageSink::with_least_severity`). pub(super) fn note_import_freed(&self, bytes: u64) { let severity = super::MessageSeverity::Verbose; let shared = self.shared(); let Some(sink) = (shared.instance.sink()).filter(|sink| sink.hears(severity)) else { return; }; let facts = super::device::argument_buffers::Facts::of(&self.properties().description); if !facts.keeps_residency_set() { return; } let in_flight: usize = shared .relayed_queues() .map(|(_, flights)| flights.in_flight()) .sum(); sink.deliver(&super::DebugMessage { severity, kind: super::MessageKind { general: true, ..super::MessageKind::default() }, id_name: "metal2vulkan-host-import-freed".into(), id: 0, text: format!( "metal2vulkan: a host import of {bytes} bytes freed with {in_flight} submissions \ in flight on the device's queues: MoltenVK removes it from its device-wide \ residency set and commits the set" ), degradation: None, }); } } 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 // deallocator runs and no keep-alive goes. for release in lock(&self.after_free).iter() { release.keep(); } if let Some(kept) = lock(&self.kept).take() { std::mem::forget(kept); } // SAFETY: dropped once, here, and never read again; its free finds the exit too. unsafe { ManuallyDrop::drop(&mut self.objects) }; return; }; let shared = self.device.shared(); let read_apart = self.read_apart.load(Ordering::Relaxed); if read_apart != 0 { shared.counts.host_import_read_apart(false); } for reason in ReadApart::ALL { if read_apart & reason.bit() != 0 { shared.counts.host_import_read_apart_for(reason, false); } } if let Some(because) = self.kept_because { shared.counts.host_import_kept(because, false); } if self.unlisted.load(Ordering::Relaxed) { shared.counts.host_import_rebound_unlisted(false); } drop(busy); // Once freed, the keep-alive goes, and the deallocators that waited for the free run. let kept = lock(&self.kept).take(); if kept.is_some() { shared.counts.host_keep_alive_freed(); } let releases: Vec = lock(&self.after_free).drain(..).collect(); let delayed = releases .iter() .find(|release| release.deallocates()) .map(Release::length); // The free goes off the releasing thread only where a keep-alive (a runtime extension // whose drop tells the caller the pages may go) alone waits for it. A deallocator waiting // for it runs in the release, as Metal runs it there (an M3 Max under macOS 27.0.1 ran an // unused buffer's deallocator inside its final release, on the releasing thread, every // time). With nothing waiting the caller may unmap the pages once the release returns, and // `VK_EXT_external_memory_host` requires the imported range to stay valid for the imported // memory's whole life (`VkImportMemoryHostPointerInfoEXT`), so the free is made here too. let posts = delayed.is_none() && (kept.is_some() || releases.iter().any(Release::keeps_alive)); // A completed command buffer's release that lets go of the import last, while a // deallocator or a keep-alive waits for its free, posts the free to the device's free // thread, which paces it (`free_thread.rs`): NVIDIA's driver holds every other thread's // `vkQueueSubmit` while it frees memory (docs/FAST-PATHS.md, known gaps), and the caller // learns that the pages may go from what waits, which goes there after the free. let waits = delayed.is_some() || posts; let paced = waits && crate::free_thread::posts_imports(); let left = AfterImport { after: Box::new(AfterFree { kept, releases }), delayed, waits, }; // SAFETY: taken once, here, as the import goes, and never read again. let objects = unsafe { ManuallyDrop::take(&mut self.objects) }; let (going, frees): (Box, bool) = match objects { // No pending command buffer uses the pages: one whose commands used them holds them // until it completed (`rebind.rs`), one that may read a texture's image over them // holds the image, which holds the import (`heap_sets.rs`), and every buffer over them // let go of them. Objects::Fixed(mut imported) => { imported.leave(left); if posts || paced { imported.hold_for_release(); } (Box::new(imported), true) } // Its objects go with their last holder, here or the last command buffer that read // them (a blit's, which holds them and not the buffer once a rebind or detach // replaced its pages), and what waits for the free with them: a driver may list a // pointer import's memory in every submission, which fails where its pages were // unmapped. #[cfg(unix)] Objects::Releasable(residency) => match residency.let_go() { Some(mut held) => { held.leave(left); // Where a command buffer's blit holds them still, that command buffer holds // the device as the program's, and they go with it. if posts || paced { if let Some(imported) = Arc::get_mut(&mut held) { imported.hold_for_release(); } } (Box::new(held), true) } // Released: nothing to free. None => (left.after, false), }, }; let going = match paced && frees { true => match post_free(shared, going) { Ok(()) => return, Err(going) => going, }, false => going, }; if posts { shared.counts.host_import_release_posted(); // A tuple drops in order: the release, then its count. The release's own handles of // the device are holders' (the count's, the import's, and its dma-buf imports' where // it alone holds them), which the program's last drop waits for // (`device/holds.rs`): so a program that let go of such a buffer, then of the device, // finds the device gone as that drop returns. let posted = (going, PostedDone(self.device.held_for_release())); self.device.let_go_elsewhere(Box::new(posted)); } else { drop(going); } } } /// Post `objects`, a host import's going at a completed command buffer's release while a /// deallocator or a keep-alive waits for their free, each handle of the device they hold a /// holder's, to the device of `shared`'s free thread (`free_thread.rs`, /// `WorkCounts::host_import_frees_posted`); given back where it refused them. fn post_free(shared: &DeviceShared, objects: Box) -> Result<(), Box> { let posted = crate::free_thread::PostedImport { objects, holds: Arc::clone(&shared.holds), }; (shared.frees.post_import(posted)).map_err(|posted| posted.objects) } /// Counts a host import's release posted to a handler thread (a keep-alive alone waiting for its /// free) run as it drops, after the release. struct PostedDone(Device); impl Drop for PostedDone { fn drop(&mut self) { self.0.shared().counts.host_import_release_done(); } } /// A host import's `VkBuffer` and memory, which the last holder lets go of, destroying the /// `VkBuffer` and freeing the memory: the import's own, and a releasable import's, held by the /// import while it is imported and by each command buffer whose blit read them until it completed /// (`EncoderCore::blit_at`, `host_residency.rs`). pub(super) struct Imported { device: Device, pub(super) pages: Pages, /// What goes once its memory is freed, which the import left as it went ([`Imported::leave`]). after: Mutex>, } /// What a going import leaves with its objects ([`Imported::leave`]): the caller's keep-alive and /// deallocators, which go once the memory is freed, the length of a deallocator's pages, /// announced where the free waits for the batches in flight, and whether a deallocator or a /// keep-alive waits for the free (a completed command buffer that lets go of the objects last /// posts their free to the free thread then, `rebind::ImportHold`). pub(super) struct AfterImport { after: Box, delayed: Option, waits: bool, } impl Imported { /// The objects of `pages`, imported now. pub(super) fn new(device: &Device, pages: Pages) -> Imported { Imported { device: device.clone(), pages, after: Mutex::new(None), } } /// Leave `left` to go once the memory is freed, the import going. fn leave(&self, left: AfterImport) { *lock(&self.after) = Some(left); } /// Whether the import went, leaving what waits for the free ([`Imported::leave`]), and a /// deallocator or a keep-alive among it: its free may go to the free thread then. pub(super) fn waits_for_free(&mut self) -> bool { let after = self.after.get_mut().unwrap_or_else(PoisonError::into_inner); after.as_ref().is_some_and(|after| after.waits) } /// Post the free of `imported`, a completed command buffer's release letting go of it last, /// to its device's free thread where a deallocator or a keep-alive waits for it /// (`rebind::ImportHold`); else, or where the thread refuses it, free it here. pub(super) fn let_go_at_completion(mut imported: Imported) { if !(crate::free_thread::posts_imports() && imported.waits_for_free()) { drop(imported); return; } imported.hold_for_release(); let device = imported.device.clone(); if let Err(objects) = post_free(device.shared(), Box::new(imported)) { drop(objects); } } /// Hold the device through a handle the program's last drop waits for, in place of its own /// ([`Device::held_for_release`]), and so the dma-buf imports its pages lie in where they /// alone hold them: the import going, these objects go in a release posted to a handler /// thread or the free thread. fn hold_for_release(&mut self) { self.device = self.device.held_for_release(); #[cfg(unix)] self.pages.memory.placement.hold_dma_buf_for_release(); } } impl Drop for Imported { fn drop(&mut self) { let left = (self.after.get_mut()) .unwrap_or_else(PoisonError::into_inner) .take(); let (after, delayed) = match left { Some(AfterImport { after, delayed, .. }) => (Some(after), delayed), None => (None, None), }; // SAFETY: no pending command buffer uses them: an import's own go as the import goes // (`HostImport::drop`), a releasable import's as the last command buffer whose blit read // them completed, and no other read reached them (`host_residency.rs`). match unsafe { self.pages.release_import(&self.device, after) } { // Freed now: what waited goes here, or, for imports of the caller's dma-bufs, once // their last holder (these pages' placement, as it drops after this) frees them. Some(after) => self.pages.after_free(after), // Its memory waits for the batches in flight (`freed_memory.rs`), and what the import // left with it, past Metal's release. None => { if let Some(length) = delayed { deallocator_delayed(&self.device, length); } } } } } /// Count and announce once that a deallocator of a no-copy buffer of `length` bytes waits for /// the batches submitted before its release (`freed_memory.rs`): its import's memory, freed, /// waits for them, and the deallocator with it. fn deallocator_delayed(device: &Device, length: u64) { device.shared().counts.host_deallocator_delayed(); device.degrade_once(Degradation::HostDeallocatorDelayed, || { ( format!("a no-copy buffer of {length} bytes"), "its pages' import, freed, waits for the batches submitted before its release: the \ device's driver fails pending work whose pipelines read device addresses where \ such memory is freed, and the caller gave no keep-alive" .to_owned(), ) }); } /// A buffer's hold on the live import of host pages it is bound inside, with no import of its own /// (`host_aliases.rs`, "One page, one import"; `Placement::in_import`, whose clones share /// it): counted in the import's `inside` while it lives, so that a release of another buffer's /// pages that the import outlives for it is counted (`WorkCounts::host_releases_held_inside`) /// and named in its announcement. pub(super) struct Inside(Arc); impl Inside { /// A hold on `import` for a buffer bound inside its memory. pub(super) fn new(import: Arc) -> Inside { import.inside.fetch_add(1, Ordering::AcqRel); Inside(import) } } impl Drop for Inside { fn drop(&mut self) { // Before the hold goes: the import may go with it. self.0.inside.fetch_sub(1, Ordering::AcqRel); } } /// What goes once a host import's memory is freed: the keep-alive of the pages that went while it /// lived, and the deallocators that waited for the free, each panic caught. It waits with the /// memory where that waits for the batches in flight (`freed_memory.rs`). struct AfterFree { kept: Option>, releases: Vec, } impl Drop for AfterFree { fn drop(&mut self) { let kept = self.kept.take(); let Some(busy) = exit_guard::enter() else { // The process is exiting: the pages stay imported to its end (`exit_guard`), so no // deallocator runs and no keep-alive goes. for release in &self.releases { release.keep(); } if let Some(kept) = kept { std::mem::forget(kept); } return; }; drop(busy); if let Some(keep_alive) = kept { exit_guard::program_release(move || drop(keep_alive)); } for release in &self.releases { release.run(); } } } impl Drop for HostPages { fn drop(&mut self) { // No command writes their copy through them from now on (`copied.rs`). if let (Some(key), Some(copied)) = (self.named.get(), self.import.copied.get()) { copied.unname(*key); } // The images and views a rebind or a detach parked go first: they may hold the import. lock(&self.parked).clear(); let others = self.import.lying.fetch_sub(1, Ordering::AcqRel) > 1; let Some(release) = self.release.take() else { return; }; // The exit guard runs no deallocator and drops no keep-alive. let Some(busy) = exit_guard::enter() else { // The process is exiting: the pages stay imported to its end (`exit_guard`). release.keep(); return; }; drop(busy); let import = &self.import; match release.keep_alive() { // The caller's keep-alive keeps the pages mapped until the import is freed: the // deallocator runs now, at Metal's moment. Where another buffer lies in the import, // or the import keeps another's keep-alive, that keeps the same bytes mapped until it // is freed: this one goes now too, after the deallocator, which may read the bytes. (A // buffer released while a table listed its pages ran this at its release, // `released_listed`, and left the import a keep-alive: none is left here.) Some(keep_alive) => self.run_kept(&release, keep_alive, others), // Another buffer lies in the import, whose contract keeps the pages mapped: the // deallocator runs now, as with an import of its own (`host_aliases.rs`). None if others => release.run(), // The deallocator runs once the import is freed: as these pages let go of it below, // where nothing else holds it; else later, announced. None => { if release.deallocates() && Arc::strong_count(import) > 1 { let counts = &import.device.shared().counts; counts.host_deallocator_delayed(); let inside = import.held_inside(); if inside { counts.host_release_held_inside(); } let length = release.length(); import .device .degrade_once(Degradation::HostDeallocatorDelayed, || { let held = match inside { true => { "a buffer bound inside its pages' import, over part of its \ bytes or the same bytes as memory of another class, still \ lives as it is released (one live import of a page: \ VK_EXT_external_memory_host leaves a page imported twice \ undefined)" } false => { "its pages' import is still held as it is released (a \ texture over them may still be read through its resource \ ID by a command buffer submitted before the texture's \ release)" } }; ( format!("a no-copy buffer of {length} bytes"), format!("{held}, and the caller gave no keep-alive"), ) }); } lock(&import.after_free).push(release); } } } } impl Pages { /// The placement the pages are bound in: what a buffer bound inside their import binds in /// (`Device::bind_in_import`). pub(super) fn placement(&self) -> &Placement { &self.memory.placement } /// Destroy the `VkBuffer` of a host import's pages and free their memory, on `device`, once /// their sparse binding completed, and note it (`Device::note_import_freed`): an import's /// last hold lets go. Left to the process's end while it exits. `after` goes once the memory /// is freed: given back for the caller to let go of ([`after_free`](Self::after_free)), /// unless it waits with the memory for the batches in flight (`freed_memory.rs`). /// /// # Safety /// /// No pending command buffer uses the pages, and nothing else frees them. pub(super) unsafe fn release_import( &self, device: &Device, after: Option>, ) -> Option> { // The Vulkan teardown is a section of the exit guard. let Some(busy) = exit_guard::enter() else { return after; }; let shared = device.shared(); // A submission that used the pages waited for their sparse binding: waited for here where // none did. self.memory.placement.settle(); // SAFETY: the caller's. unsafe { release::object(shared.vk(), self.raw) }; let after = lock(&shared.memory).release_then(shared.vk(), &self.memory.placement, after); drop(busy); device.note_import_freed(self.memory.placement.size()); after } /// Let `after` go once the pages' memory is freed, their import released /// ([`release_import`](Self::release_import)): at once, but where the memory is imports of /// the caller's dma-bufs (`dma_buf.rs`), which the placement holds and are freed as their /// last holder lets go of them, then. Pages bound in a guest RAM's chunk (`host_ram.rs`) free /// no memory of their own, whatever the chunk's import: at once. fn after_free(&self, after: Box) { let placement = &self.memory.placement; #[cfg(unix)] if let Some(imports) = placement .dma_buf_pages() .filter(|_| !placement.over_ram_chunk()) { imports.after_free(after); return; } drop(after); } } /// A buffer's bound memory: its placement, and its Vulkan device address where the device /// enables `bufferDeviceAddress`. pub(super) struct Bound { pub(super) placement: Placement, pub(super) device_address: Option, } impl OwnBytes { /// `f` of the pages the buffer lies in now: a detached buffer's stand-in (`Detached`). A /// read of a no-copy buffer's import other than a blit's, for `reason`, which keeps it /// imported for good (`HostImport::pages`). fn with(&self, reason: ReadApart, f: impl FnOnce(&Pages) -> R) -> R { match &self.lie { Lie::Fixed(fixed) => f(&fixed.pages), Lie::Host(cell) => match cell.lying() { Lying::In(pages) => f(&pages.import.pages(reason)), Lying::Detached(detached) => f(&detached.pages), Lying::Gone(_) => read_gone(), }, } } /// [`with`](Self::with) while the buffer lies in pages: `None` while it is detached. fn with_attached(&self, reason: ReadApart, f: impl FnOnce(&Pages) -> R) -> Option { match &self.lie { Lie::Fixed(fixed) => Some(f(&fixed.pages)), Lie::Host(cell) => match cell.lying() { Lying::In(pages) => Some(f(&pages.import.pages(reason))), Lying::Detached(_) | Lying::Gone(_) => None, }, } } /// Where the bytes lie in the pages the buffer lies in now ([`Shape`]), read without their /// `VkBuffer`. fn shape(&self) -> Shape { match &self.lie { Lie::Fixed(fixed) => Shape::of(&fixed.pages), Lie::Host(cell) => match cell.lying() { Lying::In(pages) => pages.import.shape, Lying::Detached(detached) => Shape::of(&detached.pages), Lying::Gone(shape) => shape, }, } } } /// A `Managed` buffer's host copy on a device without unified memory, which `contents` maps and /// `did_modify_range` and `synchronize_resource` copy to and from (`managed.rs`): the runtime's /// own ([`Mirror`]), for a buffer the runtime makes, or the caller's pages, for a no-copy buffer /// (`managed_copy.rs`'s [`CallerCopy`]). pub(super) enum HostCopy { Own(Arc), Caller(Arc), } /// What a copy from a buffer's host copy into its own bytes replaces, which says the batch that /// takes it (`texture/first_move.rs`). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum Replaces { /// Bytes no command buffer can have read: the buffer's making, or its device copy's making /// on a recovery's new `VkDevice`. Taken as a new buffer's first fill is /// (`FirstMoves::register_bytes`; on a device without a fill queue, by the device's next /// submission, whatever its commands reach), so what it copies from (an import of the /// caller's pages, a staging buffer, the host copy) is held no longer than that. Unread, /// Bytes the program's command buffers may have read already, with the stamp of the commit /// that took the range (`managed.rs`; 0 where none did: a completion's undo, a rebind): only /// a batch whose commands may reach the buffer takes it, of a command buffer committed at or /// after that commit (`FirstMoves::register_upload`). Read(u64), } /// Register with `device`'s first work the copy of `length` bytes of `source` onto `keeper`'s /// bytes at `onto` (its `VkBuffer`, and where), `held` until the submission that makes it /// completed, for the batch `replaces` says: whether the copies staged now passed their bound. fn register_copy_in( device: &Device, keeper: Weak, (onto, source): ((vk::Buffer, u64), (vk::Buffer, u64)), length: u64, held: Box, replaces: Replaces, ) -> bool { let keeper: Weak = keeper; let moves = &device.shared().textures.first_moves; match replaces { Replaces::Unread => moves.register_bytes(keeper, onto, source, length, held), Replaces::Read(commit) => moves.register_upload(keeper, onto, source, length, held, commit), } } /// A `Managed` buffer's host copy on a device without unified memory (`managed.rs`): a /// `VkBuffer` of the buffer's padded length in host-visible, coherent memory, cached where the /// device has such ([`MemoryClass::Managed`]), which `contents` maps. The GPU uses the buffer's /// own `VkBuffer`, in device-local memory: Metal's two copies of a managed resource on a device /// without unified memory, which `did_modify_range` and `synchronize_resource` copy between. /// Released as the last holder lets it go: its buffer, or a submission that uploads from it. pub(super) struct Mirror { raw: vk::Buffer, placement: Placement, /// The device it releases its `VkBuffer` and memory into. device: Device, } impl Drop for Mirror { fn drop(&mut self) { // The Vulkan teardown is a section of the exit guard. let Some(busy) = exit_guard::enter() else { // The process is exiting: the host copy and its memory are left to its end. return; }; // SAFETY: no pending command uses the host copy: its buffer is gone, and so is every // submission that uploads from it (each holds it), and a command buffer that copies into // it holds the buffer. unsafe { release_mirror(self.device.shared(), self) }; drop(busy); } } /// The bytes of a heap a buffer placed in it is: its heap's buffer's from `offset`, a multiple of /// [`PLACEMENT_ALIGNMENT`](super::heap::PLACEMENT_ALIGNMENT). struct HeapBytes { heap: Heap, /// The heap's own buffer. bytes: Buffer, offset: u64, /// `makeAliasable` was called: an automatic heap's range is free for other resources. Shared /// by the buffer's parts on each generation its device's recovery carried it to /// (`Buffer::carry_placed`). aliasable: Arc, } /// Who owns a buffer's bytes. pub(super) enum Owner { /// The runtime: the sub-allocator's memory. Runtime, /// The caller: host memory a no-copy buffer wraps ([`HostPages`]), released to its /// deallocator if it gave one. Caller, /// The caller: a `VkBuffer` and the memory it is bound to, which the caller made and keeps /// (`wrapped_buffer.rs`). The runtime destroys and frees neither. Vulkan, } /// Whose memory a buffer's bytes are, where they are the caller's. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum CallerMemory { /// Host memory a no-copy buffer imported (`host_memory.rs`). HostPages, /// The memory the caller's own `VkBuffer` is bound to (`wrapped_buffer.rs`). VkBuffer, } impl BufferShared { /// [`Buffer::memory_hold`]. fn memory_hold(&self) -> Option { match &self.bytes { Bytes::Own(own) => match &own.lie { Lie::Fixed(fixed) => Some(MemoryHold::Fixed { _pages: Arc::clone(fixed), }), Lie::Host(cell) => cell.current().map(|host| MemoryHold::Host { _import: Arc::clone(host.import()), }), }, Bytes::Heap(heap) => heap.bytes.memory_hold(), } } } impl Filled for BufferShared { fn memory(&self) -> Option> { self.memory_hold() .map(|memory| Box::new(memory) as Box) } /// Its identity's key (`Buffer::identity`): a buffer placed in a heap has the heap's own /// buffer's. fn key(&self) -> Option { Some(match &self.bytes { Bytes::Own(own) => own.identity.key, Bytes::Heap(placed) => placed.bytes.identity().key, }) } } impl BufferShared { /// Its parts on its lost generation were marked let go of, the buffer carried to the next one /// and that generation at rest (`LostBuffer::mark`): no call takes them from now on /// ([`Buffer::held_parts`]), and they go once none under way holds them. fn released(&self) -> bool { match &self.bytes { Bytes::Own(OwnBytes { lie: Lie::Fixed(fixed), .. }) => fixed.released.load(Ordering::Acquire), Bytes::Own(OwnBytes { lie: Lie::Host(cell), .. }) => cell.released.load(Ordering::Acquire), Bytes::Heap(_) => false, } } /// Whether its parts on a lost generation went (`FixedPages::release_lost`, [`LostHost`], /// [`LostPlaced`]). fn freed(&self) -> bool { match &self.bytes { Bytes::Own(OwnBytes { lie: Lie::Fixed(fixed), .. }) => fixed.freed.load(Ordering::Acquire), Bytes::Own(OwnBytes { lie: Lie::Host(cell), .. }) => cell.freed.load(Ordering::Acquire), Bytes::Heap(_) => self.device.gone(), } } } impl Drop for BufferShared { fn drop(&mut self) { // Carried to the next generation, its parts on this one went with its handle of it // (`LostBuffer`): its share of its range goes back to the space every generation shares. if self.device.gone() { if let Bytes::Own(own) = &self.bytes { let Some(_busy) = exit_guard::enter() else { return; }; let mut last = &*self; while let Some(next) = last.next.get() { last = &next.0; } lock(&last.device.shared().addresses).free(own.reserved); } return; } // Its staged work goes with it, and the staging buffer or host copy that work holds, // which hold the device: a device whose program let go of it has no submission to wait // for, and its last handle would otherwise be one of its own. if *self.staged.get_mut() { let at: *const BufferShared = self; self.device.shared().textures.first_moves.forget(at.cast()); } let own = match &mut self.bytes { Bytes::Own(own) => own, Bytes::Heap(bytes) => { // An automatic heap's range goes back to it unless `makeAliasable` returned it: // once, by the buffer's parts on the generation it was carried to last // (`Buffer::carry_placed`), which go after these. if self.next.get().is_none() { bytes .heap .release(bytes.offset, self.length, &bytes.aliasable); } let live = &self.device.shared().live_buffers; live.forget(self.address.0, self.object_id); return; } }; let shared = self.device.shared(); if let Lie::Host(_) = own.lie { shared.rebinds.forget(own.identity.key); shared.aliases.forget(own.identity.key); } // The Vulkan teardown is a section of the exit guard. A no-copy buffer's pages go with // the last hold on them (`HostPages`), which runs their deallocator. let Some(busy) = exit_guard::enter() else { // The process is exiting: the buffer and its memory are left to its end. return; }; // The buffer leaves the device's live buffers; its pages go with the last hold on them // (`FixedPages`, `HostPages`). shared.live_buffers.forget(self.address.0, self.object_id); // The host copy goes with its last holder (`Mirror`'s drop). lock(&shared.addresses).free(own.reserved); drop(busy); // The range is free and no lock is held: the caller's token goes, so a creation at the // range from its drop on succeeds. own.range_token.release(); if let Lie::Host(cell) = &own.lie { if let Lying::In(pages) = cell.lying() { pages.released_listed(&self.device); } // A detached buffer's deallocator runs at its release, as Metal's does. cell.release_held_back(); } } } /// Release `mirror`, a buffer's host copy on `shared`'s device: its `VkBuffer` and memory. /// /// # Safety /// /// No pending command uses the host copy. unsafe fn release_mirror(shared: &DeviceShared, mirror: &Mirror) { // SAFETY: the caller's. unsafe { release::object(shared.vk(), mirror.raw) }; lock(&shared.memory).free(shared.vk(), &mirror.placement); } /// A buffer's parts once its `VkBuffer` is bound and its addresses held /// ([`Device::buffer_of`]). pub(super) struct BufferParts { pub(super) raw: vk::Buffer, /// The placement it is bound to. pub(super) memory: Placement, pub(super) offset: u64, pub(super) base: u64, pub(super) length: u64, /// The bytes from byte 0 a copy reads in the `VkBuffer` ([`Buffer::copy_reach`]): the /// length, or a no-copy buffer's bytes to the end of its `VkBuffer` in its pages. pub(super) reach: u64, pub(super) modes: Modes, pub(super) address: GpuAddress, pub(super) reserved: Held, pub(super) owner: Owner, /// A no-copy buffer's release to its caller's deallocator, where it gave one. pub(super) release: Option, /// The buffer is a heap's own (`heap.rs`): `Default` hazard tracking resolves to untracked. pub(super) of_heap: bool, /// The GPU's writes to a no-copy buffer's pages are dropped, as Metal's private option bit 24 /// drops them: they are imported through a read-only view of them (`read_only_view.rs`), or /// copied, the copy's GPU writes never written back (`copied.rs`), and a rebind's are too. pub(super) drops_writes: bool, /// A `Managed` buffer's host copy, on a device without unified memory. pub(super) mirror: Option, /// What imports a no-copy buffer's dma-bufs again, where the device may release its import /// while idle (`host_residency.rs`). #[cfg(unix)] pub(super) again: Option, /// 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; or the runtime's own buffer over the caller's pages that a /// `Managed` no-copy buffer on a device without unified memory copies to and from /// (`managed_copy.rs`), new as a new buffer is, which is never a copy of the pages. pub(super) enum Naming { New, HostCopy, 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 | Naming::HostCopy => Identity::new(hazard, of_heap), Naming::Carried { identity, .. } => *identity, } } } impl std::fmt::Debug for Buffer { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Buffer") .field("length", &self.0.length) .field("gpu_address", &self.0.address) .field("options", &self.0.options) .finish() } } impl PartialEq for Buffer { fn eq(&self, other: &Buffer) -> bool { Arc::ptr_eq(&self.0, &other.0) } } impl Eq for Buffer {} impl std::hash::Hash for Buffer { fn hash(&self, state: &mut H) { std::ptr::hash(Arc::as_ptr(&self.0), state); } } /// The three modes of a buffer's resource options, each checked to be one Metal defines. #[derive(Clone, Copy, Debug)] pub(super) struct Modes { pub(super) storage: StorageMode, pub(super) cache: CpuCacheMode, pub(super) hazard: HazardTrackingMode, } impl Modes { /// The modes of `options`; refused when one is not defined. pub(super) fn of(options: ResourceOptions) -> Result { Ok(Modes { storage: options.storage_mode()?, cache: options.cpu_cache_mode()?, hazard: options.hazard_tracking_mode()?, }) } } /// The alignment every buffer the runtime places in its memory starts at: the largest /// linear-image alignment measured (256 bytes on RADV, 128 on NVIDIA, 64 on lavapipe, 16 on /// MoltenVK), so a texture over the buffer aliases its memory whenever the texture's own offset /// allows. Imported host memory starts at a host page and needs nothing. pub(super) const LINEAR_IMAGE_ALIGNMENT: u64 = 256; /// A buffer's memory `requirements`, placed at a multiple of [`LINEAR_IMAGE_ALIGNMENT`] as well /// (Vulkan's alignments are powers of two, so the larger one is a multiple of both), and, up to /// half a pooled block, taking whole units of that alignment. So the next buffer placed in the /// pool starts where the last ends: a buffer shorter than the alignment would leave the rest of /// its unit free, a gap no buffer takes, and the pool's first-fit search (`range.rs`) walks every /// such gap for each later placement, which made each new buffer cost time in proportion to the /// buffers before it. A buffer past half the largest pooled block keeps its own size: it never /// lies in a pooled block but takes a block of its own (`memory.rs`'s `place`; a pooled block is /// at most [`BLOCK_BYTES`], and that on every heap of 1 GiB or more, /// `memory::pooled_block_bytes`), where nothing follows it. One up to that size takes a block of /// its own where its memory type's blocks are smaller (a small heap's), its size rounded as /// here. /// Rounded up to a heap's 256 KiB (`texture/heap.rs`'s `HEAP_BASE_ALIGNMENT`), the largest heap /// would ask past the device's `maxMemoryAllocationSize`: 4 GiB on RADV, whose largest allocation /// is 4 GiB less 4 bytes, and 41,747,218,432 bytes on MoltenVK on an M3 Max, whose largest is /// 41,747,087,360. pub(super) fn placed(requirements: vk::MemoryRequirements) -> vk::MemoryRequirements { let alignment = requirements.alignment.max(LINEAR_IMAGE_ALIGNMENT); let size = if requirements.size > BLOCK_BYTES / 2 { requirements.size } else { requirements.size.next_multiple_of(alignment) }; vk::MemoryRequirements { alignment, size, ..requirements } } /// The usages every buffer is made with: whatever a Metal buffer can be bound or used as, and the /// device-address usage where `device_address`. A buffer the runtime places in its memory takes /// its address from its block's buffer of addresses, which has these usages /// (`memory::allocate_addressed`), and is made with `usage(false)` itself. pub(super) fn usage(device_address: bool) -> vk::BufferUsageFlags { use vk::BufferUsageFlags as U; let usage = U::TRANSFER_SRC | U::TRANSFER_DST | U::UNIFORM_BUFFER | U::STORAGE_BUFFER | U::UNIFORM_TEXEL_BUFFER | U::STORAGE_TEXEL_BUFFER | U::INDEX_BUFFER | U::VERTEX_BUFFER | U::INDIRECT_BUFFER; if device_address { usage | U::SHADER_DEVICE_ADDRESS } else { usage } } impl Device { /// `newBufferWithLength:options:`: a buffer of `length` bytes, all zero. /// /// Where it lies follows docs/API.md's "The runtime's memory model": on a device without /// unified memory, `Shared` storage of the default CPU cache mode lies in host-cached system /// memory, as on a Mac with a discrete GPU, which the device announces once /// (`metal2vulkan-degrade-shared-in-system-memory`), and of the write-combined CPU cache /// mode in device-local memory where the device maps such. /// /// Refused: a length of 0 or past the device's `max_buffer_length` (`Nil`, as plain Metal /// answers nil, its validation stopping it), `Memoryless` storage /// (`Invalid`). pub fn new_buffer(&self, length: u64, options: ResourceOptions) -> Result { self.at_serving(|device| device.new_buffer_now(length, options)) } /// [`Device::new_buffer`] on the generation that serves (`device/line.rs`). pub(crate) fn new_buffer_now( &self, length: u64, options: ResourceOptions, ) -> Result { self.new_buffer_placed(length, options, AddressPlacement::Any) } /// [`Device::new_buffer`] at `placement` in the address space: made, refused, announced and /// kept among the program's resources as that is, at `AddressPlacement::Outside` for a buffer /// whose address Metal shows no program, so that no program buffer's address depends on it /// (`address.rs`). pub(super) fn new_buffer_placed( &self, length: u64, options: ResourceOptions, placement: AddressPlacement, ) -> Result { self.keep_room(); let options = self.own_memory_options("new_buffer", options)?; let placed = (placement.into(), None); let (buffer, class) = self.buffer_of_length("new_buffer", length, options, placed, false)?; self.degrade_system_memory(&buffer, class, || format!("buffer of {length} bytes")); Ok(self.visible(buffer)) } /// A buffer of `length` bytes, all zero, with `options`, that the runtime makes for its own /// use: refused as [`Device::new_buffer`] refuses it, and announcing nothing. It lies outside /// the Metal address space (`AddressPlacement::Outside`), so no program buffer's address /// depends on it. pub(super) fn own_buffer( &self, length: u64, options: ResourceOptions, ) -> Result { let placed = (AddressPlacement::Outside.into(), None); Ok(self .buffer_of_length("new_buffer", length, options, placed, false)? .0) } /// A `Shared` buffer of `length` bytes, all zero, of the write-combined CPU cache mode, that /// the runtime makes for its own use ([`Device::own_buffer`]): one the GPU alone uses past /// the host's zeroes, or that the host only writes (`MemoryClass::WriteCombined`). pub(super) fn write_combined_buffer(&self, length: u64) -> Result { self.own_buffer( length, ResourceOptions::new( StorageMode::Shared, CpuCacheMode::WriteCombined, HazardTrackingMode::Default, ), ) } /// A buffer of `length` bytes, all zero, with `options`, at `placement` in the address space, /// its byte `aligned` (where given) on a multiple of 256 bytes of its memory, for `call`, and /// the memory class it took: refused as [`Device::new_buffer`] refuses it, and for a pin the /// address space cannot honour. Where `padding_unobserved` (its maker declares the bytes /// between a texture's rows unobserved, `BufferDescriptor::padding_unobserved`), it lies in /// a plain block wherever the device's own buffers lie ([`NewBufferOf::Unobserved`]). pub(super) fn buffer_of_length( &self, call: &'static str, length: u64, options: ResourceOptions, (placement, aligned): (Place, Option), padding_unobserved: bool, ) -> Result<(Buffer, MemoryClass), Error> { let modes = Modes::of(options)?; let class = buffer_class(call, modes)?; if length == 0 || length > self.properties().max_buffer_length { return Err(nil(call, Problem::BufferLength { length })); } let of = match padding_unobserved { true => NewBufferOf::Unobserved, false => NewBufferOf::Runtime(FreshPages::WherePaid), }; let buffer = self.zeroed_buffer_of(call, length, (modes, class), of, (placement, aligned))?; Ok((buffer, class)) } /// Announce once each where `buffer`, which the program made (`what` names it, after its /// storage mode) in memory of `class`, lies in system memory: its own bytes overflowed past /// device-local memory ([`Device::degrade_overflow`]), or it is `Shared` memory a device /// without unified memory placed there (`MemoryClass::Shared`, /// [`Degradation::SharedInSystemMemory`]). A heap's buffer is its heap's. pub(super) fn degrade_system_memory( &self, buffer: &Buffer, class: MemoryClass, what: impl FnOnce() -> String, ) { let what = || format!("a `{:?}` {}", buffer.storage_mode(), what()); if buffer.own_pages_overflowed() { self.degrade_overflow(what); return; } if class != MemoryClass::Shared || self.properties().has_unified_memory { return; } if buffer.own_pages_device_local() != Some(false) { return; } self.degrade(Degradation::SharedInSystemMemory, || { ( what(), format!( "{} has no unified memory, and the default CPU cache mode lets the host \ read it, so it lies in host-cached system memory; `Private` or `Managed` \ storage, or the write-combined CPU cache mode, puts the GPU's bytes in \ device-local memory", self.name() ), ) }); } /// Announce [`Degradation::DeviceMemoryOverflow`] once for a resource the program made /// (`what` names it) whose memory overflowed past device-local memory into system memory /// (`memory.rs`'s `overflow_candidates`). pub(super) fn degrade_overflow(&self, what: impl FnOnce() -> String) { self.degrade(Degradation::DeviceMemoryOverflow, || { ( what(), format!( "no device-local memory type of {} that it takes has room for it, so it lies \ in system memory, as Metal makes a resource past a discrete GPU's memory \ rather than refuse it", self.name() ), ) }); } /// A buffer of `length` bytes (above 0), all zero, in memory of `class` with `modes`, at /// `placement` in the address space: a heap's own buffer when `of_heap` (`heap.rs`). Its /// length is the caller's to check. pub(super) fn zeroed_buffer( &self, call: &'static str, length: u64, modes: Modes, class: MemoryClass, of_heap: bool, placement: impl Into, ) -> Result { let of = match of_heap { true => NewBufferOf::Heap, false => NewBufferOf::Runtime(FreshPages::WherePaid), }; self.zeroed_buffer_of(call, length, (modes, class), of, (placement.into(), None)) } /// [`zeroed_buffer`](Device::zeroed_buffer) for `of`, its byte `aligned` (where given) on a /// multiple of 256 bytes of its memory ([`Device::placed_new_buffer`]). fn zeroed_buffer_of( &self, call: &'static str, length: u64, (modes, class): (Modes, MemoryClass), of: NewBufferOf, placed: (Place, Option), ) -> Result { let (buffer, bytes) = self.placed_new_buffer(call, length, modes, class, of, placed)?; // Fresh pages read zero as mapped (`fresh_pages.rs`): nothing is written. if bytes == NewBytes::Zero { return Ok(buffer); } // Dropping `buffer` on failure releases it. buffer.clear_first()?; Ok(buffer) } /// A `Shared` buffer of `length` bytes (above half a pooled block, `FRESH_PAGES_PAST`), all /// zero, outside the Metal address space, in fresh pages wherever the device takes them, the /// cost of a held import to its submissions aside ([`FreshPages::Wherever`]): the in-place /// check's fresh-pages class (`in_place_check.rs`). Where the device takes no such pages, a /// buffer as ever, not in them (`Buffer::in_fresh_pages`). Refused as [`Device::new_buffer`] /// refuses its length. pub(super) fn fresh_pages_check_buffer(&self, length: u64) -> Result { const CALL: &str = "new_buffer"; let modes = Modes::of(ResourceOptions::shared())?; let class = buffer_class(CALL, modes)?; if length == 0 || length > self.properties().max_buffer_length { return Err(nil(CALL, Problem::BufferLength { length })); } let (buffer, bytes) = self.placed_new_buffer( CALL, length, modes, class, NewBufferOf::Runtime(FreshPages::Wherever), (AddressPlacement::Outside.into(), None), )?; if bytes == NewBytes::AsPlaced { buffer.clear_first()?; } Ok(buffer) } /// A `Shared` buffer of `length` bytes, all zero, outside the Metal address space, in a /// block of the runtime's pooled memory that holds `holds`, whatever kind of block the /// device's own buffers take: `Holds::Buffers` for the in-place check's class of plain /// pooled memory (`in_place_check.rs`, `PagesClass::Pooled`), whose image names no handle /// type, and `Holds::FdBuffers` for its class of the blocks allocated exportable /// (`PagesClass::FdBlocks`), whose image names their handle type (`memory.rs`'s "Buffers in /// exportable blocks"). Refused as [`Device::new_buffer`] refuses its length. pub(super) fn pooled_check_buffer(&self, length: u64, holds: Holds) -> Result { const CALL: &str = "new_buffer"; let modes = Modes::of(ResourceOptions::shared())?; let class = buffer_class(CALL, modes)?; if length == 0 || length > self.properties().max_buffer_length { return Err(nil(CALL, Problem::BufferLength { length })); } let placed = (AddressPlacement::Outside.into(), None); self.zeroed_buffer_of( CALL, length, (modes, class), NewBufferOf::Check(holds), placed, ) } /// A `Private` buffer of `length` bytes that the runtime makes for its own use and whose /// bytes hold no value before the GPU writes them: made without a submission, so that one of /// the runtime's sections, a host step's replay of an emulated mesh draw among them, makes /// it with the exit guard's entry points alone (`exit_guard`). Refused as /// [`Device::new_buffer`] refuses its length. pub(super) fn scratch_buffer(&self, length: u64) -> Result { self.unzeroed_buffer(length, HazardTrackingMode::Untracked) } /// [`scratch_buffer`](Device::scratch_buffer) of hazard tracking `tracking`: the tracker /// orders its uses as any buffer's of that mode. pub(super) fn unzeroed_buffer( &self, length: u64, tracking: HazardTrackingMode, ) -> Result { let options = ResourceOptions::new(StorageMode::Private, CpuCacheMode::DefaultCache, tracking); Ok(self.unzeroed_buffer_with(length, options)?.0) } /// [`unzeroed_buffer`](Device::unzeroed_buffer) with `options`: a buffer of `length` bytes /// that the runtime makes for its own use, whose bytes hold no value before its owner writes /// them, in memory `options` asks for, and what its bytes hold as it is made. /// /// The upload arena's chunks are such a buffer (`upload.rs`): nothing reads a byte of a chunk /// outside a region it handed out, and it sets every byte of a region that the region's data /// does not cover to zero as it hands it out, so what a chunk would pay a creation-time clear /// for is paid by the region, for the region's bytes alone. A chunk made in fresh pages reads /// zero unwritten ([`NewBytes::Zero`], `fresh_pages.rs`), so a region of one writes nothing /// past its data: that is what the second half of the answer is for. pub(super) fn unzeroed_buffer_with( &self, length: u64, options: ResourceOptions, ) -> Result<(Buffer, NewBytes), Error> { const CALL: &str = "new_buffer"; let modes = Modes::of(options)?; let class = buffer_class(CALL, modes)?; if length == 0 || length > self.properties().max_buffer_length { return Err(nil(CALL, Problem::BufferLength { length })); } self.placed_new_buffer( CALL, length, modes, class, NewBufferOf::Runtime(FreshPages::WherePaid), (AddressPlacement::Outside.into(), None), ) } /// [`zeroed_buffer`](Device::zeroed_buffer)'s buffer before its bytes are set to zero, and /// what they hold: its memory's bytes as placed, or zero where it lies in fresh pages it /// imported (`fresh_pages.rs`), which `of` says where it takes. A buffer of the runtime's own /// made where fresh pages are paid for is a parked one of the same making where the recycler /// holds one, and is noted as one it may park as it goes (`recycle.rs`); one made wherever the /// device takes them is neither: it is the in-place check's, whose import is held only for its /// round. /// /// Where `aligned` names a byte of it (`BufferDescriptor::aligned_byte`) off a multiple of /// [`LINEAR_IMAGE_ALIGNMENT`], its `VkBuffer` is bound where its placement starts, a multiple /// of that alignment, and its bytes start that byte's shortfall from the next multiple into /// both, so that the byte lies on that multiple: the buffer takes that many more bytes, is /// never parked nor taken from the parked, and lies in no fresh pages. fn placed_new_buffer( &self, call: &'static str, length: u64, modes: Modes, class: MemoryClass, of: NewBufferOf, (placement, aligned): (Place, Option), ) -> Result<(Buffer, NewBytes), Error> { let (of_heap, fresh) = match of { NewBufferOf::Heap => (true, FreshPages::WherePaid), NewBufferOf::Runtime(fresh) => (false, fresh), NewBufferOf::Unobserved | NewBufferOf::Check(_) => (false, FreshPages::WherePaid), }; let plain = matches!(of, NewBufferOf::Check(_)); if self.is_lost() { return Err(self.lost_refusal()); } let shared = self.shared(); let raw_device = shared.vk(); // The bytes before the buffer's own in its `VkBuffer` and placement. let lead = aligned.map_or(0, |byte| { (LINEAR_IMAGE_ALIGNMENT - byte % LINEAR_IMAGE_ALIGNMENT) % LINEAR_IMAGE_ALIGNMENT }); // Padded to 16 bytes, so a device fill clears every byte too. let size = length .checked_add(lead) .and_then(|size| size.checked_next_multiple_of(16)) .ok_or_else(|| nil(call, Problem::BufferLength { length }))?; // A heap is never `Managed` (`heap.rs`). let mirror = if class == MemoryClass::Managed && !self.properties().has_unified_memory { Some(HostCopy::Own(Arc::new(self.mirror(size)?))) } else { None }; let class = match mirror { Some(_) => MemoryClass::Private, None => class, }; // The kind of block it lies in: one of the runtime's own lies where the device's own // buffers do, whose blocks may be exportable as an opaque file descriptor once the // device's check of them passed, so that its `VkBuffer` names that handle type there // (`VUID-vkBindBufferMemory-memory-02726`; `memory.rs`'s `Holds::FdBuffers`); a // host-visible one in a block of pages the runtime mapped and imported, where the device // takes such blocks for its class, its check found a held import costs its submissions // nothing, and its check of fresh pages passed what a texture over such a buffer takes // that it takes over a plain block's (`in_place.rs`'s `blocks_take`), so that its // `VkBuffer` names host allocations (`VUID-vkBindBufferMemory-memory-02985`; // `memory.rs`'s `Holds::PageBuffers`); one whose // maker declares its padding unobserved lies in a plain block. let paged = matches!(of, NewBufferOf::Runtime(_)) && { let takes = lock(&shared.memory).page_buffers(class, self.fresh_pages_pay_now()); takes && self.page_blocks_taken() }; let holds = match of { NewBufferOf::Runtime(_) if paged => Holds::PageBuffers, NewBufferOf::Runtime(_) => { let exportable = lock(&shared.memory).fd_buffer_types.is_ok(); let checked = exportable && self.fd_blocks_checked(); lock(&shared.memory).own_buffers(checked) } NewBufferOf::Heap | NewBufferOf::Unobserved => Holds::Buffers, NewBufferOf::Check(holds) => holds, }; let handle = match holds { Holds::FdBuffers => Some(FD_BLOCKS_HANDLE), Holds::PageBuffers => Some(HOST_PAGES_HANDLE), _ => None, }; let mut external = vk::ExternalMemoryBufferCreateInfo::default().handle_types(handle.unwrap_or_default()); // Its device address is its block's (`place_buffer_with`). let mut info = shared.sharing().buffer( vk::BufferCreateInfo::default() .size(size) .usage(usage(false)), ); if handle.is_some() { info = info.push_next(&mut external); } // A heap's own buffer lies where its textures can too, and is never parked. A long // host-visible one of the runtime's own lies in fresh pages where the device takes them // and its check found a held import adds nothing to its submissions (`fresh_pages.rs`). // The in-place check's buffer of pooled memory lies in neither. let wants_fresh = !of_heap && !plain && lead == 0 && fresh_pages::takes_fresh_pages(size, class) && (shared.host_import.as_ref()).is_ok_and(|importer| importer.pointers().is_some()) && (fresh == FreshPages::Wherever || self.fresh_pages_pay_now()); let making = (!of_heap && !plain && lead == 0 && fresh == FreshPages::WherePaid).then_some( BufferMaking { size, class, fresh_pages: wants_fresh, holds, }, ); let mut taken = making.and_then(|making| self.recycled_buffer(&making)); let fresh = match (&taken, wants_fresh) { (None, true) => self.fresh_page_buffer(size, class)?, _ => None, }; // Where the device took no fresh pages, a parked buffer of its own memory, made so as the // buffer is made below; and for one that would lie in a block allocated exportable, a // parked one of a plain block, which any buffer may lie in (the device's buffers lie in // plain blocks until its check answered: `in_place.rs`'s `blocks_take`). Never the // other way: a buffer that declares its padding unobserved lies in a plain block. if let (None, None, Some(making)) = (&taken, &fresh, making) { let own = BufferMaking { fresh_pages: false, ..making }; let plain = BufferMaking { holds: Holds::Buffers, ..own }; let asked = [ wants_fresh.then_some(own), (holds == Holds::FdBuffers).then_some(plain), ]; taken = (asked.into_iter().flatten()).find_map(|making| self.recycled_buffer(&making)); } let bytes = match fresh { Some(_) => NewBytes::Zero, None => NewBytes::AsPlaced, }; // Its range of the address space is a new one, as a new buffer's; the buffer and its // memory go again where none is left. let place_address = |raw, memory: Placement| { let address = self.address_space_for(placement).place(placement, length); match address { Ok(address) => Ok((raw, (memory, address))), Err(error) => { lock(&shared.recycled_buffers).forget(raw); recycle::destroy(raw_device, &mut lock(&shared.memory), [(raw, memory)]); Err(error) } } }; let made = match (taken, fresh) { (Some((raw, memory)), _) => place_address(raw, memory), (None, Some((raw, memory))) => { if let Some(making) = making { lock(&shared.recycled_buffers).made(raw, making); } place_address(raw, memory) } (None, None) => (|| { // 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); let placed = if of_heap { self.place_heap_buffer(raw, length, class, placement) } else { self.place_buffer_in(raw, length, (class, holds), placement) }; match placed { Ok(placed) => { // Not in fresh pages, whatever was asked: the device took none. if let Some(making) = making { let making = BufferMaking { fresh_pages: false, ..making }; lock(&shared.recycled_buffers).made(raw, making); } Ok((raw, placed)) } Err(error) => { // SAFETY: the buffer is unused. unsafe { release::object(raw_device, raw) }; Err(error) } } })(), }; // On failure the host copy, unused, goes with `mirror` (`Mirror`'s drop). let (raw, (placement, (address, reserved))) = made?; let buffer = self.buffer_of(BufferParts { raw, memory: placement, offset: lead, base: lead, length, reach: length, modes, address, reserved, owner: Owner::Runtime, release: None, of_heap, drops_writes: false, mirror, #[cfg(unix)] again: None, naming: Naming::New, }); Ok((buffer, bytes)) } /// A parked buffer of `making` (`recycle.rs`), now live, where the recycler holds one. fn recycled_buffer(&self, making: &BufferMaking) -> Option<(vk::Buffer, Placement)> { let shared = self.shared(); let (taken, gone) = lock(&shared.recycled_buffers).take(making, Instant::now()); self.let_go_parked_buffers(gone); if taken.is_some() { shared.counts.churn.taken(Recycled::Buffer); } taken } /// Destroy the parked buffers the recycler let go of, `gone`, and free their memory. fn let_go_parked_buffers(&self, gone: recycle::Gone) { if gone.is_empty() { return; } let shared = self.shared(); shared.counts.churn.evicted(Recycled::Buffer, gone.len()); recycle::destroy(shared.vk(), &mut lock(&shared.memory), gone); } /// The device copy of a two-copy buffer (`managed_copy.rs`): a `VkBuffer` of `size` bytes /// bound at the start of device-local memory of the runtime's own, in a plain block, its /// device address its block's (`place_buffer_with`). Refused where no device-local memory has /// room: an allocation refused, or one that overflowed into system memory /// (`memory.rs`'s `overflow_candidates`), which goes again. pub(super) fn managed_device_copy(&self, size: u64) -> Result<(vk::Buffer, Placement), Error> { let shared = self.shared(); let raw_device = shared.vk(); 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 = placed(unsafe { raw_device.get_buffer_memory_requirements(raw) }); let placement = crate::memory::allocate_addressed_in( &shared.memory, raw_device, &requirements, (MemoryClass::Private, Holds::Buffers), &shared.counts, ) .and_then(|placement| match placement.overflowed() { true => { lock(&shared.memory).free(raw_device, &placement); Err(Error::OutOfMemory(crate::error::MemoryKind::Device)) } false => Ok(placement), }); let bound = placement.and_then(|placement| { // SAFETY: the placement meets the buffer's requirements and is not bound elsewhere. match unsafe { crate::creation::bind_buffer(raw_device, raw, placement.memory, placement.offset) } { Ok(()) => Ok(placement), Err(error) => { lock(&shared.memory).free(raw_device, &placement); Err(vulkan(error)) } } }); match bound { Ok(placement) => Ok((raw, placement)), Err(error) => { // SAFETY: the buffer is unused. unsafe { release::object(raw_device, raw) }; Err(error) } } } /// A `Managed` buffer's host copy of `size` bytes (its padded length) on a device without /// unified memory ([`Mirror`]): copied to and from only. fn mirror(&self, size: u64) -> Result { let shared = self.shared(); let raw_device = shared.vk(); let info = shared.sharing().buffer( vk::BufferCreateInfo::default() .size(size) .usage(vk::BufferUsageFlags::TRANSFER_SRC | vk::BufferUsageFlags::TRANSFER_DST), ); // SAFETY: the device is live and `info` valid. let raw = unsafe { crate::creation::buffer(raw_device, &info) }.map_err(vulkan)?; // SAFETY: `raw` is a live buffer of this device. let requirements = unsafe { raw_device.get_buffer_memory_requirements(raw) }; let allocated = crate::memory::allocate( &shared.memory, raw_device, &requirements, MemoryClass::Managed, ); let placed = allocated.and_then(|placement| { // SAFETY: the placement meets the buffer's requirements and is not bound elsewhere. match unsafe { crate::creation::bind_buffer(raw_device, raw, placement.memory, placement.offset) } { Ok(()) => Ok(placement), Err(error) => { lock(&shared.memory).free(raw_device, &placement); Err(vulkan(error)) } } }); match placed { Ok(placement) if placement.mapped.is_some() => Ok(Mirror { raw, placement, device: self.clone(), }), Ok(placement) => { // SAFETY: the buffer is unused. unsafe { release::object(raw_device, raw) }; lock(&shared.memory).free(raw_device, &placement); Err(internal("a managed buffer's host copy is not mapped")) } Err(error) => { // SAFETY: the buffer is unused. unsafe { release::object(raw_device, raw) }; Err(error) } } } /// A buffer of preprocess memory for executions of generated commands /// (`generated_execute.rs`), as `vkGetGeneratedCommandsMemoryRequirementsEXT` states it in /// `required` (above 0 bytes): `VK_BUFFER_USAGE_2_PREPROCESS_BUFFER_BIT_EXT` and device-address /// usage (`maintenance5`'s usage flags, which the device enabled with /// `VK_EXT_device_generated_commands`), in device-local memory of a type and at an alignment /// that meet both the buffer's requirements and `required`. Its contents are the driver's. pub(super) fn preprocess_buffer( &self, required: vk::MemoryRequirements, ) -> Result { if self.is_lost() { return Err(self.lost_refusal()); } let modes = Modes::of(ResourceOptions::private())?; let shared = self.shared(); let raw_device = shared.vk(); let mut usage = vk::BufferUsageFlags2CreateInfoKHR::default() .usage(PREPROCESS_BUFFER | vk::BufferUsageFlags2KHR::SHADER_DEVICE_ADDRESS); let info = shared.sharing().buffer( vk::BufferCreateInfo::default() .size(required.size) .push_next(&mut usage), ); // SAFETY: the device is live and `info` and its chain valid. let raw = unsafe { crate::creation::buffer(raw_device, &info) }.map_err(vulkan)?; shared .counts .buffer_made(vk::BufferUsageFlags::SHADER_DEVICE_ADDRESS); // SAFETY: `raw` is a live buffer of this device. let own = unsafe { raw_device.get_buffer_memory_requirements(raw) }; let requirements = vk::MemoryRequirements { size: own.size, alignment: own.alignment.max(required.alignment), memory_type_bits: own.memory_type_bits & required.memory_type_bits, }; // Its own address: a preprocess address is one of a buffer of preprocess usage. let made = self.place_buffer_with( raw, requirements, required.size, (MemoryClass::Private, Holds::Buffers), AddressPlacement::Outside.into(), false, ); let (placement, (address, reserved)) = match made { Ok(made) => made, Err(error) => { // SAFETY: the buffer is unused. unsafe { release::object(raw_device, raw) }; return Err(error); } }; Ok(self.buffer_of(BufferParts { raw, memory: placement, offset: 0, base: 0, length: required.size, reach: required.size, modes, address, reserved, owner: Owner::Runtime, release: None, of_heap: false, drops_writes: false, mirror: None, #[cfg(unix)] again: None, naming: Naming::New, })) } /// The buffer of `parts`. Dropping the result releases every part. pub(super) fn buffer_of(&self, parts: BufferParts) -> Buffer { let BufferParts { raw, memory, offset, base, length, reach, modes, address, reserved, owner, release, of_heap, drops_writes, mirror, #[cfg(unix)] again, naming, } = parts; let pages = self.pages_of(raw, memory, offset, base, reach); 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 => { // Kept imported where nothing imports it again: a heap's, an import of dma-bufs // whose descriptors did not fit (counted as such), or one by pointer. let kept = match (of_heap, pages.memory.placement.over_dma_buf()) { (true, _) => Some(KeptBecause::Heap), (false, true) => None, (false, false) => Some(KeptBecause::Pointer), }; #[cfg(unix)] let import = self.host_import(pages, again, kept); #[cfg(not(unix))] let import = Arc::new(HostImport::new(self, pages, kept)); self.host_lie( identity.key, (import, Joining::First), release, drops_writes, ) } Owner::Runtime | Owner::Vulkan => Lie::Fixed(Arc::new(FixedPages { device: MadeOn::new(self.clone()), pages, owned: matches!(owner, Owner::Runtime), released: AtomicBool::new(false), freed: AtomicBool::new(false), })), }; let own = OwnBytes { lie, reserved, identity, owner, mirror, range_token: KeptToken::default(), }; self.buffer_lying(own, length, modes, address, naming) } /// The import of a no-copy buffer's `pages`: one the device releases while idle where /// `again` imports them again and the device keeps a stand-in for it and a thread to release /// it (`host_residency.rs`), else one it keeps, for `kept` where nothing imports it again. #[cfg(unix)] fn host_import( &self, pages: Pages, again: Option, kept: Option, ) -> Arc { let Some(again) = again else { return Arc::new(HostImport::new(self, pages, kept)); }; let stand_in = self.detach_stand_in().ok(); let Some(stand_in) = stand_in.as_ref().and_then(Buffer::fixed_pages) else { let kept = Some(KeptBecause::NoStandIn); return Arc::new(HostImport::new(self, pages, kept)); }; let import = Arc::new(HostImport::releasable(self, pages, again, stand_in)); if !self.shared().residency.note(&import) { // No thread releases it: kept imported. import.expose(ReadApart::Unreleased); } import } /// A no-copy buffer of `length` bytes lying in `import`, the import of the same bytes a live /// no-copy buffer or heap lies in (`host_aliases.rs`), at `address`, released to `release` /// once nothing holds it: a heap's own buffer where `of_heap`, of a heap's identity. Dropping /// the result releases every part but the import, which the last buffer over it releases. pub(super) fn buffer_in_import( &self, import: Arc, (length, modes, of_heap): (u64, Modes, bool), (address, reserved): (GpuAddress, Held), release: Option, naming: Naming, ) -> Buffer { let identity = naming.identity(modes.hazard, of_heap); let joining = match of_heap { true => Joining::Heap, false => Joining::Buffer, }; let own = OwnBytes { lie: self.host_lie(identity.key, (import, joining), release, false), reserved, identity, owner: Owner::Caller, mirror: None, range_token: KeptToken::default(), }; 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` /// once nothing holds them, which a rebind replaces (`rebind.rs`); the GPU's writes to it /// dropped where `drops_writes`, or where `import` is of a read-only view of the pages. fn host_lie( &self, key: ResourceKey, (import, joining): (Arc, Joining), release: Option, drops_writes: bool, ) -> Lie { let drops_writes = drops_writes || import.drops_writes(); let host = HostPages::new(import, joining); if let Some(release) = release { host.release_to(release); } let cell = Arc::new(HostCell { pages: Mutex::new(Lying::In(Arc::new(host))), texels: Mutex::new(Vec::new()), textures: Mutex::new(TexturesOver::default()), in_place: Mutex::new(Vec::new()), exposed: AtomicU16::new(0), device: MadeOn::new(self.clone()), released: AtomicBool::new(false), freed: AtomicBool::new(false), drops_writes, held_back: Mutex::new(None), }); self.shared().rebinds.register(key, &cell); Lie::Host(cell) } /// 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 | Naming::HostCopy => (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, length, options, address, attributes, bytes: Bytes::Own(own), held_by: HeldBy::default(), handed_out: Arc::default(), padding_unobserved: AtomicBool::new(false), staged: AtomicBool::new(false), next: OnceLock::new(), carried: AtomicBool::new(false), calls: PartsCalls::default(), })) } /// The pages of a buffer `raw` in `memory`, its bytes `offset` bytes into its placement and /// `base` bytes into `raw`, `reach` bytes from byte 0 copied out. pub(super) fn pages_of( &self, raw: vk::Buffer, placement: Placement, offset: u64, base: u64, reach: u64, ) -> Pages { let memory = Bound { // A placed buffer's address is its block's (`place_buffer_with`); any other's its own. device_address: match placement.address { Some(address) => Some(address), // SAFETY: the buffer is bound to the placement, and was made with `usage` // (`device_address_of`). None => unsafe { self.device_address_of(raw) }, }, placement, }; Pages { raw, memory, offset, base, reach, } } /// Host pages a rebind gives a no-copy buffer (`rebind.rs`): `raw` in `memory`, as /// [`Device::pages_of`] says, without their release, which the rebind sets once they are /// the buffer's. pub(super) fn host_pages( &self, raw: vk::Buffer, memory: Placement, offset: u64, base: u64, reach: u64, ) -> Arc { let pages = self.pages_of(raw, memory, offset, base, reach); let import = HostImport::new(self, pages, Some(KeptBecause::Rebind)); Arc::new(HostPages::new(Arc::new(import), Joining::First)) } /// Host pages a rebind gives a no-copy buffer lying in `import`, the import of the same bytes /// a live no-copy buffer was made over (`rebind.rs`, `host_aliases.rs`), without their /// release, as [`Device::host_pages`] gives them. pub(super) fn pages_in_import(&self, import: Arc) -> Arc { Arc::new(HostPages::new(import, Joining::Rebound)) } /// The Vulkan device address of `raw`, where the device enables `bufferDeviceAddress`. /// /// # Safety /// /// `raw` is a buffer of this device made with [`usage`], bound to memory. pub(super) unsafe fn device_address_of(&self, raw: vk::Buffer) -> Option { let shared = self.shared(); shared.device_address.then(|| { let info = vk::BufferDeviceAddressInfo::default().buffer(raw); // SAFETY: the buffer was made with `SHADER_DEVICE_ADDRESS` usage (the caller's // contract) and is bound to memory allocated with the device-address flag. unsafe { shared.vk().get_buffer_device_address(&info) } }) } /// Place `raw` (for a buffer of `length` bytes) in memory of `class` and at `at` in the /// address space; released again when either fails. pub(super) fn place_buffer( &self, raw: vk::Buffer, length: u64, class: MemoryClass, at: Place, ) -> Result<(Placement, (GpuAddress, Held)), Error> { self.place_buffer_in(raw, length, (class, Holds::Buffers), at) } /// [`place_buffer`](Device::place_buffer) in a block that holds `holds`: `Holds::Buffers`, or /// `Holds::FdBuffers` for a buffer made for `FD_BLOCKS_HANDLE` (`memory.rs`). fn place_buffer_in( &self, raw: vk::Buffer, length: u64, (class, holds): (MemoryClass, Holds), at: Place, ) -> Result<(Placement, (GpuAddress, Held)), Error> { // SAFETY: `raw` is a live buffer of this device. let requirements = unsafe { self.shared().vk().get_buffer_memory_requirements(raw) }; self.place_buffer_with(raw, requirements, length, (class, holds), at, true) } /// [`place_buffer`](Device::place_buffer) for a heap's own buffer: where the heap's textures /// can lie too (`Device::heap_requirements`). pub(super) fn place_heap_buffer( &self, raw: vk::Buffer, length: u64, class: MemoryClass, at: Place, ) -> Result<(Placement, (GpuAddress, Held)), Error> { // SAFETY: `raw` is a live buffer of this device. let own = unsafe { self.shared().vk().get_buffer_memory_requirements(raw) }; let requirements = self.heap_requirements(own, class)?; self.place_buffer_with(raw, requirements, length, (class, Holds::Buffers), at, true) } /// [`place_buffer`](Device::place_buffer) in memory that meets `requirements`, which hold /// the buffer's own, in a block that holds `holds` ([`Device::place_buffer_in`]). Where /// `block_address`, `raw` was made without the device-address usage and its device address /// is its block's (`memory::allocate_addressed`, the placement's `address`); else its own, /// where it has the usage. fn place_buffer_with( &self, raw: vk::Buffer, requirements: vk::MemoryRequirements, length: u64, (class, holds): (MemoryClass, Holds), at: Place, block_address: bool, ) -> Result<(Placement, (GpuAddress, Held)), Error> { let shared = self.shared(); let raw_device = shared.vk(); let requirements = placed(requirements); let placement = if block_address { crate::memory::allocate_addressed_in( &shared.memory, raw_device, &requirements, (class, holds), &shared.counts, )? } else { crate::memory::allocate_in(&shared.memory, raw_device, &requirements, class, holds)? }; // SAFETY: the placement meets the buffer's requirements and is not bound elsewhere. let bound = unsafe { crate::creation::bind_buffer(raw_device, raw, placement.memory, placement.offset) }; let address = match bound { Ok(()) => self.address_space_for(at).place(at, length), Err(error) => { lock(&shared.memory).free(raw_device, &placement); return Err(vulkan(error)); } }; match address { Ok(address) => Ok((placement, address)), Err(error) => { lock(&shared.memory).free(raw_device, &placement); Err(error) } } } } /// Whose a buffer [`Device::placed_new_buffer`] makes is: a heap's own buffer, one of the /// runtime's own, with where it lies in fresh pages, one whose maker declares its padding /// unobserved, or the in-place check's of pooled memory. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum NewBufferOf { /// A heap's own buffer (`heap.rs`), never in fresh pages, in a block of `Holds::Buffers`. Heap, /// A buffer of the runtime's own, in fresh pages where it says, else in a block of the kind /// the device's own buffers take (`memory.rs`'s `Memory::own_buffers`). Runtime(FreshPages), /// A buffer of the runtime's own whose maker declares the bytes between a texture's rows and /// slices unobserved (`BufferDescriptor::padding_unobserved`): as /// `Runtime(FreshPages::WherePaid)`, but in a plain block (`Holds::Buffers`) wherever the /// device's own buffers lie, as a texture over such a buffer whose rows lie apart may take a /// `DRM_FORMAT_MOD_LINEAR` image at Metal's pitch there, which a block allocated exportable /// takes none of (`memory.rs`'s "Buffers in exportable blocks"). Unobserved, /// The in-place check's buffer of a class of the runtime's pooled memory /// (`in_place_check.rs`): in a block that holds this, `Holds::Buffers` for /// `PagesClass::Pooled` (exported as no handle type) and `Holds::FdBuffers` for /// `PagesClass::FdBlocks` (allocated exportable, never exported) whatever the class's /// verdicts, never in fresh pages and never parked. Check(Holds), } /// Where [`Device::placed_new_buffer`] lays a long host-visible buffer of the runtime's own in /// fresh pages (`fresh_pages.rs`). #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum FreshPages { /// Where the device takes them and its submission checks found that a held import adds /// nothing to its submissions: the product's buffers. WherePaid, /// Wherever the device takes them: the in-place check's buffer of its fresh-pages class, /// which lies where a rebind's copy under an image in place lies whatever that cost /// (`buffer_descriptor.rs`'s `copied_pages`), and whose import lives only for its round. Wherever, } /// What a new buffer's bytes hold as [`Device::placed_new_buffer`] makes it. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum NewBytes { /// Its memory's bytes as placed: undefined, or a parked buffer's last owner's. AsPlaced, /// Zero: fresh pages it imported (`fresh_pages.rs`). Zero, } /// The memory class of a buffer of `modes`' storage and CPU cache modes, for `call`: refused for /// `Memoryless`, which is no buffer's. `Shared` storage is `MemoryClass::WriteCombined` in the /// write-combined CPU cache mode, which the host does not read. pub(super) fn buffer_class(call: &'static str, modes: Modes) -> Result { match modes.storage { StorageMode::Shared => Ok(match modes.cache { CpuCacheMode::DefaultCache => MemoryClass::Shared, CpuCacheMode::WriteCombined => MemoryClass::WriteCombined, }), StorageMode::Private => Ok(MemoryClass::Private), StorageMode::Managed => Ok(MemoryClass::Managed), StorageMode::Memoryless => Err(invalid(call, Problem::StorageMode)), } } impl Heap { /// A buffer of `length` bytes with `options` (checked against the heap's), placed `offset` /// bytes into the heap: its bytes are the heap's from there, as they are. pub(super) fn placed_buffer( &self, heap_bytes: &Buffer, offset: u64, length: u64, options: ResourceOptions, ) -> Buffer { Buffer(Arc::new(BufferShared { device: MadeOn::new(heap_bytes.generation().clone()), generation: std::ptr::from_ref(heap_bytes.generation().shared()).addr(), object_id: ObjectId::new(), length, options, address: GpuAddress(heap_bytes.gpu_address().0 + offset), attributes: ResourceAttributes::new(), bytes: Bytes::Heap(HeapBytes { heap: self.clone(), bytes: heap_bytes.clone(), offset, // A placement heap's buffer answers aliasable from the start, as Metal's does. aliasable: Arc::new(AtomicBool::new(self.heap_type() == HeapType::Placement)), }), held_by: HeldBy::default(), handed_out: Arc::default(), padding_unobserved: AtomicBool::new(false), staged: AtomicBool::new(false), next: OnceLock::new(), carried: AtomicBool::new(false), calls: PartsCalls::default(), })) } } impl Buffer { /// The buffer's parts as the work at hand reaches them: its own, where its device's recovery /// never carried it, at one load (`device/carry.rs`). Where it did, inside a command buffer's /// work (`NoticesFor::generation`) those of that command buffer's generation where the /// buffer has some, so the lost generation's command buffers record its own handles alone; /// else those of the generation it was carried to last. #[inline] fn s(&self) -> &Arc { match self.0.carried.load(Ordering::Relaxed) { false => &self.0, true => self.carried(), } } /// [`s`](Self::s) of a buffer its device's recovery carried. #[cold] fn carried(&self) -> &Arc { let records = crate::degradation::NoticesFor::generation(); let mut shared = &self.0; loop { // Not its parts on a lost generation that went: a call under way that holds them // keeps them until it ends (`Buffer::held_parts`), and no command buffer is made there // after its rest (`Carry::refuses`). if records == Some(shared.generation) && !shared.freed() { return shared; } match shared.next.get() { Some(next) => shared = &next.0, None => return shared, } } } /// The buffer's parts for a call outside a command buffer's work that reaches their Vulkan /// objects (a texture over its bytes, an export of its memory, an upload, a handle handed /// out), held until the result goes: those [`s`](Self::s) answers, on the generation that /// serves where the buffer was carried there, and every read of its parts on this thread /// meanwhile answers them (`NoticesFor::of_generation`). Where its device's recovery carried /// it from their generation since, and that generation came to rest, their release waits /// for the call to end ([`LostBuffer`]); parts let go of already are never held, the call /// taking those of the generation the buffer was carried to. A call begun on parts of a lost /// generation completes there: what it makes is that generation's, refused where it meets /// the next (`RuntimeGap::MadeBeforeRecovery`), as a call that took its arguments before /// the loss (`Device::at_serving_taking`). Not for command buffers' work, whose queue slot /// holds the generation (`device/carry.rs`). pub(super) fn held_parts(&self) -> HeldParts<'_> { let mut link = self.s(); loop { // Parts not marked let go of yet, or whose release a call under way holds back, go // only once this call ends. if let Some(call) = link.calls.hold_unless(|| link.released()) { #[cfg(test)] held_hook(); return HeldParts { _call: call, _scope: NoticesFor::of_generation(link.generation), }; } // Let go of on their lost generation since this thread read them: the generation // the buffer was carried to serves its calls. Parts marked were carried. link = &link .next .get() .expect("a buffer's parts marked let go of were carried") .0; } } /// Whether the buffer lies in fresh pages it imported (`fresh_pages.rs`), to which no image /// is bound: false for a no-copy buffer, a heap's and one over the caller's `VkBuffer`. pub(super) fn in_fresh_pages(&self) -> bool { match &self.s().bytes { Bytes::Own(OwnBytes { lie: Lie::Fixed(fixed), .. }) => fixed.pages.memory.placement.over_own_pages(), Bytes::Own(_) | Bytes::Heap(_) => false, } } /// Whether the buffer lies in a block of pages the runtime mapped and imported, among other /// buffers (`memory.rs`'s `Holds::PageBuffers`): an image over its bytes is made for host /// allocations, as over fresh pages, under their class's verdicts (`texture/route.rs`). pub(super) fn in_page_block(&self) -> bool { match &self.s().bytes { Bytes::Own(OwnBytes { lie: Lie::Fixed(fixed), .. }) => fixed.pages.memory.placement.in_page_block(), Bytes::Own(_) | Bytes::Heap(_) => false, } } /// Whether the buffer's own pages, of the runtime's memory, overflowed past device-local memory /// into system memory (`memory.rs`'s `overflow_candidates`): false for a buffer over host /// pages, which are imported, and for a heap's buffer, whose bytes are its heap's. pub(super) fn own_pages_overflowed(&self) -> bool { match &self.s().bytes { Bytes::Own(OwnBytes { lie: Lie::Fixed(fixed), .. }) => fixed.pages.memory.placement.overflowed(), Bytes::Own(_) | Bytes::Heap(_) => false, } } /// `f` of the placement the buffer's own pages lie in and of the buffer's first byte's offset /// in it (`exported_memory.rs`); `None` for a heap's buffer, whose bytes are its heap's. pub(super) fn own_placement(&self, f: impl FnOnce(&Placement, u64) -> R) -> Option { match &self.s().bytes { Bytes::Own(own) => Some(own.with(ReadApart::Binding, |pages| { f(&pages.memory.placement, pages.offset) })), Bytes::Heap(_) => None, } } /// Whether the buffer's own pages, of the runtime's memory, lie in device-local memory; `None` /// for a heap's buffer, whose bytes are its heap's. A buffer's pages are its for good. pub(super) fn own_pages_device_local(&self) -> Option { let s = self.s(); match &s.bytes { Bytes::Own(own) => own.with(ReadApart::Binding, |pages| { let memory = lock(&s.device.shared().memory); Some(memory.is_device_local(&pages.memory.placement)) }), Bytes::Heap(_) => None, } } /// The length padded to 16 bytes: the bytes the `VkBuffer` holds from [`Buffer::base`]. pub(super) fn padded_length(&self) -> u64 { self.s().length.next_multiple_of(16) } /// The bytes of the buffer's memory from its byte 0 ([`Buffer::memory`]'s offset) to the end /// of the memory's placement: an import's, for a buffer over host pages (its last page's bytes /// past the buffer's among them), or a heap's. pub(super) fn memory_room(&self) -> u64 { match &self.s().bytes { Bytes::Own(own) => own.with(ReadApart::Texture, |pages| { pages.memory.placement.size().saturating_sub(pages.offset) }), Bytes::Heap(bytes) => bytes.bytes.memory_room().saturating_sub(bytes.offset), } } /// Set the buffer's padded length of bytes to zero: through the mapping for `Shared` and /// `Managed` storage (host-coherent memory), else by a device fill the call waits for; both /// for a `Managed` buffer with a host copy ([`Mirror`]). Racing the GPU's use of the buffer /// is the caller's to avoid. pub(super) fn clear(&self) -> Result<(), Error> { let s = self.s(); let size = self.padded_length(); if let Some(contents) = self.mapped_contents() { // SAFETY: the buffer's bytes, its padded length from `contents`, are host-coherent // memory (`MemoryClass::Shared` and `Managed`, or imported host memory), so the // device sees the writes at the next submission. unsafe { std::ptr::write_bytes(contents.as_ptr(), 0, size as usize) }; if self.mirror().is_none() { return Ok(()); } } let (raw, start) = self.at(0); s.device.submit_internal(|device, command_buffer| { // SAFETY: the internal command buffer is recording; the buffer is live, and its // padded length (a multiple of 16) lies in the `VkBuffer` from `start`, a multiple // of 4: 0, or a heap buffer's offset in its heap's (a buffer without contents is // none over host memory). unsafe { crate::word_fill::record(&s.device, command_buffer, raw, start..start + size, 0); let barrier = vk::MemoryBarrier::default() .src_access_mask(vk::AccessFlags::TRANSFER_WRITE) .dst_access_mask(vk::AccessFlags::MEMORY_READ | vk::AccessFlags::MEMORY_WRITE); device.cmd_pipeline_barrier( command_buffer, vk::PipelineStageFlags::TRANSFER, vk::PipelineStageFlags::ALL_COMMANDS, vk::DependencyFlags::empty(), &[barrier], &[], &[], ); } }) } /// Note the acquire of the buffer's `VkBuffer`, whole, from `families`' source, a queue family /// reserved for external memory, for its target, for the device's next submission to record /// before any of its commands (`exported_memory.rs`, `Buffer::external_write_done`). pub(super) fn note_acquire(&self, families: (u32, u32)) { let s = self.s(); let (raw, _) = self.at(0); let weak: Weak = Arc::downgrade(s); let keeper: Weak = weak; let device = &s.device; (device.shared().textures.first_moves).register_acquire(keeper, raw, families); } /// Set a new buffer's padded length of bytes to zero as [`clear`](Self::clear) does, without /// waiting for the GPU: the host's bytes (`Shared` and `Managed` storage, a `Managed` /// buffer's host copy) at once, so `contents` reads zero before any submission, and bytes the /// host cannot write (`Private` storage, a `Managed` buffer's device copy) by the device's /// next submission, before any of its commands (`texture/first_move.rs`). pub(super) fn clear_first(&self) -> Result<(), Error> { let s = self.s(); let size = self.padded_length(); if let Some(contents) = self.mapped_contents() { // SAFETY: as in `clear`: the buffer's host-coherent bytes, which nothing else uses // yet. unsafe { std::ptr::write_bytes(contents.as_ptr(), 0, size as usize) }; s.device.shared().counts.new_buffer_cleared(size); if self.mirror().is_none() { return Ok(()); } } let (raw, start) = self.at(0); let device = &s.device; let weak: Weak = Arc::downgrade(s); let keeper: Weak = weak; (device.shared().textures.first_moves).register_fill( device, keeper, raw, start..start + size, ) } /// Give a new buffer whose bytes the host cannot write (`Private` storage) the first `length` /// bytes `staging` holds, without waiting for the GPU: copied by the device's next /// submission before any of its commands, after the fill with zeros it took as it was made /// (`texture/first_move.rs`); that submission holds `staging` until it completed. Past the /// bound of what is staged, a submission waited for makes it now. pub(super) fn fill_first_from(&self, staging: Buffer, length: u64) -> Result<(), Error> { let s = self.s(); let device = &s.device; s.staged.store(true, Ordering::Relaxed); let weak: Weak = Arc::downgrade(s); let keeper: Weak = weak; let source = staging.at(0); let past = (device.shared().textures.first_moves).register_bytes( keeper, self.at(0), source, length, Box::new(staging), ); match past { true => device.submit_internal(|_, _| {}), false => Ok(()), } } /// The bytes from byte 0 a copy out of the buffer reads: its length, but for a no-copy /// buffer the rest of the host pages its range touches, as far as its `VkBuffer` holds them /// (all of them where the device's buffer of them fits the pages, `host_memory.rs`). Plain /// Metal reads the caller's bytes there, current ones, from the pointer to its pages' end /// (an M4 under macOS 27.0.1). Past them, and past another buffer's length, its API validation /// stops the copy, and plain Metal reads zeros, bytes written past the length, or another /// resource's: refused (`Invalid`). pub(super) fn copy_reach(&self) -> u64 { let s = self.s(); match &s.bytes { Bytes::Own(own) => own.shape().reach, Bytes::Heap(_) => s.length, } } /// The `VkBuffer`, and where the buffer's byte `offset` lies in it. Every Vulkan use of a /// buffer takes its offsets from here, since a buffer's byte 0 may lie past the `VkBuffer`'s: /// a no-copy buffer's ([`Buffer::base`]), and a heap buffer's, which is its heap's. pub(super) fn at(&self, offset: u64) -> (vk::Buffer, u64) { self.at_for(offset, ReadApart::Binding) } /// Whether its `VkBuffer` was handed out, shared with what watches it /// (`shadow_standing::StandingAcross`). pub(super) fn handed_out(&self) -> Arc { Arc::clone(&self.s().handed_out) } /// Note that its `VkBuffer` was handed out (`Buffer::vk_buffer`). pub(super) fn hand_out(&self) { self.s().handed_out.store(true, Ordering::Release); } /// Make the first work still waiting on its `VkBuffer` `raw` now, by a submission waited for: /// a new buffer's zeros or staged bytes, or a `Managed` buffer's upload (`clear_first`, /// `fill_first_from`, `upload`), which the device's next submission would make before its /// commands (`texture/first_move.rs`), over what the caller's own work wrote through the /// handle meanwhile. Only the work whose destination is `raw`, in the order it was noted: on /// the staging queue where the device reserved one, else on its first `VkQueue`, and after no /// other queue's work (`Device::settle_mine`). Nothing is submitted where none waits: once any /// submission of the device's took it. `raw` is the caller's: a no-copy buffer's import counts /// each read of its `VkBuffer` apart for its reason (`HostImport::note_read_apart`), so this /// reads none. pub(super) fn settle_first_work(&self, raw: vk::Buffer) -> Result<(), Error> { let device = &self.s().device; match device.shared().textures.first_moves.fills_wait(raw) { true => device.settle_mine( Mine { buffer: Some(raw), image: None, }, false, ), false => Ok(()), } } /// Note, as it is made, that its maker declared the bytes between a texture's rows and slices /// over it unobserved (`BufferDescriptor::padding_unobserved`). pub(super) fn declare_padding_unobserved(&self) { self.s().padding_unobserved.store(true, Ordering::Release); } /// Whether its maker declared the bytes between a texture's rows and slices over it /// unobserved (`BufferDescriptor::padding_unobserved`). pub(super) fn padding_unobserved(&self) -> bool { self.s().padding_unobserved.load(Ordering::Acquire) } /// Whether only the device's commands, in the order the runtime records and submits them, /// write the bytes the GPU uses: a `Private` buffer's, which no CPU maps /// ([`Buffer::mapped_contents`]), and a `Managed` buffer's own on a device without unified /// memory ([`HostCopy`]), which the CPU's writes reach only through the copies the device's /// next submission makes before its commands (`managed.rs`, `managed_copy.rs`). Not one whose /// `VkBuffer` was handed out (`Buffer::vk_buffer`) or whose memory was made exportable /// (`exported_memory.rs`), which work of another API's may write. pub(super) fn gpu_bytes_ordered(&self) -> bool { let own = self.storage_mode() == StorageMode::Private || self.mirror().is_some(); own && !self.s().handed_out.load(Ordering::Acquire) && self.exported().is_none() } /// [`Buffer::at`] for `reason`, which a no-copy buffer's import counts its read apart for /// (`HostImport::note_read_apart`). pub(super) fn at_for(&self, offset: u64, reason: ReadApart) -> (vk::Buffer, u64) { match &self.s().bytes { Bytes::Own(own) => own.with(reason, |pages| (pages.raw, pages.base + offset)), Bytes::Heap(bytes) => bytes.bytes.at_for(bytes.offset + offset, reason), } } /// [`Buffer::at`] while the buffer's bytes lie in pages, read with them at once: `None` while /// they are detached (`detach.rs`), when its `VkBuffer` is the device's stand-in, which holds /// none of its bytes. pub(super) fn attached_at(&self, offset: u64) -> Option<(vk::Buffer, u64)> { match &self.s().bytes { Bytes::Own(own) => { own.with_attached(ReadApart::Binding, |pages| (pages.raw, pages.base + offset)) } Bytes::Heap(bytes) => bytes.bytes.attached_at(bytes.offset + offset), } } /// Where the buffer's byte 0 lies in its `VkBuffer` ([`Buffer::at`]'s offset of byte 0), read /// without the `VkBuffer`: a no-copy buffer's [`Buffer::base`], a heap buffer's offset in its /// heap's. pub(super) fn start(&self) -> u64 { match &self.s().bytes { Bytes::Own(own) => own.shape().base, Bytes::Heap(bytes) => bytes.bytes.start() + bytes.offset, } } /// The `VkBuffer`, and where the space the bind layer states the buffer in starts in it: /// 0 for a buffer of its own, a heap buffer's offset in its heap's. The bind layer's offsets /// (`ArgumentTable::stage_table`) count from there, [`Buffer::base`] bytes before byte 0. /// A multiple of 256 bytes, so every alignment Vulkan asks of an offset holds of it. pub(super) fn space(&self) -> (vk::Buffer, u64) { // `at(0)` less `base()`, from one look at where the buffer lies. let space = |pages: &Pages, base: u64| (pages.raw, pages.base - base); match &self.s().bytes { Bytes::Own(own) => match &own.lie { Lie::Fixed(fixed) => space(&fixed.pages, Shape::of(&fixed.pages).base), Lie::Host(cell) => match cell.lying() { Lying::In(pages) => space( &pages.import.pages(ReadApart::Binding), pages.import.shape.base, ), Lying::Detached(detached) => { space(&detached.pages, Shape::of(&detached.pages).base) } Lying::Gone(_) => read_gone(), }, }, Bytes::Heap(bytes) => bytes.bytes.at_for(bytes.offset, ReadApart::Binding), } } /// [`space`](Self::space), where the buffer lies over host pages (or is placed in a heap that /// does) read through `kept`, which keeps where such buffers lie ([`KeptSpaces`]): the same /// answer, with no lock taken and nothing written that other threads read, while no no-copy /// buffer moved since `kept` read it. pub(super) fn space_kept(&self, kept: &mut KeptSpaces) -> (vk::Buffer, u64) { match &self.s().bytes { Bytes::Own(own) => match &own.lie { Lie::Host(cell) => { let (raw, base, shape_base) = kept.of(cell); (raw, base - shape_base) } Lie::Fixed(_) => self.space(), }, Bytes::Heap(bytes) => bytes.bytes.at_kept(bytes.offset, kept), } } /// [`at_for`](Self::at_for) for a binding, read through `kept` as /// [`space_kept`](Self::space_kept) reads. fn at_kept(&self, offset: u64, kept: &mut KeptSpaces) -> (vk::Buffer, u64) { match &self.s().bytes { Bytes::Own(own) => match &own.lie { Lie::Host(cell) => { let (raw, base, _) = kept.of(cell); (raw, base + offset) } Lie::Fixed(_) => self.at_for(offset, ReadApart::Binding), }, Bytes::Heap(bytes) => bytes.bytes.at_kept(bytes.offset + offset, kept), } } /// Where the buffer's byte 0 lies in its bind layer space ([`Buffer::space`]): 0, but for a /// no-copy buffer whose pointer misses the buffer's memory alignment (bound that many bytes /// below it). An alignment Vulkan asks of an offset holds of `base` plus Metal's offset. pub(super) fn base(&self) -> u64 { match &self.s().bytes { Bytes::Own(own) => own.shape().base, Bytes::Heap(_) => 0, } } /// [`base`](Self::base) and [`device_address`](Self::device_address) together, from one look /// at where the buffer lies, a no-copy buffer's pages read for `reason` /// (`HostImport::note_read_apart`): what a binding of it reads (`argument_table::bound_buffer`), /// each as its own call reads it. pub(super) fn base_and_device_address(&self, reason: ReadApart) -> (u64, Option) { let address = |pages: &Pages| Some(pages.memory.device_address? + pages.base); match &self.s().bytes { Bytes::Own(own) => match &own.lie { Lie::Fixed(fixed) => (Shape::of(&fixed.pages).base, address(&fixed.pages)), Lie::Host(cell) => match cell.lying() { Lying::In(pages) => { let read = pages.import.pages(reason); (pages.import.shape.base, address(&read)) } Lying::Detached(detached) => { (Shape::of(&detached.pages).base, address(&detached.pages)) } Lying::Gone(_) => read_gone(), }, }, Bytes::Heap(bytes) => ( 0, (bytes.bytes.device_address()).map(|address| address + bytes.offset), ), } } /// The external memory the buffer's bytes lie in, from that memory's record, which an image /// bound there names (`Memory::bound_memory`): a heap's buffer's, its heap's. pub(super) fn bound_memory(&self) -> BoundMemory { let s = self.s(); match &s.bytes { Bytes::Own(own) => own.with(ReadApart::Texture, |pages| { lock(&s.device.shared().memory).bound_memory(&pages.memory.placement) }), Bytes::Heap(bytes) => bytes.bytes.bound_memory(), } } /// The memory the buffer's bytes lie in: the `VkDeviceMemory`, the offset of the buffer's /// first byte in it, and its memory type's index. A texture over the buffer aliases it there /// (`texture.rs`). pub(super) fn memory(&self) -> (vk::DeviceMemory, u64, u32) { match &self.s().bytes { Bytes::Own(own) => own.with(ReadApart::Texture, |pages| { let placement = &pages.memory.placement; ( placement.memory, placement.offset + pages.offset, placement.type_index(), ) }), Bytes::Heap(bytes) => { let (memory, offset, type_index) = bytes.bytes.memory(); (memory, offset + bytes.offset, type_index) } } } /// A `Managed` buffer's host copy, on a device without unified memory ([`HostCopy`]). pub(super) fn mirror(&self) -> Option<&HostCopy> { match &self.s().bytes { Bytes::Own(own) => own.mirror.as_ref(), Bytes::Heap(_) => None, } } /// The caller's pages as the host copy of a `Managed` no-copy buffer on a device without /// unified memory (`managed_copy.rs`), where the buffer is one. pub(super) fn caller_copy(&self) -> Option<&Arc> { match self.mirror() { Some(HostCopy::Caller(caller)) => Some(caller), Some(HostCopy::Own(_)) | None => None, } } /// Where a blit encoder's `synchronize_resource` copies the buffer's bytes to, where it has a /// host copy ([`HostCopy`]): the runtime's own's `VkBuffer`, whose byte 0 is the buffer's, /// or the caller's pages (`managed_copy.rs`'s [`SyncTarget`]). pub(super) fn host_copy(&self) -> Option { match self.mirror()? { HostCopy::Own(mirror) => Some(SyncTarget::Own(mirror.raw)), HostCopy::Caller(caller) => caller.sync_target(), } } /// The CPU address of the bytes the GPU uses: [`Buffer::contents`], but `None` for a buffer /// with a host copy ([`HostCopy`]), whose `contents` are that copy. A reader of the GPU's /// writes takes the bytes from here, else through a device copy. pub(super) fn device_contents(&self) -> Option> { match self.mirror() { Some(_) => None, None => self.mapped_contents(), } } /// Copy the bytes `range` of a buffer with a host copy ([`Mirror`]) from that copy to the /// buffer's own, by the device's next submission whose commands may reach the buffer (or an /// internal one), before any of its commands, after the commands before it on its `VkQueue` /// (`texture/first_move.rs`'s `register_upload`), which the call does not wait for: every /// command buffer committed after the call reads the bytes, and none submitted before that /// submission on its `VkQueue` sees them land under it. The copy reads the host copy as that /// submission runs, and the submission holds the host copy until it completed. `replaces` /// says which batch takes it ([`Replaces`]): where no command buffer can have read the /// bytes, one that takes a new buffer's first fill (`register_bytes`). /// Past the bound of what is staged, a submission waited for makes it now. Nothing for a /// buffer without a host copy, nor for an empty range. pub(super) fn upload(&self, range: Range, replaces: Replaces) -> Result<(), Error> { let s = self.s(); let mirror = match self.mirror() { Some(HostCopy::Own(mirror)) => mirror, // The caller's pages, through their import or staging (`managed_copy.rs`). Some(HostCopy::Caller(caller)) => return caller.copy_in(self, range, true, replaces), None => return Ok(()), }; if range.is_empty() { return Ok(()); } let device = &s.device; s.staged.store(true, Ordering::Relaxed); let weak: Weak = Arc::downgrade(s); let past = register_copy_in( device, weak, (self.at(range.start), (mirror.raw, range.start)), range.end - range.start, Box::new(Arc::clone(mirror)), replaces, ); match past { true => device.submit_internal(|_, _| {}), false => Ok(()), } } /// Copy the bytes `range` of a buffer with a host copy ([`HostCopy`]) to its own as the host /// copy holds them now, at the commit stamped `commit` (`managed.rs`'s `Modified`): the CPU /// copies them into staging buffers, which the device's next submission of a command buffer /// committed at or after it that may reach the buffer copies from, before any of its commands /// (`managed_copy::stage_in`). Where the staging buffers find no memory, the bytes are copied /// from the host copy as that submission runs ([`upload`](Self::upload)). Nothing for a buffer /// without a host copy, nor for an empty range, nor for pages detached. pub(super) fn upload_now(&self, range: Range, commit: u64) { let staged = match self.mirror() { Some(HostCopy::Caller(caller)) => caller.copy_in_now(self, range.clone(), commit), Some(HostCopy::Own(_)) => match self.mapped_contents() { Some(contents) => { let replaces = Replaces::Read(commit); super::managed_copy::stage_in(self, contents, range.clone(), true, replaces) } None => Ok(()), }, None => Ok(()), }; // A failed submission past the bound fails the device, which the commit's own // submission reports. if staged.is_err() { let _ = self.upload(range, Replaces::Read(commit)); } } /// Copy `range` of the bytes of `source` (a `VkBuffer`, and where the buffer's byte /// `range.start` lies in it) into the buffer's own, by the device's next submission whose /// commands may reach the buffer (or an internal one), before any of its commands, after the /// commands before it on its `VkQueue`, as [`upload`](Self::upload) copies, the submission holding `held` until it completed: a /// two-copy buffer's copy in from the caller's pages (`managed_copy.rs`), counted /// (`WorkCounts::managed_bytes_copied_in`), or from staging buffers of a host copy's bytes /// ([`upload_now`](Self::upload_now)), taken by the batch `replaces` says ([`Replaces`]). /// Where `bounded`, past the bound of what is staged, a submission waited for makes it now; /// else it waits for the device's next. pub(super) fn copy_in_from( &self, source: (vk::Buffer, u64), range: Range, held: Box, (bounded, replaces): (bool, Replaces), ) -> Result<(), Error> { let s = self.s(); let device = &s.device; let bytes = range.end - range.start; s.staged.store(true, Ordering::Relaxed); let weak: Weak = Arc::downgrade(s); let past = register_copy_in( device, weak, (self.at(range.start), source), bytes, held, replaces, ); if self.caller_copy().is_some() { device.shared().counts.managed_copied(bytes, true); } match past && bounded { true => device.submit_internal(|_, _| {}), false => Ok(()), } } /// Whether the GPU's writes to the buffer's host pages are dropped (Metal's private option /// bit 24, or a read-only rebind: `read_only_view.rs`, `copied.rs`); false for a buffer over /// no host pages. pub(super) fn drops_writes(&self) -> bool { let Some(cell) = self.pages_cell() else { return false; }; cell.drops_writes() || cell.current().is_some_and(|pages| { pages.import.drops_writes() || pages.import.copy_drops_writes() }) } /// Keep `token` for the buffer's range, dropped once the range is free (`RangeToken`): a /// buffer of its own, as a creator makes it. Internal for a buffer of a heap, which holds no /// range of its own, or one that keeps a token already: no creator gives one so. pub(super) fn keep_range_token(&self, token: RangeToken) -> Result<(), Error> { match &self.s().bytes { Bytes::Own(own) => own.range_token.keep(token), Bytes::Heap(_) => Err(internal("a range token for a heap's buffer")), } } /// Another reference to the buffer, which a command buffer holds it by /// (`EncoderCore::retain_shared`). pub(super) fn held(&self) -> Arc { self.0.clone() } /// The encoder core that holds it from an argument table's retain (`retained::HeldBy`). pub(super) fn held_by(&self) -> &HeldBy { // The program's buffer's, whatever generation its parts are of: an encoder core's retain // names the buffer, not its parts. &self.0.held_by } /// The buffer's identity for hazard tracking: a heap buffer's is its heap's, as Metal tracks /// a heap's resources as one ([`Buffer::tracked`]). pub(super) fn identity(&self) -> Identity { // Every generation's parts keep the buffer's identity (`Buffer::carry`). match &self.0.bytes { Bytes::Own(own) => own.identity, Bytes::Heap(bytes) => bytes.bytes.identity(), } } /// The key of the host memory a no-copy buffer joined, made over the bytes another covers /// (`host_aliases.rs`): its uses carry one of that key too. `None` for any other buffer. pub(super) fn alias(&self) -> Option { let s = self.s(); match &s.bytes { Bytes::Own(own) if matches!(own.lie, Lie::Host(_)) => { s.device.shared().aliases.of(own.identity.key) } Bytes::Own(_) | Bytes::Heap(_) => None, } } /// The bytes `range` of the buffer as hazard tracking keys them: its identity /// ([`Buffer::identity`]), and the range in its bytes, or for a heap buffer in its heap's. pub(super) fn tracked(&self, range: Range) -> (Identity, Range) { // A heap's buffer is never carried (`Buffer::carry`). let shift = match &self.0.bytes { Bytes::Own(_) => 0, Bytes::Heap(bytes) => bytes.offset, }; (self.identity(), range.start + shift..range.end + shift) } /// The Vulkan device address of the buffer's byte 0, where the device enables /// `bufferDeviceAddress`. pub(super) fn device_address(&self) -> Option { match &self.s().bytes { Bytes::Own(own) => own.with(ReadApart::Binding, |pages| { let address = pages.memory.device_address?; Some(address + pages.base) }), Bytes::Heap(bytes) => bytes .bytes .device_address() .map(|address| address + bytes.offset), } } /// The buffer's range for a resident set, where the device gives buffers device addresses: /// in its `VkBuffer`'s space, as the residency states a used buffer (`residency.rs`), with /// a hold on its pages that keeps them while a command buffer may reach them. A buffer placed /// in a heap: its own range, as the residency states it, with a hold on the heap's pages. pub(super) fn resident(&self) -> Option<(ResidentRange, PagesHold)> { let s = self.s(); let own = match &s.bytes { Bytes::Own(own) => own, Bytes::Heap(heap) => { let (whole, held) = heap.bytes.resident()?; let guest = s.address.0; let host = whole.host + guest.checked_sub(whole.guest)?; return Some((ResidentRange::new(host, guest, s.length), held)); } }; let range = |pages: &Pages| { let host = pages.memory.device_address?; let guest = s.address.0.checked_sub(pages.base)?; Some(ResidentRange::new(host, guest, pages.base + s.length)) }; match &own.lie { Lie::Fixed(fixed) => Some(( range(&fixed.pages)?, PagesHold::Fixed { _pages: Arc::clone(fixed), }, )), // A releasable import released is listed without a range: no shader reaches it // unnamed (`host_residency.rs`). Lie::Host(cell) => { let host = cell.current()?; let listing = host.import.listing()?; let listed = range(&listing)?; Some(( listed, PagesHold::Host { _pages: ListedPages::new(host), }, )) } } } /// A hold on the memory the buffer's bytes lie in now, which keeps nothing else of it /// ([`MemoryHold`]): a heap's buffer's, its heap's. `None` while its bytes are detached. pub(super) fn memory_hold(&self) -> Option { self.s().memory_hold() } /// A handle that does not keep the buffer (`WeakBuffer`). pub(super) fn downgrade(&self) -> WeakBuffer { WeakBuffer(Arc::downgrade(&self.0)) } /// The buffer's label and purgeable state. pub(super) fn attributes(&self) -> &ResourceAttributes { &self.s().attributes } /// What a buffer made over the same host memory shares of this one (`BufferDescriptor:: /// range_of`): its address, the range it holds, and the first byte of host memory its bytes /// are now; `None` but for a no-copy buffer of its own range. pub(super) fn sharable_range(&self) -> Option<(GpuAddress, Held, NonNull)> { match &self.s().bytes { Bytes::Own( own @ OwnBytes { owner: Owner::Caller, .. }, ) => Some(( self.exposed_address(ReadApart::SharedRange), own.reserved, self.mapped_contents()?, )), Bytes::Own(_) | Bytes::Heap(_) => None, } } /// Whose memory the buffer's bytes are, where they are the caller's: a no-copy buffer's /// host pages, or the memory of the caller's `VkBuffer`; a heap buffer's, its heap's (a heap /// over host pages, `Device::new_heap_with_bytes_no_copy`). pub(super) fn caller_memory(&self) -> Option { match &self.s().bytes { Bytes::Own(OwnBytes { owner: Owner::Caller, .. }) => Some(CallerMemory::HostPages), Bytes::Own(OwnBytes { owner: Owner::Vulkan, .. }) => Some(CallerMemory::VkBuffer), Bytes::Own(_) => None, // A heap's buffer is its heap's bytes: the caller's where the heap is over them. Bytes::Heap(bytes) => bytes.bytes.caller_memory(), } } /// The pages a buffer of its own lies in for good (the runtime's memory, or the caller's /// `VkBuffer`); `None` for a no-copy buffer and a heap's. #[cfg(unix)] fn fixed_pages(&self) -> Option> { match &self.s().bytes { Bytes::Own(OwnBytes { lie: Lie::Fixed(fixed), .. }) => Some(Arc::clone(fixed)), Bytes::Own(_) | Bytes::Heap(_) => None, } } /// The buffer's hold on its host pages: a no-copy buffer's, or a no-copy heap's own /// buffer's; `None` for any other buffer, a heap's buffer among them. pub(super) fn host_cell(&self) -> Option<&Arc> { match &self.s().bytes { Bytes::Own(OwnBytes { lie: Lie::Host(cell), .. }) => Some(cell), Bytes::Own(_) | Bytes::Heap(_) => None, } } /// Note `views`, a texture's over the buffer's bytes, where a rebind gives those other host /// pages (a no-copy buffer's, or for a heap's buffer its heap's): the rebind empties them. pub(super) fn watch_views(&self, views: &Arc) { match &self.s().bytes { Bytes::Own(OwnBytes { lie: Lie::Host(cell), .. }) => cell.watch(views), Bytes::Own(_) => {} Bytes::Heap(bytes) => bytes.bytes.watch_views(views), } } /// Where the buffer's byte `offset` lies in the device's import of the caller's host pages /// it lies in now ([`HostPages::in_import`]): `None` for a buffer over no host pages, a /// detached one, or one whose pages' memory is no such import. pub(super) fn host_memory_at(&self, offset: u64) -> Option { match &self.s().bytes { Bytes::Own(OwnBytes { lie: Lie::Host(cell), .. }) => match cell.lying() { Lying::In(pages) => pages.in_import(offset), Lying::Detached(_) | Lying::Gone(_) => None, }, Bytes::Own(_) => None, Bytes::Heap(bytes) => bytes.bytes.host_memory_at(bytes.offset + offset), } } /// The hold on the host pages the buffer's bytes lie in: a no-copy buffer's own, a buffer /// of a no-copy heap its heap's buffer's; `None` for bytes of the runtime's memory or of the /// caller's `VkBuffer`. pub(super) fn pages_cell(&self) -> Option<&Arc> { match &self.s().bytes { Bytes::Own(OwnBytes { lie: Lie::Host(cell), .. }) => Some(cell), Bytes::Own(_) => None, Bytes::Heap(bytes) => bytes.bytes.pages_cell(), } } /// The buffer's Metal address, read for the runtime's own bookkeeping (a live-table key, a /// lookup), which hands it out to no one: [`Buffer::gpu_address`] without its exposure. pub(super) fn metal_address(&self) -> GpuAddress { // Every generation's parts keep it (`Buffer::carry`). self.0.address } /// Keep a no-copy buffer's import imported for good from now on, its Metal address handed /// out for `reason` (`host_residency.rs`): imported again now where the device released it, /// and its live-table range read again where one was noted before a release. fn expose(&self, reason: ReadApart) { let Some(cell) = self.host_cell() else { return; }; let bit = reason.bit(); let before = cell.exposed.load(Ordering::Acquire); if before & bit != 0 { return; } if let Some(pages) = cell.current() { match before { 0 => { if pages.import.expose(reason) { self.generation().shared().live_buffers.refresh(self); } } // Kept imported already: the new reason is only counted. _ => pages.import.note_read_apart(reason), } } cell.exposed.fetch_or(bit, Ordering::Release); } /// [`Buffer::at`] for a blit's command, which reads the `VkBuffer` without exposing the /// buffer: a no-copy buffer's import the device released while idle is imported again first /// (`host_residency.rs`). With what the command buffer holds of the import's objects, where /// the device may release them (`rebind::ImportHold`). Refused where the device cannot import /// them again. pub(super) fn blit_at( &self, offset: u64, ) -> Result<((vk::Buffer, u64), Option), Error> { if let Bytes::Own(OwnBytes { lie: Lie::Host(cell), .. }) = &self.s().bytes { if let Lying::In(pages) = cell.lying() { let (held, hold) = pages.import.blit_pages()?; return Ok(((held.raw, held.base + offset), hold)); } } Ok((self.at(offset), None)) } /// The host pages the buffer's bytes lie in now ([`Buffer::pages_cell`]): a no-copy /// buffer's, or a no-copy heap's for a buffer of the heap; `None` for any other buffer, and /// while they are detached. pub(super) fn host_pages(&self) -> Option> { self.pages_cell()?.current() } /// Where the buffer's byte 0 lies from the first byte of the host pages it lies in /// ([`host_pages`](Self::host_pages)), read without their import: 0 for a no-copy buffer's /// own pages, the buffer's offset in its heap for a no-copy heap's buffer. pub(super) fn offset_in_host_pages(&self) -> u64 { match &self.s().bytes { Bytes::Own(_) => 0, Bytes::Heap(bytes) => bytes.bytes.offset_in_host_pages() + bytes.offset, } } /// The runtime wrote the host addresses `addresses` of the buffer's bytes through its /// `contents` itself (a `replaceRegion`, an argument encoder's or a rasterization-rate map's /// write): reported to the logs of the writes to its pages, where their memory came with one /// (`dirty_pages::PagesLog`, writer 0), so every copy of the pages takes them. The pages are /// looked at only on a device some of whose pages came with a log. pub(super) fn wrote_host(&self, addresses: Range) { if !self.s().device.shared().dirty.logged() { return; } if let Some(log) = self.host_pages().as_ref().and_then(|pages| pages.log()) { log.wrote_at(addresses); } } /// The host imports `buffers` lie in now, each counted once however many lie in it /// (`host_aliases.rs`): a committed command buffer's used buffers' /// (`WorkCounts::host_imports_used`). Buffers over no host pages count none. The first /// [`FEW_IMPORTS`] distinct imports are told apart in place, with no list made and nothing /// sorted; past them, all of them are listed and sorted. An import lives while a buffer of /// `buffers` holds it, so no two of them share an address. pub(super) fn distinct_host_imports(buffers: &[Buffer]) -> u64 { let imports = || { (buffers.iter()) .filter_map(|buffer| buffer.host_pages()) .map(|pages| Arc::as_ptr(&pages.import)) }; let mut few = [std::ptr::null::(); FEW_IMPORTS]; let mut seen = 0; for import in imports() { if few[..seen].contains(&import) { continue; } if seen == FEW_IMPORTS { let mut all: Vec<*const HostImport> = imports().collect(); all.sort_unstable(); all.dedup(); return all.len() as u64; } few[seen] = import; seen += 1; } seen as u64 } /// Note `noted`, a texture over the buffer's bytes (`TexturesOver`), where they are host /// pages (a no-copy buffer's, or for a heap's buffer its heap's): a detach makes its image /// present a stand-in (`detach.rs`). pub(super) fn note_texture(&self, noted: NotedTexture) { if let Some(cell) = self.pages_cell() { // Made over detached bytes, its stand-in's sink may be read through. if noted.sink && cell.detached() { let reached = std::iter::once((noted.texture(), noted.id, Unexact::StorageSink)); self.generation().note_stale(cell, reached); } cell.watch_texture(noted); } } /// Note `watch`, an image in place over the buffer's bytes, where they are host pages (a /// no-copy buffer's, or for a heap's buffer its heap's): a rebind makes it again over its new /// pages (`texture/in_place_image.rs`). pub(super) fn watch_in_place(&self, watch: InPlaceWatch) { if let Some(cell) = self.pages_cell() { cell.watch_in_place(watch); } } /// Whether the buffer's bytes are detached host pages (a no-copy buffer's, or for a heap's /// buffer its heap's, `detach.rs`). pub(super) fn detached(&self) -> bool { self.pages_cell().is_some_and(|cell| cell.detached()) } /// A texture is being made over the buffer's bytes: where they are host pages (a no-copy /// buffer's, or for a heap's buffer its heap's), a detach, and a rebind of them while they /// are detached, refuse until the hold goes (`detach.rs`, `buffer_descriptor.rs`), so /// whether they are detached holds while the texture is made. Take it before the texture /// binds or views them, and keep it until the texture is noted. pub(super) fn making_texture(&self) -> Option { let cell = self.pages_cell()?; lock(&cell.textures).making += 1; Some(TextureMaking(Arc::clone(cell))) } /// The index of the memory type of 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; else of /// its memory's. pub(super) fn pages_type_index(&self) -> u32 { match self.pages_cell().map(|cell| cell.lying()) { Some(Lying::In(pages)) => pages.type_index(), Some(Lying::Detached(detached)) => detached.type_index, Some(Lying::Gone(_)) => read_gone(), None => self.memory().2, } } /// 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 ([`Buffer::host_backing`]); false for a buffer over no /// host pages, or detached. pub(crate) fn copied(&self) -> bool { self.host_backing() == Some(crate::HostBacking::Copied) } /// 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. pub(super) fn over_dma_buf(&self) -> bool { match self.pages_cell().map(|cell| cell.lying()) { Some(Lying::In(pages)) => pages.over_dma_buf(), Some(Lying::Detached(detached)) => detached.over_dma_buf, Some(Lying::Gone(_)) | None => false, } } /// `device`: a generation handle of the device, owned, as Metal's `device` answers a retained /// device: of the generation the buffer was made on, then of each one the device's recoveries /// carried the buffer to. The handle is the caller's: it keeps meaning that generation while /// held, past a recovery that carries the buffer on, its raw handles that generation's /// `VkDevice`'s, kept alive while held. pub fn device(&self) -> Device { self.generation().clone() } /// The generation handle [`device`](Self::device) answers a clone of, borrowed for the /// runtime's own reads: a caller's handle is `device`'s, as a recovery lets go of the /// object's handle of a lost generation at that generation's rest (`device/carry.rs`). pub(crate) fn generation(&self) -> &Device { &self.s().device } /// `length`: the length the buffer was made with. pub fn length(&self) -> u64 { // Every generation's parts keep it (`Buffer::carry`). self.0.length } /// `contents`: the CPU address of the buffer's bytes, or `None` for `Private` storage. A /// no-copy buffer's is the caller's pointer. Reading or writing through it while the GPU /// writes those bytes is a data race, as in Metal. /// /// While a no-copy buffer is detached ([`detach_backing`](Buffer::detach_backing); for a /// heap's buffer, its heap), it answers the caller's pointer of the pages it lay in last (its /// making's or its last rebind's), as Metal's does: the pages are the caller's, which the /// runtime reads and writes nothing of until a rebind gives the buffer pages again. pub fn contents(&self) -> Option> { self.mapped_contents().or_else(|| self.detached_contents()) } /// [`contents`](Buffer::contents) where the bytes are mapped now, which the runtime reads and /// writes through: `None` while a no-copy buffer is detached. pub(crate) fn mapped_contents(&self) -> Option> { if self.storage_mode() == StorageMode::Private { return None; } match &self.s().bytes { // A host copy holds the buffer's bytes from its start. Bytes::Own(OwnBytes { mirror: Some(HostCopy::Own(mirror)), .. }) => mirror .placement .mapped .and_then(|mapped| NonNull::new(mapped.as_ptr())), // The caller's pages (`managed_copy.rs`): `None` while they are detached. Bytes::Own(OwnBytes { mirror: Some(HostCopy::Caller(caller)), .. }) => caller.mapped_contents(), // The offset is inside the placement, which the mapping covers. Bytes::Own(own) => { let shape = own.shape(); let mapped = shape.mapped?; NonNull::new(mapped.as_ptr().wrapping_add(shape.offset as usize)) } // The heap's storage mode is the buffer's, and the offset lies inside the heap. Bytes::Heap(bytes) => bytes.bytes.mapped_contents().and_then(|contents| { NonNull::new(contents.as_ptr().wrapping_add(bytes.offset as usize)) }), } } /// Whether the host maps the bytes the GPU reads and writes, through which the runtime may /// read what the GPU wrote once it completed ([`read_mapped`](Buffer::read_mapped)): not a /// `Private` buffer, nor a `Managed` one's host copy on a device without unified memory /// ([`HostCopy`]), nor a copy of the caller's pages ([`copied`](Buffer::copied)), whose /// GPU's bytes are not the pages. pub(super) fn maps_gpu_bytes(&self) -> bool { self.storage_mode() != StorageMode::Private && self.mirror().is_none() && !self.copied() } /// The `N` bytes at `offset`, as the host reads them now through the buffer's mapping /// ([`mapped_contents`](Buffer::mapped_contents)): where they lie in host pages (a no-copy /// buffer's, or for a heap's buffer its heap's), read with those pages held, so a detach and /// a rebind meanwhile let none of them go under the read. `None` where nothing maps them now /// (a `Private` buffer, a detached one), or `offset + N` passes the buffer's length. pub(super) fn read_mapped(&self, offset: u64) -> Option<[u8; N]> { if offset.checked_add(N as u64)? > self.length() { return None; } let contents = match &self.s().bytes { Bytes::Heap(bytes) => return bytes.bytes.read_mapped(bytes.offset + offset), Bytes::Own(OwnBytes { mirror: None, lie: Lie::Host(cell), .. }) => return cell.read(offset), Bytes::Own(_) => self.mapped_contents()?, }; let mut bytes = [0u8; N]; // SAFETY: the mapping holds the buffer's `length` bytes from `contents`, which its own // memory keeps mapped while the buffer lives, and `offset + N` is at most that. A write // to them meanwhile races, as a read of `contents` does on Metal. unsafe { let at = contents.as_ptr().wrapping_add(offset as usize); std::ptr::copy_nonoverlapping(at, bytes.as_mut_ptr(), N); } Some(bytes) } /// The caller's pointer of the pages a detached no-copy buffer lay in last, or for a heap's /// buffer its offset from its detached heap's: what [`contents`](Buffer::contents) answers /// while it is detached. `None` for any other buffer. fn detached_contents(&self) -> Option> { if self.storage_mode() == StorageMode::Private { return None; } match &self.s().bytes { Bytes::Own(OwnBytes { mirror: Some(HostCopy::Caller(caller)), .. }) => caller.contents(), Bytes::Own(OwnBytes { mirror: Some(HostCopy::Own(_)), .. }) => None, Bytes::Own(own) => match &own.lie { Lie::Host(cell) => cell.detached_pointer(), Lie::Fixed(_) => None, }, Bytes::Heap(bytes) => bytes.bytes.detached_contents().and_then(|contents| { NonNull::new(contents.as_ptr().wrapping_add(bytes.offset as usize)) }), } } /// The buffer's identity, a runtime extension ([`ObjectId`]): Metal names a buffer by its /// pointer; this is unique among the process's buffers, textures and heaps for the buffer's /// life and never reused, where a `gpu_address` is taken again once its buffer is freed. pub fn object_id(&self) -> ObjectId { // Every generation's parts keep it (`Buffer::carry`). self.0.object_id } /// `gpuAddress`: the buffer's address in the device's Metal address space. A heap buffer's /// is its heap's plus its offset there (`Heap::gpu_address`). /// /// A no-copy buffer whose import the device may release while idle and import again at its /// next blit (an import of dma-bufs: a runtime-internal residency, which nothing of Metal's /// observes) is kept imported for good from this call on: a command may reach it unnamed by /// this address. pub fn gpu_address(&self) -> GpuAddress { self.exposed_address(ReadApart::Address) } /// [`Buffer::gpu_address`] for the runtime's use that hands the address on for `reason` (a /// binding's, a buffer sharing the range): the import kept as `gpu_address` keeps it, /// counted for that reason. pub(super) fn exposed_address(&self, reason: ReadApart) -> GpuAddress { self.expose(reason); self.s().address } /// `resourceOptions`: the options the buffer was made with, its hazard tracking mode /// resolved (`Default` reports `Tracked` for a buffer made outside a heap, as Metal's do, and /// a heap buffer reports its heap's). pub fn resource_options(&self) -> ResourceOptions { self.s().options } /// `cpuCacheMode`. pub fn cpu_cache_mode(&self) -> CpuCacheMode { self.0 .options .cpu_cache_mode() .expect("checked when the buffer was made") } /// `storageMode`. pub fn storage_mode(&self) -> StorageMode { self.0 .options .storage_mode() .expect("checked when the buffer was made") } /// `hazardTrackingMode`: `Tracked` or `Untracked`, `Default` resolved as Metal resolves it. pub fn hazard_tracking_mode(&self) -> HazardTrackingMode { self.identity().mode() } /// `heap`: the heap the buffer is placed in, if it is. pub fn heap(&self) -> Option<&Heap> { match &self.s().bytes { Bytes::Own(_) => None, Bytes::Heap(bytes) => Some(&bytes.heap), } } /// The bytes of the heap the buffer is placed in, and where its byte 0 lies among them: /// `None` for a buffer outside a heap. pub(super) fn heap_bytes(&self) -> Option<(&Buffer, u64)> { match &self.s().bytes { Bytes::Own(_) => None, Bytes::Heap(bytes) => Some((&bytes.bytes, bytes.offset)), } } /// `heapOffset`: where the buffer lies in a placement heap. Metal answers 0 for a buffer of an /// automatic heap, whatever its place (measured), and for one outside a heap. pub fn heap_offset(&self) -> u64 { match &self.s().bytes { Bytes::Heap(bytes) if bytes.heap.heap_type() == HeapType::Placement => bytes.offset, Bytes::Heap(_) | Bytes::Own(_) => 0, } } /// `makeAliasable`: a heap buffer's bytes may be another resource's from now on. An automatic /// heap gives its range to the next resource it places (which then reads the bytes as they /// are); a placement heap's buffer is aliasable from the start, so nothing changes. Using the /// buffer after is the program's error, as in Metal. /// /// A buffer outside a heap stays as it is, not aliasable, as plain Metal leaves it where its /// validation stops the call. pub fn make_aliasable(&self) -> Result<(), Error> { let s = self.s(); let Bytes::Heap(bytes) = &s.bytes else { return Ok(()); }; bytes .heap .make_aliasable(bytes.offset, s.length, &bytes.aliasable); Ok(()) } /// `isAliasable`: whether `make_aliasable` was called on an automatic heap's buffer; true for /// a placement heap's from the start, and false outside a heap, as Metal answers. pub fn is_aliasable(&self) -> bool { match &self.s().bytes { Bytes::Heap(bytes) => bytes.aliasable.load(Ordering::Acquire), Bytes::Own(_) => false, } } } impl Buffer { /// Carry the buffer to `to`, its device's next generation, by the recovery that made it or by /// its maker (`device/carry.rs`): its parts there, the same buffer (its `ObjectId`, hazard /// key, Metal address with a share of its range, its range token, label and purgeable state), /// kept among `to`'s program resources and live buffers. A buffer in fresh pages lies in the /// same pages there, imported again, its contents and `contents` pointer as they were, and so /// does one in a block of the runtime's own pages (`memory.rs`'s `Holds::PageBuffers`), at its /// offset in them; a `Private` one in new memory, its contents lost with the `VkDevice` (it /// reads zero), but one in exportable memory over that memory's payload imported again, at its /// offset there, reading what the memory holds (`exported_memory.rs`). Its parts on the /// generation it leaves are let go of once none of that /// generation's command buffers may record. Left the lost generation's, refused where it meets /// the next (`RuntimeGap::MadeBeforeRecovery`): a buffer of pooled host-visible memory the /// device allocated, whose `contents` pointer is its block's mapping (or a `Managed` buffer's /// host copy's), a detached no-copy buffer, a heap's (its heap's carry carries it, /// `Heap::carry`), one over the caller's `VkBuffer`, a `Shared` or `Managed` one in exportable /// memory or one in an opaque descriptor's dedicated allocation, and one whose making there /// fails. pub(crate) fn carry(&self, to: &Device) -> Result { self.carry_as(to, false) } /// [`Buffer::carry`] of a heap's own buffer (`heap.rs`), for its heap's carry /// (`Heap::carry`), kept among none of `to`'s program resources or live buffers, as it was /// among none of its lost generation's: a `Private` one in new memory where the heap's /// textures can lie too ([`Device::place_heap_buffer`]), its contents lost with the /// `VkDevice` (it reads zero); one over the caller's host memory made again over the same /// pages, as a no-copy buffer is, its bytes as they are. Left the lost generation's: a /// `Shared` one, of pooled host-visible memory (a heap's own buffer never lies in the /// runtime's own pages), and one over the caller's memory a no-copy buffer's carry leaves. pub(crate) fn carry_heap_bytes(&self, to: &Device) -> Result { self.carry_as(to, true) } /// [`Buffer::carry`], of a heap's own buffer where `of_heap`. fn carry_as(&self, to: &Device, of_heap: bool) -> Result { // The generation it was carried to last: a later recovery carries it on from there. let mut last = &self.0; while let Some(next) = last.next.get() { last = &next.0; } if last.device.same(to) { // Carried already, by its maker. return Ok(Contents::Kept); } let own = match &last.bytes { Bytes::Own(own) => own, Bytes::Heap(_) => return Err(Left::Heap), }; let fixed = match (&own.owner, &own.lie) { (Owner::Runtime, Lie::Fixed(fixed)) => fixed, (Owner::Caller, Lie::Host(cell)) => { return self.carry_no_copy(last, own, cell, to, of_heap) } (Owner::Caller, _) => return Err(Left::NoCopy), (Owner::Vulkan, _) | (Owner::Runtime, Lie::Host(_)) => return Err(Left::Caller), }; let from = last.device.shared(); let placement = &fixed.pages.memory.placement; let bound = lock(&from.memory).bound_memory(placement); let runtime_s = matches!(bound, BoundMemory::Own | BoundMemory::Blocks); // Exportable memory, which another API imports (`exported_memory.rs`). A block of the // runtime's own buffers allocated exportable is never exported (`Holds::FdBuffers`). let exportable = !runtime_s && !placement.over_own_pages() && !placement.in_page_block(); let modes = Modes::of(last.options).map_err(|_| Left::Failed)?; let class = buffer_class("carry", modes).map_err(|_| Left::Failed)?; let (length, lead, reach) = (last.length, fixed.pages.offset, fixed.pages.reach); let size = (length + lead).next_multiple_of(16); let at = Place::Shared { address: last.address, held: own.reserved, }; // A two-copy buffer's host copy, made again there (`managed_copy.rs`). let mut mirror = None; let (raw, placement, contents) = if exportable { // A `Private` buffer's memory is its block's payload, imported again there, the // buffer at its offset in it: the memory the other API imported before, which it // reaches still, read as it holds it (`exported_memory.rs`). A `Shared` or `Managed` // one's `contents` pointer is its block's mapping, which new memory cannot keep. if modes.storage != StorageMode::Private || own.mirror.is_some() { return Err(Left::Exported); } #[cfg(not(unix))] return Err(Left::Exported); #[cfg(unix)] { let (raw, placement) = to.buffer_in_carried_export(size, &last.device, placement)?; if to.address_space_for(at).place(at, length).is_err() { let shared = to.shared(); // SAFETY: the buffer is unused. unsafe { release::object(shared.vk(), raw) }; lock(&shared.memory).free(shared.vk(), &placement); return Err(Left::Failed); } (raw, placement, Contents::Kept) } } else if let Some(HostCopy::Caller(caller)) = &own.mirror { let carried = caller.carry(to, length, last.options).ok_or(Left::NoCopy)?; let Ok((raw, placement)) = to.managed_device_copy(carried.device_bytes()) else { return Err(Left::Failed); }; if to.address_space_for(at).place(at, length).is_err() { let shared = to.shared(); // SAFETY: the buffer is unused. unsafe { release::object(shared.vk(), raw) }; lock(&shared.memory).free(shared.vk(), &placement); return Err(Left::Failed); } mirror = Some(HostCopy::Caller(Arc::new(carried))); (raw, placement, Contents::Kept) } else if modes.storage == StorageMode::Private { // New memory, as a new buffer's: its contents went with the lost `VkDevice`. In a // plain block (`Device::place_buffer`), where any of the device's buffers may lie, as // they do until its check of exportable blocks answered (`Holds::FdBuffers`); a // heap's where its textures can lie too, as its making placed it. let shared = to.shared(); 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(shared.vk(), &info) }.map_err(|_| Left::Failed)?; shared.counts.buffer_made(info.usage); let placed = match of_heap { true => to.place_heap_buffer(raw, length, class, at), false => to.place_buffer(raw, length, class, at), }; match placed { Ok((placement, _shared_range)) => (raw, placement, Contents::Lost(length)), Err(_) => { // SAFETY: the buffer is unused. unsafe { release::object(shared.vk(), raw) }; return Err(Left::Failed); } } } else if placement.over_own_pages() { // The same pages, imported again: the `contents` pointer and the bytes as they are. let pages = lock(&from.memory).own_pages(placement); let Some(pages) = pages else { return Err(Left::Failed); }; let Ok(Some((raw, placement))) = to.buffer_over_own_pages(size, class, Some(pages)) else { return Err(Left::Failed); }; if to.address_space_for(at).place(at, length).is_err() { let shared = to.shared(); // SAFETY: the buffer is unused. unsafe { release::object(shared.vk(), raw) }; lock(&shared.memory).free(shared.vk(), &placement); return Err(Left::Failed); } (raw, placement, Contents::Kept) } else if placement.in_page_block() { // A block of pages the runtime mapped and imported for the program's buffers // (`memory.rs`'s `Holds::PageBuffers`): the same pages imported again, once for every // buffer carried from the block, the buffer at its offset in them: the `contents` // pointer and the bytes as they are. let pages = lock(&from.memory).page_block_pages(placement); let Some(pages) = pages else { return Err(Left::Failed); }; let Ok(Some((raw, placement))) = to.buffer_in_carried_pages(size, pages, placement) else { return Err(Left::Failed); }; if to.address_space_for(at).place(at, length).is_err() { let shared = to.shared(); // SAFETY: the buffer is unused. unsafe { release::object(shared.vk(), raw) }; lock(&shared.memory).free(shared.vk(), &placement); return Err(Left::Failed); } (raw, placement, Contents::Kept) } else { // Pooled host-visible memory the device allocated, or a `Managed` buffer's host copy: // its `contents` pointer is their mapping, which new memory cannot keep (the module // docs of `device/carry.rs`). return Err(Left::Pooled); }; let range_token = KeptToken::default(); own.range_token.hand_to(&range_token); let carried = Buffer(Arc::new(BufferShared { device: MadeOn::new(to.clone()), generation: std::ptr::from_ref(to.shared()).addr(), object_id: last.object_id, length, options: last.options, address: last.address, attributes: last.attributes.carried(), bytes: Bytes::Own(OwnBytes { lie: Lie::Fixed(Arc::new(FixedPages { device: MadeOn::new(to.clone()), pages: to.pages_of(raw, placement, lead, lead, reach), owned: true, released: AtomicBool::new(false), freed: AtomicBool::new(false), })), reserved: own.reserved, identity: own.identity, owner: Owner::Runtime, mirror, range_token, }), held_by: HeldBy::default(), handed_out: Arc::default(), padding_unobserved: AtomicBool::new(last.padding_unobserved.load(Ordering::Acquire)), staged: AtomicBool::new(false), next: OnceLock::new(), carried: AtomicBool::new(false), calls: PartsCalls::default(), })); // A two-copy buffer's device copy takes the pages' bytes, its GPU writes not synchronized // lost with the `VkDevice` (`managed_copy.rs`). if let Some(caller) = carried.caller_copy() { if caller .copy_in(&carried, 0..caller.reach(), true, Replaces::Unread) .is_err() { if let Bytes::Own(parts) = &carried.0.bytes { parts.range_token.hand_to(&own.range_token); } return Err(Left::Failed); } } // Zero, as a new buffer's. Dropping it on failure lets go of its parts and range share, // and of the range token, which goes back to the buffer left. if let Contents::Lost(_) = contents { if carried.clear_first().is_err() { if let Bytes::Own(parts) = &carried.0.bytes { parts.range_token.hand_to(&own.range_token); } return Err(Left::Failed); } } let lost = LostBuffer { pages: Arc::clone(fixed), buffer: Arc::downgrade(last), }; let _set = last.next.set(carried); // Every link before it is carried already. last.carried.store(true, Ordering::Release); // Its parts on the lost generation go once none of its command buffers may record. from.carry.lost(from, Box::new(lost)); // The program's buffer is the next generation's from now on; a heap's own buffer is its // heap's, among no program resources. if !of_heap { let _kept = to.visible(self.clone()); } Ok(contents) } /// Carry a buffer placed in a heap to `to`, the generation the heap's own buffer was carried /// to (`Heap::carry`): the same buffer there (its `ObjectId`, Metal address, label and /// purgeable state, and the aliasable state it shares with its parts on each generation), /// at the same offset of the heap's bytes, which are its bytes there as they were here. Its /// parts on the generation it leaves hold no Vulkan object of their own: their entry among /// that generation's live buffers and their handle of it go once none of its command /// buffers may record ([`LostPlaced`]). Nothing where it was carried there already. pub(crate) fn carry_placed(&self, to: &Device) { let mut last = &self.0; while let Some(next) = last.next.get() { last = &next.0; } let Bytes::Heap(placed) = &last.bytes else { return; }; if last.device.same(to) { return; } let carried = Buffer(Arc::new(BufferShared { device: MadeOn::new(to.clone()), generation: std::ptr::from_ref(to.shared()).addr(), object_id: last.object_id, length: last.length, options: last.options, address: last.address, attributes: last.attributes.carried(), bytes: Bytes::Heap(HeapBytes { heap: placed.heap.clone(), bytes: placed.bytes.clone(), offset: placed.offset, aliasable: Arc::clone(&placed.aliasable), }), held_by: HeldBy::default(), handed_out: Arc::default(), padding_unobserved: AtomicBool::new(last.padding_unobserved.load(Ordering::Acquire)), staged: AtomicBool::new(false), next: OnceLock::new(), carried: AtomicBool::new(false), calls: PartsCalls::default(), })); let from = last.device.shared(); let _set = last.next.set(carried); // Every link before it is carried already. last.carried.store(true, Ordering::Release); let lost = LostPlaced { buffer: Arc::downgrade(last), }; from.carry.lost(from, Box::new(lost)); } } impl Buffer { /// [`Buffer::carry`] of a no-copy buffer, or of a no-copy heap's own buffer where `of_heap` /// (`Device::new_heap_with_bytes_no_copy`, among no program resources), whose parts on the /// generation it leaves are `last`, `own` their bytes and `cell` their hold on the caller's /// pages: made again on `to` of the /// caller's memory its pages were made of ([`HostPages::made_of`]), over the same pages, as its /// making or last rebind made it (an import of the pointer or of the source's dma-bufs, a run /// of a guest RAM the device uses, a copy, a read-only view), the caller's gate and resolver /// asked again there, its `contents` pointer and bytes as they are. Its deallocator and /// keep-alive wait for its release, or next rebind, there and for the import on each /// generation to be freed ([`Release::carry_on`]). Left the lost generation's: a buffer /// detached, or whose last detach's deallocator waits for its next rebind (a detach is not /// carried), and one whose making there fails. fn carry_no_copy( &self, last: &Arc, own: &OwnBytes, cell: &Arc, to: &Device, of_heap: bool, ) -> Result { let call = match of_heap { true => "new_heap_with_bytes_no_copy", false => "new_buffer_with_bytes_no_copy", }; if lock(&cell.held_back).is_some() { return Err(Left::NoCopy); } let pages = cell.current().ok_or(Left::NoCopy)?; let parts = pages.made_of().cloned().ok_or(Left::NoCopy)?; let pointer = parts.pointer; let naming = Naming::Carried { object_id: last.object_id, identity: own.identity, attributes: last.attributes.carried(), }; let at = Place::Shared { address: last.address, held: own.reserved, }; let made = (call, last.length, last.options, at); // SAFETY: the caller's pages stay mapped while the buffer lives, as the contract of the // memory it was made or rebound over says (`HostMemory::new`). let carried = unsafe { to.buffer_over_host_parts(made, parts, None, of_heap, cell.drops_writes(), naming) } .map_err(|_| Left::Failed)?; let (Bytes::Own(carried_own), Some(carried_pages)) = (&carried.0.bytes, carried.host_pages()) else { return Err(Left::Failed); }; // What the caller gave back the pages to waits for the buffer's release there and for // each import of them to be freed. if let Some(held) = pages.release.get().and_then(Release::carry_on) { carried_pages.release_to(Release::carried(pointer, last.length, held)); } own.range_token.hand_to(&carried_own.range_token); let unobserved = last.padding_unobserved.load(Ordering::Acquire); carried .0 .padding_unobserved .store(unobserved, Ordering::Release); let from = last.device.shared(); let lost = LostHost { cell: Arc::clone(cell), buffer: Arc::downgrade(last), }; let _set = last.next.set(carried); // Every link before it is carried already. last.carried.store(true, Ordering::Release); // Its parts on the lost generation go once none of its command buffers may record. from.carry.lost(from, Box::new(lost)); // The program's buffer is the next generation's from now on; a heap's own buffer is its // heap's, among no program resources. if !of_heap { let _kept = to.visible(self.clone()); } Ok(Contents::Kept) } /// Whether the buffer's parts on the generation it was made on went, carried from there /// (`FixedPages::release_lost`). #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] pub(crate) fn first_parts_freed(&self) -> bool { match &self.0.bytes { Bytes::Own(OwnBytes { lie: Lie::Fixed(fixed), .. }) => fixed.freed.load(Ordering::Acquire), _ => false, } } } #[cfg(test)] thread_local! { /// A test's hook into [`Buffer::held_parts`], run once by this thread's next call that holds /// a buffer's parts after the test set it: the test parks that call there across a recovery /// (`tests/device_recovery_carry.rs`). pub(crate) static HELD_HOOK: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; } /// Run this thread's [`HELD_HOOK`], where a test set it. #[cfg(test)] fn held_hook() { let hook = HELD_HOOK.with(|hook| hook.borrow_mut().take()); if let Some(hook) = hook { hook(); } }