diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 9105a84dd..7ad0069d3 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -833,8 +833,8 @@ meanwhile wait for it. and completes on the lost one where the loss came after, its object then one made before the recovery. - The recovery carries the events, the uses of guest RAM (`HostRamUse`), the no-copy buffers, the - `Private` buffers and the buffers in the runtime's own pages to the new `VkDevice`: the same - objects, at the same addresses. An event keeps the value the host saw and its listeners' + `Private` buffers, the buffers in the runtime's own pages and the `Private` heaps with the + buffers placed in them to the new `VkDevice`: the same objects, at the same addresses. An event keeps the value the host saw and its listeners' notifications. A buffer in the runtime's own pages keeps its bytes and its `contents` pointer: a long host-visible buffer's fresh pages, and, on a device whose checks found that a held import of host pages costs its submissions nothing and that textures over such pages take in place @@ -845,16 +845,19 @@ meanwhile wait for it. out is lost, as a `Private` buffer's contents are); its import gate, run resolver and dma-buf source are asked again, on the thread that recovers, and must not call into the device. Its deallocator runs at its release once no `VkDevice` imports its pages. A - `Private` buffer's contents are lost: it reads zero. + `Private` buffer's contents are lost: it reads zero. So are a `Private` heap's, whose buffers + placed before go on with it and in which buffers and textures are made again; the textures it + made before are refused, as every texture made before the recovery is. - Any other object made before the recovery is refused where it meets the new `VkDevice` (an encoder's bind, a pipeline made from its functions) and in its own calls that need its lost one: `Error::NotImplemented(RuntimeGap::MadeBeforeRecovery)`. That covers pooled `Shared` and `Managed` buffers in memory the device allocated, whose `contents` pointer is the lost memory's mapping (on a device that imports no host pointer, or whose checks found that a held import costs its submissions or that textures over such pages take less, or had not answered; and a - `Managed` buffer without unified memory), detached no-copy buffers, heaps, textures, pipeline - states, libraries and exportable memory or events. Make it again. - Metal's objects go on. The recovery's notice counts the buffers and events it carried and left. + `Managed` buffer without unified memory), detached no-copy buffers, `Shared`, no-copy and + sparse heaps with the buffers placed in them, textures, pipeline states, libraries, buffers over + the caller's `VkBuffer`, and exportable memory or events. Make it again. Metal's objects go on. + The recovery's notice counts the buffers, heaps and events it carried and left, by kind. - The lost `VkDevice` is destroyed once the objects left on it went and, where `Device::raw` answered its handles, a later `raw` call answered the new one's: `WorkCounts::vk_devices_live` reads 2 until then. A carried object holds nothing of it once none of its command buffers diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index c9dba7101..599e8ff3c 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -843,6 +843,37 @@ impl LostBuffer { } } +/// 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; + }; + { + let mut calls = lock(&buffer.calls); + if calls.under_way > 0 { + // The last call under way on them lets them go (`Buffer::held_parts`). + calls.waiting = Some(self); + 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 @@ -2255,8 +2286,10 @@ struct HeapBytes { /// The heap's own buffer. bytes: Buffer, offset: u64, - /// `makeAliasable` was called: an automatic heap's range is free for other resources. - aliasable: AtomicBool, + /// `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. @@ -2331,7 +2364,8 @@ impl BufferShared { } } - /// Whether its parts on a lost generation went (`FixedPages::release_lost`, [`LostHost`]). + /// Whether its parts on a lost generation went (`FixedPages::release_lost`, [`LostHost`], + /// [`LostPlaced`]). fn freed(&self) -> bool { match &self.bytes { Bytes::Own(OwnBytes { @@ -2342,7 +2376,7 @@ impl BufferShared { lie: Lie::Host(cell), .. }) => cell.freed.load(Ordering::Acquire), - Bytes::Heap(_) => false, + Bytes::Heap(_) => self.device.gone(), } } } @@ -2374,10 +2408,14 @@ impl Drop for BufferShared { 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. - bytes - .heap - .release(bytes.offset, self.length, &bytes.aliasable); + // 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; @@ -3714,7 +3752,7 @@ impl Heap { bytes: heap_bytes.clone(), offset, // A placement heap's buffer answers aliasable from the start, as Metal's does. - aliasable: AtomicBool::new(self.heap_type() == HeapType::Placement), + aliasable: Arc::new(AtomicBool::new(self.heap_type() == HeapType::Placement)), }), held_by: HeldBy::default(), handed_out: Arc::default(), @@ -5034,10 +5072,26 @@ impl Buffer { /// 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 no-copy - /// buffer, a heap's, one over the caller's `VkBuffer` or exportable memory, and one whose + /// 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` or in exportable memory, 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`): 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), + /// kept among none of `to`'s program resources or live buffers, as it was among none of its + /// lost generation's. 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 host memory. + 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() { @@ -5053,7 +5107,9 @@ impl Buffer { }; 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), + (Owner::Caller, Lie::Host(cell)) if !of_heap => { + return self.carry_no_copy(last, own, cell, to) + } (Owner::Caller, _) => return Err(Left::NoCopy), (Owner::Vulkan, _) | (Owner::Runtime, Lie::Host(_)) => return Err(Left::Caller), }; @@ -5064,7 +5120,7 @@ impl Buffer { if !runtime_s && !placement.over_own_pages() && !placement.in_page_block() { // Exportable memory, which another API imports (`exported_memory.rs`). A block of the // runtime's own buffers allocated exportable is never exported (`Holds::FdBuffers`). - return Err(Left::Caller); + return Err(Left::Exported); } let modes = Modes::of(last.options).map_err(|_| Left::Failed)?; let class = buffer_class("carry", modes).map_err(|_| Left::Failed)?; @@ -5093,7 +5149,8 @@ impl Buffer { } 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`). + // 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() @@ -5104,7 +5161,11 @@ impl Buffer { let raw = unsafe { crate::creation::buffer(shared.vk(), &info) }.map_err(|_| Left::Failed)?; shared.counts.buffer_made(info.usage); - match to.place_buffer(raw, length, class, at) { + 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. @@ -5218,10 +5279,63 @@ impl Buffer { 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. - let _kept = to.visible(self.clone()); + // 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: Mutex::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 { diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index 87e6d5dcf..0e95bc123 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -2335,13 +2335,14 @@ degradations! { /// waits on), and where its new `VkDevice` could not be made (the device then answers as /// a lost one). DeviceRecovered = "device-recovered", Performance, - "the events, uses of guest RAM, no-copy buffers, `Private` buffers and buffers in the \ + "the events, uses of guest RAM, no-copy buffers, `Private` buffers, buffers in the \ runtime's own pages (fresh pages, and the blocks of pages the `Shared` and `Managed` \ buffers lie in where the device's checks found a held host-page import costs its \ submissions nothing and textures over such pages take what they take over its own \ - memory) made before it go on, a `Private` buffer's contents lost (it \ - reads zero); the other objects made before it are refused (`MadeBeforeRecovery`), \ - where Metal's go on; the calls during it wait for it"; + memory) and `Private` heaps with the buffers placed in them made before it go on, a \ + `Private` buffer's or heap's contents lost (it reads zero); the other objects made \ + before it are refused (`MadeBeforeRecovery`), where Metal's go on; the calls during \ + it wait for it"; /// Apple's private device properties the device has no answer for /// (`private_properties.rs`): no document describes them and nothing the device reports /// maps to them. Announced once, when `Device::private_properties` is first read; the diff --git a/crates/metal2vulkan-runtime/src/device/carry.rs b/crates/metal2vulkan-runtime/src/device/carry.rs index 351fe5229..540baddd1 100644 --- a/crates/metal2vulkan-runtime/src/device/carry.rs +++ b/crates/metal2vulkan-runtime/src/device/carry.rs @@ -1,10 +1,11 @@ //! What a device's recovery carries to its next generation (`line.rs`): the program's events, its -//! uses of guest RAM, its no-copy buffers and the buffers of the runtime's memory whose bytes no -//! pointer of the program's reaches or whose pages the runtime owns, each the same object on the -//! new `VkDevice`, as Metal keeps its objects across its GPU's recovery. +//! uses of guest RAM, its no-copy buffers, the buffers of the runtime's memory whose bytes no +//! pointer of the program's reaches or whose pages the runtime owns, and its `Private` heaps with +//! the buffers placed in them, each the same object on the new `VkDevice`, as Metal keeps its +//! objects across its GPU's recovery. //! -//! - **Kept as made.** Each event (`EventShared::new`) is kept here, held weakly, by the -//! generation it was made on; each buffer the program made of its own (`Device::visible`) is +//! - **Kept as made.** Each event (`EventShared::new`) and heap (`Device::new_heap`) is kept here, +//! held weakly, by the generation it was made on; each buffer the program made of its own (`Device::visible`) is //! kept among the generation's program resources already (`Owners::buffer`), which the //! recovery reads ([`Carry::take`]), so making one costs a load of a flag more and no lock. //! - **Carried before the next generation serves.** The recovery takes the lost generation's live @@ -15,8 +16,10 @@ //! generation (`Device::at_serving_taking`), and what it makes after the recovery took the //! generation's objects its maker carries ([`Device::carry_late`]). The take names the buffers //! it took under the registry's lock, which a maker that finds the generation taken asks -//! ([`Carry::late_buffer`]), and an event is kept under it, so each object is carried once, by -//! one or the other. +//! ([`Carry::late_buffer`]), and an event or heap is kept under it, so each object is carried +//! once, by one or the other. A buffer placed in a heap as the heap is carried finds its bytes +//! carried under the lock the heap's carry takes its buffers under, and carries itself +//! (`Heap::carry`). //! - **What each kind becomes.** An event: a new timeline semaphore at the value the host saw //! (`EventShared::carry`). A `Private` buffer: new memory, its contents lost with the //! `VkDevice` (it reads zero). A buffer in fresh pages (`fresh_pages.rs`): the same pages @@ -31,7 +34,12 @@ //! and for its pages' import on each generation to be freed (`Release::carry_on`). A use of //! guest RAM (`HostRamUse`), before the buffers: made again on the new device, the lost one's //! let go of. Each buffer keeps its identity: its `ObjectId`, hazard key, Metal address (a -//! share of its range) and range token, its label and purgeable state. +//! share of its range) and range token, its label and purgeable state. A `Private` heap, after +//! the buffers: its own buffer in new memory where its textures can lie too, its contents lost +//! (it reads zero), its identity kept as a buffer's, registered there by its key; each buffer +//! placed in it that lives, the same buffer there at its offset in the heap's carried bytes, +//! its identity and aliasable state kept, its range in an automatic heap given back once, by its +//! parts on the generation it was carried to last (`Heap::carry`, `Buffer::carry_placed`). //! - **What stays the lost generation's**, refused where it meets the next //! (`RuntimeGap::MadeBeforeRecovery`): a buffer of pooled host-visible memory (`Shared`, and //! `Managed`) the device allocated, whose `contents` pointer is its block's mapping, which @@ -40,10 +48,15 @@ //! costs its submissions, its check of fresh pages refused what a texture over such a buffer //! takes, one of them has not answered, or no memory type of the buffer's class takes such //! pages; and a `Managed` buffer's host copy without unified memory); a detached no-copy -//! buffer, or one whose last detach's deallocator waits -//! for its next rebind; a heap's buffer, one over the caller's `VkBuffer` or exported memory, -//! and an event whose semaphore was made exportable, whose importers hold the lost one. The recovery's notice counts those it kept by kind (`Degradation::DeviceRecovered`): -//! every one but a heap's buffer, which its heap holds. +//! buffer, or one whose last detach's deallocator waits for its next rebind; a `Shared` heap, +//! whose bytes are such pooled memory (a heap's own buffer lies where its textures can, never +//! in the runtime's own pages), a heap over the caller's memory and a sparse heap, each with +//! the buffers placed in it; every texture, a heap's too; a buffer over the caller's +//! `VkBuffer`, an object of the lost `VkDevice` that only the caller can make again on the +//! new one; a buffer in exported memory, and an event whose semaphore was made exportable, +//! whose importers hold the lost allocation or semaphore. The recovery's notice counts the +//! buffers, heaps and events it carried and left by kind (`Degradation::DeviceRecovered`): a +//! heap's buffers with their heap. //! - **Each generation's work reaches its own parts** (`NoticesFor::generation`). A command buffer of the //! lost generation may still record once the recovery carried its objects: an encoder a //! program's thread opened before the loss, a render encoder's end on the lowering thread. @@ -79,6 +92,7 @@ use super::{lock, Device, DeviceShared}; use crate::buffer::Buffer; use crate::event::EventShared; +use crate::heap::{Heap, WeakHeap}; use crate::host_ram::RamUseCell; use crate::queue::Slots; use crate::resource::ObjectId; @@ -121,6 +135,8 @@ struct State { /// The program's uses of guest RAM (`host_ram.rs`'s `HostRamUse`), held weakly: few, so their /// gone entries are dropped at each keeping. ram_uses: Vec>, + /// The program's heaps, held weakly: as `ram_uses`. + heaps: Vec, /// The size at which the next keeping drops the gone events' entries. prune_at: usize, /// The recovery took the generation's objects ([`Carry::take`]): what is kept from now on, @@ -167,6 +183,7 @@ pub(crate) struct Taken { buffers: Vec, events: Vec>, ram_uses: Vec>, + heaps: Vec, } impl Carry { @@ -203,9 +220,17 @@ impl Carry { state.taken } + /// Keep `heap`, made on this generation: as [`ram_use`](Self::ram_use). + pub(crate) fn heap(&self, heap: &Heap) -> bool { + let mut state = lock(&self.state); + state.heaps.retain(WeakHeap::lives); + state.heaps.push(heap.downgrade()); + state.taken + } + /// The live objects of `shared`, this generation, for its recovery to carry: its events, its - /// uses of guest RAM and its program resources' buffers (`Owners::buffers`). From now on, each - /// one made is its maker's to carry. + /// uses of guest RAM, its heaps and its program resources' buffers (`Owners::buffers`). From + /// now on, each one made is its maker's to carry. fn take(&self, shared: &DeviceShared) -> Taken { let mut state = lock(&self.state); state.taken = true; @@ -216,6 +241,7 @@ impl Carry { buffers, events: state.events.iter().filter_map(Weak::upgrade).collect(), ram_uses: state.ram_uses.iter().filter_map(Weak::upgrade).collect(), + heaps: state.heaps.iter().filter_map(WeakHeap::upgrade).collect(), } } @@ -361,14 +387,43 @@ pub(crate) enum Left { /// A no-copy buffer detached from the caller's pages, or whose last detach's deallocator /// waits for its next rebind. NoCopy, - /// A heap's buffer. + /// A heap's buffer, which its heap's carry carries or leaves (`Heap::carry`). Heap, - /// Over the caller's `VkBuffer`, or memory another API imports (`exported_memory.rs`). + /// Over the caller's `VkBuffer` (`wrapped_buffer.rs`), which is an object of the lost + /// `VkDevice`, made by the caller. Caller, + /// In memory another API imports (`exported_memory.rs`), allocated exportable on the lost + /// `VkDevice`. + Exported, /// Its making on the new generation failed (out of memory, the driver's refusal). Failed, } +/// Why a heap stays the lost generation's, with the buffers placed in it (`Heap::carry`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum HeapLeft { + /// A `Shared` heap: its bytes are pooled host-visible memory, whose mapping its buffers' + /// `contents` pointers are, as a pooled buffer's ([`Left::Pooled`]). + Pooled, + /// A heap over the caller's host memory (`Device::new_heap_with_bytes_no_copy`). + NoCopy, + /// A sparse heap, whose textures' tiles the lost `VkDevice` bound. + Sparse, + /// Its making on the new generation failed. + Failed, +} + +impl HeapLeft { + /// Why a heap stays, its own buffer's carry having answered `left`. + pub(crate) fn of(left: Left) -> HeapLeft { + match left { + Left::Pooled => HeapLeft::Pooled, + Left::NoCopy => HeapLeft::NoCopy, + Left::Heap | Left::Caller | Left::Exported | Left::Failed => HeapLeft::Failed, + } + } +} + /// What the carry of a buffer did with its contents ([`Buffer::carry`]). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum Contents { @@ -391,7 +446,12 @@ pub(crate) struct Carried { /// The uses of guest RAM carried, and those the new generation refused. ram_uses: (u64, u64), /// The buffers left the lost generation's, by why. - left: [u64; 5], + left: [u64; 6], + /// The `Private` heaps carried, their bytes, which read zero, and the buffers placed in them + /// carried with them. + heaps: (u64, u64, u64), + /// The heaps left the lost generation's, by why. + heaps_left: [u64; 4], } impl Carried { @@ -405,12 +465,24 @@ impl Carried { "pooled `Shared` or `Managed` buffers", "detached no-copy buffers", "heaps' buffers", - "buffers over the caller's or exportable memory", + "buffers over the caller's `VkBuffer`", + "buffers in exportable memory", "buffers whose making there failed", ]; + let heap_kinds = [ + "`Shared` heaps", + "no-copy heaps", + "sparse heaps", + "heaps whose making there failed", + ]; let left = (kinds.iter().zip(self.left).enumerate()) .filter(|&(at, (_, count))| at == Left::Pooled as usize || count > 0) .map(|(_, (kind, count))| format!("{count} {kind}")) + .chain( + (heap_kinds.iter().zip(self.heaps_left)) + .filter(|&(_, count)| count > 0) + .map(|(kind, count)| format!("{count} {kind}")), + ) .chain( (self.events_left > 0) .then(|| format!("{} events made exportable", self.events_left)), @@ -425,10 +497,17 @@ impl Carried { 0 => String::new(), _ => format!("{ram_uses} guest RAM uses, "), }; + let heaps = match self.heaps { + (0, ..) => String::new(), + (heaps, bytes, buffers) => format!( + ", and {heaps} `Private` heaps ({bytes} bytes) with the {buffers} buffers placed \ + in them, whose contents were lost too" + ), + }; format!( "it carried {} events, {ram}{} buffers with their contents and {lost} `Private` \ - buffers ({lost_bytes} bytes) whose contents were lost (they read zero); left refused \ - (`MadeBeforeRecovery`): {left}", + buffers ({lost_bytes} bytes) whose contents were lost (they read zero){heaps}; left \ + refused (`MadeBeforeRecovery`): {left}", self.events, self.kept ) } @@ -445,6 +524,18 @@ impl Carried { } } + /// One heap's carry: its bytes and the buffers placed in it carried, or why it was left. + fn heap(&mut self, carried: Result<(u64, u64), HeapLeft>) { + match carried { + Ok((bytes, buffers)) => { + self.heaps.0 += 1; + self.heaps.1 += bytes; + self.heaps.2 += buffers; + } + Err(left) => self.heaps_left[left as usize] += 1, + } + } + /// One event's carry. fn event(&mut self, carried: Result<(), Error>) { match carried { @@ -463,15 +554,16 @@ impl Carried { } impl Device { - /// Carry this generation's live events and buffers, lost, to `next`, the generation its - /// recovery made, before `next` serves (the module docs): what was carried and left, for the - /// recovery's notice. + /// Carry this generation's live events, buffers and heaps, lost, to `next`, the generation + /// its recovery made, before `next` serves (the module docs): what was carried and left, for + /// the recovery's notice. pub(super) fn carry_to(&self, next: &Device) -> Carried { let shared = self.shared(); let Taken { buffers, events, ram_uses, + heaps, } = shared.carry.take(shared); let mut carried = Carried::default(); for event in &events { @@ -484,6 +576,9 @@ impl Device { for buffer in &buffers { carried.buffer(buffer.carry(next)); } + for heap in &heaps { + carried.heap(heap.carry(next)); + } carried } diff --git a/crates/metal2vulkan-runtime/src/error.rs b/crates/metal2vulkan-runtime/src/error.rs index 4ce35ea82..c373355bb 100644 --- a/crates/metal2vulkan-runtime/src/error.rs +++ b/crates/metal2vulkan-runtime/src/error.rs @@ -2131,23 +2131,25 @@ pub enum RuntimeGap { /// An object made before its device's recovery from the loss of its `VkDevice` that the /// recovery did not carry to the new one (the runtime made a new `VkDevice` behind the device, /// announced as `Degradation::DeviceRecovered`; `Device::recover_for_test` runs the same - /// recovery). The recovery carries the events, the uses of guest RAM, the no-copy buffers - /// (made again over the same pages), the `Private` buffers (their contents lost: they read - /// zero) and the buffers in the runtime's own pages (their contents and `contents` pointer - /// kept): a long host-visible buffer's fresh pages, and the blocks of pages the `Shared` and - /// `Managed` buffers lie in where the device's checks found a held host-page import costs its - /// submissions nothing and textures over such pages take what they take over its own memory. - /// Every other object's Vulkan objects are the lost `VkDevice`'s, which serves nothing more: - /// a pooled `Shared` or `Managed` buffer in memory the device allocated, whose `contents` - /// pointer is its lost memory's mapping, a detached no-copy buffer, a heap and its resources, - /// a texture, a pipeline state, a library, a sampler state, an indirect command buffer, a - /// buffer over the caller's `VkBuffer` or exportable memory, and an event made exportable. A - /// call that meets such an object with the new generation (an encoder's bind, a pipeline's - /// making from its functions, a buffer or texture placed in its heap) or that needs its own - /// lost `VkDevice` (its placements, its imports again, its event signals) is refused, where - /// Metal's object goes on; the recovery's notice counts the buffers and events it left. The - /// same object made again on the device serves; a command buffer made before the recovery - /// fails as its victim (`GpuRecoveryVictim`). + /// recovery). The recovery carries the events, the uses of guest RAM, the no-copy buffers (made + /// again over the same pages), the `Private` buffers (their contents lost: they read zero), the + /// buffers in the runtime's own pages (their contents and `contents` pointer kept): a long + /// host-visible buffer's fresh pages, and the blocks of pages the `Shared` and `Managed` + /// buffers lie in where the device's checks found a held host-page import costs its submissions + /// nothing and textures over such pages take what they take over its own memory; and the + /// `Private` heaps with the buffers placed in them (their contents lost: they read zero), in + /// which buffers and textures are made again after it. Every other object's Vulkan objects are + /// the lost `VkDevice`'s, which serves nothing more: a pooled `Shared` or `Managed` buffer in + /// memory the device allocated, whose `contents` pointer is its lost memory's mapping, a + /// detached no-copy buffer, a `Shared`, no-copy or sparse heap and the buffers placed in it, a + /// texture (a heap's too), a pipeline state, a library, a sampler state, an indirect command + /// buffer, a buffer over the caller's `VkBuffer` or in exportable memory, and an event made + /// exportable. A call that meets such an object with the new generation (an encoder's bind, a + /// pipeline's making from its functions, a buffer or texture placed in its heap) or that needs + /// its own lost `VkDevice` (its placements, its imports again, its event signals) is refused, + /// where Metal's object goes on; the recovery's notice counts the buffers, heaps and events it + /// left. The same object made again on the device serves; a command buffer made before the + /// recovery fails as its victim (`GpuRecoveryVictim`). MadeBeforeRecovery, /// `Device::recover_for_test` on a device the consumer made (`Device::from_raw`): the runtime /// cannot make a new `VkDevice` of the consumer's, so it recovers none, and the device is diff --git a/crates/metal2vulkan-runtime/src/heap.rs b/crates/metal2vulkan-runtime/src/heap.rs index b927c27bd..d55d77ac9 100644 --- a/crates/metal2vulkan-runtime/src/heap.rs +++ b/crates/metal2vulkan-runtime/src/heap.rs @@ -43,6 +43,10 @@ //! caps each at 256, as powers of two), and a smaller one would let a program pack its buffers //! tighter than on Metal and change what a read past a buffer's end reaches. The 16-KiB size //! granule is the address space's page, Metal's too. +//! - **A recovery.** A device's recovery from the loss of its `VkDevice` carries a `Private` heap +//! to the new one, with the buffers placed in it, its bytes reading zero there; a `Shared`, a +//! no-copy and a sparse heap stay the lost one's, with their buffers ([`Heap::carry`], +//! `device/carry.rs`). //! - **The largest heap.** One allocation of the device, at most `maxMemoryAllocationSize` (a //! larger heap answers out of device memory, as Metal answers nil for a heap too large), and one //! `VkBuffer`, at most `maxBufferSize`: a heap past that is refused @@ -54,6 +58,7 @@ use super::address::{AddressPlacement, GpuAddress, RangeToken, PAGE}; use super::attributes::PurgeableState; use super::attributes::ResourceAttributes; use super::buffer::{buffer_class, Buffer, Modes, WeakBuffer}; +use super::device::carry::{Contents, HeapLeft}; use super::device::lock; use super::error::{invalid, nil, Error, MemoryKind, Problem, RuntimeGap}; use super::host_memory::{Deallocator, HostMemory, HostRelease, KeepAlive}; @@ -435,6 +440,12 @@ impl Numbered { self.made } + /// Hold none of those held: their numbers stay taken, so the next one held is numbered after + /// every one held before. + pub(super) fn forget_held(&mut self) { + self.held.clear(); + } + /// Those numbered `from` or later that may still live, in the order they were held. pub(super) fn since(&self, from: u64) -> impl Iterator> { self.held @@ -745,7 +756,17 @@ impl Device { self.shared() .heap_keys .register(key, Arc::downgrade(&heap), id); - Heap(heap) + self.kept(Heap(heap)) + } + + /// `heap`, made on this generation, kept for its recovery to carry (`device/carry.rs`), or + /// carried by its maker here, where that recovery took this generation's objects before it was + /// kept: a lock taken, as an event's keeping takes it. + fn kept(&self, heap: Heap) -> Heap { + if self.shared().carry.heap(&heap) { + self.carry_late(|serving| heap.carry(serving)); + } + heap } /// A sparse heap of `descriptor`, whose options are `modes`, keeping `token` where given. @@ -785,7 +806,7 @@ impl Device { if let Some(token) = token { sparse.range_token.keep(token)?; } - Ok(Heap(Arc::new(HeapShared { + Ok(self.kept(Heap(Arc::new(HeapShared { storage: HeapStorage::Sparse(sparse), heap_type: HeapType::Sparse, ranges: Mutex::new(RangeAllocator::new(0, size)), @@ -794,7 +815,7 @@ impl Device { used: AtomicBool::new(false), object_id: ObjectId::new(), placed: Mutex::new(Placed::default()), - }))) + })))) } /// `heapBufferSizeAndAlignWithLength:options:`: `length` bytes at a multiple of 256, for every @@ -1136,9 +1157,90 @@ impl Heap { ) -> Buffer { let buffer = self.placed_buffer(bytes, offset, length, options); self.device().shared().live_buffers.placed(self, &buffer); + // Placed as its device's recovery carried the heap's bytes on, after that carry looked + // at the heap's buffers (`Heap::carry`): carried here. + if !buffer.device().same(self.device()) { + self.carry_placed_late(&buffer); + } buffer } + /// Carry the heap, made on a generation of its device that a recovery leaves, to `to`, the + /// generation that recovery made (`device/carry.rs`), with the buffers placed in it. A + /// `Private` heap's own buffer lies in new memory there ([`Buffer::carry_heap_bytes`]), its + /// contents lost with the `VkDevice` (it reads zero), and it keeps its identity (its + /// `ObjectId`, hazard key, Metal address and range, range token, label and purgeable state): + /// the heap is the same heap there, registered by its key, and each buffer placed in it that + /// lives is the same buffer there, at its offset ([`Buffer::carry_placed`]), listed among the + /// generation's live buffers where a command buffer's commands used the heap already. The + /// textures it made stay the lost generation's, as every texture does: they are refused where + /// they meet the next generation (`RuntimeGap::MadeBeforeRecovery`), and no use of the heap + /// there makes them resident; those it makes there are that generation's, numbered after + /// them. The bytes carried, and the buffers placed in it carried with them; or why the heap + /// is left the lost generation's, with its buffers: a `Shared` heap's bytes are pooled + /// host-visible memory, whose mapping its buffers' `contents` pointers are; a heap over the + /// caller's memory and a sparse heap are not carried; or its making there failed. + pub(crate) fn carry(&self, to: &Device) -> Result<(u64, u64), HeapLeft> { + let bytes = match &self.0.storage { + HeapStorage::Bytes(bytes) => bytes, + HeapStorage::Sparse(_) => return Err(HeapLeft::Sparse), + }; + if bytes.device().same(to) { + // Carried already, by its maker. + return Ok((0, 0)); + } + let lost = match bytes.carry_heap_bytes(to).map_err(HeapLeft::of)? { + Contents::Lost(lost) => lost, + Contents::Kept => 0, + }; + to.shared().heap_keys.register( + bytes.identity().key, + Arc::downgrade(&self.0), + self.0.object_id, + ); + lock(&self.0.textures).forget_held(); + // Under the lock a buffer's placing takes: one placed from now on finds the heap's bytes + // carried, and carries itself (`program_buffer`). + let (buffers, reached) = { + let mut placed = lock(&self.0.placed); + placed.buffers.retain(WeakBuffer::lives); + let buffers: Vec = (placed.buffers.iter()) + .filter_map(WeakBuffer::upgrade) + .collect(); + for buffer in &buffers { + buffer.carry_placed(to); + } + (buffers, placed.reached) + }; + if reached { + for buffer in &buffers { + to.shared().live_buffers.made(buffer); + } + } + // Kept there for a later recovery to carry on, as a heap made there is. + if to.shared().carry.heap(self) { + to.carry_late(|serving| self.carry(serving)); + } + Ok((lost, buffers.len() as u64)) + } + + /// Carry `buffer`, placed in the heap on the generation its bytes were carried from, to the + /// one they were carried to ([`Heap::carry`]), under the lock its carry looks at the heap's + /// buffers under: once, by the one or the other. + fn carry_placed_late(&self, buffer: &Buffer) { + let reached = { + let placed = lock(&self.0.placed); + if buffer.device().same(self.device()) { + return; + } + buffer.carry_placed(self.device()); + placed.reached + }; + if reached { + self.device().shared().live_buffers.made(buffer); + } + } + /// The options of a buffer or texture `call` places with `options`: the heap's, its hazard /// tracking mode resolved, where `options` names the heap's storage and CPU cache modes. A /// hazard tracking mode named other than the heap's becomes the heap's, as plain Metal makes diff --git a/docs/API.md b/docs/API.md index 4f3e8e67c..2c922b32e 100644 --- a/docs/API.md +++ b/docs/API.md @@ -3669,19 +3669,24 @@ bound. kind. Announced too, at most once each per recovery whatever an earlier recovery announced: where a call waited past 10 seconds for the recovery under way, where its command buffers in flight took past 10 seconds to fail, and where its new `VkDevice` could not - be made, after which the device answers as a lost one. `Device::recover_for_test` runs the same recovery with no GPU fault. Cost: the events, - uses of guest RAM, no-copy buffers, `Private` buffers and buffers in the runtime's own pages - (fresh pages, and the blocks of pages the `Shared` and `Managed` buffers lie in where the - device's checks found a held host-page import costs its submissions nothing and textures over - such pages take what they take over its own memory) made before it go on, a `Private` buffer's - contents lost (it reads zero); the other objects made before it are - refused (`MadeBeforeRecovery`), where Metal's go on; the calls during it wait for it, and a + be made, after which the device answers as a lost one. `Device::recover_for_test` runs the + same recovery with no GPU fault. Cost: the events, uses of guest RAM, no-copy buffers, + `Private` buffers, buffers in the runtime's own pages (fresh pages, and the blocks of pages the + `Shared` and `Managed` buffers lie in where the device's checks found a held host-page import + costs its submissions nothing and textures over such pages take what they take over its own + memory) and `Private` heaps with the buffers placed in them made before it go on, a `Private` + buffer's or heap's contents lost (it reads zero); the other objects made before it are refused + (`MadeBeforeRecovery`), where Metal's go on; the calls during it wait for it, and a device call the loss met while it ran runs again after it. A no-copy buffer is made again over the same pages on the new `VkDevice`, as its making or last rebind made it, so the caller's import gate, resolver of guest RAM runs and dma-buf source are asked again, on the thread that recovers, before the new device serves; its deallocator runs at its release once no `VkDevice`'s import of its pages is left. A detached no-copy buffer, and a no-copy heap's buffers, are - refused. + refused. A `Private` heap is the same heap on the new `VkDevice` (its identity, address and + label), its bytes new memory that reads zero, with the buffers placed in it; buffers and + textures are made in it again, and the textures it made before are refused, as every texture + made before the recovery is. A `Shared` heap, whose bytes are pooled host-visible memory the + device allocated, is refused with its buffers, as a pooled buffer is. - `metal2vulkan-degrade-private-properties-unknown` (precision). `PrivatePropertiesUnknown`: Apple's private device properties the device has no answer for: no document describes them and nothing the device reports maps to them. Cost: the device gives no answer for them (`PrivateAnswer::value` is