From ff837ae87d67d81b5d18b9348c32ed10cbb804ae Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Thu, 12 Nov 2026 23:10:01 -0800 Subject: [PATCH] :fire: Delete the detach and replace machinery no call reaches Since apple-gfx's detach and replace went on 11-07, nothing the guest or the host reaches calls a buffer's or heap's detach_backing or replace_backing, or the runtime's rebind_bytes_no_copy behind them: the device's wire has no op for them, reims-vgpu's decoder never calls them, the C API has no entry for them, and the guest bundle's RgfxHeap raises an unrecognized selector at detachBacking and replaceBackingWithRanges:readOnly:, as Metal's base heap does. Only tests called them. Deleted with them: the trait methods and the testkit's, the backing's detached state, its registry of detached objects, held deallocators and kept contents, the per-command-buffer parts and the submission check every commit set for them, and EncodedUseRebound's death, which no rebind can reach now (the runtime's kind stays placed, and a failure of that kind would die unanswered). tests/detach_backing.rs goes; its heap-over-address-ranges cases, with Metal's recorded heap answers, move to tests/address_ranges.rs. reach.metal's comment named the deleted file, so its metallib is compiled again (the bytes this Xcode writes; the record changes for reach alone). What the guest and the host see: nothing changes. The device still answers supportsResourceDetachBacking as before: that answer is the guest's, and changes only with boots. --- .config/nextest.toml | 4 +- .../metallibs/metallibs.toml | 2 +- .../metallibs/reach.metallib | Bin 3611 -> 3627 bytes crates/reims-vgpu-vulkan/src/answer.rs | 43 +- .../src/core/platform/resource.rs | 12 - .../src/core/testkit/impls/resource.rs | 48 - .../src/core/testkit/objects.rs | 6 +- crates/reims-vgpu-vulkan/src/gpu/backing.rs | 1621 +---------- crates/reims-vgpu-vulkan/src/gpu/caps.rs | 10 +- crates/reims-vgpu-vulkan/src/gpu/command.rs | 268 +- crates/reims-vgpu-vulkan/src/gpu/device.rs | 51 +- .../src/gpu/encode_render.rs | 2 +- .../reims-vgpu-vulkan/src/gpu/frame_cost.rs | 19 +- crates/reims-vgpu-vulkan/src/gpu/reach.metal | 4 +- crates/reims-vgpu-vulkan/src/gpu/resource.rs | 185 +- crates/reims-vgpu-vulkan/src/gpu/writes.rs | 56 +- .../reims-vgpu-vulkan/src/os/linux/budget.rs | 2 +- .../reims-vgpu-vulkan/src/os/linux/import.rs | 34 +- .../src/os/linux/plane_copy.rs | 9 +- .../reims-vgpu-vulkan/src/os/linux/surface.rs | 6 +- crates/reims-vgpu-vulkan/src/os/linux/vm.rs | 11 +- crates/reims-vgpu-vulkan/src/os/macos.rs | 2 +- crates/reims-vgpu-vulkan/src/platform.rs | 2 +- crates/reims-vgpu-vulkan/src/remap.rs | 19 +- .../reims-vgpu-vulkan/tests/address_ranges.rs | 479 ++++ .../reims-vgpu-vulkan/tests/detach_backing.rs | 2492 ----------------- ...unaligned_ranges_on_vulkan_are_metals.txt} | 6 - docs/accuracy-ledger.md | 2 +- docs/lessons.md | 2 +- docs/qemu.md | 10 +- 30 files changed, 784 insertions(+), 4623 deletions(-) create mode 100644 crates/reims-vgpu-vulkan/tests/address_ranges.rs delete mode 100644 crates/reims-vgpu-vulkan/tests/detach_backing.rs rename crates/reims-vgpu-vulkan/tests/metal_answers/{detach_backing.unaligned_ranges_on_vulkan_are_metals.txt => address_ranges.unaligned_ranges_on_vulkan_are_metals.txt} (66%) diff --git a/.config/nextest.toml b/.config/nextest.toml index 4e3bb1f62..8dd488deb 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -13,8 +13,8 @@ # they test, with `--run-ignored only`. Each fault is a GPU recovery (84 GPU events in its # 1.8 s, measured on the M3 Max, macOS 27.0.1), and every command buffer of another process in # flight then fails as its victim ("Discarded (victim of GPU error/recovery)"): the YCbCr -# sweeps, the extended-range blends (Metal's side then reads zeros), the in-flight detaches, the -# textures made while a kernel runs. +# sweeps, the extended-range blends (Metal's side then reads zeros), the textures made while a +# kernel runs. [[profile.default.overrides]] platform = 'cfg(target_os = "macos")' filter = 'binary_id(reims-vgpu-vulkan::client_direction) & test(=metal_drops_small_blits_into_the_texture)' diff --git a/crates/reims-vgpu-vulkan/metallibs/metallibs.toml b/crates/reims-vgpu-vulkan/metallibs/metallibs.toml index 41ececbbf..a55b573a7 100644 --- a/crates/reims-vgpu-vulkan/metallibs/metallibs.toml +++ b/crates/reims-vgpu-vulkan/metallibs/metallibs.toml @@ -6,7 +6,7 @@ "icb_encode.metallib" = "354ca4fee482115b1cb9bbd867b10bb36c37828e7ef8ff404ebfcf9c78bf6e9d" "barycentric.metallib" = "7decabb9010e04bfa6edf67aa618ee8603f9df4c6aa9299f84ba70585e3077f9" "vertex_ids.metallib" = "d4c2056c7c97ada7fa1bc8cc53bc4c42998ec4e868e51539e633c0fc2f7b89f5" -"reach.metallib" = "62d21bb7cec8cf6571cf826ccccbfb1c7d3d6ea70aa815bc75d5cd5593f41a84" +"reach.metallib" = "136d9ac1881689e6259ce3ded3a52dbdb5b389000c6bd5c3e7bb279ce2085572" "rounding.metallib" = "7b3aae32d6a18dff647575486d81a44f8b17d34d4a670f852987960bd30e583b" "ycbcr_probe.metallib" = "798733169dfc75586bc6a6ce39f6f191ccb527f2b187389d3835b00ec74a8948" "refused.metallib" = "9fdfdf20dfe3f369d2327680d3deb895c42d1f200a6778c64ca60679ada375e1" diff --git a/crates/reims-vgpu-vulkan/metallibs/reach.metallib b/crates/reims-vgpu-vulkan/metallibs/reach.metallib index 1b8fa60432f8aea0ce8a6516e7f018f17d5327e2..07863afc61c618845173b083b29a2283b1b03216 100644 GIT binary patch delta 606 zcmbO&vsy;bH^j$@v4M$!lYya8nt_Qyd!nE{qr=2N4fUR)>e*s59ZgTazg6_lB+F#R zkuu3!T_(#e|538-OZL|GbqS8*U~rhYK$nqo;yF!5m5D!;83i`WFxD_hH``=17c{U} zB(xW0G?#I-7gn@a9$>fJ!E8QZ^JeCBMy^gqh6Wu01_lQ1$ttYMT$3ai6=b|`urM%e z_GMkf#CU7-2X;nAF(U^QJKH6>)k`F5aj;dA4_Tv9xN(WC3mo?I#M$H<(yX-?-guhsm~0>&-28 zZ86`zGqBBaL9>;Is*dlu)U`h6*7oF1ap2z^!kxfqIpL7}8VRpP5r@R130zAAxTKlv zZy0W)fd!WT~52P>_?Vo12)NUtD2iu4klY0MQ5`0UVaaR{#J2 delta 613 zcmZ22Gh0T`H^j$@v4M$!lYya8ih+SadZM5`qrt>L4Rts637Vy8@j~0~NoM!u{VU%t z-8bt`$p1}hJ9Mtkoa;5k*CjZLgTY|p0$oOqiRUyKWhVYmX5`x}!&t*4&1{p=T+qN? zkN5RtFS7w2{Iho*uuLxkaZCg z7qTQ%e$a(o%JejSP&8^(>7H^~@G?b2193`2sZpfkBf2hcd?rqsh`- zvh@iJ#yl|>&Kgu4GC$0~#tb4{B+eK#I0~{E^CTp+9OPk^kV!HC3ZDQAJFywFoZ?|N zXG=9;-dK|w0OX$GaWr;*aE9Rw!_w zn>&!vvZqOYjf6*{$iIZ60bGk2xTKrxZWw%M)a*FamdNktC}PI5qJeAC21SKdUPsLw z38#l5E{TT^aII08{FO&j$)QzQR3P+*5eK7oj%8beC|{^UP~z!8mNf+{m?m*Ww<#w~ wcHk9dJUTgyca<_QLJ~8J%uM3Tj4X5$3kq^lb#oJw^NTBt%=8TO3_$J!09|F&YXATM diff --git a/crates/reims-vgpu-vulkan/src/answer.rs b/crates/reims-vgpu-vulkan/src/answer.rs index b5ee40ead..f4a6ff32b 100644 --- a/crates/reims-vgpu-vulkan/src/answer.rs +++ b/crates/reims-vgpu-vulkan/src/answer.rs @@ -367,27 +367,12 @@ pub fn created_or_decided( /// encoding thread, inside its call, which dies at its selector, as `YCbCrFilterNotExact` is. /// It dies on every device, a native one included: Apple's blend arithmetic for those forms is /// not measured, and the exact form is a measured one or the blend in the function; -/// - `EncodedUseRebound`: a command buffer's command named a buffer or heap over the guest's -/// pages that was rebound (a replace, `crate::gpu::backing`) after the command was encoded and -/// before the command buffer's first submission, in an encoder the rebind could not encode again -/// (a compute encoder of the runtime's command predication that shares its unit, holds a loop -/// or leaves work out, which no record of ours reaches, a render pass that executes an indirect -/// command buffer, which the runtime records later, or whose end captured its draws' tile -/// reach, a call that answers otherwise than at its encoding; every other compute, blit and -/// render encoder, one with a pipeline still being made at the commit among them, it encodes -/// again over the new pages, as Metal runs it, a call refused at its -/// encoding refused again and the calls after it running, and a resource state encoder takes no -/// pages), and neither the submission check nor the failure the command buffer was committed with -/// (`commit_failed`) failed the submission holding it: the runtime runs nothing of that -/// submission and fails the command buffer, where Metal runs the command over the pages the -/// object lies in as it submits. A command buffer an earlier submission failed already (a use -/// detached behind an event wait, Metal's code 8) keeps that code. A submission the check fails -/// keeps that code and announces nothing. Announced once per device, whatever `announce_each` -/// says, as the submission is made, on the thread that makes it: the runtime's scheduler thread, -/// outside every call here, or a thread inside a later command buffer's `commit`, in which the -/// runtime submits every batch ready then. It dies there and ends the process. The failure it -/// leaves dies where it is first read too (`crate::gpu::command`), so a later one, which the -/// device does not announce again, dies; +/// - `EncodedUseRebound`: a command buffer's command named a buffer or heap the runtime rebound +/// to new pages after the command was encoded, in an encoder it could not encode again, where +/// Metal runs the command over the pages the object lies in as it submits. No call of this +/// platform rebinds a buffer or heap, so the runtime announces it for none; it stays placed for +/// the runtime's kind, and a failure it left would die where it is first read, unanswered +/// (`crate::gpu::command`); /// - `ZeroLayerMapAfterRelease`: a draw in a pass over a rasterization rate map of no layers made /// after the device released a map of layers, which writes nothing where Metal draws rows of /// the pass. Announced at the draw, inside its call, which dies at its selector. No draw over a @@ -576,7 +561,8 @@ pub fn created_or_decided( /// commit; /// - `DetachedStorageKeepsWrites`: a storage texture over detached bytes a committed command /// buffer's heap set reaches, whose unnamed storage reads read what an earlier such write -/// left, where Metal drops those writes and reads zero. Announced at `commit`; +/// left, where Metal drops those writes and reads zero. Announced at `commit`; no call of +/// this platform detaches bytes, so the runtime announces it for none; /// - what a pass or a copy leaves in its texture otherwise than Metal, each announced inside the /// call that encodes it, which dies at its selector: /// - `MixedDepthStencilResolve`: a pass that stores and resolves one texture's depth beside @@ -837,7 +823,8 @@ pub fn created_or_decided( /// it reads zeros, where Metal's reads the pages the guest gave back. Those pages hold what /// they held until the guest writes them again, so Metal's answer is one value, and no fact of /// the hardware forces the difference, so it dies on every device. Announced once per device, -/// at the first such submission, inside its call, which dies at its selector; +/// at the first such submission, inside its call, which dies at its selector; no call of this +/// platform detaches bytes, so the runtime announces it for none; /// - `CrossClassTextureNeutral`: a draw or dispatch binding, at a texture slot declared of /// another numeric class (`float` or `half`, `int`, `uint`) than its texture's format, one the /// runtime has no exact answer for (a storage slot, a texture buffer, a multisampled, sparse, @@ -912,8 +899,8 @@ pub fn created_or_decided( /// keep-alive: with one, it runs the deallocator at the release, as Metal's, and the import /// keeps the keep-alive, which keeps the pages mapped, until it is freed, wherever they are held /// (an image over them holding their import, a live buffers' table that lists them, MoltenVK's -/// freed memory waiting for the batches in flight), and announces nothing. Every no-copy buffer, -/// heap and rebind this platform makes gives one ([`crate::gpu::backing::keep_alive`]), so the +/// freed memory waiting for the batches in flight), and announces nothing. Every no-copy buffer +/// and heap this platform makes gives one ([`crate::gpu::backing::keep_alive`]), so the /// runtime announces it for none of them. Announced once per device, on the thread that lets go /// of the buffer, inside its release here or on one of the runtime's as a command buffer /// completes, outside every call here: it dies where it is announced; @@ -1287,12 +1274,12 @@ pub fn created_or_decided( /// them, and whose later levels lie apart from the heap's bytes, a 1D array's GPU reads reading /// each texel, where Metal's paths address those texels at bytes that differ by path. Announced /// inside the heap's creator of the texture, which dies at its selector; -/// - `CopiedHostPages`: a no-copy buffer, heap or rebind made over a copy of the guest's pages in +/// - `CopiedHostPages`: a no-copy buffer or heap made over a copy of the guest's pages in /// memory of the device's own, as their import failed (out of memory, or a driver out of the /// mappings the host's kernel allows), or the views' gate refused it on Linux, where mapping the /// pages from their files would have run the views of memory within the headroom of their -/// budget of kernel mappings, or the pages are a guest's read-only object's (a replace -/// `readOnly:YES`, a heap or no-copy buffer made with `MTLResourceOptions` bit 24, pages mapped +/// budget of kernel mappings, or the pages are a guest's read-only object's (a heap or no-copy +/// buffer made with `MTLResourceOptions` bit 24, pages mapped /// read-only), whose copy drops the GPU's writes, as Metal's GPU drops them (`crate::os`'s /// import gate, `crate::gpu::writes`), which each commit fills from the pages and each /// completion writes back: a CPU write the GPU reads mid-command-buffer, or a GPU write the CPU diff --git a/crates/reims-vgpu-vulkan/src/core/platform/resource.rs b/crates/reims-vgpu-vulkan/src/core/platform/resource.rs index a09435765..90ca0a6b0 100644 --- a/crates/reims-vgpu-vulkan/src/core/platform/resource.rs +++ b/crates/reims-vgpu-vulkan/src/core/platform/resource.rs @@ -42,9 +42,6 @@ pub trait Buffer: GpuResource

{ /// sel: contents /// The buffer's CPU address; core reads and writes through it (never NULL-checked). fn contents(&self) -> HostPtr; - /// sel: detachBacking SPI - /// The runtime returns `BOOL` (`B16@0:8`); core never reads it. - fn detach_backing(&self) -> RaiseResult<()>; /// sel: didModifyRange: /// Reached both under a handler and with none: `on` says which this call is. fn did_modify_range(&self, on: OnFault, range: NsRange) -> RaiseResult<()>; @@ -97,9 +94,6 @@ pub trait Buffer: GpuResource

{ descriptor: &P::TextureDescriptor, plane: SurfacePlane, ) -> RaiseResult>; - /// sel: replaceBackingWithRanges:readOnly: SPI - /// `false` makes core throw "Failed to replace buffer backing". - fn replace_backing(&self, ranges: &P::AddressRangeArray, read_only: bool) -> RaiseResult; /// No Metal counterpart: the buffer's memory as a new file descriptor another API imports, /// with what the import names ([`ExportedMemory`]), where the buffer was made exportable /// ([`GpuDevice::new_exportable_buffer_of_length`](super::device::GpuDevice::new_exportable_buffer_of_length)). @@ -258,9 +252,6 @@ pub trait Texture: GpuResource

{ /// `MTLHeap` (with `MTLHeapSPI`). Not an `MTLResource`: its purgeable state, storage mode and /// options are its own selectors. pub trait Heap: Handle { - /// sel: detachBacking SPI - /// The runtime returns `BOOL` (`B16@0:8`); core never reads it. - fn detach_backing(&self) -> RaiseResult<()>; /// sel: gpuAddress SPI fn gpu_address(&self) -> u64; /// sel: newBufferWithLength:options:offset: @@ -276,9 +267,6 @@ pub trait Heap: Handle { descriptor: &P::TextureDescriptor, offset: u64, ) -> RaiseResult>; - /// sel: replaceBackingWithRanges:readOnly: SPI - /// `false` makes core throw "Failed to replace heap backing". - fn replace_backing(&self, ranges: &P::AddressRangeArray, read_only: bool) -> RaiseResult; /// sel: resourceOptions fn resource_options(&self) -> u64; /// sel: setPurgeableState: diff --git a/crates/reims-vgpu-vulkan/src/core/testkit/impls/resource.rs b/crates/reims-vgpu-vulkan/src/core/testkit/impls/resource.rs index d5e2ab45c..35601978f 100644 --- a/crates/reims-vgpu-vulkan/src/core/testkit/impls/resource.rs +++ b/crates/reims-vgpu-vulkan/src/core/testkit/impls/resource.rs @@ -115,14 +115,6 @@ impl Buffer for Fk { self.buffer(|m| m.contents) } - fn detach_backing(&self) -> RaiseResult<()> { - self.act(Policy::Caught, "detachBacking", vec![])?; - if let Model::Buffer(m) = &mut self.state().model { - m.detached = true; - } - Ok(()) - } - fn did_modify_range(&self, on: OnFault, range: NsRange) -> RaiseResult<()> { self.act(Policy::On(on), "didModifyRange:", vec![Arg::val(&range)]) } @@ -231,24 +223,6 @@ impl Buffer for Fk { |w| Some(new_texture(w, desc, None, 0, Some(parent), false)), ) } - - fn replace_backing( - &self, - ranges: &::AddressRangeArray, - read_only: bool, - ) -> RaiseResult { - let r = ranges.erase(); - let ok = self.thr( - Policy::Caught, - "replaceBackingWithRanges:readOnly:", - vec![Arg::obj(ranges), Arg::Bool(read_only)], - || true, - )?; - if ok && let Model::Buffer(m) = &mut self.state().model { - m.ranges = Some(r); - } - Ok(ok) - } } impl Texture for Fk { @@ -512,10 +486,6 @@ impl Texture for Fk { } impl Heap for Fk { - fn detach_backing(&self) -> RaiseResult<()> { - self.act(Policy::Caught, "detachBacking", vec![]) - } - fn gpu_address(&self) -> u64 { self.heap(|m| m.gpu_address) } @@ -571,24 +541,6 @@ impl Heap for Fk { ) } - fn replace_backing( - &self, - ranges: &::AddressRangeArray, - read_only: bool, - ) -> RaiseResult { - let r = ranges.erase(); - let ok = self.thr( - Policy::Caught, - "replaceBackingWithRanges:readOnly:", - vec![Arg::obj(ranges), Arg::Bool(read_only)], - || true, - )?; - if ok && let Model::Heap(m) = &mut self.state().model { - m.ranges = Some(r); - } - Ok(ok) - } - fn resource_options(&self) -> u64 { self.heap(|m| m.options) } diff --git a/crates/reims-vgpu-vulkan/src/core/testkit/objects.rs b/crates/reims-vgpu-vulkan/src/core/testkit/objects.rs index 8221c06cd..aac60387a 100644 --- a/crates/reims-vgpu-vulkan/src/core/testkit/objects.rs +++ b/crates/reims-vgpu-vulkan/src/core/testkit/objects.rs @@ -213,10 +213,6 @@ pub struct BufferModel { pub deallocator: Option, /// A descriptor-made buffer's deallocator `(contents, length)`, run when the buffer dies. pub desc_deallocator: Option, - /// `detachBacking` was sent. - pub detached: bool, - /// The address ranges it was re-backed with (retained). - pub ranges: Option, /// Common resource state. pub common: ResourceCommon, } @@ -341,7 +337,7 @@ pub struct HeapModel { pub gpu_address: u64, /// Memory the fake owns for a CPU-visible heap. pub mem: Option>, - /// The address ranges it was made over or re-backed with. + /// The address ranges it was made over. pub ranges: Option, /// Common resource state. pub common: ResourceCommon, diff --git a/crates/reims-vgpu-vulkan/src/gpu/backing.rs b/crates/reims-vgpu-vulkan/src/gpu/backing.rs index 7e9732b35..e666e5cd4 100644 --- a/crates/reims-vgpu-vulkan/src/gpu/backing.rs +++ b/crates/reims-vgpu-vulkan/src/gpu/backing.rs @@ -1,199 +1,60 @@ //! Buffers and heaps over the guest's pages: the alias a heap over address ranges is made over -//! (`setAddressRanges:`), and the one each replace of a detached backing gives a buffer or a heap -//! (`replaceBackingWithRanges:readOnly:`); and what `detachBacking` keeps. +//! (`setAddressRanges:`), and the one the buffers over a surface lie in ([`Alias`]); and the +//! guest's pages and the read-only bit each object keeps ([`Backing`]). //! -//! - **An alias per attach.** The ranges' pages are remapped, shared, into a fresh range of this +//! - **An alias per object.** The ranges' pages are remapped, shared, into a fresh range of this //! platform's own (`mach_vm_remap`, one call per run of host-contiguous ranges), and the //! runtime is given that range with a keep-alive that frees it (`new_heap_with_bytes_no_copy`, -//! `rebind_bytes_no_copy`, [`keep_alive`]), and no deallocator: no one but this platform sees -//! the alias go. A write through the alias shows in the guest's pages and one through the -//! guest's pages in the alias, so the GPU's writes land in the guest's memory at once and it -//! reads the guest's latest bytes, as Metal's do. The runtime keeps an alias, and so the pages -//! under it, until every command buffer committed with it completed and it freed its import of -//! them, which it does before it drops the keep-alive: a later replace, a detach or -//! the object's release never takes pages a committed command buffer still uses or the device -//! still imports, and the guest's memory stays mapped under it whatever the guest's own mapping -//! does meanwhile. A replace never remaps under a range the runtime holds: the runtime keeps -//! the pages a range had when it imported them (`tests/no_copy_remap.rs`). +//! [`keep_alive`]), and no deallocator: no one but this platform sees the alias go. A write +//! through the alias shows in the guest's pages and one through the guest's pages in the alias, +//! so the GPU's writes land in the guest's memory at once and it reads the guest's latest bytes, +//! as Metal's do. The runtime keeps an alias, and so the pages under it, until every command +//! buffer committed with it completed and it freed its import of them, which it does before it +//! drops the keep-alive: the object's release never takes pages a committed command buffer +//! still uses or the device still imports, and the guest's memory stays mapped under it +//! whatever the guest's own mapping does meanwhile. The runtime keeps the pages a range had +//! when it imported them (`tests/no_copy_remap.rs`). //! - **Ranges off whole pages.** Core's ranges are whole pages, each starting on a page; Metal -//! takes others, a heap's and a replace's alike, and this platform takes them as Metal does -//! (measured on the M3 Max, macOS 26.7, `tests/detach_backing.rs`'s `unaligned`): ranges whose -//! bytes follow on from the previous range's are one run of bytes, and each run of bytes takes -//! the pages it lies in, whole, from the page of its first byte through the page of its last -//! ([`spans`]). A range of part of a page takes all of it, the page's bytes past the range -//! included (the CPU and the GPU read them, and the GPU's fill writes them), and a later range -//! starting off its page takes it from the page's start. A first range starting off its page dies -//! where it is given ([`off_the_page`]): Metal's `contents` answers its bytes from the range's -//! own address, and its GPU reads and writes them from its page's start, which no alias gives at -//! once. -//! - **Read-only.** A read-only alias (the replace's `readOnly:`, or an object made with -//! `MTLResourceOptions` bit 24) has its maximum protection lowered to read (`mach_vm_protect` -//! with `set_maximum`), as Metal's alias of a read-only replace of several ranges is -//! (measured: current and maximum protection read). The GPU's writes never reach such pages, -//! and the command buffer completes: later commands of the same command buffer read what it -//! wrote, and a later command buffer the guest's bytes, as under a read-only replace on Metal -//! (blit fills, measured on Metal, which `tests/detach_backing.rs` holds this platform to; -//! kernel stores are dropped alike on Metal). On Linux the runtime makes the object over a copy -//! of such an alias's pages, or of a no-copy object's pages made with bit 24 or mapped read-only, -//! whose GPU writes it drops, as the views' gate refuses read-only pages -//! (`crate::os::import_view`): a shader's, a blit's into a buffer and a visibility result's are -//! sent, and dropped as Metal's are, while a pass's store into the object's memory and a write of -//! a texture over it are answered where they are encoded ([`Backing::read_only_now`], -//! `crate::gpu::writes`). -//! - **Detach** marks the object detached; its `contents` and its GPU address stay, as Metal's do -//! (measured: `contents` stays the alias of the last replace, still over its pages). A -//! submission of a command buffer that uses it fails while it is detached, as do those of -//! command buffers made before it was released detached ([`submission_check`], -//! `crate::gpu::command`'s docs). A command that names the object, encoded before a replace, -//! and whose command buffer is first submitted after it (committed after it, or committed -//! before it and held behind an event wait), reaches the new pages as Metal's does where the -//! runtime encodes its compute, blit or render encoder again from its calls; in an encoder it -//! cannot (a compute encoder of the runtime's command predication that shares its unit, holds -//! a loop or leaves work out, which no record of ours reaches, a render pass that executes an -//! indirect command buffer or whose end captured its draws' tile reach, one with a call that -//! answers otherwise than at its encoding) it fails, as the runtime resolved the use as the -//! command was encoded -//! (`CommandBufferError::EncodedUseRebound`): that dies where its failure is first read -//! (`crate::gpu::command`), where Metal runs the command over the pages the object lies in as -//! it submits. The runtime decides each of the command buffer's -//! submissions as it submits it, after the submission check, so one the check fails keeps its -//! code: a use detached behind a wait, in the first submission or a later one (an event's -//! split), fails with code 8, as Metal's (`tests/detach_backing.rs`). A rebound use in a later -//! submission dies all the same, the command buffer keeping that code, where Metal runs it over -//! the new pages. One submitted before keeps the pages it had, as Metal's does. Detaching a -//! buffer placed in a heap over address ranges detaches the heap, as Metal's does (measured): -//! every resource placed in it fails from then on, and a replace of the placed buffer answers -//! NO, leaving the heap detached. A heap made over no address ranges, and a buffer placed in -//! one, never detach: Metal answers NO to the detach and to a replace, and their command -//! buffers run (measured, `tests/detach_backing.rs`). Core detaches neither: its detached -//! buffers are no-copy buffers of their own, and its detached heaps placement heaps over -//! address ranges. Any other detach succeeds but one in flight (below), and detaching a -//! detached object is no change. -//! - **No memory while detached.** A detach is the runtime's (`detach_backing`): the -//! object lies in no memory until a replace gives it some, so the runtime holds the memory it -//! was over no more, the guest's pages a replace gave it or what it was made over (core's -//! temporary allocation, which core makes its detached buffers and heaps over and detaches at -//! once). The detach ends the object's use: a command that reaches it without naming it (an -//! address a kernel loads), which no submission check sees, reads 0 and its writes are dropped, -//! the command buffer completing with no error, until a command buffer uses the object after a -//! replace, where it would reach pages the guest has given up, or core's memory. Metal answers -//! so too: a detached buffer, used or not, replaced or not, and a buffer placed in a detached -//! heap, reached through an indirect command's buffer address or a loaded pointer, read 0 and -//! drop the write, the command buffer completing with no error (measured on the M3 Max, macOS -//! 26.7: through a loaded pointer in `tests/detach_backing.rs`'s `detached_reach` and -//! `never_replaced`, which hold this platform to it, and through an indirect command's buffer -//! address by a probe outside the tree). No memory is imported for it, so nothing the GPU writes -//! there is kept on any host. A texture over the object's bytes stays, and presents a stand-in of -//! its image's plan, zero bytes, until they lie in pages again (after Metal's answer measured on -//! an M4: such a texture reads zero bytes and drops its writes). Where a texture over the bytes -//! has no exact stand-in (a multisample or multi-planar one, or one with a depth or decoded twin) -//! or is being made, the runtime refuses the detach, and the process ends there -//! ([`refused_detach`]). `contents` stays what it was: the alias of the last replace, or of the -//! ranges a heap was made over, or the memory a no-copy buffer was made over ([`Own`]), which the -//! detach does not free: Metal runs a no-copy buffer's deallocator at its first replace, inside -//! the call, or as it is destroyed, never at a detach, so the run the runtime hands over as it -//! lets go of the memory at the detach waits until then ([`Held`]). A buffer neither replaced nor -//! made over memory of the caller's by `newBufferWithDescriptor:` (one of the device's own -//! memory, one made on a surface, one `newBufferWithBytesNoCopy:` made) dies at the detach, where -//! what Metal's `contents` answers and when it runs the deallocator are not measured; core -//! detaches none. A replace's rebind ends the use too, as Metal's replace does, so after it such -//! a command reads 0 and drops the write until a command buffer uses the object again, and then -//! reaches its new pages (measured on Metal so: a buffer or a heap used, detached and replaced; -//! `tests/detach_backing.rs` holds this platform to it). A command buffer not yet committed that -//! used the object, its encoder ended or still open, leaves the detach as it is: it fails with -//! code 8 as it is submitted, and a command that reaches the object unnamed meanwhile reads 0, as -//! on Metal (measured, `tests/detach_backing.rs`'s `held`). The runtime resolves what a command -//! buffer reaches unnamed as it is first submitted, so one committed before the detach and -//! submitted after it reads 0 there too, and one submitted before it keeps the pages it reached -//! until it completed, as Metal's does. -//! - **In flight.** Metal answers NO to a detach, and the object stays attached, while a command -//! buffer submitted and not yet completed took it (a command that named it, a buffer placed in -//! the heap included, or made it resident): a heap's at once, a buffer's once each such command -//! buffer completed, the call blocking until then. A buffer's answer after that wait is a race -//! in the kernel's one call, NO in most runs and YES in some (13 of 150 on 2026-10-11); a heap's -//! is always NO (measured on the M3 Max, macOS 26.7, 25G229, `tests/detach_backing.rs`'s -//! `in_flight` and `expected_in_flight`). This platform answers NO, one of Metal's two. -//! -//! Once the command buffer completed, Metal lets go of what it took as it processes the -//! completion, which races the start of its completed handlers, unseen by any caller: a detach -//! made before then answers NO, one made after YES (measured on the M3 Max, macOS 27.0.1, -//! 26A434, 2026-10-23, a heap's and a buffer's, used by a blit fill, a kernel's write, a -//! `useResource:` or a draw, by a probe outside the tree; `tests/detach_backing.rs`'s -//! `in_a_completed_handler`). Made at once in the first or a second completed handler, a detach -//! answered NO in 257 of 1132 runs, from 1 in 50 to 40 in 40 per batch, the odds moving with -//! the host's load from one minute to the next, in the same layouts and with the same work in -//! the process (197 of 200 on macOS 26.7); and YES in all 134 where a draw used the object. -//! Made 20 µs or more into the handler, it answered YES in all 684 runs; with 32 command -//! buffers queued before and after this one, from 100 µs in (all 152; NO in 17 of 40 at 60 µs). -//! Every NO detached when made again, 10 to 101 µs later, within 117 µs of the handler's start -//! (all 467). Made on another thread as `waitUntilCompleted` returned, a detach answered NO in -//! 21 of 184 runs (9 of 200 on macOS 26.7, and none of 200 made 2 ms later). A command buffer -//! that completes with an error, its status `Error`, is let go of before its completed handlers -//! run: Metal answers YES to a detach made in its completed handler, whether the encoders that -//! took the object ran or ran nothing (measured on the M3 Max, macOS 27.0.1, 26A434: 2796 of -//! 2800 detaches of a heap's and a buffer's, in command buffers failed with code 1 or 16 by -//! protection options and with code 8 by a detached use; `tests/detach_backing.rs`'s -//! `expected_in_a_failed_completed_handler`). So once a command buffer completed, YES is one -//! of Metal's answers at every moment, and NO only at its handlers' start, by a race. -//! -//! The runtime's own detach answers NO while the work of a submission that took the object has -//! not completed, and lets go of what a command buffer's submissions took as it processes its -//! completion, before its completed handlers run, failed or not (the runtime's `detach.rs` and -//! `CommandBufferShared::complete`). This platform answers first: each submission the runtime submits is noted with -//! its encoders as its check decides it ([`Opened::submit`]), until the command buffer closes, -//! after its completed handlers ran; a detach asks the runtime what those encoders use -//! ([`in_flight`]), of the command buffers with a submission noted since the object was made -//! alone that have not completed, their status neither `Completed` nor `Error`, which the runtime -//! sets before it runs the completed handlers; a buffer's waits by reading it until each such -//! command buffer completed. One Metal's GPU fails at its commit for what its encoders did is -//! noted nowhere, as it is committed with no check (`crate::gpu::command`). Where none took it, -//! the runtime's detach answers, by its rule over what it holds, a NO of its own answered as -//! Metal's NO, the object attached: a detach made once a command buffer completed, in its -//! completed handlers or after, answers YES, whichever of its submissions took the object, and -//! whether it completed or failed, those of encoders its commit failed included: Metal's answer -//! later in the handlers and in a failed one's, and one of its two at their start -//! (`tests/detach_backing.rs`'s `in_a_completed_handler`). Core never reads the answer: after a NO, its next -//! prepare has the replace answer NO, which raises (`BufferBackingRefused`, -//! `HeapBackingRefused`), and a command buffer that uses the object before it runs. The GPU's own -//! failures (a hang, a fault, a victim of its recovery), which no test here may run, follow the -//! failed command buffer's rule unmeasured. A detach made while a command buffer that fails is in -//! flight is unmeasured too, and answers as for any other. +//! takes others, and this platform takes them as Metal does (measured on the M3 Max, macOS 26.7, +//! `tests/address_ranges.rs`'s `unaligned`): ranges whose bytes follow on from the previous +//! range's are one run of bytes, and each run of bytes takes the pages it lies in, whole, from +//! the page of its first byte through the page of its last ([`spans`]). A range of part of a +//! page takes all of it, the page's bytes past the range included (the CPU and the GPU read +//! them, and the GPU's fill writes them), and a later range starting off its page takes it from +//! the page's start. A first range starting off its page dies where it is given +//! ([`off_the_page`]): Metal's `contents` answers its bytes from the range's own address, and +//! its GPU reads and writes them from its page's start, which no alias gives at once. +//! - **Read-only.** A read-only alias (of an object made with `MTLResourceOptions` bit 24) has +//! its maximum protection lowered to read (`mach_vm_protect` with `set_maximum`), as Metal's +//! alias of read-only memory over several ranges is (measured: current and maximum protection +//! read). The GPU's writes never reach such pages, and the command buffer completes: later +//! commands of the same command buffer read what it wrote, and a later command buffer the +//! guest's bytes, as on Metal (blit fills, measured on Metal; kernel stores are dropped alike +//! on Metal). On Linux the runtime makes the object over a copy of such an alias's pages, or of +//! a no-copy object's pages made with bit 24 or mapped read-only, whose GPU writes it drops, as +//! the views' gate refuses read-only pages (`crate::os::import_view`): a shader's, a blit's +//! into a buffer and a visibility result's are sent, and dropped as Metal's are, while a pass's +//! store into the object's memory and a write of a texture over it are answered where they are +//! encoded ([`Backing::read_only_now`], `crate::gpu::writes`). //! //! What Metal answers, measured on the M3 Max (macOS 26.7, 25G229), and this platform with it: -//! - **A replace** answers NO, and leaves the object detached, for an attached object, an empty -//! array, a NULL or unmapped range, a range with a page mapped without access, and ranges -//! whose lengths total other than the buffer's length or the heap descriptor's size (a heap of -//! descriptor size 0x4010, size 0x8000, takes ranges of 0x4010 bytes, and neither 0x4000 nor -//! 0x8000; a buffer of two pages refuses a range of 0x1000 bytes, or of a page and 0x40 bytes, -//! before one of a page or two, whose pages would fill it). One that answers YES keeps the -//! object's GPU address, and runs the deallocator of a buffer's memory before it inside the -//! call (this platform's runtime once no committed command buffer still uses it). //! - **A heap over address ranges** is made over ranges of any total, shorter or longer than its //! size: this platform's heap takes the ranges' pages up to its size, and zero-filled pages of //! its own past them. None is made over an empty array or a NULL or unmapped range, or one -//! with a page mapped without access, past its size too, nor of size 0. Read-only pages make one, -//! and replace, read-only or not (`tests/detach_backing.rs`, `pages_without_access`). +//! with a page mapped without access, past its size too, nor of size 0. Read-only pages make +//! one, read-only or not (`tests/address_ranges.rs`, `pages_without_access`). //! - **`contents`** answers the alias: the bytes are the guest's either way, and the address is -//! the host's alone. Metal's differs in where it points: a buffer replaced by one range answers -//! that range's own address (writable whatever `readOnly:` says), and the buffers of a heap -//! made over one range, as core makes its heaps, answer their offsets in that range after any -//! replace, over its pages and not the replacing ones; core frees that range after the heap's -//! first replace. A CPU read through such a heap buffer's `contents` after a replace (a texture -//! filled from its bytes) reads the guest's bytes here, where Metal reads memory core has -//! freed. +//! the host's alone. Metal's differs in where it points: the buffers of a heap made over one +//! range answer their offsets in that range. -use std::collections::{BTreeMap, BTreeSet, VecDeque}; -use std::num::NonZeroU64; use std::ptr::NonNull; -use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Weak}; use crate::core::host::HostPtr; use crate::core::num::ToU64; use crate::core::platform::os::vm::{HostVm, KernReturn, VmProt}; use crate::core::platform::types::ResourceAddressRange; -use crate::core::raise::RaiseResult; -use crate::core::raise::death::{DeathId, DeathKind, fatal_with_detail}; use crate::core::rt::BlockEnv; use crate::core::sync::Mutex; use metal2vulkan_runtime as rt; @@ -201,159 +62,35 @@ use metal2vulkan_runtime as rt; use crate::answer::unrepresentable; use crate::os::OsVm; -/// `replaceBackingWithRanges:readOnly:`. -pub(crate) const REPLACE: &str = "replaceBackingWithRanges:readOnly:"; - -/// `detachBacking`. -const DETACH: &str = "detachBacking"; - /// The runtime rounds a heap's size up to a multiple of this (16 KiB), and the heap's memory /// covers all of it. pub(crate) const HEAP_GRANULE: u64 = 0x4000; -/// Whether a buffer or heap is detached (`detachBacking`), and the read-only bit it was made -/// with, which every alias it takes keeps. Core sends one object's detaches and replaces one at a -/// time. While it is detached, and once it is released detached, the submissions that use it -/// fail ([`submission_check`]), by its runtime identity. +/// The guest's pages a buffer or heap lies in, and the read-only bit it was made with, which +/// every alias it takes keeps. #[derive(Debug)] pub struct Backing { - detached: AtomicBool, read_only: bool, - /// Whether the object is a heap, whose detach answers NO at once where a command buffer in - /// flight took it; a buffer's waits for each such command buffer first ([`Backing::detach`]). - heap: bool, - /// Its number among the buffers and heaps made ([`MADE`]): a submission noted before it was - /// made never took it ([`in_flight`]). - made: u64, - /// The runtime object's identity, which names it in [`DETACHED`]; `None` for one a detach - /// never detaches: a heap made over no address ranges, and a buffer placed in a heap, whose - /// detach is its heap's (module docs). - id: Option, - /// The memory `contents` stays over while the object is detached. - alias: Mutex, - /// Whether the memory the object lies in now is read-only where the runtime does not import - /// read-only memory as it is mapped ([`crate::os::COPIES_READ_ONLY`]): the alias of a - /// read-only replace, or of the ranges a heap was made over with bit 24, or the memory a - /// no-copy buffer or heap was made over, mapped read-only or made with bit 24; counted while it - /// holds ([`crate::gpu::writes::set_kept`]). + /// Whether the memory the object lies in is read-only where the runtime does not import + /// read-only memory as it is mapped ([`crate::os::COPIES_READ_ONLY`]): the alias of the + /// ranges a heap was made over with bit 24, or the memory a no-copy buffer or heap was made + /// over, mapped read-only or made with bit 24; counted while it holds + /// ([`crate::gpu::writes::set_kept`]). kept: AtomicBool, - /// The guest's pages the object's memory is over, and whether a detach left it in no memory - /// since its last replace, which work encoded reads without the object - /// ([`crate::gpu::writes::Kept`]). + /// The guest's pages the object's memory is over, which work encoded reads without the + /// object ([`crate::gpu::writes::Kept`]). pages: Arc, } -/// The memory a buffer's or heap's `contents` stays over while a detach left it in no memory -/// ([`Pages::zeroed`]): the alias of its last replace, or of the address ranges a heap was made -/// over ([`Alias`]), which the runtime holds until the object is detached or rebound and no -/// command buffer submitted uses it, and [`Backing`] until another takes its place; or the memory -/// a no-copy buffer was made over ([`Own`]), until its first replace. -#[derive(Debug, Default)] -struct Aliased { - /// The alias of the last replace, or the one a heap over address ranges was made over; - /// `None` for a buffer never replaced. - last: Option>, - /// The memory of the caller's a no-copy buffer was made over, until its first replace; - /// `None` for any other object. - own: Option, -} - -/// The memory of the caller's a no-copy buffer was made over (`newBufferWithDescriptor:`, as core -/// makes its detached buffers over a temporary allocation): its first byte, which `contents` -/// answers while the buffer is detached, as Metal's stays, and the hold on the run of its -/// deallocator ([`Held`]). -#[derive(Debug)] -pub(crate) struct Own { - /// The first byte. - at: NonNull, - held: Arc, -} - -// SAFETY: `at` is an address only, which nothing here reads through: it is answered as -// `contents`. -unsafe impl Send for Own {} - -// SAFETY: as for `Send`. -unsafe impl Sync for Own {} - -impl Own { - /// The memory of `at`, whose deallocator's run, which the runtime makes once it lets go of - /// the memory, goes through `held`. - pub(crate) fn new(at: NonNull, held: Arc) -> Own { - Own { at, held } - } -} - -/// The run of a no-copy buffer's deallocator. Metal makes it at the buffer's first replace, -/// inside the call, or as the buffer is destroyed, and never at a detach (measured on the M3 Max, -/// macOS 26.7: `tests/detach_backing.rs`'s `buffer_life`). The runtime makes it once it lets go of -/// the memory, which a rebind does, and a detach: so a run the runtime hands over after such a -/// detach is held ([`Held::hold`]) until the replace that follows, or until the buffer is -/// destroyed ([`Held::release`], [`Backing`]'s drop). -#[derive(Default)] -pub(crate) struct Held(Mutex); - -/// Whether [`Held`] holds a run. -#[derive(Default)] -enum Hold { - /// A run handed over is made at once. - #[default] - Runs, - /// A run handed over waits for [`Held::release`]: the run, once handed over. - Holding(Option>), -} - -impl std::fmt::Debug for Held { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let holding = matches!(*self.0.lock(), Hold::Holding(_)); - f.debug_struct("Held").field("holding", &holding).finish() - } -} - -impl Held { - /// The run of the deallocator, which the runtime hands over: made now, or held. - pub(crate) fn run(&self, run: Box) { - let mut hold = self.0.lock(); - if let Hold::Holding(held) = &mut *hold { - *held = Some(run); - return; - } - drop(hold); - run(); - } - - /// A run handed over from now on is held. - fn hold(&self) { - let mut hold = self.0.lock(); - if matches!(*hold, Hold::Runs) { - *hold = Hold::Holding(None); - } - } - - /// A run held is made now, and one handed over later at once. - fn release(&self) { - let held = match std::mem::take(&mut *self.0.lock()) { - Hold::Holding(held) => held, - Hold::Runs => None, - }; - if let Some(run) = held { - run(); - } - } -} - -/// The guest's pages a buffer's or heap's memory is over now, as the host maps them, and whether a -/// detach left it in no memory since its last replace, which its [`Backing`] keeps and work -/// encoded reads without the object ([`crate::gpu::writes::Kept`]): a reference that revived a -/// heap or buffer could run its release on the thread that reads. +/// The guest's pages a buffer's or heap's memory is over, as the host maps them, which its +/// [`Backing`] keeps and work encoded reads without the object ([`crate::gpu::writes::Kept`]): a +/// reference that revived a heap or buffer could run its release on the thread that reads. #[derive(Debug, Default)] pub struct Pages { /// The pages. paged: Mutex, - /// Whether a detach left the object in no memory since its last replace, where the GPU reads - /// zeros through it: written with `paged` locked, and read without it, as each bind asks. - zeroed: AtomicBool, - /// Whether it is over the guest's pages now: `paged` has pages and it is not zeroed. + /// Whether it is over the guest's pages: `paged` has pages. Written with `paged` locked, and + /// read without it, as each bind asks. guests: AtomicBool, } @@ -361,7 +98,7 @@ pub struct Pages { #[derive(Debug, Default)] struct Paged { /// The guest's pages, as the host maps them (each a first byte and an end): those of the - /// object's last replace, or of the address ranges a heap was made over. + /// address ranges a heap was made over. pages: Vec>, /// Where each of `pages` ends in the object's bytes, laid out over them in their order: the /// lengths up to it added up, so the run holding an object's byte is found by a search, not @@ -417,27 +154,18 @@ impl Pages { let guests = !pages.is_empty(); let mut paged = self.paged.lock(); *paged = Paged::of(pages); - self.zeroed.store(false, Ordering::Release); self.guests.store(guests, Ordering::Release); } - /// A detach left the object in no memory: the GPU reads zeros through it, and its writes - /// reach no guest page. - fn zero(&self) { - let _paged = self.paged.lock(); - self.zeroed.store(true, Ordering::Release); - self.guests.store(false, Ordering::Release); - } - - /// The host memory of the object's bytes `bytes` in the guest's pages it is over now, read - /// under its lock with no copy of the pages; `None` for one over memory of its own, or - /// detached, answered without the lock. + /// The host memory of the object's bytes `bytes` in the guest's pages it is over, read under + /// its lock with no copy of the pages; `None` for one over memory of its own, answered + /// without the lock. fn in_pages(&self, bytes: &std::ops::Range) -> Option>> { if !self.guests.load(Ordering::Acquire) { return None; } let paged = self.paged.lock(); - (!self.zeroed() && !paged.pages.is_empty()).then(|| paged.in_runs(bytes)) + (!paged.pages.is_empty()).then(|| paged.in_runs(bytes)) } /// Whether [`Pages::in_pages`] finds any memory of `bytes`, read as it reads it, with nothing @@ -447,147 +175,29 @@ impl Pages { return None; } let paged = self.paged.lock(); - (!self.zeroed() && !paged.pages.is_empty()).then(|| paged.meets(bytes)) - } - - /// Whether a detach left the object in no memory since its last replace. - pub(crate) fn zeroed(&self) -> bool { - self.zeroed.load(Ordering::Acquire) + (!paged.pages.is_empty()).then(|| paged.meets(bytes)) } } impl Backing { - /// The attached backing of the runtime buffer `id`, over the memory it was made with; - /// `read_only` for one made with `MTLResourceOptions` bit 24. - pub(crate) fn new(read_only: bool, id: rt::ObjectId) -> Backing { - Backing::of(read_only, false, id) - } - - /// The attached backing of the runtime heap `id`, made over address ranges, as - /// [`Backing::new`]'s. - pub(crate) fn heap(read_only: bool, id: rt::ObjectId) -> Backing { - Backing::of(read_only, true, id) - } - - /// The attached backing of the runtime buffer or `heap` `id`. - fn of(read_only: bool, heap: bool, id: rt::ObjectId) -> Backing { + /// The backing of a buffer or heap over the memory it was made with; `read_only` for one + /// made with `MTLResourceOptions` bit 24. + pub(crate) fn new(read_only: bool) -> Backing { Backing { - detached: AtomicBool::new(false), read_only, - heap, - made: MADE.fetch_add(1, Ordering::SeqCst), - id: Some(id), - alias: Mutex::new(Aliased::default()), kept: AtomicBool::new(false), pages: Arc::default(), } } - /// The backing of an object a detach never detaches: it stays attached, and a replace - /// answers NO, as Metal's does (module docs). - pub(crate) fn fixed() -> Backing { - Backing { - detached: AtomicBool::new(false), - read_only: false, - heap: false, - made: 0, - id: None, - alias: Mutex::new(Aliased::default()), - kept: AtomicBool::new(false), - pages: Arc::default(), - } - } - - /// `detachBacking` of the object, which `detach`, the runtime's detach of its runtime object - /// (`detach_backing`), detaches: the object is detached from now on, but for one that never - /// detaches ([`Backing::fixed`]), and one a command buffer submitted and not yet completed - /// took, which stays attached, Metal's NO: a heap's at once, a buffer's once each such command - /// buffer completed ([`in_flight`], module docs). The runtime's object then lies in no memory, - /// so the GPU no longer reaches the memory it was over through it, the guest's pages a replace - /// gave it or what it was made over, and a command reaches it unnamed nowhere until a replace; - /// where the runtime refuses that, the process ends here ([`refused_detach`]), and where it - /// answers NO, holding what a submission whose work has not completed took (one submitted as - /// the detach is made), it stays attached. A buffer neither replaced nor made over memory of the caller's by - /// `newBufferWithDescriptor:` dies here ([`unmeasured_detach`]). - pub(crate) fn detach(&self, detach: impl FnOnce() -> Result) { - let Some(id) = self.id else { - return; - }; - if self.is_detached() { - return; - } - let held = { - let aliased = self.alias.lock(); - match (&aliased.last, &aliased.own) { - (None, None) => unmeasured_detach(), - // A buffer never replaced: the run of its deallocator, which the runtime hands - // over as it lets go of the memory, waits for the first replace or the release. - (None, Some(own)) => Some(Arc::clone(&own.held)), - (Some(_), _) => None, - } - }; - let takers = in_flight(id, self.made); - if !takers.is_empty() { - if !self.heap { - takers.iter().for_each(completed); - } - return; - } - if let Some(held) = &held { - held.hold(); - } - match detach() { - Ok(true) => {} - Ok(false) => { - if let Some(held) = held { - held.release(); - } - return; - } - Err(refused) => fatal_with_detail( - DeathId::Platform { - kind: DeathKind::Abort, - call: DETACH, - }, - &refused_detach(&refused), - ), - } - self.detached.store(true, Ordering::Release); - DETACHED.detached(id); - self.pages.zero(); - } - - /// Where the object's `contents` stays while it is detached: the first byte of the alias of - /// its last replace or of the ranges a heap was made over, or of the memory a no-copy buffer - /// was made over, which it had when it was detached ([`Backing::detach`]); `None` for one - /// attached, whose runtime object answers. - pub(crate) fn kept_contents(&self) -> Option> { - if !self.pages.zeroed() { - return None; - } - let aliased = self.alias.lock(); - match (&aliased.last, &aliased.own) { - (Some(alias), _) => Some(alias.at), - (None, Some(own)) => Some(own.at), - (None, None) => None, - } - } - - /// The object, a heap, was made over `alias`, the alias of `ranges` of the guest's pages - /// ([`Backing::in_pages`]), which its `contents` stays over while it is detached: read-only - /// where it was made with bit 24 ([`gather`]). - pub(crate) fn made_over(&self, ranges: &[ResourceAddressRange], alias: Option>) { - let kept = crate::os::COPIES_READ_ONLY && alias.is_some() && self.read_only; - self.alias.lock().last = alias; + /// The object, a heap, was made over the alias of `ranges` of the guest's pages + /// ([`Backing::in_pages`]), read-only where it was made with bit 24 ([`gather_or_nil`]). + pub(crate) fn made_over(&self, ranges: &[ResourceAddressRange]) { + let kept = crate::os::COPIES_READ_ONLY && self.read_only; crate::gpu::writes::set_kept(&self.kept, kept); self.pages.set(pages(ranges)); } - /// The object, a no-copy buffer, was made over `own`, memory of the caller's. - pub(crate) fn made_over_own(&self, own: Own) { - self.alias.lock().own = Some(own); - } - /// The object, a no-copy buffer or heap, was made over memory of the caller's that is /// read-only where `read_only` (mapped so, [`crate::os::ImportView::read_only`], or made with /// bit 24): its memory is read-only then, and where it was made with bit 24 @@ -597,28 +207,26 @@ impl Backing { crate::gpu::writes::set_kept(&self.kept, kept); } - /// Whether the memory the object lies in now is read-only where the runtime does not import + /// Whether the memory the object lies in is read-only where the runtime does not import /// read-only memory as it is mapped (on Linux, [`crate::os::COPIES_READ_ONLY`]): it makes the /// object over a copy of it, dropping the GPU's writes, where Metal's GPU keeps them from the - /// memory itself and faults a pass that stores into it; not while it is detached, in no - /// memory. + /// memory itself and faults a pass that stores into it. pub(crate) fn read_only_now(&self) -> bool { - self.kept.load(Ordering::Acquire) && !self.pages.zeroed() + self.kept.load(Ordering::Acquire) } - /// [`Backing::read_only_now`], asked again as work that may write through a texture over the + /// [`Backing::read_only_now`], asked as work that may write through a texture over the /// object is encoded ([`crate::gpu::writes::Kept`]). pub(crate) fn kept(&self) -> crate::gpu::writes::Kept { match self.read_only_now() { - true => crate::gpu::writes::Kept::Until(Arc::clone(&self.pages)), + true => crate::gpu::writes::Kept::Copied(Arc::clone(&self.pages)), false => crate::gpu::writes::Kept::No, } } - /// The host memory of the object's bytes `bytes` in the guest's pages its memory is over now, - /// as the host maps them (each a first byte and an end): those of its last replace, or of the - /// address ranges a heap was made over; `None` for one over memory of its own, or detached, - /// whose writes reach no guest page ([`Pages::in_pages`]). + /// The host memory of the object's bytes `bytes` in the guest's pages its memory is over, as + /// the host maps them (each a first byte and an end): those of the address ranges a heap was + /// made over; `None` for one over memory of its own ([`Pages::in_pages`]). pub(crate) fn in_pages( &self, bytes: &std::ops::Range, @@ -632,468 +240,19 @@ impl Backing { self.pages.meets_pages(bytes) } - /// Whether a detach detaches the object: a buffer not placed in a heap, or a heap made over - /// address ranges; not one [`Backing::fixed`] made. - pub(crate) fn detaches(&self) -> bool { - self.id.is_some() - } - - /// Whether the object is detached. - pub(crate) fn is_detached(&self) -> bool { - self.detached.load(Ordering::Acquire) - } - - /// `replaceBackingWithRanges:readOnly:` of an object whose ranges must total `length` bytes - /// (a buffer's length, a heap descriptor's size) and whose runtime object covers `size` - /// (its length, the heap's size): NO for an attached object, ranges of another total, and - /// ranges [`gather`] cannot alias, as Metal answers; else `rebind` gives the runtime's object - /// the alias, and YES. The alias is freed by its keep-alive, which a refused `rebind` drops - /// at once. A no-copy buffer's first YES runs its deallocator inside the call, as Metal's - /// does, where the runtime let go of the memory it was made over ([`Held`]). - pub(crate) fn replace( - &self, - ranges: &[ResourceAddressRange], - read_only: bool, - length: u64, - size: u64, - rebind: impl FnOnce(NonNull, rt::KeepAlive, crate::os::ImportMade) -> RaiseResult<()>, - ) -> RaiseResult { - if !self.is_detached() || total(ranges) != Some(length) { - return Ok(false); - } - let Some(alias) = gather(REPLACE, ranges, size, read_only || self.read_only) else { - return Ok(false); - }; - let alias = Arc::new(alias); - let (first, keep, made) = Arc::clone(&alias).into_runtime(ImportSite::Replace); - rebind(first, keep, made)?; - let own = { - let mut aliased = self.alias.lock(); - let kept = crate::os::COPIES_READ_ONLY && (read_only || self.read_only); - crate::gpu::writes::set_kept(&self.kept, kept); - aliased.last = Some(alias); - self.pages.set(pages(ranges)); - aliased.own.take() - }; - // The memory the buffer was made over goes now, inside the call, as Metal's does. - if let Some(own) = own { - own.held.release(); - } - self.detached.store(false, Ordering::Release); - if let Some(id) = self.id { - DETACHED.attached(id); - } - Ok(true) + /// Whether the object is over the guest's pages: a heap made over address ranges. + pub(crate) fn over_guest_pages(&self) -> bool { + self.pages.guests.load(Ordering::Acquire) } } impl Drop for Backing { - /// The object's release: the command buffers made before it that use it, detached, still - /// fail. The runtime object may go before or after: no other object takes its identity. A - /// no-copy buffer never replaced runs its deallocator now where a detach held the run, as - /// Metal's runs it as the buffer is destroyed ([`Held`]). + /// The object's release: its memory is read-only no longer ([`crate::gpu::writes::set_kept`]). fn drop(&mut self) { - if self.is_detached() - && let Some(id) = self.id - { - DETACHED.released(id); - } - let own = self.alias.lock().own.take(); - if let Some(own) = own { - own.held.release(); - } crate::gpu::writes::set_kept(&self.kept, false); } } -/// The `MTLCommandBufferError` code of a submission that uses a detached buffer or heap: -/// `MTLCommandBufferErrorOutOfMemory`, as Metal fails it (module docs of -/// [`crate::gpu::command`]). -pub(crate) const DETACHED_USE: u64 = 8; - -/// The detached objects, the command buffers they may fail, and those open. -static DETACHED: Registry = Registry::new(); - -/// How many buffers and heaps a detach may detach were made ([`Backing::new`], -/// [`Backing::heap`]): each takes the count before it as its number, and a submission notes the -/// count as it is checked ([`Submitted::made`]). A command takes an object only once the object -/// was made, so a submission noted with a count of at most an object's number never took it. -static MADE: AtomicU64 = AtomicU64::new(0); - -/// [`Detached`], under its lock, and what a submission reads of it without the lock, each -/// written under the lock as it changes: whether an object is detached, and the latest release -/// kept, so a command buffer no object can fail takes no lock of the process's; and the most of -/// [`MADE`] a submission noted, so a detach of an object made since takes none either. -#[derive(Debug)] -struct Registry { - /// How many objects are detached now: the length of [`Detached::detached`]. - detached: AtomicUsize, - /// The number of the latest release [`Detached::releases`] keeps, plus one; 0 for none. - latest: AtomicU64, - /// The most of [`MADE`] a submission noted ([`Submitted::made`]), taken before the note is - /// written, under its command buffer's lock: a detach of an object made as the count reached - /// it, or after, finds no command buffer that took it ([`in_flight`]). - noted: AtomicU64, - state: Mutex, - /// For tests: run in [`Registry::released`] between its stores of `latest` and `detached`, - /// where a reader without the lock may run. - #[cfg(test)] - between: Option, -} - -/// The objects detached now and those released detached since the oldest open command buffer -/// was made, and the open command buffers, numbered in one sequence of makes and releases. An -/// object is named by its runtime identity ([`rt::Buffer::object_id`], [`rt::Heap::object_id`]), -/// which no other object ever takes, as the runtime lists a command's uses -/// ([`rt::UsedResources`]): a buffer not placed in a heap, or a heap. `released` holds an object -/// at most once, so it grows at most to the objects released while the oldest open command buffer -/// stays open; whether a command buffer can fail by one is read from the latest alone, in -/// constant time, as each submission asks it ([`Registry::any`]). -#[derive(Debug)] -struct Detached { - /// The next number of the sequence. - next: u64, - /// The objects detached now. - detached: BTreeSet, - /// The objects released detached: the number of the release. A command buffer made before - /// it may hold a use of the object. - released: BTreeMap, - /// The releases of `released`, in the order of their numbers, the oldest first. - releases: VecDeque<(u64, rt::ObjectId)>, - /// The open command buffers, by number, until they close ([`Opened`]). - open: BTreeMap>, -} - -/// An open command buffer ([`Opened`]): its number, and what the runtime submitted of it. -#[derive(Debug)] -struct Open { - /// Its number in the sequence of [`Detached`]. - number: u64, - /// Its submissions the runtime submitted, until it closes: each decided and noted under this - /// lock ([`Opened::submit`]), which a detach reads them under ([`in_flight`]), a note for - /// each part of it the platform committed apart ([`Opened::next_part`]). A note holds its - /// part's command buffer, which holds its check, which holds this: the part's close takes it. - submitted: Mutex>, - /// The places of its parts not yet closed ([`Opened`]): it closes with the last. - parts: AtomicUsize, -} - -/// A command buffer whose submissions the runtime submitted, until it closes ([`Opened`]): it, -/// and the encoders of each submission, by their places among its ended encoders -/// ([`rt::Submission::encoders`]). -#[derive(Debug)] -struct Submitted { - /// Which part of the command buffer it is, the first 0 ([`Opened::next_part`]). - part: usize, - cb: rt::CommandBuffer, - encoders: Vec>, - /// The count of [`MADE`] as its latest submission was checked: it took no object made since. - made: u64, -} - -impl Detached { - /// The next number of the sequence. - fn number(&mut self) -> u64 { - let number = self.next; - self.next += 1; - number - } - - /// The objects a command buffer made at `made` fails by where it uses one: those detached - /// now, and those released detached after it was made. - fn failing(&self, made: u64) -> Vec { - let released = (self.released.iter()) - .filter(|&(_, &at)| at > made) - .map(|(&id, _)| id); - self.detached.iter().copied().chain(released).collect() - } -} - -impl Registry { - /// None detached, released or open. - const fn new() -> Registry { - Registry { - detached: AtomicUsize::new(0), - latest: AtomicU64::new(0), - noted: AtomicU64::new(0), - state: Mutex::new(Detached { - next: 0, - detached: BTreeSet::new(), - released: BTreeMap::new(), - releases: VecDeque::new(), - open: BTreeMap::new(), - }), - #[cfg(test)] - between: None, - } - } - - /// A command buffer made now: its place, open until it closes. - fn open(&self) -> Arc { - let mut state = self.state.lock(); - let open = Arc::new(Open { - number: state.number(), - submitted: Mutex::new(Vec::new()), - parts: AtomicUsize::new(1), - }); - state.open.insert(open.number, Arc::clone(&open)); - open - } - - /// Object `id` detached. - fn detached(&self, id: rt::ObjectId) { - let mut state = self.state.lock(); - state.detached.insert(id); - self.detached.store(state.detached.len(), Ordering::SeqCst); - } - - /// Object `id`, detached, replaced: attached again. A command buffer committed before the - /// replace that names it fails in the runtime, which resolved the use as it was encoded - /// (module docs). - fn attached(&self, id: rt::ObjectId) { - let mut state = self.state.lock(); - state.detached.remove(&id); - self.detached.store(state.detached.len(), Ordering::SeqCst); - } - - /// Object `id` released detached: kept while a command buffer is open, which may have been - /// made before it. The release is stored before the count of the objects detached: a reader - /// without the lock that sees the object no longer detached sees it released, so a command - /// buffer open before the release can fail by the object at every moment ([`Registry::any`]), - /// and no close forgets the release while that command buffer is open. - fn released(&self, id: rt::ObjectId) { - let mut state = self.state.lock(); - state.detached.remove(&id); - let number = state.number(); - if !state.open.is_empty() { - state.released.insert(id, number); - state.releases.push_back((number, id)); - self.latest.store(number + 1, Ordering::SeqCst); - } - #[cfg(test)] - if let Some(between) = self.between { - between(self); - } - self.detached.store(state.detached.len(), Ordering::SeqCst); - } - - /// Whether a command buffer made at `made` can fail by any object: one is detached, or the - /// latest release kept came after it. Read without the lock, the count of the objects - /// detached first, in the order opposite to [`Registry::released`]'s stores. - fn any(&self, made: u64) -> bool { - self.detached.load(Ordering::SeqCst) > 0 - || self.latest.load(Ordering::SeqCst) > made.saturating_add(1) - } - - /// The objects a command buffer made at `made` fails by where it uses one - /// ([`Detached::failing`]). - fn failing(&self, made: u64) -> Vec { - self.state.lock().failing(made) - } - - /// Whether a command buffer made at `made` fails where it uses any of `ids`, as the runtime - /// answers of what it uses and [`Registry::failing`] ([`Opened::submit`]). - #[cfg(test)] - fn fails(&self, ids: &[rt::ObjectId], made: u64) -> bool { - let failing = self.failing(made); - ids.iter().any(|id| failing.contains(id)) - } - - /// Command buffer `number` closed: the releases no open command buffer was made before are - /// forgotten. Its place is answered, to be let go of - /// without the lock. - fn closed(&self, number: u64) -> Option> { - let mut state = self.state.lock(); - let open = state.open.remove(&number); - let oldest = state.open.keys().next().copied().unwrap_or(u64::MAX); - while let Some(&(at, id)) = state.releases.front() - && at <= oldest - { - state.releases.pop_front(); - state.released.remove(&id); - } - if state.releases.is_empty() { - self.latest.store(0, Ordering::SeqCst); - } - open - } - - /// The open command buffers with a submission noted when `made` buffers and heaps had been - /// made, or more ([`Submitted::made`]): each, and the encoders of its submissions. - fn noted_since(&self, made: u64) -> Vec<(rt::CommandBuffer, Vec>)> { - if self.noted.load(Ordering::SeqCst) <= made { - return Vec::new(); - } - let open: Vec> = self.state.lock().open.values().cloned().collect(); - // Read under each command buffer's lock, without the registry's. - open.iter() - .flat_map(|open| { - let submitted = open.submitted.lock(); - (submitted.iter()) - .filter(|s| s.made > made) - .map(|s| (s.cb.clone(), s.encoders.clone())) - .collect::>() - }) - .collect() - } -} - -/// A command buffer's place in the sequence of [`Detached`], where it was made, open until it -/// drops: when the command buffer is released uncommitted, when it commits with no check, or -/// when it completes, as the runtime then drops its check ([`submission_check`]). The parts of -/// a command buffer the platform commits apart share its place, each open until it closes so, -/// and the place until the last of them closes ([`Opened::next_part`]). -#[derive(Debug)] -pub(crate) struct Opened { - open: Arc, - /// Which part of its command buffer it is the place of, the first 0. - part: usize, -} - -impl Opened { - /// The place of a command buffer made now. - pub(crate) fn new() -> Opened { - Opened { - open: DETACHED.open(), - part: 0, - } - } - - /// The place of the command buffer's next part, which goes on from this one's - /// (`CommandBuffer::split`): the same place, as the parts are one command buffer of Metal's, - /// whose submissions fail by the objects released detached since the first part was made. - pub(crate) fn next_part(&self) -> Opened { - self.open.parts.fetch_add(1, Ordering::SeqCst); - Opened { - open: Arc::clone(&self.open), - part: self.part + 1, - } - } - - /// The submission check of `submission` of the command buffer ([`submission_check`]): it - /// fails with [`DETACHED_USE`] where it uses a buffer or heap detached now, or one released - /// detached since the command buffer was made ([`Detached::failing`]); else it is noted - /// submitted, with its encoders, until the command buffer closes. It is decided and noted at - /// once, under the command buffer's lock, which a detach reads the notes under - /// ([`in_flight`]), so a detach either fails it or sees it. Whether it uses one is asked only - /// where an object could fail it, of the runtime (`rt::Submission::uses`), which lists - /// nothing and holds no handle. - fn submit(&self, submission: &rt::Submission<'_>) -> Option { - let objects = MADE.load(Ordering::SeqCst); - let number = self.open.number; - let mut submitted = self.open.submitted.lock(); - if DETACHED.any(number) && submission.uses(&DETACHED.failing(number)) { - return NonZeroU64::new(DETACHED_USE); - } - DETACHED.noted.fetch_max(objects, Ordering::SeqCst); - let at = match submitted.iter().position(|s| s.part == self.part) { - Some(at) => at, - None => { - submitted.push(Submitted { - part: self.part, - cb: submission.command_buffer().clone(), - encoders: Vec::new(), - made: objects, - }); - submitted.len() - 1 - } - }; - let noted = &mut submitted[at]; - noted.encoders.push(submission.encoders()); - noted.made = noted.made.max(objects); - None - } -} - -impl Drop for Opened { - /// Its part closes, its note let go of; the last part's close closes the place. - fn drop(&mut self) { - let last = self.open.parts.fetch_sub(1, Ordering::SeqCst) == 1; - let open = last.then(|| DETACHED.closed(self.open.number)); - // Let go of without the registry's lock: it holds the command buffer, whose last handle - // it may be. - let submitted = { - let mut submitted = self.open.submitted.lock(); - let at = submitted.iter().position(|s| s.part == self.part); - at.map(|at| submitted.swap_remove(at)) - }; - drop((submitted, open)); - } -} - -/// Whether command buffer `cb`, made at `opened`, fails: it uses a buffer or heap detached now, -/// or one released detached since it was made ([`Detached::failing`]). Asked of the runtime -/// (`rt::CommandBuffer::uses`) only where an object could fail it. -pub(crate) fn uses_detached(cb: &rt::CommandBuffer, opened: &Opened) -> bool { - let number = opened.open.number; - DETACHED.any(number) && cb.uses(&DETACHED.failing(number)) -} - -/// The check of each submission of the command buffer committed as `cb` -/// ([`rt::CommandBuffer::set_submission_check`]), which the runtime runs once the submission's -/// event waits are met, just before it submits it, on the thread that submits it (the -/// committing thread inside its commit, or the runtime's scheduler thread): one that uses a -/// detached buffer or heap, or one released detached since `cb` was made, fails with -/// [`DETACHED_USE`]; any other is noted submitted ([`Opened::submit`]). The runtime drops it, -/// and so closes `cb`, once the command buffer completed, after its completed handlers ran. -pub(crate) fn submission_check(cb: Opened) -> rt::SubmissionCheck { - Arc::new(move |submission: &rt::Submission<'_>| { - // A callout inside the runtime's submission: marked ours, so a panic here aborts. - let _env = BlockEnv::foreign(); - cb.submit(submission) - }) -} - -/// The command buffers submitted and not yet completed that took object `id`, a buffer not -/// placed in a heap or a heap, made as the `made`th of them ([`MADE`]): through a command of a -/// submission the runtime submitted that named it (a buffer placed in the heap included) or made -/// it resident, as the runtime lists what each of its ended encoders uses until it lets go of -/// those uses, after the completed handlers ran ([`rt::CommandBuffer::ended_encoders`]). Only the -/// command buffers with a submission noted since the object was made are asked: none noted -/// before it took it, and none is asked where no submission was noted since -/// ([`Registry::noted_since`]). A submission noted after they were read is decided by the -/// runtime's own detach, which makes the object's uses in submissions after it fail as Metal's -/// do, and answers NO where one submitted before it took the object ([`Backing::detach`]). One -/// that completed, its status `Completed` or `Error` ([`has_completed`]), took nothing, though -/// it stays noted until it closes: Metal lets go of what a command buffer used once it completed, -/// as it starts its completed handlers, and of a failed one's before them (module docs, "In -/// flight"). -fn in_flight(id: rt::ObjectId, made: u64) -> Vec { - // The command buffers not taken are let go of here, under no lock. - (DETACHED.noted_since(made).into_iter()) - .filter(|(cb, _)| !has_completed(cb)) - .filter(|(cb, encoders)| took(cb, encoders, id)) - .map(|(cb, _)| cb) - .collect() -} - -/// Whether `cb`'s ended encoders at `encoders`, those of its submissions the runtime submitted, -/// use object `id` ([`in_flight`]), as the runtime answers it (`rt::CommandBuffer::encoders_use`, -/// which lists nothing). -fn took(cb: &rt::CommandBuffer, encoders: &[std::ops::Range], id: rt::ObjectId) -> bool { - (encoders.iter()).any(|at| cb.encoders_use(at.clone(), &[id])) -} - -/// Whether `cb` completed, its status `Completed` or `Error`, which the runtime sets before it -/// runs its completed handlers: a handler of its own sees it so. -fn has_completed(cb: &rt::CommandBuffer) -> bool { - matches!( - cb.status(), - rt::CommandBufferStatus::Completed | rt::CommandBufferStatus::Error - ) -} - -/// Returns once `cb` completed ([`has_completed`]). The status is read every -/// [`COMPLETION_POLL`]. -fn completed(cb: &rt::CommandBuffer) { - while !has_completed(cb) { - std::thread::sleep(COMPLETION_POLL); - } -} - -/// How often [`completed`] reads a command buffer's status. -const COMPLETION_POLL: std::time::Duration = std::time::Duration::from_micros(100); - /// The host's pages `ranges` lie in, in their order, as an alias of them maps them ([`spans`]), /// each a first byte and an end, those that meet merged. fn pages(ranges: &[ResourceAddressRange]) -> Vec> { @@ -1107,15 +266,8 @@ fn pages(ranges: &[ResourceAddressRange]) -> Vec> { runs } -/// The ranges' lengths added up; `None` past `u64::MAX`. -fn total(ranges: &[ResourceAddressRange]) -> Option { - ranges - .iter() - .try_fold(0u64, |sum, range| sum.checked_add(range.length)) -} - /// A range of this platform's address space whose pages are the guest's, shared, and zeros past -/// them ([`gather`]), freed when it drops; or a range another holder maps, which the alias +/// them ([`gather_or_nil`]), freed when it drops; or a range another holder maps, which the alias /// borrows ([`Alias::borrowing`]): a surface's own view of the guest's pages on Linux, which /// holds the same pages, zeros past them included, and lets the surface's buffers lie over it /// with no second view of its pages (`crate::os::surface_alias`). @@ -1236,14 +388,12 @@ impl Drop for Alias { pub(crate) enum ImportSite { /// A no-copy buffer over host memory core gives (`newBufferWithBytesNoCopy`). NoCopyBytes, - /// A no-copy buffer a descriptor names (a detached buffer). + /// A no-copy buffer a descriptor names (`newBufferWithDescriptor:`). NoCopyDescriptor, /// A buffer over a surface's alias. Surface, /// A heap over guest ranges. Heap, - /// A buffer's replaced backing. - Replace, /// A buffer over a surface, at its base address. SurfaceBase, } @@ -1257,9 +407,8 @@ impl ImportSite { /// each commit would miss while that writer runs. /// /// Elsewhere the runtime copies such memory, dropping the GPU's writes, as Metal drops them: - /// the guest's read-only objects (a replace `readOnly:YES`, a heap over address ranges or a - /// no-copy buffer or heap made with bit 24), and a no-copy buffer or heap over pages mapped - /// read-only. + /// the guest's read-only objects (a heap over address ranges or a no-copy buffer or heap made + /// with bit 24), and a no-copy buffer or heap over pages mapped read-only. pub(crate) fn twins(self) -> bool { matches!(self, Self::Surface) } @@ -1271,14 +420,13 @@ impl ImportSite { Self::NoCopyDescriptor => 2, Self::Surface => 3, Self::Heap => 4, - Self::Replace => 5, Self::SurfaceBase => 6, } } } -/// The trace of the host memory this platform hands the runtime for one no-copy buffer, heap or -/// rebind, with `REIMS_VGPU_TRACE` set ([`crate::core::trace`]): `imp` as its keep-alive is +/// The trace of the host memory this platform hands the runtime for one no-copy buffer or heap, +/// with `REIMS_VGPU_TRACE` set ([`crate::core::trace`]): `imp` as its keep-alive is /// made (the site, the first byte given, its length, the first byte handed over), and `impfree` /// as the keep-alive goes ([`keep_alive`]). It marks each buffer, not each import: a buffer /// made over exactly the bytes a live no-copy buffer was made over lies in that one's import @@ -1400,8 +548,8 @@ pub(crate) fn runs( /// The death at `sel` of address ranges whose first starts at `address`, `into` bytes into its /// page ([`runs`]). Metal's `contents` answers the range's bytes from its own address, and its /// GPU reads and writes them from the start of its page, `into` bytes before it (measured on the -/// M3 Max, macOS 26.7: one range from 0x40 and from 0x1000 into its page, a heap's and a -/// replace's alike, `tests/detach_backing.rs`); a buffer of the runtime's has one address for +/// M3 Max, macOS 26.7: one range from 0x40 and from 0x1000 into its page, a heap's, +/// `tests/address_ranges.rs`); a buffer of the runtime's has one address for /// the CPU and the GPU, the first byte of the memory it imports, so no alias of this platform's /// gives both. fn off_the_page(sel: &'static str, address: u64, into: u64) -> ! { @@ -1422,8 +570,9 @@ fn off_the_page(sel: &'static str, address: u64, into: u64) -> ! { /// unmapped range, one with a page the host maps without read access, which the runtime refuses /// to import, past `size` too). Where the host refuses the alias what it needs past those checks /// (address space, a remap of the guest's pages, which on Linux takes pages with a file behind -/// them, the block of zeros, a protection), the process ends at `sel` ([`refused_by_host`]): -/// Metal takes the ranges. [`gather_or_nil`] answers nil there instead. +/// them, the block of zeros, a protection), the call it is for (a buffer over a surface, a heap +/// over address ranges) answers nil, as Metal's does when memory runs out, nothing left mapped +/// (`crate::answer::out_of_host_memory`, counted; in strict mode the process ends at `sel`). /// /// Where the runtime imports a surface's read-only alias through a writable twin of its files /// ([`crate::os::TWINS_READ_ONLY`], Linux), a read-only alias's zeros past the ranges' pages map @@ -1435,19 +584,6 @@ fn off_the_page(sel: &'static str, address: u64, into: u64) -> ! { /// either as host memory, which RADV refuses for any page with a file behind it, or as dma-bufs, /// which udmabuf makes of files alone (`crate::os::host_memory`), so an alias of the guest's file /// pages and anonymous zeros would import neither way; on Mach any allocation. -pub(crate) fn gather( - sel: &'static str, - ranges: &[ResourceAddressRange], - size: u64, - read_only: bool, -) -> Option { - gather_short(sel, ranges, size, read_only).unwrap_or_else(|short| refused_by_host(sel, &short)) -} - -/// [`gather`] for a call whose refusal is a nil object (a buffer over a surface, a heap over -/// address ranges): where the host refuses the alias what it needs, the call answers nil, as -/// Metal's does when memory runs out, nothing left mapped -/// (`crate::answer::out_of_host_memory`, counted; in strict mode the process ends at `sel`). pub(crate) fn gather_or_nil( sel: &'static str, ranges: &[ResourceAddressRange], @@ -1460,7 +596,7 @@ pub(crate) fn gather_or_nil( }) } -/// What the host refused [`gather`]'s alias past the checks of its ranges, where Metal's call +/// What the host refused [`gather_or_nil`]'s alias past the checks of its ranges, where Metal's call /// goes on: the line that names it. #[derive(Debug)] struct HostShort(String); @@ -1476,7 +612,7 @@ impl HostShort { } } -/// [`gather`], `Err` where the host refuses the alias what it needs, nothing left mapped. +/// [`gather_or_nil`], `Err` where the host refuses the alias what it needs, nothing left mapped. fn gather_short( sel: &'static str, ranges: &[ResourceAddressRange], @@ -1544,54 +680,6 @@ fn gather_short( Ok(Some(alias)) } -/// The death at `sel` of what the host refused ([`HostShort`]), where Metal's call goes on: this -/// platform's alias of the guest's pages, or its zeros, need what Metal's own call does not, and -/// no answer of Metal's fits without them (a NO where Metal answers YES, or a detach whose object -/// stays over the guest's pages). -fn refused_by_host(sel: &'static str, short: &HostShort) -> ! { - fatal_with_detail( - DeathId::Platform { - kind: DeathKind::Abort, - call: sel, - }, - &short.0, - ) -} - -/// The line of the death at `detachBacking` of an object the runtime refused to detach -/// ([`Backing::detach`]), `refused` its answer: a texture over its bytes whose image no stand-in -/// of zero bytes presents exactly (a multisample or multi-planar texture, or one with a depth or -/// decoded twin), or one being made over them (`RuntimeGap::DetachTextures`); memory for a -/// stand-in; a lost device. Metal detaches it, and such a texture reads zero bytes and drops its -/// writes (measured on an M4), which the runtime has no form for there. -fn refused_detach(refused: &rt::Error) -> String { - format!( - "{}: the detach of a buffer or heap, which the runtime refuses where a texture over its \ - bytes has no stand-in of zero bytes (a multisample or multi-planar texture, or one with \ - a depth or decoded twin) or is being made, or for memory or a lost device; Metal \ - detaches it, and such a texture reads zeros and drops its writes", - crate::answer::refusal(refused) - ) -} - -/// The death at `detachBacking` of a buffer neither replaced nor made over memory of the -/// caller's by `newBufferWithDescriptor:` ([`Backing::detach`]): one of the device's own memory, -/// one made on a surface, or one `newBufferWithBytesNoCopy:length:options:deallocator:` made. -/// What Metal's `contents` answers after such a detach, and when it runs such a buffer's -/// deallocator, is not measured, and core detaches none of them. -fn unmeasured_detach() -> ! { - fatal_with_detail( - DeathId::Platform { - kind: DeathKind::Abort, - call: DETACH, - }, - "a detach of a buffer neither replaced nor made by newBufferWithDescriptor: over memory \ - of the caller's (one of the device's own memory, one made on a surface, or one \ - newBufferWithBytesNoCopy: made): what Metal's contents answers after it, and when \ - Metal runs the buffer's deallocator, is not measured", - ) -} - /// The bytes of [`zero_block`]'s block: 1 MiB, whole pages on every host. const ZERO_BLOCK: u64 = 0x10_0000; @@ -1672,6 +760,9 @@ mod tests { use super::*; use crate::os::PAGE; + /// The selector the tests' gathers are for. + const SEL: &str = "newHeapWithDescriptor:"; + fn range(address: u64, length: u64) -> ResourceAddressRange { ResourceAddressRange { address, length } } @@ -1716,31 +807,6 @@ mod tests { u64::try_from(at.addr()).unwrap() } - /// A command buffer's parts share its place among the releases of detached objects, which - /// stays open until the last of them closes, whichever closes first - #[test] - fn a_command_buffer_s_parts_share_its_place_until_the_last_closes() { - let open = |number| DETACHED.state.lock().open.contains_key(&number); - for first_closes_first in [true, false] { - let first = Opened::new(); - let second = first.next_part(); - let third = second.next_part(); - let number = first.open.number; - assert_eq!((second.open.number, third.open.number), (number, number)); - assert_eq!((second.part, third.part), (1, 2)); - let (early, late) = if first_closes_first { - (first, third) - } else { - (third, first) - }; - drop(early); - drop(second); - assert!(open(number), "closed with a part still open"); - drop(late); - assert!(!open(number), "open once its parts closed"); - } - } - /// Host-contiguous ranges make one run, as core cuts its runs at two pages; the ranges' /// bytes are cut at the size, and a short last range is remapped to its page's end #[test] @@ -1752,23 +818,20 @@ mod tests { range(at + 0x10_0000, PAGE), ]; assert_eq!( - runs(REPLACE, &ranges, 3 * PAGE, PAGE), + runs(SEL, &ranges, 3 * PAGE, PAGE), Some(vec![ run(0, at, 2 * PAGE), run(2 * PAGE, at + 0x10_0000, PAGE) ]) ); + assert_eq!(runs(SEL, &ranges, PAGE, PAGE), Some(vec![run(0, at, PAGE)])); assert_eq!( - runs(REPLACE, &ranges, PAGE, PAGE), + runs(SEL, &[range(at, 0x10)], PAGE, PAGE), Some(vec![run(0, at, PAGE)]) ); + assert_eq!(runs(SEL, &[], PAGE, PAGE), None); assert_eq!( - runs(REPLACE, &[range(at, 0x10)], PAGE, PAGE), - Some(vec![run(0, at, PAGE)]) - ); - assert_eq!(runs(REPLACE, &[], PAGE, PAGE), None); - assert_eq!( - runs(REPLACE, &[range(at, PAGE), range(0, PAGE)], 2 * PAGE, PAGE), + runs(SEL, &[range(at, PAGE), range(0, PAGE)], 2 * PAGE, PAGE), None ); } @@ -1776,7 +839,7 @@ mod tests { /// Each run of ranges whose bytes follow on takes the pages it lies in, whole, as Metal maps /// them: a range of part of a page all of it, before another too, and a later range starting /// off its page from the page's start, through the page of its last byte; up to the size, - /// those that follow on in the host's memory one remap: the shapes `tests/detach_backing.rs` + /// those that follow on in the host's memory one remap: the shapes `tests/address_ranges.rs` /// compares with Metal's (its `unaligned_shape`'s 2 to 7), and more #[test] fn runs_take_the_pages_each_run_of_bytes_lies_in() { @@ -1858,7 +921,7 @@ mod tests { ]; for (ranges, size, expected) in cases { assert_eq!( - runs(REPLACE, &ranges, size, PAGE), + runs(SEL, &ranges, size, PAGE), Some(expected), "{ranges:x?}" ); @@ -1873,10 +936,14 @@ mod tests { use crate::core::raise::death::DeathKind; use crate::core::testkit::capture::catch_death; let guest = pages(3, 0); - for (into, sel) in [(0x40, REPLACE), (PAGE / 4, "newHeapWithDescriptor:")] { + for (into, sel) in [ + (0x40, "newBufferWithIOSurface:"), + (PAGE / 4, "newHeapWithDescriptor:"), + ] { let ranges = [range(address(guest) + into, 2 * PAGE)]; *crate::answer::LAST_LINE.lock() = None; - let site = catch_death(|| gather(sel, &ranges, 2 * PAGE, false).is_some()).unwrap_err(); + let site = + catch_death(|| gather_or_nil(sel, &ranges, 2 * PAGE, false).is_some()).unwrap_err(); let line = crate::answer::LAST_LINE.lock().take().unwrap_or_default(); assert_eq!((site.kind, site.file), (DeathKind::Abort, sel), "{line}"); assert!( @@ -1887,14 +954,14 @@ mod tests { } let null = range(0, PAGE); let off = range(address(guest) + 0x40, PAGE); - assert_eq!(runs(REPLACE, &[off, null], 2 * PAGE, PAGE), None); + assert_eq!(runs(SEL, &[off, null], 2 * PAGE, PAGE), None); let vm = OsVm::new(); assert!( vm.deallocate(guest.wrapping_add(2 * PAGE), PAGE) .is_success() ); let unmapped = [range(address(guest) + 0x40, 2 * PAGE)]; - assert!(gather(REPLACE, &unmapped, 2 * PAGE, false).is_none()); + assert!(gather_or_nil(SEL, &unmapped, 2 * PAGE, false).is_none()); assert!(vm.deallocate(guest, 2 * PAGE).is_success()); } @@ -1909,7 +976,7 @@ mod tests { range(address(guest) + PAGE, PAGE), range(address(guest) + 3 * PAGE, PAGE), ]; - let alias = gather(REPLACE, &ranges, 4 * PAGE, false).unwrap(); + let alias = gather_or_nil(SEL, &ranges, 4 * PAGE, false).unwrap(); let first = alias.first(); assert_eq!( [0, PAGE, 2 * PAGE, 3 * PAGE].map(|at| read(first, at)), @@ -1954,7 +1021,7 @@ mod tests { vec![range(address(last), 2 * PAGE)], ] { assert!( - gather(REPLACE, &ranges, 2 * PAGE, false).is_none(), + gather_or_nil(SEL, &ranges, 2 * PAGE, false).is_none(), "{ranges:?}" ); } @@ -1968,7 +1035,7 @@ mod tests { vec![range(address(last), 2 * PAGE)], ] { assert!( - gather(REPLACE, &ranges, PAGE, false).is_none(), + gather_or_nil(SEL, &ranges, PAGE, false).is_none(), "{ranges:?}" ); } @@ -1977,205 +1044,22 @@ mod tests { range(address(around), PAGE), range(address(last) + 0x40, PAGE - 0x40), ]; - assert!(gather(REPLACE, &ends, 2 * PAGE, false).is_some()); + assert!(gather_or_nil(SEL, &ends, 2 * PAGE, false).is_some()); let read_only = pages(1, 0); vm.protect_max(read_only, PAGE, VmProt::READ).unwrap(); - assert!(gather(REPLACE, &[range(address(read_only), PAGE)], PAGE, false).is_some()); + assert!(gather_or_nil(SEL, &[range(address(read_only), PAGE)], PAGE, false).is_some()); for page in [around, around.wrapping_add(2 * PAGE), last, read_only] { assert!(vm.deallocate(page, PAGE).is_success()); } assert!(vm.deallocate(shut, 2 * PAGE).is_success()); } - /// Runtime identities of `N` objects, made and released here, which no other object takes. - fn ids() -> [rt::ObjectId; N] { - let dev = crate::gpu::device::tests::dev(); - std::array::from_fn(|_| { - dev.raw - .new_buffer(16, rt::ResourceOptions::default()) - .unwrap() - .object_id() - }) - } - - /// A registry of its own, empty. - fn registry() -> Registry { - Registry::new() - } - - /// A command buffer made now in `d`: its number. Its place stays in `d` until it closes - /// there. - fn made(d: &Registry) -> u64 { - d.open().number - } - - /// The numbers of the command buffers open in `d`. - fn open(d: &Registry) -> Vec { - d.state.lock().open.keys().copied().collect() - } - - /// A replace answers NO for an attached object and for ranges of another total, and YES once - /// the runtime took the alias, which leaves the object attached. A detach is the runtime's, - /// once; `contents` then stays the memory the object was over: what a no-copy buffer was made - /// over, whose deallocator's run, which the runtime hands over as it lets go of it, is held - /// until the first replace, or a replace's alias. The runtime's NO leaves the object - /// attached, and its refusal ends the process at `detachBacking`, naming it and what Metal's - /// textures read; so does a detach of a buffer neither replaced nor made over memory of the - /// caller's - #[test] - fn replace_answers_as_metal() { - use crate::core::testkit::capture::catch_death; - let guest = pages(2, 0xa1); - let ranges = [range(address(guest), 2 * PAGE)]; - let [id, other] = ids(); - let site = catch_death(|| Backing::new(false, other).detach(|| Ok(true))); - assert_eq!( - site.map_err(|site| (site.kind, site.file)), - Err((DeathKind::Abort, DETACH)), - "no memory of the caller's" - ); - let backing = Backing::new(false, id); - let made_over = pages(2, 0x11); - let made_at = NonNull::new(made_over.as_ptr::()).unwrap(); - let held = Arc::new(Held::default()); - backing.made_over_own(Own::new(made_at, Arc::clone(&held))); - let ran = Arc::new(AtomicBool::new(false)); - let deallocate = || { - let ran = Arc::clone(&ran); - Box::new(move || ran.store(true, Ordering::Release)) as Box - }; - let rebinds = std::cell::Cell::new(0); - let rebind = |_: NonNull, _: rt::KeepAlive, _: crate::os::ImportMade| { - rebinds.set(rebinds.get() + 1); - Ok(()) - }; - // The runtime's detaches, and its answer to each. - let detaches = std::cell::Cell::new(0); - let detach = |answer: Result| { - let detaches = &detaches; - move || { - detaches.set(detaches.get() + 1); - answer - } - }; - let refusal = || rt::Error::NotImplemented(rt::RuntimeGap::DetachTextures); - assert_eq!( - backing.replace(&ranges, false, 2 * PAGE, 2 * PAGE, rebind), - Ok(false), - "attached" - ); - backing.detach(detach(Ok(false))); - assert!(!backing.is_detached(), "the runtime's NO"); - assert_eq!(backing.kept_contents(), None); - held.run(deallocate()); - assert!(ran.load(Ordering::Acquire), "not held past a NO"); - ran.store(false, Ordering::Release); - backing.detach(detach(Ok(true))); - backing.detach(detach(Ok(true))); - assert!(backing.is_detached()); - assert_eq!(detaches.take(), 2, "never replaced: detached once"); - assert_eq!(backing.kept_contents(), Some(made_at), "contents stays"); - held.run(deallocate()); - assert!(!ran.load(Ordering::Acquire), "held at the detach"); - for length in [PAGE, 3 * PAGE] { - assert_eq!( - backing.replace(&ranges, false, length, length, rebind), - Ok(false), - "{length:#x}" - ); - } - assert_eq!(rebinds.get(), 0); - assert!(!ran.load(Ordering::Acquire), "held past refused replaces"); - assert_eq!( - backing.replace(&ranges, false, 2 * PAGE, 2 * PAGE, rebind), - Ok(true) - ); - assert_eq!(rebinds.get(), 1); - assert!(ran.load(Ordering::Acquire), "run inside the first replace"); - assert!(!backing.is_detached()); - let alias = backing.alias.lock().last.as_ref().map(|alias| alias.at); - backing.detach(detach(Ok(true))); - assert_eq!(detaches.take(), 1); - assert_eq!(backing.kept_contents(), alias, "contents stays the alias"); - assert_eq!( - backing.replace(&ranges, false, 2 * PAGE, 2 * PAGE, rebind), - Ok(true) - ); - assert_eq!(backing.kept_contents(), None); - let site = catch_death(|| backing.detach(detach(Err(refusal())))).unwrap_err(); - assert_eq!((site.kind, site.file), (DeathKind::Abort, DETACH)); - assert_eq!(detaches.take(), 1); - let line = refused_detach(&refusal()); - assert!( - line.starts_with("the Vulkan runtime refused it: ") - && line.contains("Metal detaches it, and such a texture reads zeros"), - "{line}" - ); - let fixed = Backing::fixed(); - fixed.detach(detach(Ok(true))); - assert!(!fixed.is_detached(), "a fixed backing never detaches"); - assert_eq!(detaches.take(), 0); - assert_eq!( - fixed.replace(&ranges, false, 2 * PAGE, 2 * PAGE, rebind), - Ok(false) - ); - let vm = OsVm::new(); - assert!(vm.deallocate(guest, 2 * PAGE).is_success()); - assert!(vm.deallocate(made_over, 2 * PAGE).is_success()); - } - - /// A no-copy buffer never replaced runs its deallocator as it goes where a detach held the - /// run, as Metal's runs it as the buffer is destroyed - #[test] - fn a_held_run_is_made_as_the_buffer_goes() { - let [id] = ids(); - let backing = Backing::new(false, id); - let made_over = pages(1, 0x11); - let held = Arc::new(Held::default()); - let made_at = NonNull::new(made_over.as_ptr::()).unwrap(); - backing.made_over_own(Own::new(made_at, Arc::clone(&held))); - backing.detach(|| Ok(true)); - let ran = Arc::new(AtomicBool::new(false)); - let run = Arc::clone(&ran); - held.run(Box::new(move || run.store(true, Ordering::Release))); - assert!(!ran.load(Ordering::Acquire), "held at the detach"); - drop(backing); - assert!(ran.load(Ordering::Acquire), "run as it went"); - assert!(OsVm::new().deallocate(made_over, PAGE).is_success()); - } - - /// A deallocator's run is made at once but while a detach holds it; then at the release, - /// once, and at once again after it - #[test] - fn a_held_run_is_made_at_its_release() { - let held = Held::default(); - let runs = Arc::new(std::sync::atomic::AtomicU32::new(0)); - let run = || { - let runs = Arc::clone(&runs); - Box::new(move || { - runs.fetch_add(1, Ordering::AcqRel); - }) as Box - }; - let count = || runs.load(Ordering::Acquire); - held.run(run()); - assert_eq!(count(), 1); - held.hold(); - held.run(run()); - assert_eq!(count(), 1, "held"); - held.release(); - assert_eq!(count(), 2, "released"); - held.release(); - assert_eq!(count(), 2, "once"); - held.run(run()); - assert_eq!(count(), 3, "at once after it"); - } - /// A read-only alias reads the guest's pages, and zeros past them, and its pages cannot be /// made writable #[test] fn a_read_only_alias_reads_zeros_past_its_pages() { let guest = pages(1, 0xa5); - let alias = gather(REPLACE, &[range(address(guest), PAGE)], 3 * PAGE, true).unwrap(); + let alias = gather_or_nil(SEL, &[range(address(guest), PAGE)], 3 * PAGE, true).unwrap(); assert_eq!(alias.length, 3 * PAGE); assert_eq!(read(alias.at, 0), 0xa5); for offset in [PAGE, 2 * PAGE + 5, 3 * PAGE - 1] { @@ -2187,280 +1071,11 @@ mod tests { assert!(OsVm::new().deallocate(guest, PAGE).is_success()); } - /// An object fails the command buffers that use it while it is detached; released detached, - /// those made before the release until they close; replaced, none here, committed before the - /// replace or not (the runtime fails one that names it, module docs). No release is kept - /// while no command buffer is open - #[test] - fn detached_objects_fail_their_command_buffers() { - let d = registry(); - let [buffer, heap] = ids(); - let first = made(&d); - assert!(!d.any(first)); - d.detached(buffer); - assert!(d.any(first) && d.fails(&[buffer], first) && !d.fails(&[heap], first)); - d.attached(buffer); - assert!(!d.any(first) && !d.fails(&[buffer], first), "replaced"); - d.detached(buffer); - d.released(buffer); - let second = made(&d); - assert!(d.state.lock().detached.is_empty()); - assert!(d.fails(&[buffer], first), "made before the release"); - assert!( - !d.fails(&[buffer], second) && !d.any(second), - "made after it" - ); - d.detached(heap); - assert!( - d.fails(&[heap], second) && d.fails(&[heap], first), - "detached" - ); - assert!(d.fails(&[buffer, heap], second) && !d.fails(&[], second)); - d.attached(heap); - assert!(!d.fails(&[heap], second), "committed before the replace"); - d.closed(first); - assert!( - d.state.lock().released.is_empty(), - "no open command buffer made before it" - ); - d.closed(second); - assert!(open(&d).is_empty()); - d.detached(buffer); - d.released(buffer); - let state = d.state.lock(); - assert!(state.detached.is_empty() && state.released.is_empty()); - } - - /// A command buffer open before an object's release, the only object detached, can fail by - /// it at every moment of the release, as a reader without the lock sees it ([`Registry::any`]): - /// between the release's stores as before and after them, the object is detached or released - #[test] - fn a_release_is_seen_by_a_reader_at_every_moment() { - static SEEN: Mutex> = Mutex::new(Vec::new()); - let d = Registry { - between: Some(|d| SEEN.lock().push(d.any(0))), - ..Registry::new() - }; - let [buffer] = ids(); - let open = made(&d); - assert_eq!(open, 0); - d.detached(buffer); - assert!(d.any(open)); - d.released(buffer); - assert_eq!(*SEEN.lock(), [true], "between the stores"); - assert!(d.any(open) && d.fails(&[buffer], open), "after them"); - d.closed(open); - } - - /// Releases made while an old command buffer stays open fail the command buffers made before - /// each, and none made after the last; as the oldest open command buffers close, the releases - /// none of those still open was made before are forgotten, in order, the later ones kept - #[test] - fn releases_are_forgotten_in_order_as_the_oldest_command_buffers_close() { - let d = registry(); - let objects: [rt::ObjectId; 6] = ids(); - let old = made(&d); - let [first, second, third, rest @ ..] = objects; - for id in [first, second] { - d.detached(id); - d.released(id); - } - let middle = made(&d); - for id in std::iter::once(third).chain(rest) { - d.detached(id); - d.released(id); - } - let new = made(&d); - assert!(d.any(old) && d.any(middle) && !d.any(new)); - assert!(d.fails(&[first], old) && !d.fails(&[first], middle) && d.fails(&[third], middle)); - d.closed(old); - assert!( - !d.fails(&[first], old) && !d.fails(&[second], old), - "made before the oldest open" - ); - assert_eq!(d.state.lock().released.len(), 4); - assert!(d.fails(&[third], middle) && d.any(middle)); - d.closed(middle); - let state = d.state.lock(); - assert!(state.released.is_empty() && state.releases.is_empty()); - drop(state); - assert!(!d.any(new) && !d.any(0), "no release kept"); - d.closed(new); - } - - /// A command buffer committed while a buffer it fills is detached fails with code 8 as it is - /// submitted, as Metal's (`tests/detach_backing.rs`'s `never_replaced`), on every host: the - /// detached buffer lies in no memory, so no host keeps what a command that reaches it unnamed - /// writes - #[test] - fn a_commit_while_detached_fails_on_every_host() { - use crate::core::platform::blit::{BlitCmd, BlitEncoder}; - use crate::core::platform::command::{CommandBuffer, CommandQueue}; - use crate::core::platform::device::GpuDevice; - use crate::core::platform::resource::Buffer; - use crate::core::platform::types::NsRange; - use crate::core::platform::values::{BufferDesc, OptionSet}; - use crate::core::raise::OnFault; - const TEST: &str = "gpu::backing::tests::a_commit_while_detached_fails_on_every_host"; - if std::env::var("RVG_CHILD").as_deref() == Ok(TEST) { - crate::core::testkit::capture::set_capture_enabled(false); - let d = crate::gpu::device::tests::dev(); - let memory = pages(1, 0xd0); - // SAFETY: the pages stay mapped for the process, which exits below. - let contents = unsafe { crate::core::platform::HostRange::new(memory, PAGE) }; - let buffer = d - .new_buffer(BufferDesc { - length: PAGE, - options: vec![OptionSet::StorageMode(0)], - pinned_gpu_address: None, - contents: Some(contents), - no_copy: true, - deallocator: None, - }) - .unwrap() - .unwrap(); - buffer.detach_backing().unwrap(); - let queue = d.new_command_queue().unwrap(); - let cb = queue.command_buffer(OnFault::Return).unwrap().unwrap(); - let e = cb.blit_encoder(OnFault::Return).unwrap().unwrap(); - for command in [ - BlitCmd::FillBuffer { - buffer: &buffer, - range: NsRange::new(0, 16), - value: 0x5c, - }, - BlitCmd::EndEncoding, - ] { - e.encode(OnFault::Return, command).unwrap(); - } - cb.commit(OnFault::Return).unwrap(); - cb.wait_until_completed(OnFault::Return).unwrap(); - let code = cb.error().map_or(0, |e| e.code); - println!("status {} code {code}", cb.status().0); - std::process::exit(0); - } - let out = std::process::Command::new(std::env::current_exe().unwrap()) - .args(["--exact", TEST, "--nocapture", "--test-threads=1"]) - .env("RVG_CHILD", TEST) - .output() - .unwrap(); - let (stdout, stderr) = ( - String::from_utf8_lossy(&out.stdout), - String::from_utf8_lossy(&out.stderr), - ); - let death = stderr - .lines() - .find(|l| l.starts_with("reims-vgpu: fatal: ")); - assert!(out.status.success() && death.is_none(), "{out:?}"); - assert!(stdout.contains("status 5 code 8"), "{stdout}"); - } - - /// A command buffer took the object from its submission that used it until it completed, - /// whether it completed with an error or not: a detach finds it in flight while it waits on - /// an event after its fill of the object, and none of its noted submissions in flight in its - /// completed handler, as Metal lets go of what a command buffer used as its completed - /// handlers start, and of a failed one's before them ([`in_flight`], module docs, "In - /// flight"); the failed one's fill of the object ran, and a later submission failed with - /// code 8 by a detached use - #[test] - fn a_command_buffer_took_the_object_until_it_completed() { - use crate::core::platform::blit::{BlitCmd, BlitEncoder}; - use crate::core::platform::command::{CommandBuffer, CommandQueue}; - use crate::core::platform::device::GpuDevice; - use crate::core::platform::event::{EventRef, SharedEvent}; - use crate::core::platform::resource::Buffer; - use crate::core::platform::types::NsRange; - use crate::core::platform::values::{BufferDesc, OptionSet}; - use crate::core::raise::OnFault; - use crate::gpu::command::VulkanCommandBuffer; - use crate::gpu::resource::VulkanBuffer; - fn fill(cb: &VulkanCommandBuffer, buffer: &VulkanBuffer) { - let e = cb.blit_encoder(OnFault::Return).unwrap().unwrap(); - for command in [ - BlitCmd::FillBuffer { - buffer, - range: NsRange::new(0, 16), - value: 0x5c, - }, - BlitCmd::EndEncoding, - ] { - e.encode(OnFault::Return, command).unwrap(); - } - } - let d = crate::gpu::device::tests::dev(); - // A no-copy buffer over a page of the test's, which stays mapped for the process. - let no_copy = || { - // SAFETY: the page stays mapped for the process. - let contents = unsafe { crate::core::platform::HostRange::new(pages(1, 0), PAGE) }; - d.new_buffer(BufferDesc { - length: PAGE, - options: vec![OptionSet::StorageMode(0)], - pinned_gpu_address: None, - contents: Some(contents), - no_copy: true, - deallocator: None, - }) - .unwrap() - .unwrap() - }; - let used = no_copy(); - let other = no_copy(); - let detached = no_copy(); - detached.detach_backing().unwrap(); - let (id, made) = (used.backing.id.unwrap(), used.backing.made); - let queue = d.new_command_queue().unwrap(); - let (event, gate) = (d.new_shared_event().unwrap(), d.new_shared_event().unwrap()); - let mut before = Vec::new(); - let mut seen = Vec::new(); - for fails in [false, true] { - let cb = queue.command_buffer(OnFault::Return).unwrap().unwrap(); - let (taken, handler) = std::sync::mpsc::channel(); - cb.add_completed_handler( - OnFault::Return, - Box::new(move |info| { - let _ = taken.send((info.status.0, in_flight(id, made).len())); - }), - ) - .unwrap(); - fill(&cb, &used); - if fails { - cb.encode_signal(Some(EventRef::Shared(&event)), 1).unwrap(); - fill(&cb, &detached); - } else { - cb.encode_wait(Some(EventRef::Shared(&gate)), 1).unwrap(); - fill(&cb, &other); - } - cb.commit(OnFault::Return).unwrap(); - if !fails { - // The first submission is noted as the runtime submits it, read for up to 5 s; - // the second waits for the gate, so the command buffer has not completed. - let mut taking = in_flight(id, made).len(); - for _ in 0..5000 { - if taking != 0 { - break; - } - std::thread::sleep(std::time::Duration::from_millis(1)); - taking = in_flight(id, made).len(); - } - before.push((cb.status().0 < 4, taking)); - gate.set_signaled_value(1).unwrap(); - } - cb.wait_until_completed(OnFault::Return).unwrap(); - seen.push(handler.recv().unwrap()); - } - assert_eq!( - (before, seen), - (vec![(true, 1)], vec![(4, 0), (5, 0)]), - "(not completed, command buffers taking it) waiting; (status, them) in the handlers" - ); - } - /// The length of a run of pages in [`Pages`]' tests. const RUN: u64 = 0x4000; /// Whether an object's bytes meet its pages is what its memory there answers: none over memory - /// of its own, whether any of them lie in its pages, and none once a detach zeroes it, until - /// a replace gives it pages again + /// of its own, and whether any of them lie in its pages #[test] #[expect(clippy::single_range_in_vec_init, reason = "lists of host ranges")] fn meeting_pages_is_whether_the_bytes_lie_in_them() { @@ -2488,12 +1103,6 @@ mod tests { agree(&pages); assert_eq!(pages.meets_pages(&(RUN - 1..RUN + 1)), Some(true)); assert_eq!(pages.meets_pages(&(3 * RUN..4 * RUN)), Some(false)); - pages.zero(); - agree(&pages); - assert_eq!(pages.meets_pages(&(0..RUN)), None); - pages.set(vec![0x50_0000..0x50_0000 + RUN]); - agree(&pages); - assert_eq!(pages.meets_pages(&(0..1)), Some(true)); } /// An object's bytes are found in its pages by a search from the run that holds their first diff --git a/crates/reims-vgpu-vulkan/src/gpu/caps.rs b/crates/reims-vgpu-vulkan/src/gpu/caps.rs index 67e02981a..e135a32d0 100644 --- a/crates/reims-vgpu-vulkan/src/gpu/caps.rs +++ b/crates/reims-vgpu-vulkan/src/gpu/caps.rs @@ -76,9 +76,10 @@ //! - buffers and heaps over address ranges and detach backing (key 33's 0x8 and 0x10, and key 42, //! which core sets from detach backing, not from the argument buffer tier) are yes where the //! runtime imports host memory (`VK_EXT_external_memory_host`), which every heap over address -//! ranges and every replace of a detached backing is made over ([`crate::gpu::backing`]), as -//! on MoltenVK, where they are Metal's answers. A submission that uses a detached buffer or -//! heap fails as Metal's does; [`crate::gpu::command`]'s docs list where it differs; +//! ranges is made over ([`crate::gpu::backing`]), as on MoltenVK, where they are Metal's +//! answers. Nothing detaches or replaces a backing: the guest's heaps answer neither (the Metal +//! bundle's `RgfxHeap` raises an unrecognized selector, as Metal's base heap), and this +//! platform makes neither; //! - `heapTextureSizeAndAlignWithDescriptor:` of a depth or stencil texture with //! `allowGPUOptimizedContents` off answers Metal's size, the runtime's model of Metal's answer, //! which answers an X32_Stencil8 texture as a Stencil8 one of its shape, as the runtime's own @@ -155,8 +156,7 @@ //! import dies where it is encoded (`crate::gpu::writes::kept_write`; `encode_compute`'s //! `a_dispatch_through_a_read_only_surface_dies_on_linux`), but a function's write through an //! address it loads into one not made resident for writing, which names nothing. Other read-only -//! memory (the guest's read-only objects, a read-only replace or a heap or no-copy buffer made -//! with bit 24, and a no-copy buffer or heap over pages mapped read-only) the runtime makes over +//! memory (the guest's read-only objects, a heap or no-copy buffer made with bit 24, and a no-copy buffer or heap over pages mapped read-only) the runtime makes over //! a copy whose GPU writes it drops, announced (`copied-host-pages`), and what Metal answers //! otherwise there is `crate::gpu::writes`'s. diff --git a/crates/reims-vgpu-vulkan/src/gpu/command.rs b/crates/reims-vgpu-vulkan/src/gpu/command.rs index efaa311b5..3fda4491a 100644 --- a/crates/reims-vgpu-vulkan/src/gpu/command.rs +++ b/crates/reims-vgpu-vulkan/src/gpu/command.rs @@ -20,9 +20,7 @@ //! - **A command buffer in parts** (`split`, which the graphics lane's walk asks for at an //! encoder's end, `reims-vgpu`'s `decode/split.rs`): the work encoded so far is committed as //! `commit` commits it, and a command buffer of the same queue goes on from it. The next part -//! takes the buffer's place among the releases of detached objects ([`Opened::next_part`]), so -//! its submissions fail by what the whole buffer's would, and numbers its runtime encoders from -//! 0, as the runtime counts a command buffer's. The parts run in their commit order on the +//! numbers its runtime encoders from 0, as the runtime counts a command buffer's. The parts run in their commit order on the //! queue, as one buffer's encoders do. The buffer is kept whole, `split` answering `None`, where //! a part would answer otherwise than the whole ([`CommandBufferObject::splits`]): with an //! encoder open; with a way Metal's GPU fails it from an encoder on, every encoder after it @@ -68,27 +66,6 @@ //! the runtime does not filter bicubically through an argument buffer's sampler, and fails a //! command buffer whose function reached one, where Metal samples and fails none. A function //! that never reaches one runs as Metal's. -//! - **A command whose buffer over the guest's pages was rebound before its command buffer was -//! submitted, in an encoder the runtime cannot encode again** -//! (`CommandBufferError::EncodedUseRebound`) dies there too ([`encoded_use_rebound`]): the -//! runtime resolves a command's use of a buffer over the caller's host pages as the command is -//! encoded, and where the buffer is rebound (a backing replaced, `crate::gpu::backing`) before -//! the command buffer's first submission, it encodes the compute, blit and render encoders that -//! named it again from their calls, so they reach the new pages as Metal's do (a call refused at -//! its encoding is refused again, and the calls after it run), and a resource state encoder takes -//! no pages (an indirect mapping update reads its buffer as it runs). It fails only an encoder it -//! cannot encode again: a compute encoder of the runtime's command predication that shares its -//! unit, holds a loop or leaves work out (no record of ours reaches the runtime's predication: -//! this platform's is its own, [`crate::gpu::predication`]); a render pass that executes an -//! indirect command buffer, which the runtime records later, or whose end captured its draws' -//! tile reach; and one a call of which answers otherwise than at its encoding. An encoder whose -//! dispatch, draw or tile dispatch had its pipeline still being made at the commit is encoded -//! again as any other, its pipeline's making left to the submission: the replace waits for no -//! making. Each submission holding such an encoder runs nothing and the command -//! buffer fails, where Metal resolves the use as it submits and runs the command over the pages -//! the buffer lies in then. The runtime announces the first such failure (`EncodedUseRebound`, -//! [`crate::answer::DIES`]) on the thread that makes the submission, where it dies first, ending -//! the process. //! - **Every other failure of the runtime's own**, where Metal fails no command buffer, dies //! there too, naming it ([`answered`]): a mesh draw's grid the device cannot launch where Metal //! draws it (`MeshGridPastLimits`, which dies as unanswered); an emulated mesh draw past the @@ -151,8 +128,7 @@ //! `AccessRevoked` (4), running nothing and signalling nothing, as Metal's //! (`type_9_faults_revoke_queues_as_metals`). Such a draw is told to the command buffer //! ([`CommandBufferObject::fails_at_type_9`]): one that fails another way too, by its own -//! encoders, its protection options, a use of a detached object at its commit, or another -//! type-9 draw's other failure, dies at the commit, as do two different ways at once of any +//! encoders, its protection options, or another type-9 draw's other failure, dies at the commit, as do two different ways at once of any //! kind, which nothing measured. //! //! A render pass that stores an attachment into read-only memory the runtime copies @@ -165,51 +141,6 @@ //! buffer run, and whether its signals fire, are not measured for this fault. Metal then fails //! every later command buffer of the process, with a code nothing recorded, so the commit of //! one dies ([`READ_ONLY_FAULTED`]). -//! - **A submission that uses a detached buffer or heap** fails with -//! `MTLCommandBufferErrorOutOfMemory` (8), whose description is Metal's ("Insufficient -//! Memory"), as Metal fails it. Metal splits a command buffer into submissions, and decides -//! each as it submits it, once the event waits before it are met (measured on the M3 Max, -//! macOS 26.7, `tests/detach_backing.rs`): -//! - every render pass is a submission of its own; -//! - a run of consecutive blit encoders is one, and so is a run of consecutive compute -//! encoders; -//! - an event wait or signal ends a run. -//! -//! The runtime splits a command buffer so, and checks each submission as it submits it, once -//! its event waits are met ([`backing::submission_check`]): a wait another command buffer's -//! GPU signal meets, once that signal landed, as Metal checks it once the signal happened. One -//! that uses a detached object, or one released detached since the command buffer was made, -//! runs nothing; every other submission runs, the event signals fire, the scheduled and -//! completed handlers run, and the command buffer completes in its queue's order with status -//! `Error`. The use can be a binding, a `useResource:` or `useHeap:`, a blit's operand, a -//! command of an indirect command buffer it executes, or a texture over the buffer, a view of -//! that texture, or a resource placed in the heap, as the runtime lists a submission's uses. -//! This platform differs from Metal where: -//! - the object is replaced after the command was encoded and before its command buffer's -//! first submission (committed after the replace, or committed before it and held behind an -//! event wait), in an encoder the runtime cannot encode again (the failure above): Metal -//! runs the submission over the new pages. The runtime resolved the command's use as it -//! encoded it, and fails the command buffer (`CommandBufferError::EncodedUseRebound`), which -//! dies ([`encoded_use_rebound`]); a compute, blit or render encoder it encodes again -//! reaches the new pages, as Metal's. The runtime decides each submission so as it submits -//! it, after the check: one the check fails, a use detached then, keeps code 8, as Metal's, -//! and a later one rebound so dies all the same, the command buffer keeping that code; -//! - a submission that executes an indirect command buffer the GPU may write is checked again -//! once the runtime recorded what its commands reach, and failing then, only what had not -//! run yet runs nothing. Metal decides it once, before any of it runs. -//! -//! A command that reaches a detached object only through an address it loads names nothing the -//! check sees, so its submission runs, as Metal's does, reading 0 and dropping the write, on -//! every host: the runtime's detach leaves the object in no memory, replaced or never replaced, -//! and out of what such a command reaches until a command buffer uses it after a replace -//! (`backing`'s docs). -//! -//! A texture over a buffer or placed in a heap, and a buffer placed in a heap, hold the buffer -//! or heap, as Metal's do, so a detached one is released only with the last of them, and a use -//! through one fails until then ([`crate::gpu::resource::Under`]). -//! -//! A command buffer Metal's GPU fails for what its encoders did is decided at its commit, with -//! no check: one that uses a detached object then dies there, as one failing two ways does. use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; @@ -233,7 +164,6 @@ use metal2vulkan_runtime as rt; use crate::answer::{ Policy, get, hang, metal_aborts, plain, plain_at, refusal, refused, send, unrepresentable, }; -use crate::gpu::backing::{self, Opened}; use crate::gpu::desc::VulkanRenderPassDescriptor; use crate::gpu::device::VulkanDevice; use crate::gpu::encode_blit::{EncoderObject, VulkanBlitEncoder}; @@ -281,9 +211,8 @@ pub struct CommandBufferObject { progress: Mutex>>, /// Its command predication. pub(crate) predication: Arc, - /// Its place among the releases of detached objects until it commits, which its submission - /// check then holds ([`backing::submission_check`]). - opened: Mutex>, + /// Whether it was committed: it is split no more ([`CommandBufferObject::splits`]). + committed: AtomicBool, /// How many runtime encoders it has made: each encoder of Metal's, or a part of one where /// [`predication`] ends a compute encoder's runtime encoder and makes another. As no two are /// open at once, each one's count before it is its place among the encoders the runtime @@ -330,12 +259,11 @@ static READ_ONLY_FAULTED: AtomicBool = AtomicBool::new(false); /// buffer encoded once the process took the allocation carries none: the allocation is held for /// good, and a submission handler makes the runtime run the command buffer's transition to /// scheduled on a handler thread, woken for it, where it runs it on its scheduler thread as it -/// submits the command buffer (`rt::WorkCounts::scheduled_where_submitted`). Every command -/// buffer this platform commits carries a submission check ([`backing::submission_check`]), which -/// the runtime runs just before it submits the command buffer, once its waits are met and the work -/// ahead of it on its queue is submitted: inside `commit`, on the committing thread, where that -/// thread makes the submission pass ([`CommandBuffer::commit`]), else on the runtime's scheduler -/// thread after `commit` returns, as Metal submits on a thread of its own and tells the program +/// submits the command buffer (`rt::WorkCounts::scheduled_where_submitted`). The thread that +/// submits it, once its waits are met and the work ahead of it on its queue is submitted, is the +/// committing thread, inside `commit`, where that thread makes the submission pass +/// ([`CommandBuffer::commit`]), else the runtime's scheduler thread after `commit` returns, as +/// Metal submits on a thread of its own and tells the program /// only through scheduled (the runtime's measurement on an M4). A range placed between the commit /// and the submission lies by the threads' timing, on Metal as here. A command buffer the runtime /// fails before its submission takes nothing. @@ -463,7 +391,7 @@ impl CommandBufferObject { && self.progress.lock().is_none() && !self.predication.in_unit() && !self.signals_scheduled.load(Ordering::SeqCst) - && self.opened.lock().is_some() + && !self.committed.load(Ordering::SeqCst) }) } @@ -525,15 +453,9 @@ impl CommandBufferObject { /// and protection options with a bit from 0x10 up, which fail it with [`INVALID_INPUT`] /// though no encoder was made under them (measured), all of its encoders running; `None` /// where nothing does, or only its draws of primitive type 9, which the runtime fails it at - /// ([`CommandBufferObject::fails_at_type_9`]). Where either fails it, a use of a detached - /// object at the commit (`detached`, asked only then) is another way. Two different ways at - /// once, which nothing measured, die. A use of a detached object alone fails only its - /// submissions ([`backing::submission_check`]). - fn failure( - &self, - sel: &'static str, - detached: impl FnOnce() -> bool, - ) -> Option { + /// ([`CommandBufferObject::fails_at_type_9`]). Two different ways at once, which nothing + /// measured, die. + fn failure(&self, sel: &'static str) -> Option { let mut ways = plain(|| self.failing.lock().clone()); let options = plain(|| self.protection.lock().options); if protection_code(options) == INVALID_INPUT { @@ -546,13 +468,6 @@ impl CommandBufferObject { let own = ways.len(); ways.extend(plain(|| self.type_9.lock().clone())); let first = *ways.first()?; - if detached() { - ways.push(Failing { - code: backing::DETACHED_USE, - from: 0, - signals: true, - }); - } if ways .iter() .any(|w| (w.code, w.signals) != (first.code, first.signals)) @@ -977,7 +892,7 @@ impl CommandQueue for VulkanCommandQueue { open_encoders: Arc::default(), progress: Mutex::new(None), predication, - opened: Mutex::new(Some(Opened::new())), + committed: AtomicBool::new(false), made: AtomicUsize::new(0), failing: Mutex::new(Vec::new()), type_9: Mutex::new(Vec::new()), @@ -1010,7 +925,7 @@ fn failure(cb: &rt::CommandBuffer) -> Option { /// Dies at `sel`, where a command buffer's failure `e` is read first, unless `e` is one of Metal's /// failures, which core then sees as Metal's: a failure this platform committed the command buffer -/// with as Metal's GPU fails it ([`Failing`], a detached object's use), a lost device's, memory's, +/// with as Metal's GPU fails it ([`Failing`]), a lost device's, memory's, /// an address fault, a GPU hang and a victim of the GPU's recovery, a revoked queue's, a render /// pass without attachments past 16384, a detached buffer's use, an encoder made under protection /// options, a unit of command predication left with a block open, a render pass without attachments @@ -1022,8 +937,7 @@ fn failure(cb: &rt::CommandBuffer) -> Option { /// other is the runtime's own (`rt::FailureOrigin::Runtime`), where Metal fails no command buffer, /// and dies naming it: an indirect draw's indices the index pool could not hold /// ([`pool_overflow`]), a sample through a cubic sampler an argument buffer holds -/// ([`cubic_argument_sampler`]), a command's buffer rebound before the command buffer was submitted -/// ([`encoded_use_rebound`]), an emulated mesh or tessellation draw past the records pool +/// ([`cubic_argument_sampler`]), an emulated mesh or tessellation draw past the records pool /// ([`mesh_records_overflow`], [`tessellation_records_overflow`]), a Vulkan failure of a /// submission ([`vulkan_failure`]), and any other ([`unanswered`]). A host step's /// refusal and a draw's pipeline die before, where `cb` names them ([`refused_step`], @@ -1049,7 +963,6 @@ fn answered(sel: &'static str, e: rt::CommandBufferError, cb: Option<&rt::Comman } rt::CommandBufferError::IndexPoolOverflow => pool_overflow(sel), rt::CommandBufferError::CubicArgumentSampler => cubic_argument_sampler(sel), - rt::CommandBufferError::EncodedUseRebound => encoded_use_rebound(sel), rt::CommandBufferError::MeshRecordsOverflow(overflow) => { mesh_records_overflow(sel, overflow) } @@ -1139,22 +1052,6 @@ fn cubic_argument_sampler(sel: &'static str) -> ! { ) } -/// The death at `sel` of a command buffer the runtime failed as it was first submitted, as a -/// command of it named a buffer over the guest's pages that was rebound after the command was -/// encoded, in an encoder the runtime could not encode again (the module docs): the runtime -/// resolved the use as the command was encoded, and ran nothing of each submission holding such -/// a command, where Metal resolves it as it submits the command buffer and runs the command over -/// the pages the buffer lies in then. -fn encoded_use_rebound(sel: &'static str) -> ! { - unrepresentable( - sel, - "a command naming a buffer over the guest's pages that was rebound after the command was \ - encoded and before its command buffer was submitted, in an encoder the runtime could \ - not encode again, whose use it resolved as it was encoded and ran nothing of, failing \ - the command buffer, where Metal runs it over the pages the buffer lies in as it submits", - ) -} - /// The death at `sel` of a command buffer an indexed indirect draw failed: the runtime keeps /// such a draw's indices, checked or rewritten by a pass before the render pass, in the command /// buffer's index pool, a sixty-fourth of the device's largest device-local heap, and draws @@ -1231,23 +1128,20 @@ fn refused_step(sel: &'static str, cb: &rt::CommandBuffer) -> ! { } } -/// The `NSError` of a failed command buffer: Metal's domain and code for the runtime's error, -/// and Metal's description of a use of a detached buffer or heap. A failure the driver relayed +/// The `NSError` of a failed command buffer: Metal's domain and code for the runtime's error. A +/// failure the driver relayed /// (`Execution`, and the `PageFault` and `DeviceLost` the runtime maps codes 3 and 11 to) names /// the runtime's error and, beside it, Metal's `relayed` description of the failure, as the /// driver's message gave it (`rt::CommandBuffer::error_description`), where not empty. Core /// prints the description in its log lines of a failed command buffer; nothing else reads it. fn command_buffer_error(e: rt::CommandBufferError, relayed: Option) -> NsErrorText { - let description = match (e, relayed.filter(|d| !d.is_empty())) { - (rt::CommandBufferError::Injected(backing::DETACHED_USE), _) => { - "Insufficient Memory (00000008:kIOGPUCommandBufferCallbackErrorOutOfMemory)".to_owned() - } - (e, Some(metal)) => { + let description = match relayed.filter(|d| !d.is_empty()) { + Some(metal) => { format!( "the Vulkan runtime's command buffer failed: {e:?} (Metal's description: {metal})" ) } - (e, None) => format!("the Vulkan runtime's command buffer failed: {e:?}"), + None => format!("the Vulkan runtime's command buffer failed: {e:?}"), }; NsErrorText { domain: "MTLCommandBufferErrorDomain".to_owned(), @@ -1392,8 +1286,7 @@ impl CommandBuffer for VulkanCommandBuffer { /// Refused while an encoder is open or after a commit, as Metal's validation refuses it. /// Every refusal dies naming the runtime's, and one of the records of an indirect command /// buffer it executes says so ([`committing`]). One that Metal's GPU fails for what its encoders did is committed failed - /// ([`CommandBufferObject::failure`]); any other is committed with its submission check, - /// which fails a submission that uses a detached buffer or heap (module docs). A slow commit + /// ([`CommandBufferObject::failure`]); any other is committed as it is. A slow commit /// and a late completion are debug lines ([`timing::commit`]). One that holds work for /// Metal's tiler takes Metal's allocation for it as the runtime submits it /// ([`tiler_handler`]). One committed while a command buffer of its queue that Metal's GPU @@ -1401,12 +1294,10 @@ impl CommandBuffer for VulkanCommandBuffer { /// runtime commits it (the module docs). It is committed through the runtime's /// `commit_and_submit`, which, where no other submission pass is under way, submits on this /// thread the device's ready batches committed first, this one's among them, and runs their - /// submission checks and submission handlers here, inside the call, of whichever command - /// buffer, queue or thread they are; a batch whose checks wait for another submission's GPU - /// signal to land, and what is behind it, is the scheduler thread's. So no check or - /// submission handler of the process takes a lock a caller holds across a commit: the check - /// takes its command buffer's note and the detach registry's lock - /// ([`backing::submission_check`]), the tiler's handler the process's space + /// submission handlers here, inside the call, of whichever command buffer, queue or thread + /// they are; a batch that waits for another submission's GPU signal to land, and what is + /// behind it, is the scheduler thread's. So no submission handler of the process takes a lock + /// a caller holds across a commit: the tiler's handler takes the process's space /// ([`tiler_handler`]), and the decoder's handlers their records' locks and the completion /// ring's. The call is marked as one that runs submission handlers inside it /// (`crate::core::platform::command::committing`), so a handler of a buffer whose records @@ -1429,27 +1320,16 @@ impl CommandBuffer for VulkanCommandBuffer { } encoding("commit", Policy::Dies, || { predication::boundary(&self.predication, "commit"); - let opened = self.opened.lock().take(); - let detached = || { - opened - .as_ref() - .is_some_and(|opened| backing::uses_detached(&self.raw, opened)) - }; - let failure = self.failure("commit", detached); + self.committed.store(true, Ordering::SeqCst); + let failure = self.failure("commit"); self.check_executions(failure.as_ref().map(|f| &f.encoders), progress.as_deref()); - let check = match (&failure, opened) { - (None, Some(opened)) => Some(backing::submission_check(opened)), - _ => None, - }; if let Some(progress) = &progress { progress.committing(); } committing(|| { - timing::commit(&self.raw, || match (failure, check) { - (Some(failure), _) => self.raw.commit_failed(failure), - (None, Some(check)) => (self.raw.set_submission_check(check)) - .and_then(|()| committing_here(|| self.raw.commit_and_submit())), - (None, None) => committing_here(|| self.raw.commit_and_submit()), + timing::commit(&self.raw, || match failure { + Some(failure) => self.raw.commit_failed(failure), + None => committing_here(|| self.raw.commit_and_submit()), }) }) }) @@ -1474,17 +1354,12 @@ impl CommandBuffer for VulkanCommandBuffer { /// Commits the work encoded so far as it is committed at `commit`, and answers a command /// buffer of its queue that goes on from it (the module docs' "A command buffer in parts"), /// where it may be split ([`CommandBufferObject::splits`]); `None` otherwise, the command - /// buffer as it was. The next part takes the command buffer's place among the releases of - /// detached objects ([`Opened::next_part`]), so its submissions fail by what the whole - /// buffer's would. Its make waits while the queue holds 64 uncompleted command buffers, as + /// buffer as it was. Its make waits while the queue holds 64 uncompleted command buffers, as /// `commandBuffer` does: the caller leaves room. fn split(&self, on: OnFault) -> RaiseResult> { if !self.splits() { return Ok(None); } - let Some(opened) = plain(|| self.opened.lock().as_ref().map(Opened::next_part)) else { - return Ok(None); - }; let raw = waiting("commandBuffer", || { self.raw.command_queue().command_buffer() })?; @@ -1494,7 +1369,7 @@ impl CommandBuffer for VulkanCommandBuffer { open_encoders: Arc::default(), progress: Mutex::new(None), predication: Predication::new(&self.device), - opened: Mutex::new(Some(opened)), + committed: AtomicBool::new(false), made: AtomicUsize::new(0), failing: Mutex::new(Vec::new()), type_9: Mutex::new(Vec::new()), @@ -1780,19 +1655,17 @@ mod tests { } } - /// A commit runs the command buffer's submission check and its submission handler inside the - /// call, on the committing thread, where no other submission pass is under way - /// (`rt::CommandBuffer::commit_and_submit`): the handler finds a lock the caller holds across - /// the commit held, as the decoder's device caches hold theirs across an early copy, so a - /// check or handler that took a lock its commit's caller holds would deadlock there. Those of - /// this platform and the decoder take none: the check takes its command buffer's note and the - /// detach registry's lock ([`backing::submission_check`]), the decoder's handlers their - /// records' locks and the completion ring's, and the tiler's handler the process's space - /// ([`tiler_handler`]), none of which a commit's caller holds. The commit is marked on its + /// A commit runs the command buffer's submission handler inside the call, on the committing + /// thread, where no other submission pass is under way (`rt::CommandBuffer::commit_and_submit`): + /// the handler finds a lock the caller holds across the commit held, as the decoder's device + /// caches hold theirs across an early copy, so a handler that took a lock its commit's caller + /// holds would deadlock there. Those of this platform and the decoder take none: the + /// decoder's handlers their records' locks and the completion ring's, and the tiler's handler + /// the process's space ([`tiler_handler`]), none of which a commit's caller holds. The commit is marked on its /// thread (`crate::core::platform::command::committing`), so a decoder's handler run there /// on a thread the host's raise is not named for hands its records over to post. #[test] - fn a_commit_checks_and_submits_inside_the_call_under_the_caller_s_locks() { + fn a_commit_submits_inside_the_call_under_the_caller_s_locks() { use crate::core::platform::blit::{BlitCmd, BlitEncoder as _}; use crate::core::platform::types::NsRange; @@ -1820,7 +1693,6 @@ mod tests { }), ) .unwrap(); - let checked = d.raw.work_counts().batches_checked_at_commit; let held = caller.lock(); cb.commit(OnFault::Return).unwrap(); let seen = ran.lock().take(); @@ -1831,11 +1703,6 @@ mod tests { "its handler ran inside the commit, on its thread, the caller's lock held, the commit \ marked" ); - assert_eq!( - d.raw.work_counts().batches_checked_at_commit, - checked + 1, - "its check ran inside the commit" - ); cb.wait_until_completed(OnFault::Return).unwrap(); assert_eq!(cb.status(), CommandBufferStatus::COMPLETED); } @@ -2579,7 +2446,7 @@ mod tests { /// A relayed failure's description and death line carry Metal's description beside the /// runtime's error, as the driver's message gave it (MoltenVK 1.4.1's forms), and the error - /// alone where the message gave none; a detached object's use keeps Metal's own description + /// alone where the message gave none #[test] fn relayed_failures_name_metals_description() { use rt::CommandBufferError as E; @@ -2610,11 +2477,6 @@ mod tests { "the Vulkan runtime's command buffer failed: Execution(9)" ); } - let detached = command_buffer_error(E::Injected(backing::DETACHED_USE), Some(metal.into())); - assert_eq!( - detached.description, - "Insufficient Memory (00000008:kIOGPUCommandBufferCallbackErrorOutOfMemory)" - ); assert!(relayed_line(13, Some(metal)).ends_with( "with code 13, which no failure of Metal's command buffers has (Metal's description: \ Discarded (victim of GPU error/recovery))" @@ -2859,19 +2721,15 @@ mod tests { } /// A command buffer Metal's GPU fails in one way fails so at its commit, from the first - /// encoder that fails; one that only uses a detached object is left to its submissions, and - /// one only its draws of primitive type 9 fail, of one kind, to the runtime. One it would - /// fail in two, a use of a detached object and a failure of its own or a draw of type 9's, - /// or a draw of type 9's and another of its own or of another kind, dies at its commit, as + /// encoder that fails; one nothing fails commits as it is, and one only its draws of + /// primitive type 9 fail, of one kind, is left to the runtime. One it would fail in two, a + /// draw of type 9's and another of its own or of another kind, dies at its commit, as /// nothing measured it #[test] fn a_command_buffer_failing_two_ways_dies_at_its_commit() { let q = dev().new_command_queue().unwrap(); let cb = buffer(&q); - assert!( - cb.failure("commit", || true).is_none(), - "a detached use alone" - ); + assert!(cb.failure("commit").is_none(), "nothing fails it"); for from in [3, 1] { cb.fail(Failing { code: PROTECTION_VIOLATION, @@ -2879,58 +2737,32 @@ mod tests { signals: false, }); } - let failure = cb.failure("commit", || false).unwrap(); + let failure = cb.failure("commit").unwrap(); assert_eq!( (failure.code, failure.encoders, failure.signals), (PROTECTION_VIOLATION, rt::FailedEncoders::From(1), false) ); - let site = catch_death(|| cb.failure("commit", || true)).unwrap_err(); - assert_eq!(site.file, "commit"); let hang = Failing { code: rt::CommandBufferError::GpuHang.metal_code(), from: 2, signals: true, }; cb.fails_at_type_9(hang); - let site = catch_death(|| cb.failure("commit", || false)).unwrap_err(); + let site = catch_death(|| cb.failure("commit")).unwrap_err(); assert_eq!(site.file, "commit"); let cb = buffer(&q); for from in [2, 4] { cb.fails_at_type_9(Failing { from, ..hang }); } - assert!(cb.failure("commit", || false).is_none(), "type 9 alone"); - let site = catch_death(|| cb.failure("commit", || true)).unwrap_err(); - assert_eq!(site.file, "commit"); + assert!(cb.failure("commit").is_none(), "type 9 alone"); cb.fails_at_type_9(Failing { code: rt::CommandBufferError::PageFault.metal_code(), ..hang }); - let site = catch_death(|| cb.failure("commit", || false)).unwrap_err(); + let site = catch_death(|| cb.failure("commit")).unwrap_err(); assert_eq!(site.file, "commit"); } - /// A command buffer the runtime failed for a command's buffer rebound before its first - /// submission (`CommandBufferError::EncodedUseRebound`) dies at the selector where its - /// failure is read, at the commit's (a completed handler's, its status or error) and at the - /// wait, its line naming the rebind and where Metal runs the command - #[test] - fn an_encoded_use_rebound_dies_naming_the_rebind() { - for sel in ["commit", "waitUntilCompleted"] { - *crate::answer::LAST_LINE.lock() = None; - let site = catch_death(|| { - encoded_use_rebound(sel); - }) - .unwrap_err(); - let line = crate::answer::LAST_LINE.lock().take().unwrap_or_default(); - assert_eq!((site.kind, site.file), (DeathKind::Abort, sel), "{line}"); - assert!( - line.contains("rebound after the command was encoded"), - "{line}" - ); - assert!(line.ends_with("the buffer lies in as it submits"), "{line}"); - } - } - /// While an encoder is open, what Metal asserts at dies whatever the handler: another /// encoder, an event, setProtectionOptions:, commit; once it ends, each is taken. An encoder /// that goes without endEncoding is open no more, but abandons its command buffer, whose diff --git a/crates/reims-vgpu-vulkan/src/gpu/device.rs b/crates/reims-vgpu-vulkan/src/gpu/device.rs index c0bfe9266..75e87f533 100644 --- a/crates/reims-vgpu-vulkan/src/gpu/device.rs +++ b/crates/reims-vgpu-vulkan/src/gpu/device.rs @@ -640,8 +640,8 @@ const BUFFER_DESCRIPTOR_OPTIONS: u64 = 0; /// A heap descriptor's `resourceOptions` before any setter: `Private` (measured). const HEAP_DESCRIPTOR_OPTIONS: u64 = 0x20; -/// `MTLResourceOptions` bit 24, which core sets on a read-only detached buffer or heap, and which -/// the runtime takes and drops ([`crate::gpu::backing`] keeps it). +/// `MTLResourceOptions` bit 24, which makes a buffer or heap read-only, and which the runtime +/// takes and drops ([`crate::gpu::backing`] keeps it). const READ_ONLY_OPTION: u64 = 0x100_0000; /// The resource options a descriptor holds after core's storage properties, in order, from @@ -810,26 +810,24 @@ impl VulkanDevice { /// The handle of a buffer this device made, over `surface` when it was made on one. pub(crate) fn buffer(&self, raw: rt::Buffer, surface: Option>) -> VulkanBuffer { - let id = raw.object_id(); let gpu_read_only = surface.as_deref().is_some_and(crate::os::gpu_read_only); Obj::new(BufferObject { raw, device: self.clone_ref(), surface, - backing: Backing::new(false, id), + backing: Backing::new(false), heap: None, gpu_read_only, }) } - /// The handle of a buffer placed in `heap`, whose detach detaches the heap and whose replace - /// answers NO ([`crate::gpu::backing`]). + /// The handle of a buffer placed in `heap`. pub(crate) fn placed_buffer(&self, raw: rt::Buffer, heap: &VulkanHeap) -> VulkanBuffer { Obj::new(BufferObject { raw, device: self.clone_ref(), surface: None, - backing: Backing::fixed(), + backing: Backing::new(false), heap: Some(heap.clone_ref()), gpu_read_only: false, }) @@ -850,7 +848,7 @@ impl VulkanDevice { /// (`newBufferWithIOSurface:`) answers the allocation size too, its first byte the surface's at /// the base address, and reads 0 past the allocation's end (measured on the M3 Max at 0x40, /// 0x1000 and 0x4000, by a kernel's copy). So the buffer is over an alias of the allocation's - /// pages followed by zero-filled pages of the platform's own ([`backing::gather`]), from the + /// pages followed by zero-filled pages of the platform's own ([`backing::gather_or_nil`]), from the /// offset into it, where the pages past the allocation would be other memory or none; what a /// write past the allocation's end does on Metal is not measured, and here it reaches those /// pages alone. On Linux a surface over several ranges of the guest's pages lends its own @@ -1922,8 +1920,7 @@ impl GpuDevice for VulkanDevice { /// with `no_copy`, the contents themselves with the deallocator, at the pinned address when /// there is one. Nil as `newBufferWithLength:options:` is, for a pinned address the space /// cannot honour, and for no-copy contents of length 0, whose deallocator never runs, as - /// Metal answers (measured: NULL contents of length 0, as core's detached buffer of length 0 - /// is). What the runtime's descriptor has no form for (no-copy without contents, a + /// Metal answers (measured: NULL contents of length 0). What the runtime's descriptor has no form for (no-copy without contents, a /// deallocator of a buffer that is not no-copy, copied contents of another length) dies. fn new_buffer(&self, desc: BufferDesc<'_>) -> RaiseResult> { let sel = "newBufferWithDescriptor:"; @@ -1944,9 +1941,6 @@ impl GpuDevice for VulkanDevice { }; let (placement, mut placing) = metal_space::placing(desc.length, bytes, desc.pinned_gpu_address); - // A no-copy buffer's memory, whose deallocator's run a detach may hold - // ([`backing::Held`]). - let mut own = None; // Whether a no-copy buffer's pages are mapped read-only. let mut read_only = false; // The word that a no-copy buffer's import was made ([`crate::os::ImportMade`]). @@ -1964,15 +1958,11 @@ impl GpuDevice for VulkanDevice { let start = pointer(sel, bytes.ptr()); // The bytes, and what keeps them mapped until the runtime freed its import; the // deallocator is given the bytes' own address, at Metal's moment. - let held = Arc::new(backing::Held::default()); let run = slot.as_ref().map(|slot| { - let held = Arc::clone(&held); runtime_deallocator(slot, move |d: BufferDeallocator, p, len| { - let at = p.as_ptr().addr(); - held.run(Box::new(move || d(HostPtr::from_addr(at), len))); + d(HostPtr::from_addr(p.as_ptr().addr()), len); }) }); - own = Some(backing::Own::new(start, held)); let NoCopyImport { at: imported, run, @@ -2018,10 +2008,7 @@ impl GpuDevice for VulkanDevice { } made.map(|b| { b.map(|raw| { - let backing = Backing::new(held & READ_ONLY_OPTION != 0, raw.object_id()); - if let Some(own) = own { - backing.made_over_own(own); - } + let backing = Backing::new(held & READ_ONLY_OPTION != 0); backing.imported(read_only); Obj::new(BufferObject { raw, @@ -2108,8 +2095,6 @@ impl GpuDevice for VulkanDevice { })) => metal_aborts(sel, &format!("a heap of resource options {held:#x}")), made => made, }; - // The alias a heap over address ranges is made over. - let mut made_over = None; let heap = match desc.address_ranges { None => create(sel, Policy::Dies, nil, || { storage(match token { @@ -2119,7 +2104,8 @@ impl GpuDevice for VulkanDevice { })?, Some(_) if desc.size == 0 => None, Some(ranges) => { - made_over = desc + // The alias the heap is made over, which the runtime's import keeps. + let made_over = desc .size .checked_next_multiple_of(HEAP_GRANULE) .and_then(|size| backing::gather_or_nil(sel, &ranges.ranges, size, read_only)) @@ -2133,8 +2119,7 @@ impl GpuDevice for VulkanDevice { let heap = create(sel, Policy::Dies, nil, || { // SAFETY: the alias covers the heap's size, the descriptor's rounded up // to the runtime's granule, and starts on a page, the runtime's import - // unit on this host. It is as a replace's alias is otherwise - // (`VulkanBuffer::replace_backing`). + // unit on this host. storage(unsafe { match token { Some(token) => { @@ -2165,14 +2150,14 @@ impl GpuDevice for VulkanDevice { }; Ok(HeapMade { heap: heap.map(|raw| { - // Only a heap over address ranges detaches ([`crate::gpu::backing`]). + // A heap over address ranges keeps their pages ([`crate::gpu::backing`]). let backing = match &desc.address_ranges { Some(ranges) => { - let backing = Backing::heap(read_only, raw.object_id()); - backing.made_over(&ranges.ranges, made_over); + let backing = Backing::new(read_only); + backing.made_over(&ranges.ranges); backing } - None => Backing::fixed(), + None => Backing::new(false), }; Obj::new(HeapObject { raw, @@ -2190,7 +2175,7 @@ impl GpuDevice for VulkanDevice { /// A heap whose memory is `bytes`, imported in place as a no-copy buffer's is /// ([`no_copy_release`]), at the address Metal's space gives it or the value's pin: its /// resources lie in `bytes` from their offsets, so the guest's writes there and the GPU's are - /// each other's, and it never detaches ([`Backing::fixed`]). Nil for a size of 0, for bytes + /// each other's. Nil for a size of 0, for bytes /// short of the size rounded up to the runtime's granule, and as [`Self::new_heap`] answers /// for its address; storage other than `Shared` dies, as there. A type the runtime lacks /// dies at `setType:`. @@ -2267,7 +2252,7 @@ impl GpuDevice for VulkanDevice { } Ok(HeapMade { heap: heap.map(|raw| { - let backing = Backing::fixed(); + let backing = Backing::new(false); backing.imported(read_only || bit_24); Obj::new(HeapObject { raw, diff --git a/crates/reims-vgpu-vulkan/src/gpu/encode_render.rs b/crates/reims-vgpu-vulkan/src/gpu/encode_render.rs index 48b389030..e36675a90 100644 --- a/crates/reims-vgpu-vulkan/src/gpu/encode_render.rs +++ b/crates/reims-vgpu-vulkan/src/gpu/encode_render.rs @@ -1112,7 +1112,7 @@ fn stores_out(store: rt::StoreAction) -> bool { } /// Whether `texture`, an attachment's, lies in read-only memory the runtime copies, dropping the -/// GPU's writes: read-only and not a surface's twin ([`crate::gpu::writes::Kept::Until`]). +/// GPU's writes: read-only and not a surface's twin ([`crate::gpu::writes::Kept::Copied`]). fn over_read_only_copy(texture: &Source) -> bool { texture.writes_kept() && !texture.twinned() } diff --git a/crates/reims-vgpu-vulkan/src/gpu/frame_cost.rs b/crates/reims-vgpu-vulkan/src/gpu/frame_cost.rs index 7f033fc8f..68fcf13c1 100644 --- a/crates/reims-vgpu-vulkan/src/gpu/frame_cost.rs +++ b/crates/reims-vgpu-vulkan/src/gpu/frame_cost.rs @@ -21,9 +21,7 @@ //! //! The environment picks what runs: `FRAME_COST_RUNS` the runs (5), `FRAME_COST_SHAPE` one shape //! (`wide` or `many`), `FRAME_COST_ONLY` one path, for a profile of it (`platform` or `runtime`), -//! `FRAME_COST_OPTIONS` other device options ([`product_device`]), and -//! `FRAME_COST_RUNTIME_CHECK=1` a submission check on each of the runtime's command buffers -//! ([`runtime_checks`]). +//! and `FRAME_COST_OPTIONS` other device options ([`product_device`]). use crate::core::platform::Platform; use crate::core::platform::blit::{BlitCmd, BlitEncoder as _, ResourceRef}; @@ -517,26 +515,11 @@ fn runtime_command_buffer( t.time(15, || { let handler = Box::new(move |_: &rt::CommandBuffer| tx.send(()).unwrap()); cb.add_completed_handler(handler).unwrap(); - if runtime_checks() { - cb.set_submission_check(std::sync::Arc::new(|_| None)) - .unwrap(); - } cb.commit().unwrap(); }); (cb, rx) } -/// Whether the runtime alone commits each command buffer with a submission check that passes -/// every submission (`FRAME_COST_RUNTIME_CHECK=1`), as the platform commits each with its own -/// ([`crate::gpu::backing::submission_check`]): what the check costs the runtime, apart from what -/// the platform's check does. -fn runtime_checks() -> bool { - static ON: std::sync::LazyLock = std::sync::LazyLock::new(|| { - std::env::var_os("FRAME_COST_RUNTIME_CHECK").is_some_and(|v| v == "1") - }); - *ON -} - /// A device of the system default's physical device made with the product's options: the /// platform's, but announcing at every occurrence only what the product's device does (the kinds /// a call hears and those that die by default), where a test process's device announces every diff --git a/crates/reims-vgpu-vulkan/src/gpu/reach.metal b/crates/reims-vgpu-vulkan/src/gpu/reach.metal index 4588578a1..aaca8d206 100644 --- a/crates/reims-vgpu-vulkan/src/gpu/reach.metal +++ b/crates/reims-vgpu-vulkan/src/gpu/reach.metal @@ -1,6 +1,6 @@ // The tests' kernel that reaches a buffer through an address it loads from another -// (`tests/detach_backing.rs`), naming nothing of it: it reads the word there into `words[0]`, and -// writes `words[1]` to the word after it. +// (`tests/client_direction.rs`, `src/gpu/resource/tests/metal_tests.rs`), naming nothing of it: it +// reads the word there into `words[0]`, and writes `words[1]` to the word after it. #include using namespace metal; diff --git a/crates/reims-vgpu-vulkan/src/gpu/resource.rs b/crates/reims-vgpu-vulkan/src/gpu/resource.rs index c00ff3375..2f04ab88d 100644 --- a/crates/reims-vgpu-vulkan/src/gpu/resource.rs +++ b/crates/reims-vgpu-vulkan/src/gpu/resource.rs @@ -36,13 +36,13 @@ use crate::answer::{ unrepresentable, }; use crate::gpu; -use crate::gpu::backing::{Backing, REPLACE}; +use crate::gpu::backing::Backing; use crate::gpu::desc::{Maker, VulkanTextureDescriptor, created_format_refused}; use crate::gpu::device::VulkanDevice; use crate::gpu::metal_space::Hold; use crate::gpu::writes::{Reflected, Reflection}; use crate::os::OsSurface; -use crate::platform::{Obj, VulkanAddressRangeArray, VulkanPlatform}; +use crate::platform::{Obj, VulkanPlatform}; /// A runtime buffer, with the device that made it and the IOSurface it retains. #[derive(Debug)] @@ -54,10 +54,10 @@ pub struct BufferObject { /// The IOSurface whose memory it is (`newBufferWithIOSurface:`): one reference, which the /// runtime's deallocator of the buffer shares. pub surface: Option>, - /// Whether it is detached, and the read-only bit it was made with ([`crate::gpu::backing`]). - pub backing: Backing, - /// The heap it is placed in, which its detach detaches, held while it lives + /// The guest's pages it is over, and the read-only bit it was made with /// ([`crate::gpu::backing`]). + pub backing: Backing, + /// The heap it is placed in, held while it lives. pub heap: Option, /// Whether the GPU's writes to its bytes never reach their memory: it was made on a surface /// of [`crate::os::gpu_read_only`] (`newBufferWithIOSurface:`). Read once, as it is made, as @@ -126,9 +126,7 @@ pub(crate) fn writes_never_reach(surface: Option<&OsSurface>, under: Option<&Und pub type VulkanTexture = Obj; /// The buffer a texture is over, or the heap it is placed in, which the texture holds as -/// Metal's does: a detached one is released with the last texture in it, so a command buffer -/// that uses such a texture fails as Metal's does ([`crate::gpu::backing`]). Each holds the -/// bytes of the buffer or heap the texture's texels may lie in, a first byte and an end, which +/// Metal's does. Each holds the bytes of the buffer or heap the texture's texels may lie in, a first byte and an end, which /// a write of the texture may change ([`crate::gpu::writes::texture_memory`]). #[derive(Debug)] pub enum Under { @@ -405,9 +403,10 @@ pub struct HeapObject { pub raw: rt::Heap, /// The device that made it. pub device: VulkanDevice, - /// Its descriptor's size, which a replace's ranges total. + /// Its descriptor's size. pub descriptor_size: u64, - /// Whether it is detached, and the read-only bit it was made with ([`crate::gpu::backing`]). + /// The guest's pages it is over, and the read-only bit it was made with + /// ([`crate::gpu::backing`]). pub backing: Backing, /// Its buffers and textures, while they live, for the ranges of its textures nothing may /// share ([`Placements::place`]). @@ -442,7 +441,7 @@ pub struct HeapObject { /// ([`crate::answer::HEARD`]). /// /// Core makes a buffer over all of the bytes the heap's descriptor asked for with each heap, at -/// its creation, before anything else is asked of it: a detached heap's cover buffer, which a +/// its creation, before anything else is asked of it: a heap's cover buffer, which a /// command that lists the heap where a buffer is expected uses, and a legacy heap's private /// buffer, through which core pages the heap's bytes to and from the guest's pages. It is told /// by that alone: the first buffer or texture asked of the heap, made or not @@ -722,12 +721,6 @@ impl HeapObject { ); } } - - /// `detachBacking`: detached from now on by the runtime, in no memory until a replace, for a - /// heap made over address ranges ([`Backing::detach`]). - pub(crate) fn detach(&self) { - self.backing.detach(|| self.raw.detach_backing()); - } } /// `id`. @@ -1058,36 +1051,13 @@ impl Buffer for VulkanBuffer { /// NULL for a `Private` buffer, as Metal's, and for one made on a surface /// (`newBufferWithIOSurface:`), as Metal's on every surface, of `Shared` storage all the same /// (measured on the M3 Max: a surface of its own memory, and ones over the guest's pages - /// without `kIOSurfaceClientDirection` and with 2 and 3). A detached buffer, or one placed in - /// a detached heap, which lies in no memory, answers where it did before - /// ([`Backing::kept_contents`]). + /// without `kIOSurfaceClientDirection` and with 2 and 3). fn contents(&self) -> HostPtr { if self.surface.is_some() { return HostPtr::NULL; } let at = |p: NonNull| HostPtr::from_ptr(p.as_ptr()); - plain(|| { - let kept = match &self.heap { - Some(heap) => heap - .backing - .kept_contents() - .map(|first| at(first).wrapping_add(self.raw.heap_offset())), - None => self.backing.kept_contents().map(at), - }; - kept.or_else(|| self.raw.contents().map(crate::os::shown_at).map(at)) - }) - .unwrap_or(HostPtr::NULL) - } - - /// The buffer is detached from now on: its `contents` and GPU address stay, and the GPU - /// reads zeros where it reached the guest's pages, as the runtime's detach leaves it in no - /// memory. One placed in a heap detaches the heap instead ([`crate::gpu::backing`]). - fn detach_backing(&self) -> RaiseResult<()> { - plain(|| match &self.heap { - Some(heap) => heap.detach(), - None => self.backing.detach(|| self.raw.detach_backing()), - }); - Ok(()) + plain(|| self.raw.contents().map(crate::os::shown_at).map(at)).unwrap_or(HostPtr::NULL) } /// Nothing for a buffer that is not `Managed`, as Metal; for a `Managed` one, refused for a @@ -1290,41 +1260,6 @@ impl Buffer for VulkanBuffer { Ok(Some(self.device.texture_in(raw, under, usage))) } - /// A detached no-copy buffer over an alias of the ranges, which total its length, from now - /// on; NO as Metal answers ([`crate::gpu::backing`]). The runtime's refusal dies: core - /// replaces only its own no-copy buffers, and no command buffer it has not committed holds - /// a use of one then. - fn replace_backing( - &self, - ranges: &VulkanAddressRangeArray, - read_only: bool, - ) -> RaiseResult { - let length = plain(|| self.raw.length()); - self.backing.replace( - &ranges.ranges, - read_only, - length, - length, - |first, keep, made| { - send(REPLACE, Policy::Dies, || { - // SAFETY: the alias is mapped and readable; a read-only one only the GPU - // writes, whose writes this host's GPU drops (`backing`'s docs), and any - // other is writable. It stays mapped, with the same pages, until its - // keep-alive is dropped, as nothing else frees or remaps it. - unsafe { - (self.raw).rebind_bytes_no_copy( - crate::os::host_memory(first), - None, - Some(keep), - ) - } - })?; - made.made(&self.raw.device()); - Ok(()) - }, - ) - } - /// The runtime's export of the buffer's memory (`export_memory_fd`): a buffer the runtime /// made exportable ([`VulkanDevice`]'s `new_exportable_buffer_of_length`), else refused. fn export_memory(&self) -> Result { @@ -1939,13 +1874,6 @@ fn placed(sel: &'static str, made: Result) -> Result for VulkanHeap { - /// The heap is detached from now on: its buffers' `contents` and its GPU address stay, and - /// the GPU reads zeros where it reached the guest's pages ([`crate::gpu::backing`]). - fn detach_backing(&self) -> RaiseResult<()> { - plain(|| self.detach()); - Ok(()) - } - fn gpu_address(&self) -> u64 { plain(|| self.raw.gpu_address()).0 } @@ -2061,7 +1989,7 @@ impl Heap for VulkanHeap { // Over the guest's pages alone: in a legacy heap, over the device's memory, what // the runtime announces of the texture's layout there is relayed alone. let lossless = heard.contains(&rt::Degradation::HeapTextureLosslessLayout) - && self.backing.detaches(); + && self.backing.over_guest_pages(); if lossless && desc.sample_count > 1 { crate::answer::inexact(sel, crate::answer::Inexact::HeapLayout, || { format!( @@ -2098,39 +2026,6 @@ impl Heap for VulkanHeap { }) } - /// A detached heap over an alias of the ranges, which total its descriptor's size, from now - /// on; NO as Metal answers ([`crate::gpu::backing`]). Every buffer and texture in it stays, - /// at its offset. The runtime's refusal dies: core replaces only heaps it made over address - /// ranges, and no command buffer it has not committed holds a use of one then. - fn replace_backing( - &self, - ranges: &VulkanAddressRangeArray, - read_only: bool, - ) -> RaiseResult { - let size = plain(|| self.raw.size()); - self.backing.replace( - &ranges.ranges, - read_only, - self.descriptor_size, - size, - |first, keep, made| { - send(REPLACE, Policy::Dies, || { - // SAFETY: as a buffer's, for the heap's size; the alias starts on a page, - // which is the runtime's import unit on this host. - unsafe { - (self.raw).rebind_bytes_no_copy( - crate::os::host_memory(first), - None, - Some(keep), - ) - } - })?; - made.made(&self.raw.device()); - Ok(()) - }, - ) - } - /// The heap's modes, an untracked mode where its descriptor named the default, as Metal's. fn resource_options(&self) -> u64 { plain(|| self.raw.resource_options()).raw() @@ -2557,7 +2452,7 @@ pub(crate) mod tests { (b, guest) } - /// `MTLResourceOptions` bit 24, which core sets on a read-only detached buffer or heap. + /// `MTLResourceOptions` bit 24, which makes a buffer or heap read-only. pub(crate) const BIT_24: u64 = 0x100_0000; /// A no-copy buffer a descriptor names over `pages` pages of zeros of the platform's own, @@ -4753,11 +4648,11 @@ pub(crate) mod tests { assert!(heap.new_texture(&desc(166, 0x1), 0xc000).unwrap().is_some()); } - /// A writable heap of 4 KiB over a page of the guest's, as core's detach heap makes one of - /// an x86_64 guest's pages, is made on every host. The runtime's heap covers 16 KiB + /// A writable heap of 4 KiB over a page of the guest's, as of an x86_64 guest's pages, is + /// made on every host. The runtime's heap covers 16 KiB /// ([`crate::gpu::backing::HEAP_GRANULE`]), so on a host of 4 KiB pages its alias has zeros /// past the page: on Linux a file of their own, which the runtime imports with the guest's - /// page as dma-bufs (`crate::gpu::backing::gather`); anonymous zeros beside them would import + /// page as dma-bufs (`crate::gpu::backing::gather_or_nil`); anonymous zeros beside them would import /// neither as host memory nor as a dma-buf #[test] fn a_heap_over_less_than_its_granule_is_made() { @@ -4822,40 +4717,20 @@ pub(crate) mod tests { .unwrap() } - /// A `Shared` heap of [`over_pages`] bytes as core's detach heap is made: over pages of its - /// own (core's temporary allocation), detached at once. Core gives it the guest's pages at - /// its first prepare ([`replace_heap`]), and makes a cover buffer over all of it, which the - /// tests that need one make. - fn detached_heap(p: &P, d: &P::Device) -> P::Heap { - let ranges = ranges_at(p, guest_pages()); - let heap = d - .new_heap(&HeapDesc { - size: over_pages(), - heap_type: 1, - options: vec![OptionSet::StorageMode(0), OptionSet::HazardTrackingMode(0)], - address_ranges: Some(&ranges), - pinned_gpu_address: None, - }) - .unwrap() - .heap - .unwrap(); - heap.detach_backing().unwrap(); - heap - } - - /// `heap`'s backing replaced with the pages at `address`, as core's first prepare gives a - /// detached heap the guest's pages. - fn replace_heap(p: &P, heap: &P::Heap, address: u64) { - let replaced = heap.replace_backing(&ranges_at(p, address), false); - assert!(replaced.unwrap(), "the heap's backing replaced"); - } - - /// A heap over the pages at `address`, made as core makes its detach heap: a - /// [`detached_heap`], given the pages by [`replace_heap`]. + /// A `Shared` heap of [`over_pages`] bytes over the pages at `address`, made over their + /// address range. pub(crate) fn heap_at(p: &P, d: &P::Device, address: u64) -> P::Heap { - let heap = detached_heap(p, d); - replace_heap(p, &heap, address); - heap + let ranges = ranges_at(p, address); + d.new_heap(&HeapDesc { + size: over_pages(), + heap_type: 1, + options: vec![OptionSet::StorageMode(0), OptionSet::HazardTrackingMode(0)], + address_ranges: Some(&ranges), + pinned_gpu_address: None, + }) + .unwrap() + .heap + .unwrap() } /// A `Shared` heap of [`over_pages`] bytes over pages of its own, a `Depth32Float_Stencil8` diff --git a/crates/reims-vgpu-vulkan/src/gpu/writes.rs b/crates/reims-vgpu-vulkan/src/gpu/writes.rs index 7a6686da2..48f777805 100644 --- a/crates/reims-vgpu-vulkan/src/gpu/writes.rs +++ b/crates/reims-vgpu-vulkan/src/gpu/writes.rs @@ -27,9 +27,9 @@ //! unmeasured for, which refuses the whole state's reflection, leaves every other slot answered. //! A function's write through an address it loads (an argument buffer's, a pointer's) into such //! an object not made resident for writing names nothing and is not seen: it reaches the pages. -//! - **The guest's read-only objects** (a read-only replace, a heap made with `MTLResourceOptions` -//! bit 24 over address ranges, a no-copy buffer or heap made with it or over pages mapped -//! read-only; [`Kept::Until`]; [`crate::os::COPIES_READ_ONLY`]), which the runtime makes +//! - **The guest's read-only objects** (a heap made with `MTLResourceOptions` bit 24 over address +//! ranges, a no-copy buffer or heap made with it or over pages mapped +//! read-only; [`Kept::Copied`]; [`crate::os::COPIES_READ_ONLY`]), which the runtime makes //! over a copy of the pages whose GPU writes it drops, as Metal's GPU drops them: a write through //! a buffer over it is sent (a shader's store through a slot or a loaded address, a blit's fill //! or copy into the buffer, a pass's visibility results), and so is a pass whose attachment lies @@ -101,14 +101,13 @@ pub enum Kept { /// writable twin of its pages, so the GPU's writes through the object reach them /// ([`surface_kept`]). Always, - /// Until a detach leaves the buffer or heap in no memory: for a texture over a buffer or - /// heap, read-only memory the runtime makes the buffer or heap over a copy of, dropping the - /// GPU's writes, where what Metal does with a texture's writes is unmeasured - /// ([`crate::gpu::backing::Backing::read_only_now`]); no replace gives it other memory while - /// work encoded holds it, as the runtime refuses the replace (`crate::gpu::backing`). A - /// buffer's own memory the runtime copies is never `Until`: the runtime drops its writes, as - /// Metal's GPU does. - Until(Arc), + /// For the object's life: for a texture over a buffer or heap, read-only memory the runtime + /// makes the buffer or heap over a copy of, dropping the GPU's writes, where what Metal does + /// with a texture's writes is unmeasured ([`crate::gpu::backing::Backing::read_only_now`]), + /// with the buffer's or heap's pages, which tell one object's from another's. A buffer's own + /// memory the runtime copies is never `Copied`: the runtime drops its writes, as Metal's GPU + /// does. + Copied(Arc), } impl Kept { @@ -121,8 +120,7 @@ impl Kept { pub fn holds(&self) -> bool { match self { Kept::No => false, - Kept::Always => true, - Kept::Until(pages) => !pages.zeroed(), + Kept::Always | Kept::Copied(_) => true, } } } @@ -131,7 +129,7 @@ impl PartialEq for Kept { fn eq(&self, other: &Kept) -> bool { match (self, other) { (Kept::No, Kept::No) | (Kept::Always, Kept::Always) => true, - (Kept::Until(a), Kept::Until(b)) => Arc::ptr_eq(a, b), + (Kept::Copied(a), Kept::Copied(b)) => Arc::ptr_eq(a, b), _ => false, } } @@ -319,8 +317,8 @@ impl Drop for Keeping { /// this platform does not answer as Metal's GPU does ([`Memory::kept`]): a surface the GPU only /// reads, which the runtime imports through a writable twin of its pages, where the write would /// land in those pages, and later reads see it; or, for a -/// texture's write, a resolve into one or a CPU write, read-only guest pages (a read-only replace -/// or heap, a resource made with `MTLResourceOptions` bit 24) the runtime copies, dropping the +/// texture's write, a resolve into one or a CPU write, read-only guest pages (a read-only heap, a +/// resource made with `MTLResourceOptions` bit 24) the runtime copies, dropping the /// write, where what Metal does is unmeasured. Metal's GPU drops a shader's store, a fill's or /// a visibility result's there and completes the command, and fails the command buffer of a /// pass that stores an attachment back to it (the module's measurements), and its CPU's write @@ -332,7 +330,7 @@ pub(crate) fn kept_write(sel: &'static str, what: &str) -> ! { &format!( "{what} read-only memory (a surface the GPU only reads, which this host's runtime \ imports through a writable twin, so the write would reach it; or, \ - for a texture, a read-only replace, heap or resource, whose copy drops it), where \ + for a texture, a read-only heap or resource, whose copy drops it), where \ Metal's GPU drops the write or faults, or what it does is unmeasured, and its CPU's \ write through the read-only mapping ends the process" ), @@ -393,8 +391,7 @@ pub fn buffer_memory(b: &BufferObject) -> Memory { /// The host memory `b`'s bytes `bytes` (a first byte and an end) lie in now: in its surface's /// memory (`newBufferWithIOSurface:`, from the surface's base address), at its place in its -/// heap's, in the guest's pages of its last replace, or in the memory it was made over; none -/// where a detach left it in no memory, or for a `Private` one. +/// heap's, or in the memory it was made over; none for a `Private` one. pub fn buffer_bytes_memory(b: &BufferObject, bytes: Range) -> Memory { if let Some(s) = &b.surface { return Memory::of_surface_bytes(s, bytes); @@ -412,10 +409,6 @@ pub fn buffer_bytes_memory(b: &BufferObject, bytes: Range) -> Memory { } // Its writes into read-only memory the runtime copies are dropped, as Metal's GPU drops them: // nothing kept. - let paged = b.backing.in_pages(&bytes); - if paged.is_some() || b.backing.kept_contents().is_some() { - return Memory::over(paged.unwrap_or_default(), Kept::No); - } let contents = plain(|| b.raw.contents()).map(|first| { let first = first.as_ptr().addr().to_u64(); std::iter::once(first.saturating_add(bytes.start)..first.saturating_add(bytes.end)) @@ -485,10 +478,6 @@ fn buffer_bytes_bound(b: &BufferObject, bytes: Range) -> Bound { }; } // Nothing kept, as `buffer_bytes_memory`'s. - let paged = b.backing.meets_pages(&bytes); - if paged.is_some() || b.backing.kept_contents().is_some() { - return Bound::over(paged.unwrap_or(false), Kept::No); - } Bound::over(plain(|| b.raw.contents()).is_some(), Kept::No) } @@ -534,8 +523,8 @@ pub fn texture_bound(t: &TextureObject) -> Bound { } /// The host memory of `h`'s bytes `bytes`, a first byte and an end: in the guest's pages it was -/// made over or last replaced with; none for one of memory of its own. What it keeps is a -/// texture's in it ([`Kept::Until`]); a buffer in it keeps nothing ([`buffer_bytes_memory`]). +/// made over; none for one of memory of its own. What it keeps is a +/// texture's in it ([`Kept::Copied`]); a buffer in it keeps nothing ([`buffer_bytes_memory`]). pub(crate) fn heap_bytes_memory(h: &HeapObject, bytes: Range) -> Memory { Memory::over( h.backing.in_pages(&bytes).unwrap_or_default(), @@ -931,7 +920,7 @@ pub(crate) mod tests { use crate::gpu::backing::Backing; let count = || KEPT_NOW.load(Ordering::SeqCst); assert!(!any_kept()); - let (a, b) = (Backing::fixed(), Backing::fixed()); + let (a, b) = (Backing::new(false), Backing::new(false)); a.imported(false); assert_eq!(count(), 0); a.imported(true); @@ -954,7 +943,7 @@ pub(crate) mod tests { /// what the memory collected answers: for a buffer of the device's memory, one placed in a /// heap over the guest's pages (at its bytes and past the pages), one on a surface, textures /// placed in the heap, over a buffer, on surfaces over the guest's pages and over memory of - /// their own, and one of memory of its own; and once the heap is detached, in no memory + /// their own, and one of memory of its own #[test] fn bound_memory_is_the_memory_collected() { let (p, d) = ( @@ -1026,11 +1015,8 @@ pub(crate) mod tests { ); } }; - agree("attached"); + agree("made"); assert!(buffer_bound(&placed).meets && texture_bound(&in_heap).meets); - heap.detach_backing().unwrap(); - agree("detached"); - assert!(!buffer_bound(&placed).meets && !texture_bound(&in_heap).meets); drop((on_pages, over)); crate::os::tests::free(pages, length); } diff --git a/crates/reims-vgpu-vulkan/src/os/linux/budget.rs b/crates/reims-vgpu-vulkan/src/os/linux/budget.rs index 432069332..97b48ec46 100644 --- a/crates/reims-vgpu-vulkan/src/os/linux/budget.rs +++ b/crates/reims-vgpu-vulkan/src/os/linux/budget.rs @@ -22,7 +22,7 @@ //! [`HEADROOM`] below it ([`claim`], [`Reach::ShortOfHeadroom`]): a view a device would need from //! its files goes through dma-bufs instead, and a no-copy buffer's or heap's import of such a //! view's pages, or of read-only pages with no twin, is refused at the runtime's gate, the buffer -//! or heap made over a copy (`super::vm`'s module docs, "Imports of views"), as a rebind's is. +//! or heap made over a copy (`super::vm`'s module docs, "Imports of views"). //! What has no other way has the headroom to itself: a view through dma-bufs, a range, a //! stand-in, and a twin where no device needs imported pages mapped from their files //! ([`Reach::Whole`]). diff --git a/crates/reims-vgpu-vulkan/src/os/linux/import.rs b/crates/reims-vgpu-vulkan/src/os/linux/import.rs index cc9e04417..798e6f5b4 100644 --- a/crates/reims-vgpu-vulkan/src/os/linux/import.rs +++ b/crates/reims-vgpu-vulkan/src/os/linux/import.rs @@ -3,8 +3,8 @@ //! //! Linux drivers pin imported pages for writing, so the runtime imports no read-only memory //! (typed, `HostMemory`), where Metal reads it: the guest's ranges core maps read-only, aliases -//! of a read-only replace or heap, and surfaces the GPU only reads. For aliases of a read-only -//! replace or heap, and a no-copy buffer or heap over pages mapped read-only, the runtime is +//! of a read-only heap, and surfaces the GPU only reads. For aliases of a read-only heap, and a +//! no-copy buffer or heap over pages mapped read-only, the runtime is //! given the pages themselves: the views' gate refuses them ([`import_gate`]), and the runtime //! makes the buffer or heap over a copy of them whose GPU writes it drops, as Metal's GPU drops //! them (its `copied-host-pages`, a kind of `crate::answer::DIES`), so the GPU reads what Metal's @@ -25,8 +25,7 @@ //! The block of zeros a read-only alias maps past its ranges' pages is a file of zeros all such //! aliases share ([`allocate_zeros`]). Its twin is private memory of zeros instead, so the GPU's //! writes there stay in that twin and never reach the block, though they are kept for the -//! alias's life, where Metal drops them, which the same deaths stop. A detached object lies in -//! no memory (the runtime's detach, `crate::gpu::backing`), so nothing of it is imported. +//! alias's life, where Metal drops them, which the same deaths stop. //! //! A buffer made over a twin answers the address it was made over as its contents //! ([`shown_at`]): the runtime's contents are the twin's. The twin goes once the runtime frees the @@ -377,9 +376,9 @@ static COPIED: Refused = Refused::new("nrcopy"); /// budget ([`twin`]), which the gate refuses, so the runtime copies them. static TWINLESS: Refused = Refused::new("notwin"); -/// The views' gate over the runtime's import of a no-copy buffer's or heap's pages, or a buffer's -/// new pages, by their pointer (`rt::HostMemory::with_import_gate`), which every [`host_memory`] -/// carries, asked on the thread that makes the buffer, heap or rebind, with no lock of the +/// The views' gate over the runtime's import of a no-copy buffer's or heap's pages, by their +/// pointer (`rt::HostMemory::with_import_gate`), which every [`host_memory`] carries, asked on +/// the thread that makes the buffer or heap, with no lock of the /// runtime's held, after [`import_view`] made what it imports. It refuses read-only pages, which /// reach it where no twin was asked for them (all but a surface's read-only alias), or none was /// made short of the headroom of the views' budget ([`twin`], counted there), so the runtime @@ -1204,8 +1203,8 @@ impl SendPtr { /// page (module docs). Where a device needs imported pages mapped from their files, what of the /// bytes lies in views through dma-bufs is mapped from them, and a twin made, short of the /// headroom of the views' budget, past which the gate refuses the pages and the runtime copies -/// them ([`import_gate`]): the runtime asks the gate about every import, a no-copy buffer's, -/// heap's or rebind's. Where none does, a twin may take the whole budget. +/// them ([`import_gate`]): the runtime asks the gate about every import, a no-copy buffer's or +/// heap's. Where none does, a twin may take the whole budget. pub(crate) fn import_view(at: NonNull, length: u64, twin: bool) -> ImportView { let mut plain = ImportView { at, @@ -1600,7 +1599,7 @@ mod tests { assert!(vm.deallocate(at, PAGE).is_success()); } - /// A read-only alias of guest pages shorter than its size, a heap's or a replace's, is + /// A read-only alias of guest pages shorter than its size, a heap's, is /// imported through a writable twin: the pages' bytes, then zeros of the twin's own past /// them, as its zeros map the block of zeros #[test] @@ -1615,7 +1614,7 @@ mod tests { address: first, length: PAGE, }]; - let alias = crate::gpu::backing::gather("test", &ranges, 3 * PAGE, true).unwrap(); + let alias = crate::gpu::backing::gather_or_nil("test", &ranges, 3 * PAGE, true).unwrap(); let at = alias.first(); let view = import_view(at, 3 * PAGE, true); let twin = addr(view.at()); @@ -1633,9 +1632,9 @@ mod tests { assert!(vm.deallocate(guest, PAGE).is_success()); } - /// Readable pages with no file behind them, which no view is made of, end the process at the - /// call that gathers them into an alias, where Metal takes them; a call whose refusal is nil - /// answers nil there by default, counted, as when memory runs out, and dies in strict mode + /// Readable pages with no file behind them, which no view is made of, are the host's refusal + /// of an alias of them, where Metal takes them: the call that gathers them, whose refusal is + /// nil, answers nil by default, counted, as when memory runs out, and dies in strict mode #[test] fn a_gather_of_pages_without_a_file_is_the_hosts_refusal() { use crate::core::platform::types::ResourceAddressRange; @@ -1648,9 +1647,6 @@ mod tests { address: at.addr().to_u64(), length: PAGE, }]; - let gathered = || crate::gpu::backing::gather("test", &ranges, PAGE, false).is_some(); - let site = catch_death(gathered).unwrap_err(); - assert_eq!((site.kind, site.file), (DeathKind::Abort, "test")); let or_nil = || crate::gpu::backing::gather_or_nil("test", &ranges, PAGE, false).is_some(); let site = catch_death(or_nil).unwrap_err(); assert_eq!((site.kind, site.file), (DeathKind::Abort, "test"), "strict"); @@ -1673,8 +1669,8 @@ mod tests { /// Where a device of the process needs imported pages mapped from their files, a view that /// from its files would come within the headroom of the views' budget is mapped through a - /// dma-buf, though the budget has room for it. An import of it (a buffer's, a heap's or a - /// rebind's) leaves it so, and the gate refuses its pages, counted with their bytes, in strict + /// dma-buf, though the budget has room for it. An import of it (a buffer's or a heap's) + /// leaves it so, and the gate refuses its pages, counted with their bytes, in strict /// mode too, as the runtime copies them; with room short of the headroom, an import maps the /// pages from their files, which the gate lets through. Where udmabuf does not open, the view /// is mapped from its files, and ends the process past the budget. The flag is the process's, diff --git a/crates/reims-vgpu-vulkan/src/os/linux/plane_copy.rs b/crates/reims-vgpu-vulkan/src/os/linux/plane_copy.rs index 2a1c4b28a..4a8623f8f 100644 --- a/crates/reims-vgpu-vulkan/src/os/linux/plane_copy.rs +++ b/crates/reims-vgpu-vulkan/src/os/linux/plane_copy.rs @@ -14,8 +14,7 @@ //! family (`VK_QUEUE_FAMILY_FOREIGN_EXT`, in `GENERAL`) for the copy and handed back after it. //! - **The destination** is a runtime buffer whose bytes are its memory: one in the device's own //! memory, or over host pages the device imported in place. A buffer whose pages are a copy the -//! runtime keeps (`copied-host-pages`), or that is detached, or whose GPU writes never reach its -//! memory, is refused: a write into its `VkBuffer` would never reach the pages. +//! runtime keeps (`copied-host-pages`), or whose GPU writes never reach its memory, is refused: a write into its `VkBuffer` would never reach the pages. //! - **The copy** is one command buffer of the copier's own on a runtime queue of its own, whose //! `VkQueue` it borrows for the submission, as `crate::awake` does: `vkCmdCopyImageToBuffer` of //! each plane's texels into the buffer at the plane's first byte, its rows `bytes_per_row` apart, @@ -840,9 +839,6 @@ fn destination( if copy.to.gpu_read_only { return Err(refused("the buffer drops the GPU's writes".to_owned())); } - if copy.to.backing.is_detached() { - return Err(refused("the buffer is detached from its memory".to_owned())); - } match buffer.host_backing() { Some(rt::HostBacking::Copied) => { return Err(refused( @@ -851,9 +847,6 @@ fn destination( .to_owned(), )); } - Some(rt::HostBacking::Detached) => { - return Err(refused("the buffer is detached from its pages".to_owned())); - } _ => {} } let texel = copy.source.format.texel_bytes(); diff --git a/crates/reims-vgpu-vulkan/src/os/linux/surface.rs b/crates/reims-vgpu-vulkan/src/os/linux/surface.rs index 108bb2904..467d92d65 100644 --- a/crates/reims-vgpu-vulkan/src/os/linux/surface.rs +++ b/crates/reims-vgpu-vulkan/src/os/linux/surface.rs @@ -449,7 +449,7 @@ fn checked_ranges(ranges: &[PhysicalMemoryRange], alloc_size: u64) -> Option<()> /// /// The zeros are the tail the buffers over the surface at an offset read past its allocation, /// which lie over the view ([`own_alias`]), as an alias of the allocation would give them -/// (`crate::gpu::backing::gather`): a writable view's are a file of its own, which the runtime +/// (`crate::gpu::backing::gather_or_nil`): a writable view's are a file of its own, which the runtime /// imports with the guest's pages, as host memory or as dma-bufs (`super::dma_buf`), which /// udmabuf makes of files alone; a read-only view's map the block of zeros, whose twin, which the /// runtime imports, is zeros of its own (`super::import`). @@ -507,7 +507,7 @@ fn view(runs: &[std::ops::Range], length: u64, zeros: u64, read_only: bool) /// of the guest's pages (`crate::os::surface_alias`), borrowed: the view holds the allocation's /// pages and the zeros a buffer at the surface's offset reads past them ([`view`]), read-only /// where the surface is read-only for the GPU, as an alias of the allocation would be -/// (`crate::gpu::backing::gather`), and stays mapped while the alias holds the surface's memory +/// (`crate::gpu::backing::gather_or_nil`), and stays mapped while the alias holds the surface's memory /// ([`surface_memory_hold`]). `None` for a surface with no view: its own memory, one range of the /// guest's pages, or none. pub(crate) fn own_alias(surface: &LinuxSurface) -> Option { @@ -1078,7 +1078,7 @@ mod tests { /// buffers lie over ([`own_alias`]): the allocation's whole pages, then zeros as far as a /// buffer at its offset reads, writable or read-only as the surface is for the GPU, the /// zeros of a writable one a file of their own and of a read-only one the block of zeros, as - /// an alias of the allocation's would be (`crate::gpu::backing::gather`). The alias keeps the + /// an alias of the allocation's would be (`crate::gpu::backing::gather_or_nil`). The alias keeps the /// view mapped past the surface's last reference, and frees nothing of its own. A surface of /// one range, or of its own memory, has no view to lend #[test] diff --git a/crates/reims-vgpu-vulkan/src/os/linux/vm.rs b/crates/reims-vgpu-vulkan/src/os/linux/vm.rs index dffec8cbc..1654f9f43 100644 --- a/crates/reims-vgpu-vulkan/src/os/linux/vm.rs +++ b/crates/reims-vgpu-vulkan/src/os/linux/vm.rs @@ -14,7 +14,7 @@ //! from [`allocate_aliasable`], a shared mapping of a file of its own: the detach heap's //! temporary, which Metal's heap is made over, is one (core's `HostVm::allocate_aliasable`), //! and so is an alias whose zeros past the guest's pages the runtime imports with them -//! (`crate::gpu::backing::gather`), as a dma-buf takes file pages alone. +//! (`crate::gpu::backing::gather_or_nil`), as a dma-buf takes file pages alone. //! - **`remap_shared_overwrite`** fails with `KERN_INVALID_ADDRESS` where a byte of the source //! has no file behind it, as Mach fails for an unmapped source, before it maps anything. A //! piece the kernel refuses fails the call with nothing changed, as Mach's remap is all or @@ -542,8 +542,7 @@ pub(super) fn file( /// A fresh range of `len` bytes, rounded up to whole pages, of zeros, that a view can be made of: /// a shared mapping of a file of its own, recorded in the backing table. Freed by `deallocate`, -/// as any other range. The block of zeros a detached object reads, and the tests' stand-in for -/// guest memory, are such ranges. +/// as any other range. The tests' stand-in for guest memory is such a range. pub(crate) fn allocate_aliasable(len: u64) -> Result { let Some((_, length)) = pages(HostAddr::NULL, len) else { return Err(NO_SPACE); @@ -1996,11 +1995,11 @@ pub(crate) mod tests { /// An alias of a guest page with zeros past it, as a heap of less than the runtime's 16 KiB /// is made over, has a file behind every byte, writable or read-only, so a dma-buf can be /// made of all of it, as the runtime asks where the device refuses file pages as host memory - /// (`crate::gpu::backing::gather`, `super::dma_buf`) + /// (`crate::gpu::backing::gather_or_nil`, `super::dma_buf`) #[test] fn an_alias_with_zeros_past_its_pages_has_a_file_behind_every_byte() { use crate::core::platform::types::ResourceAddressRange; - use crate::gpu::backing::{REPLACE, gather}; + use crate::gpu::backing::gather_or_nil; let p = page(); for read_only in [false, true] { let guest = allocate_aliasable(p).unwrap(); @@ -2009,7 +2008,7 @@ pub(crate) mod tests { address: guest.addr().to_u64(), length: p, }]; - let alias = gather(REPLACE, &ranges, 4 * p, read_only).unwrap(); + let alias = gather_or_nil("test", &ranges, 4 * p, read_only).unwrap(); let first = alias.first().as_ptr().addr().to_u64(); assert!( files::pieces(first, 4 * p).is_some(), diff --git a/crates/reims-vgpu-vulkan/src/os/macos.rs b/crates/reims-vgpu-vulkan/src/os/macos.rs index b494690ba..0624e4610 100644 --- a/crates/reims-vgpu-vulkan/src/os/macos.rs +++ b/crates/reims-vgpu-vulkan/src/os/macos.rs @@ -307,7 +307,7 @@ thread_local! { } /// Runs `call` with every import [`host_memory`] makes on this thread refused at a gate of its -/// own, so the runtime makes each buffer, heap or rebind over a copy of the pages, as Linux's +/// own, so the runtime makes each buffer or heap over a copy of the pages, as Linux's /// views' gate has it past the headroom of their budget (`os/linux/import.rs`): the copies' /// coherence, on a host whose imports never fail. #[cfg(test)] diff --git a/crates/reims-vgpu-vulkan/src/platform.rs b/crates/reims-vgpu-vulkan/src/platform.rs index cd8d20a69..1a47abfd7 100644 --- a/crates/reims-vgpu-vulkan/src/platform.rs +++ b/crates/reims-vgpu-vulkan/src/platform.rs @@ -783,7 +783,7 @@ impl Platform for VulkanPlatform { } /// The private `MTLResourceAddressRangeArray *`: the ranges, as the array copies them, which a -/// heap is made over and a detached buffer or heap is replaced by ([`crate::gpu::backing`]). +/// heap is made over ([`crate::gpu::backing`]). #[derive(Debug)] pub struct AddressRanges { /// The ranges, in order. diff --git a/crates/reims-vgpu-vulkan/src/remap.rs b/crates/reims-vgpu-vulkan/src/remap.rs index 364794977..1bf1ded52 100644 --- a/crates/reims-vgpu-vulkan/src/remap.rs +++ b/crates/reims-vgpu-vulkan/src/remap.rs @@ -24,16 +24,15 @@ //! bytes changes none. `protect_max` changes no pages. //! //! The platform's own Mach VM calls in [`crate::gpu::backing`] report nothing: an alias's -//! mapping (`gather`), the block of zeros, and an alias's release; nor do those of Linux's +//! mapping (`gather_or_nil`), the block of zeros, and an alias's release; nor do those of Linux's //! surface stand-in (`os::linux::surface`), whose view of the guest's pages is the alias of a //! surface over several ranges of them. Each range is a fresh one of the platform's own, which -//! backs a heap, a rebind, or the no-copy buffers over a surface at an offset into its allocation -//! or whose GPU writes never reach its memory (`buffer_over_surface_at` in -//! [`crate::gpu::device`]). The runtime lets no buffer lie in the import of a heap's bytes or of -//! the memory a rebound buffer takes, and a surface's alias is released by the keep-alive of the -//! last buffer over it, which the runtime drops after it freed that buffer's import, or, where it -//! is the surface's view, by the surface's last release where that comes later, so no buffer made -//! later at the address could lie in one. +//! backs a heap, or the no-copy buffers over a surface at an offset into its allocation or whose +//! GPU writes never reach its memory (`buffer_over_surface_at` in [`crate::gpu::device`]). The +//! runtime lets no buffer lie in the import of a heap's bytes, and a surface's alias is released +//! by the keep-alive of the last buffer over it, which the runtime drops after it freed that +//! buffer's import, or, where it is the surface's view, by the surface's last release where that +//! comes later, so no buffer made later at the address could lie in one. //! //! **Not reported**: the pages of the host's own RAM a memory map names, which core reads at the //! host's addresses with no mapping of its own. The host changes those without the library: no call @@ -43,8 +42,8 @@ //! a mapping of its own there, measured), at no offset into its allocation and with GPU writes that //! reach its memory (the others lie over an alias): one made after the host replaced the pages lies //! in a live one's import, over the old pages, and what Metal's texture on such a surface reads -//! then is not measured. Detached buffers and heaps lie in aliases of their own, fresh at each -//! attach ([`crate::gpu::backing`]), never there. +//! then is not measured. Heaps over address ranges lie in aliases of their own +//! ([`crate::gpu::backing`]), never there. //! //! **Unmaps an import waits for** ([`UnmapHold`]). The runtime runs a no-copy buffer's //! deallocator, given with a keep-alive, as the buffer is released, Metal's moment, and then diff --git a/crates/reims-vgpu-vulkan/tests/address_ranges.rs b/crates/reims-vgpu-vulkan/tests/address_ranges.rs new file mode 100644 index 000000000..b843ee643 --- /dev/null +++ b/crates/reims-vgpu-vulkan/tests/address_ranges.rs @@ -0,0 +1,479 @@ +//! Heaps over address ranges, as a heap over the guest's pages is made, on this crate's +//! platform against Metal's answers, measured on `AppleM3Max-40c-25G229`: which ranges make one, +//! past the heap's size ([`past_the_size`]) and over pages without access, unmapped or read-only +//! ([`without_access`]), and ranges off whole pages ([`unaligned`]): whether the heap is made, +//! and what `contents`, a GPU copy and a GPU fill of a buffer placed over them reach. + +#![cfg(target_os = "macos")] +// Compares with Metal's answers, recorded on macOS. +// Every platform object is `Send` and `Sync` (core's `Handle`, and `Obj`'s bound, which an +// encoder's drop asks of `PredicatedEncoder`), and the proof walks the object's fields: an +// encoder's command buffer, its predication, and the runtime objects that holds, 141 to 150 +// levels deep (measured: rustc warns at a limit of 140, not at 150). That is deeper than +// rustc's default of 128, as in the library (`src/lib.rs`). +#![recursion_limit = "256"] +#![allow( + clippy::unwrap_used, + clippy::indexing_slicing, + clippy::panic, + missing_docs, + unsafe_code +)] + +use reims_vgpu_vulkan::VulkanPlatform; +use reims_vgpu_vulkan::core::host::HostPtr; +use reims_vgpu_vulkan::core::platform::Platform; +use reims_vgpu_vulkan::core::platform::blit::{BlitCmd, BlitEncoder}; +use reims_vgpu_vulkan::core::platform::command::{CommandBuffer, CommandQueue}; +use reims_vgpu_vulkan::core::platform::device::GpuDevice; +use reims_vgpu_vulkan::core::platform::os::vm::{HostVm, VmProt}; +use reims_vgpu_vulkan::core::platform::resource::{Buffer, Heap}; +use reims_vgpu_vulkan::core::platform::types::{NsRange, ResourceAddressRange}; +use reims_vgpu_vulkan::core::platform::values::{HeapDesc, OptionSet}; +use reims_vgpu_vulkan::core::raise::OnFault; +use reims_vgpu_vulkan::remap::VulkanVm; + +const PAGE: u64 = 0x4000; + +/// Fresh pages of the host, each byte `byte`. +fn pages(count: u64, byte: u8) -> HostPtr { + let at = VulkanVm::new().allocate_anywhere(count * PAGE).unwrap(); + // SAFETY: the pages were just allocated, readable and writable. + unsafe { + std::ptr::write_bytes( + at.as_ptr::(), + byte, + usize::try_from(count * PAGE).unwrap(), + ); + }; + at +} + +/// Word `index` of the 32-bit words at `at`. +fn word(at: HostPtr, index: usize) -> u32 { + // SAFETY: the test's own mapped memory. + unsafe { at.as_ptr::().add(index).read_volatile() } +} + +fn range(at: HostPtr, offset: u64, length: u64) -> ResourceAddressRange { + ResourceAddressRange { + address: u64::try_from(at.addr()).unwrap() + offset, + length, + } +} + +/// What the platform does, step by step: each step's name and what it answered or showed. +type Steps = Vec<(&'static str, Vec)>; + +/// A blit encoder of `cb` with `commands`, ended. +fn blit(cb: &P::CommandBuffer, commands: Vec>) { + let e = cb.blit_encoder(OnFault::Return).unwrap().unwrap(); + for command in commands { + e.encode(OnFault::Return, command).unwrap(); + } + e.encode(OnFault::Return, BlitCmd::EndEncoding).unwrap(); +} + +/// `cb` committed and waited for: its status and its error's code (0 for none). +fn finish(cb: &P::CommandBuffer) -> Vec { + cb.commit(OnFault::Return).unwrap(); + cb.wait_until_completed(OnFault::Return).unwrap(); + vec![ + cb.status().0, + cb.error().map_or(0, |e| u64::try_from(e.code).unwrap()), + ] +} + +/// A command buffer of `queue`. +fn command_buffer(queue: &P::CommandQueue) -> P::CommandBuffer { + queue.command_buffer(OnFault::Return).unwrap().unwrap() +} + +/// Frees `length` bytes of the test's pages at `at`. +fn vm_free(at: HostPtr, length: u64) -> bool { + VulkanVm::new().deallocate(at, length).is_success() +} + +/// Two fresh pages of the host after `case`: 0 leaves them readable and writable, 1 takes all +/// access from the second, 2 from both, 3 unmaps the second, 4 leaves both read-only. +fn pages_after(case: u8) -> HostPtr { + let vm = VulkanVm::new(); + let at = pages(2, 0x5a); + let second = at.wrapping_add(PAGE); + match case { + 1 => vm.protect_max(second, PAGE, VmProt(0)).unwrap(), + 2 => vm.protect_max(at, 2 * PAGE, VmProt(0)).unwrap(), + 3 => assert!(vm.deallocate(second, PAGE).is_success()), + 4 => vm.protect_max(at, 2 * PAGE, VmProt::READ).unwrap(), + _ => {} + } + at +} + +/// Lets go of what [`pages_after`] left mapped of its two pages at `at` for `case`: both +/// pages, but only the first after case 3, whose second page it already unmapped. Unmapping +/// that second page again would unmap whatever the process has mapped there since, as a new +/// thread's malloc cache or the GPU driver's shared memory, and the process's next touch of it +/// faults. +fn let_go_pages_after(case: u8, at: HostPtr) { + let length = if case == 3 { PAGE } else { 2 * PAGE }; + let _ = VulkanVm::new().deallocate(at, length); +} + +/// The heaps cases' options: Shared, and read-only (resource option bit 24) or not. +fn heap_options(read_only: bool) -> Vec { + let mut options = vec![OptionSet::StorageMode(0)]; + if read_only { + options.push(OptionSet::ResourceOptionsOr(0x100_0000)); + } + options +} + +/// What a platform makes over the two pages of each of [`pages_after`]'s cases: a heap over +/// their address range, read-only or not; 1 for each made, by case. +fn without_access(p: &P, dev: &P::Device) -> Steps { + let cases = [0, 1, 2, 3, 4]; + let mut steps: Steps = Vec::new(); + for read_only in [false, true] { + let heaps = cases.map(|case| { + let at = pages_after(case); + let array = p + .new_address_range_array(&[range(at, 0, 2 * PAGE)]) + .unwrap(); + let made = dev + .new_heap(&HeapDesc { + size: 2 * PAGE, + heap_type: 1, + options: heap_options(read_only), + address_ranges: Some(&array), + pinned_gpu_address: None, + }) + .unwrap(); + let made = u64::from(made.heap.is_some()); + let_go_pages_after(case, at); + made + }); + steps.push(( + if read_only { + "read-only heaps" + } else { + "heaps" + }, + heaps.to_vec(), + )); + } + steps +} + +/// What Metal makes over pages without access, measured on +/// `AppleM3Max-40c-25G229`: nothing over a page mapped without access or unmapped, as over +/// read-only pages what it makes over readable and writable ones. +fn expected_without_access() -> Steps { + vec![ + ("heaps", vec![1, 0, 0, 0, 1]), + ("read-only heaps", vec![1, 0, 0, 0, 1]), + ] +} + +/// What a platform makes as a heap of one page over ranges of two pages, read-only or not, the +/// second page past its size: one range over both of [`pages_after`]'s pages, then one range +/// of a page each, with the second readable and writable, without access, and unmapped (its +/// cases 0, 1 and 3), and a first range followed by a NULL one; 1 for each made. +fn past_the_size(p: &P, dev: &P::Device) -> Steps { + let vm = VulkanVm::new(); + let mut steps: Steps = Vec::new(); + for read_only in [false, true] { + let mut made = Vec::new(); + for split in [false, true] { + for case in [0, 1, 3] { + let at = pages_after(case); + let ranges = match split { + false => vec![range(at, 0, 2 * PAGE)], + true => vec![range(at, 0, PAGE), range(at, PAGE, PAGE)], + }; + made.push(heap_over::

(p, dev, &ranges, read_only)); + let_go_pages_after(case, at); + } + } + let at = pages(1, 0x5a); + let null = ResourceAddressRange { + address: 0, + length: PAGE, + }; + made.push(heap_over::

( + p, + dev, + &[range(at, 0, PAGE), null], + read_only, + )); + let _ = vm.deallocate(at, PAGE); + let name = match read_only { + false => "heaps past the size", + true => "read-only heaps past the size", + }; + steps.push((name, made)); + } + steps +} + +/// 1 where a platform makes a Shared heap of one page over `ranges`, read-only or not, else 0. +fn heap_over( + p: &P, + dev: &P::Device, + ranges: &[ResourceAddressRange], + read_only: bool, +) -> u64 { + let array = p.new_address_range_array(ranges).unwrap(); + let made = dev + .new_heap(&HeapDesc { + size: PAGE, + heap_type: 1, + options: heap_options(read_only), + address_ranges: Some(&array), + pinned_gpu_address: None, + }) + .unwrap(); + u64::from(made.heap.is_some()) +} + +/// What Metal makes past a heap's size, measured on `AppleM3Max-40c-25G229`: as +/// within it, nothing where a page of the ranges past it is mapped without access or unmapped, +/// in one range or a range of its own, and nothing after a NULL range. +fn expected_past_the_size() -> Steps { + vec![ + ("heaps past the size", vec![1, 0, 0, 1, 0, 0, 0]), + ("read-only heaps past the size", vec![1, 0, 0, 1, 0, 0, 0]), + ] +} + +/// This crate in [`past_the_size`], in a child copy of this test binary under strict mode +/// (`REIMS_VGPU_STRICT=1`), where a death ends the process as in production: Metal's heaps, and +/// nothing dies. The read-only ones (resource option bit 24) are made as Metal makes them: the +/// runtime imports their pages through a read-only view of them, which drops the GPU's writes as +/// Metal's memory of the option does +#[test] +fn pages_past_the_size_on_vulkan() { + const CHILD: &str = "RVG_PAGES_PAST_THE_SIZE"; + if std::env::var_os(CHILD).is_some() { + reims_vgpu_vulkan::core::testkit::capture::set_capture_enabled(false); + let dev = VulkanPlatform::system_default_device().unwrap(); + let p = VulkanPlatform::new(); + println!("made {:?}", past_the_size(&p, &dev)); + std::process::exit(0); + } + if VulkanPlatform::system_default_device().is_none() { + return; + } + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "pages_past_the_size_on_vulkan", "--nocapture"]) + .args(["--test-threads=1"]) + .env(CHILD, "1") + .env("REIMS_VGPU_STRICT", "1") + .output() + .unwrap(); + let (stdout, stderr) = ( + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr), + ); + let death = stderr + .lines() + .find(|l| l.starts_with("reims-vgpu: fatal: ")); + assert!(out.status.success() && death.is_none(), "{out:?}"); + let metal = expected_past_the_size(); + assert!(stdout.contains(&format!("made {metal:?}")), "{stdout}"); +} + +/// This crate in [`without_access`], in a child copy of this test binary under strict mode +/// (`REIMS_VGPU_STRICT=1`), where a death ends the process as in production: Metal's heaps, and +/// nothing dies. The read-only ones (resource option bit 24) are made as Metal makes them: the +/// runtime imports their pages through a read-only view of them, which drops the GPU's writes as +/// Metal's memory of the option does +#[test] +fn pages_without_access_on_vulkan() { + const CHILD: &str = "RVG_PAGES_WITHOUT_ACCESS"; + if std::env::var_os(CHILD).is_some() { + reims_vgpu_vulkan::core::testkit::capture::set_capture_enabled(false); + let dev = VulkanPlatform::system_default_device().unwrap(); + let p = VulkanPlatform::new(); + println!("made {:?}", without_access(&p, &dev)); + std::process::exit(0); + } + if VulkanPlatform::system_default_device().is_none() { + return; + } + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "pages_without_access_on_vulkan", "--nocapture"]) + .args(["--test-threads=1"]) + .env(CHILD, "1") + .env("REIMS_VGPU_STRICT", "1") + .output() + .unwrap(); + let (stdout, stderr) = ( + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr), + ); + let death = stderr + .lines() + .find(|l| l.starts_with("reims-vgpu: fatal: ")); + assert!(out.status.success() && death.is_none(), "{out:?}"); + let metal = expected_without_access(); + assert!(stdout.contains(&format!("made {metal:?}")), "{stdout}"); +} + +/// How many shapes [`unaligned_shape`] holds. +const UNALIGNED: usize = 8; + +/// The address ranges off whole pages [`unaligned`] takes, by index, over guest pages whose +/// 32-bit words hold their own offset there, top bit set, and the pages of the heap or buffer +/// over them: +/// 0. one range from 0x40 into a page, of two pages; +/// 1. one from 0x1000 into a page, of two pages; +/// 2. a range of 0x1000 bytes before one of two pages; +/// 3. a range of a page and 0x40 bytes before one of a page; +/// 4. a range of a page before one of a page from 0x40 into its page; +/// 5. the same before a third range, of a page, over three pages: whether the second takes the +/// pages its bytes lie in (pages 2 and 3, the third range past the size) or its length rounded +/// up (page 2, then the third range's page 5); +/// 6. a range of a page and 0x40 bytes before one whose bytes follow on from it, to the end of +/// page 2, over three pages: whether the two are one run of bytes (pages 0 to 2) or each takes +/// its own pages (pages 0 and 1, then 1 again); +/// 7. a range of a page, one of 0x1000 bytes from a page's start and one of a page, over three +/// pages. +fn unaligned_shape(guest: HostPtr, index: usize) -> (Vec, u64) { + let r = |offset, length| range(guest, offset, length); + match index { + 0 => (vec![r(0x40, 2 * PAGE)], 2), + 1 => (vec![r(0x1000, 2 * PAGE)], 2), + 2 => (vec![r(0, 0x1000), r(2 * PAGE, 2 * PAGE)], 2), + 3 => (vec![r(0, PAGE + 0x40), r(3 * PAGE, PAGE)], 2), + 4 => (vec![r(0, PAGE), r(2 * PAGE + 0x40, PAGE)], 2), + 5 => ( + vec![r(0, PAGE), r(2 * PAGE + 0x40, PAGE), r(5 * PAGE, PAGE)], + 3, + ), + 6 => (vec![r(0, PAGE + 0x40), r(PAGE + 0x40, 2 * PAGE - 0x40)], 3), + _ => (vec![r(0, PAGE), r(2 * PAGE, 0x1000), r(4 * PAGE, PAGE)], 3), + } +} + +/// The guest pages [`unaligned`] lies over. +const UNALIGNED_PAGES: u64 = 8; + +/// What `P` does with the shape `index` ([`unaligned_shape`]) as a placement heap's address +/// ranges: whether it is made; then, of a buffer of the shape's pages placed at 0 in it, the +/// words `contents` reads and those a GPU copy reads at the start, 0x40 and 0x1000 into each page +/// and its last word, and the runs of the guest's words a GPU fill of the whole buffer reached, +/// as guest offsets. +fn unaligned(p: &P, dev: &P::Device, index: usize) -> Steps { + let guest = pages(UNALIGNED_PAGES, 0); + for at in (0..UNALIGNED_PAGES * PAGE).step_by(4) { + // SAFETY: a word of the test's own pages, which no GPU work uses yet. + unsafe { + guest + .wrapping_add(at) + .as_ptr::() + .write(0x8000_0000 | u32::try_from(at).unwrap()); + } + } + let (ranges, count) = unaligned_shape(guest, index); + let array = p.new_address_range_array(&ranges).unwrap(); + let length = count * PAGE; + let mut steps: Steps = Vec::new(); + let made = dev + .new_heap(&HeapDesc { + size: length, + heap_type: 1, + options: vec![OptionSet::StorageMode(0)], + address_ranges: Some(&array), + pinned_gpu_address: None, + }) + .unwrap(); + steps.push(("heap made", vec![u64::from(made.heap.is_some())])); + let Some(heap) = made.heap else { + assert!(vm_free(guest, UNALIGNED_PAGES * PAGE)); + return steps; + }; + let buffer = heap.new_buffer_of_length(length, 0, 0).unwrap(); + steps.push(("placed", vec![u64::from(buffer.is_some())])); + let Some(buffer) = buffer else { + drop(heap); + assert!(vm_free(guest, UNALIGNED_PAGES * PAGE)); + return steps; + }; + let offsets: Vec = (0..count) + .flat_map(|page| [0, 0x40, 0x1000, PAGE - 4].map(|at| page * PAGE + at)) + .collect(); + let words = |at: HostPtr| -> Vec { + offsets + .iter() + .map(|&offset| u64::from(word(at.wrapping_add(offset), 0))) + .collect() + }; + steps.push(("contents", words(buffer.contents()))); + let out = dev + .new_buffer_of_length(OnFault::Return, length, 0) + .unwrap() + .unwrap(); + let queue = dev.new_command_queue().unwrap(); + let cb = command_buffer::

(&queue); + let copy = BlitCmd::CopyBufferToBuffer { + source_buffer: Some(&buffer), + source_offset: 0, + destination_buffer: Some(&out), + destination_offset: 0, + size: length, + }; + blit::

(&cb, vec![copy]); + steps.push(("copy", finish::

(&cb))); + steps.push(("the GPU read", words(out.contents()))); + let cb = command_buffer::

(&queue); + let fill = BlitCmd::FillBuffer { + buffer: &buffer, + range: NsRange::new(0, length), + value: 0x5c, + }; + blit::

(&cb, vec![fill]); + steps.push(("fill", finish::

(&cb))); + let mut runs: Vec = Vec::new(); + for at in (0..UNALIGNED_PAGES * PAGE).step_by(4) { + let filled = word(guest.wrapping_add(at), 0) == 0x5c5c_5c5c; + match (filled, runs.len() % 2) { + (true, 0) | (false, 1) => runs.push(at), + _ => {} + } + } + if runs.len() % 2 == 1 { + runs.push(UNALIGNED_PAGES * PAGE); + } + steps.push(("filled guest runs", runs)); + drop((cb, queue, out, buffer, heap)); + assert!(vm_free(guest, UNALIGNED_PAGES * PAGE)); + steps +} + +/// Address ranges off whole pages ([`unaligned_shape`]), as a heap's, on this platform as on +/// Metal: shapes 2 to 7 alike, step by step. A first range starting off its page (shapes 0 and 1) +/// dies at the creator here, where Metal's `contents` answers its bytes from the range's own +/// address and its GPU reads them from its page's start (`src/gpu/backing.rs`'s +/// `off_the_page`), which Metal's first words show +#[test] +fn unaligned_ranges_on_vulkan_are_metals() { + use reims_vgpu_vulkan::core::raise::death::DeathKind; + use reims_vgpu_vulkan::core::testkit::capture::catch_death; + let dev = VulkanPlatform::system_default_device().unwrap(); + let p = VulkanPlatform::new(); + for index in 0..UNALIGNED { + let case = format!("heap {index}"); + if index < 2 { + let site = catch_death(|| unaligned(&p, &dev, index)).unwrap_err(); + assert_eq!( + (site.kind, site.file), + (DeathKind::Abort, "newHeapWithDescriptor:"), + "{case}" + ); + continue; + } + let ours = unaligned(&p, &dev, index); + reims_vgpu_vulkan::metal_check!(&case, ours); + } +} diff --git a/crates/reims-vgpu-vulkan/tests/detach_backing.rs b/crates/reims-vgpu-vulkan/tests/detach_backing.rs deleted file mode 100644 index 5224c3f10..000000000 --- a/crates/reims-vgpu-vulkan/tests/detach_backing.rs +++ /dev/null @@ -1,2492 +0,0 @@ -//! Detached buffers and heaps as core's isolated tasks make and use them -//! (`resources/buffer/detach.rs`, `resources/heap/detach.rs`), on this crate's platform: a -//! no-copy buffer over a temporary allocation and a heap over its address range, detached at -//! once, then replaced by guest pages, scattered, read-only or not, detached and replaced again. -//! Its answers, the GPU address, the deallocator's runs, the bytes `contents` reads, and what the -//! GPU reads and writes in the guest's pages, are Metal's: under a -//! read-only replace the GPU's fill never reaches the pages, a copy later in its command buffer -//! reads the fill, or the pages where the GPU's caches no longer hold it ([`cached_or_pages`]), -//! and one in the next command buffer the pages. Measured on -//! `AppleM3Max-40c-25G229`. -//! -//! Command buffers that use a detached buffer or heap ([`detached_use`]): Metal and this crate's -//! platform both fail -//! the submission that uses it, run the command buffer's other submissions, decide a submission -//! behind an event wait as they submit it, and fail a use through a texture over a buffer or -//! placed in a heap released detached. A command buffer committed behind an event wait whose -//! buffer is detached, replaced, or both before the signal ([`behind_a_wait`]): this crate's -//! fails a use detached then as Metal's does, in the first submission or a later one, and dies -//! at a use replaced then, also in a submission after one a detached use failed, where Metal -//! runs it over the new pages (`src/gpu/command.rs`'s docs). A kernel's dispatch committed so, -//! its pipeline state made for it or warm, whose buffer is detached and replaced before the -//! signal, runs over the new pages on both ([`dispatch_behind_a_wait`]). A buffer placed in a -//! heap over address ranges detaches the heap on both, and one in a plain heap, as the plain -//! heap, never detaches ([`placed_detach`]). -//! -//! A detach while a command buffer submitted and not yet completed took the object answers NO -//! on both, a heap's at once and a buffer's once the command buffer completed, where Metal's -//! buffer answers YES in some runs from the same state, an answer its test does not compare -//! ([`in_flight`], [`expected_in_flight`]). One made in the completed handler of the command -//! buffer that took the object ([`in_a_completed_handler`]) answers NO or YES on Metal where it -//! is made at once, and YES once the use retired ([`expected_in_a_completed_handler`]), or where -//! the command buffer failed, in all but a few runs ([`expected_in_a_failed_completed_handler`]). -//! This crate's detaches where the runtime let go of what the command buffer took, its -//! submissions before the last, and answers NO where the object's submission was the last. -//! One while a command buffer not yet committed used it detaches on both, an unnamed reach -//! reading 0 and the holder failing with code 8 ([`held`]). An object detached at once and never -//! replaced reads 0 on both where a kernel reaches it unnamed, its `contents` and the memory it -//! was made over staying, and a buffer's deallocator running only once it went -//! ([`never_replaced`]). - -#![cfg(target_os = "macos")] -// Compares with Metal's answers, recorded on macOS. -// Every platform object is `Send` and `Sync` (core's `Handle`, and `Obj`'s bound, which an -// encoder's drop asks of `PredicatedEncoder`), and the proof walks the object's fields: an -// encoder's command buffer, its predication, and the runtime objects that holds, 141 to 150 -// levels deep (measured: rustc warns at a limit of 140, not at 150). That is deeper than -// rustc's default of 128, as in the library (`src/lib.rs`). -#![recursion_limit = "256"] -#![allow( - clippy::unwrap_used, - clippy::indexing_slicing, - clippy::panic, - missing_docs, - unsafe_code -)] - -use std::sync::mpsc; - -use reims_vgpu_vulkan::VulkanPlatform; -use reims_vgpu_vulkan::core::host::HostPtr; -use reims_vgpu_vulkan::core::platform::blit::{BlitCmd, BlitEncoder}; -use reims_vgpu_vulkan::core::platform::command::{CommandBuffer, CommandQueue}; -use reims_vgpu_vulkan::core::platform::compute::{ComputeCmd, ComputeEncoder}; -use reims_vgpu_vulkan::core::platform::device::GpuDevice; -use reims_vgpu_vulkan::core::platform::event::{EventRef, SharedEvent}; -use reims_vgpu_vulkan::core::platform::os::vm::{HostVm, VmProt}; -use reims_vgpu_vulkan::core::platform::resource::{Buffer, Heap, Library, Texture}; -use reims_vgpu_vulkan::core::platform::types::{MtlOrigin, MtlSize, NsRange, ResourceAddressRange}; -use reims_vgpu_vulkan::core::platform::values::{BufferDesc, HeapDesc, OptionSet, TextureDesc}; -use reims_vgpu_vulkan::core::platform::{Handle, HostRange, Platform}; -use reims_vgpu_vulkan::core::raise::OnFault; -use reims_vgpu_vulkan::remap::VulkanVm; - -const PAGE: u64 = 0x4000; - -/// Fresh pages of the host, each byte `byte`. -fn pages(count: u64, byte: u8) -> HostPtr { - let at = VulkanVm::new().allocate_anywhere(count * PAGE).unwrap(); - // SAFETY: the pages were just allocated, readable and writable. - unsafe { - std::ptr::write_bytes( - at.as_ptr::(), - byte, - usize::try_from(count * PAGE).unwrap(), - ); - }; - at -} - -fn read(at: HostPtr, offset: u64) -> u8 { - // SAFETY: the test's own mapped memory, or a buffer's contents over it. - unsafe { at.wrapping_add(offset).as_ptr::().read_volatile() } -} - -fn write(at: HostPtr, offset: u64, byte: u8) { - // SAFETY: the test's own mapped, writable memory. - unsafe { at.wrapping_add(offset).as_ptr::().write_volatile(byte) } -} - -/// Word `index` of the 32-bit words at `at`. -fn word(at: HostPtr, index: usize) -> u32 { - // SAFETY: the test's own mapped memory. - unsafe { at.as_ptr::().add(index).read_volatile() } -} - -/// Waits past the time Metal takes to retire an object's last GPU use: a detach before then -/// answers NO in some runs and leaves the object attached (measured: 9 of 200 detaches right -/// after `waitUntilCompleted`, none 2 ms later, on macOS 26.7; on 27.0.1, none of 836 made 20 µs -/// or more into a completed handler, 100 µs or more with 32 command buffers queued around it; -/// `src/gpu/backing.rs`'s docs, "In flight"). Every detach of an object a completed command -/// buffer used comes after it, but those [`in_a_completed_handler`] makes at once. -fn retire() { - std::thread::sleep(std::time::Duration::from_millis(20)); -} - -fn range(at: HostPtr, offset: u64, length: u64) -> ResourceAddressRange { - ResourceAddressRange { - address: u64::try_from(at.addr()).unwrap() + offset, - length, - } -} - -/// What the platform does, step by step: each step's name and what it answered or showed. -type Steps = Vec<(&'static str, Vec)>; - -/// A GPU fill of the buffer's first `length` bytes with `value`, then a copy of its bytes at -/// `offsets` out to a buffer of the device's: the command buffer's status, and the bytes. -fn fill_then_copy( - dev: &P::Device, - buffer: &P::Buffer, - length: u64, - value: Option, - offsets: &[u64], -) -> Vec { - let out = dev - .new_buffer_of_length(OnFault::Return, length, 0) - .unwrap() - .unwrap(); - let cb = dev - .new_command_queue() - .unwrap() - .command_buffer(OnFault::Return) - .unwrap() - .unwrap(); - let e = cb.blit_encoder(OnFault::Return).unwrap().unwrap(); - if let Some(value) = value { - let fill = BlitCmd::FillBuffer { - buffer, - range: NsRange::new(0, length), - value, - }; - e.encode(OnFault::Return, fill).unwrap(); - } - let copy = BlitCmd::CopyBufferToBuffer { - source_buffer: Some(buffer), - source_offset: 0, - destination_buffer: Some(&out), - destination_offset: 0, - size: length, - }; - e.encode(OnFault::Return, copy).unwrap(); - e.encode(OnFault::Return, BlitCmd::EndEncoding).unwrap(); - cb.commit(OnFault::Return).unwrap(); - cb.wait_until_completed(OnFault::Return).unwrap(); - let mut seen = vec![cb.status().0]; - seen.extend( - offsets - .iter() - .map(|&at| u64::from(read(out.contents(), at))), - ); - seen -} - -/// `seen`, a [`fill_then_copy`] of `fill` into read-only pages of `pages` bytes: the status, then -/// each byte the copy read as the fill where it read the pages. The copy later in the fill's -/// command buffer reads the dropped fill while the GPU's caches hold it, and the pages where -/// they no longer do, which is Metal's own variance: Metal reads the fill when nothing else runs -/// on the GPU, and the pages where 64 MiB of other GPU work came between -/// (`tests/client_direction.rs`, `BufferFillThrash`), and this platform's fill and copy reach -/// Metal's GPU through a read-only mapping too. Any other byte stays, and fails the comparison. -fn cached_or_pages(mut seen: Vec, fill: u8, pages: u8) -> Vec { - for byte in seen.iter_mut().skip(1) { - if *byte == u64::from(pages) { - *byte = u64::from(fill); - } - } - seen -} - -/// A detached buffer of three pages: made over a temporary allocation, detached, replaced by -/// scattered guest pages, detached and replaced by other pages read-only, then writable. -fn buffer_life(p: &P, dev: &P::Device) -> Steps { - let mut steps: Steps = Vec::new(); - let length = 3 * PAGE; - let dummy = pages(3, 0x11); - let (ran, runs) = mpsc::channel(); - // SAFETY: the dummy's pages stay mapped until the deallocator, which frees them, runs. - let contents = unsafe { HostRange::new(dummy, length) }; - let buffer = dev - .new_buffer(BufferDesc { - length, - options: vec![OptionSet::StorageMode(0)], - pinned_gpu_address: None, - contents: Some(contents), - no_copy: true, - deallocator: Some(Box::new(move |at, length| { - let _ = ran.send(at == dummy); - let _ = VulkanVm::new().deallocate(at, length); - })), - }) - .unwrap() - .unwrap(); - let gpu_address = buffer.gpu_address(); - buffer.detach_backing().unwrap(); - let guest = pages(5, 0xa1); - write(guest, 3 * PAGE, 0xb2); - let scattered = [ - range(guest, 0, PAGE), - range(guest, PAGE, PAGE), - range(guest, 3 * PAGE, PAGE), - ]; - let null = [ - range(guest, 0, PAGE), - range(guest, PAGE, PAGE), - ResourceAddressRange { - address: 0, - length: PAGE, - }, - ]; - let mut answers = Vec::new(); - for ranges in [ - &[][..], - &null[..], - &scattered[..2], - &[&scattered[..], &[range(guest, 4 * PAGE, PAGE)]].concat()[..], - ] { - let array = p.new_address_range_array(ranges).unwrap(); - answers.push(u64::from(buffer.replace_backing(&array, false).unwrap())); - } - steps.push(("refused replaces", answers)); - steps.push(( - "deallocator runs", - vec![u64::try_from(runs.try_iter().count()).unwrap()], - )); - let array = p.new_address_range_array(&scattered).unwrap(); - steps.push(( - "replace, then again", - vec![ - u64::from(buffer.replace_backing(&array, false).unwrap()), - u64::from(buffer.replace_backing(&array, false).unwrap()), - ], - )); - steps.push(( - "the dummy's deallocator ran", - runs.try_iter().map(u64::from).collect(), - )); - steps.push(( - "same GPU address", - vec![u64::from(buffer.gpu_address() == gpu_address)], - )); - let contents = buffer.contents(); - steps.push(( - "contents", - [0, PAGE, 2 * PAGE] - .map(|at| u64::from(read(contents, at))) - .to_vec(), - )); - steps.push(( - "the GPU's fill", - fill_then_copy::

(dev, &buffer, length, Some(0x5c), &[0, 2 * PAGE]), - )); - steps.push(( - "the guest's pages", - [0, PAGE, 2 * PAGE, 3 * PAGE, 4 * PAGE] - .map(|at| u64::from(read(guest, at))) - .to_vec(), - )); - write(guest, 3 * PAGE + 8, 0x6d); - steps.push(( - "the GPU reads the guest's write", - fill_then_copy::

(dev, &buffer, length, None, &[2 * PAGE + 8]), - )); - retire(); - buffer.detach_backing().unwrap(); - buffer.detach_backing().unwrap(); - steps.push(( - "contents stays while detached", - vec![u64::from(buffer.contents() == contents)], - )); - let other = pages(3, 0xc3); - for read_only in [true, false] { - let array = p - .new_address_range_array(&[range(other, 0, length)]) - .unwrap(); - steps.push(( - "replace by other pages", - vec![u64::from( - buffer.replace_backing(&array, read_only).unwrap(), - )], - )); - let value = if read_only { 0x7e } else { 0x7f }; - let seen = fill_then_copy::

(dev, &buffer, length, Some(value), &[0, 2 * PAGE]); - steps.push(( - "the GPU's fill", - match read_only { - true => cached_or_pages(seen, value, 0xc3), - false => seen, - }, - )); - steps.push(( - "the other pages", - vec![u64::from(read(other, 0)), u64::from(read(other, 2 * PAGE))], - )); - steps.push(( - "the GPU's next read", - fill_then_copy::

(dev, &buffer, length, None, &[0, 2 * PAGE]), - )); - retire(); - buffer.detach_backing().unwrap(); - } - steps.push(( - "the first pages", - vec![u64::from(read(guest, 0)), u64::from(read(guest, 3 * PAGE))], - )); - drop(buffer); - steps -} - -/// A detached heap of two pages: made over a temporary allocation's address range, detached, -/// with a buffer over all of it, replaced by scattered guest pages (the allocation then freed, as -/// core frees it), detached and replaced by other pages read-only. -fn heap_life(p: &P, dev: &P::Device) -> Steps { - let mut steps: Steps = Vec::new(); - let size = 2 * PAGE; - let vm = VulkanVm::new(); - let dummy = pages(2, 0); - let array = p.new_address_range_array(&[range(dummy, 0, size)]).unwrap(); - let made = dev - .new_heap(&HeapDesc { - size, - heap_type: 1, - options: vec![OptionSet::StorageMode(0), OptionSet::HazardTrackingMode(0)], - address_ranges: Some(&array), - pinned_gpu_address: None, - }) - .unwrap(); - let heap = made.heap.unwrap(); - let gpu_address = heap.gpu_address(); - heap.detach_backing().unwrap(); - let cover = heap - .new_buffer_of_length(size, made.descriptor_resource_options, 0) - .unwrap() - .unwrap(); - let guest = pages(3, 0xa1); - let scattered = [range(guest, 0, PAGE), range(guest, 2 * PAGE, PAGE)]; - let mut answers = Vec::new(); - for ranges in [ - &scattered[..1], - &[range(guest, 0, PAGE), range(guest, PAGE, 2 * PAGE)][..], - &[ - range(guest, 0, PAGE), - ResourceAddressRange { - address: 0, - length: PAGE, - }, - ][..], - &scattered[..], - &scattered[..], - ] { - let array = p.new_address_range_array(ranges).unwrap(); - answers.push(u64::from(heap.replace_backing(&array, false).unwrap())); - } - steps.push(("replaces", answers)); - assert!(vm.deallocate(dummy, size).is_success()); - steps.push(( - "same GPU address", - vec![u64::from(heap.gpu_address() == gpu_address)], - )); - steps.push(( - "the GPU's fill", - fill_then_copy::

(dev, &cover, size, Some(0x5c), &[0, PAGE]), - )); - steps.push(( - "the guest's pages", - [0, PAGE, 2 * PAGE] - .map(|at| u64::from(read(guest, at))) - .to_vec(), - )); - write(guest, 2 * PAGE + 4, 0x33); - steps.push(( - "the GPU reads the guest's write", - fill_then_copy::

(dev, &cover, size, None, &[PAGE + 4]), - )); - retire(); - heap.detach_backing().unwrap(); - let other = pages(2, 0xc3); - let array = p.new_address_range_array(&[range(other, 0, size)]).unwrap(); - steps.push(( - "read-only replace", - vec![u64::from(heap.replace_backing(&array, true).unwrap())], - )); - let seen = fill_then_copy::

(dev, &cover, size, Some(0x7e), &[0, PAGE]); - steps.push(("the GPU's fill", cached_or_pages(seen, 0x7e, 0xc3))); - steps.push(( - "the other pages", - vec![u64::from(read(other, 0)), u64::from(read(other, PAGE))], - )); - steps.push(( - "the GPU's next read", - fill_then_copy::

(dev, &cover, size, None, &[0, PAGE]), - )); - steps -} - -/// Heaps over address ranges Metal makes or answers nil for, and a no-copy buffer of length 0, -/// which is nil and whose deallocator never runs: 1 for each made. -fn edges(p: &P, dev: &P::Device) -> Steps { - let guest = pages(4, 0xa1); - let null = ResourceAddressRange { - address: 0, - length: 0, - }; - let heaps = [ - (2 * PAGE, vec![range(guest, 0, PAGE)]), - (PAGE, vec![range(guest, 0, 2 * PAGE)]), - (0, vec![null]), - (PAGE, vec![]), - ( - PAGE, - vec![ResourceAddressRange { - address: 0, - length: PAGE, - }], - ), - ] - .map(|(size, ranges)| { - let array = p.new_address_range_array(&ranges).unwrap(); - let made = dev - .new_heap(&HeapDesc { - size, - heap_type: 1, - options: vec![OptionSet::StorageMode(0)], - address_ranges: Some(&array), - pinned_gpu_address: None, - }) - .unwrap(); - u64::from(made.heap.is_some()) - }); - let (ran, runs) = mpsc::channel(); - // SAFETY: no byte of a range of length 0 is read. - let contents = unsafe { HostRange::new(HostPtr::NULL, 0) }; - let buffer = dev - .new_buffer(BufferDesc { - length: 0, - options: vec![OptionSet::StorageMode(0)], - pinned_gpu_address: None, - contents: Some(contents), - no_copy: true, - deallocator: Some(Box::new(move |_, _| { - let _ = ran.send(()); - })), - }) - .unwrap(); - vec![ - ("heaps", heaps.to_vec()), - ( - "a buffer of length 0, its deallocator's runs", - vec![ - u64::from(buffer.is_some()), - u64::try_from(runs.try_iter().count()).unwrap(), - ], - ), - ] -} - -/// A detached buffer of `count` pages, as core makes one: a no-copy buffer over a temporary -/// allocation, detached at once. -fn detached_buffer(dev: &P::Device, count: u64) -> P::Buffer { - let length = count * PAGE; - let dummy = pages(count, 0); - // SAFETY: the dummy's pages stay mapped until the deallocator, which frees them, runs. - let contents = unsafe { HostRange::new(dummy, length) }; - let buffer = dev - .new_buffer(BufferDesc { - length, - options: vec![OptionSet::StorageMode(0)], - pinned_gpu_address: None, - contents: Some(contents), - no_copy: true, - deallocator: Some(Box::new(|at, length| { - let _ = VulkanVm::new().deallocate(at, length); - })), - }) - .unwrap() - .unwrap(); - buffer.detach_backing().unwrap(); - buffer -} - -/// A Shared buffer of the device's, of one page of zeros. -fn plain_buffer(dev: &P::Device) -> P::Buffer { - let buffer = dev - .new_buffer_of_length(OnFault::Return, PAGE, 0) - .unwrap() - .unwrap(); - // SAFETY: the buffer's own Shared contents, one page. - unsafe { std::ptr::write_bytes(buffer.contents().as_ptr::(), 0, PAGE as usize) }; - buffer -} - -/// A blit encoder of `cb` with `commands`, ended. -fn blit(cb: &P::CommandBuffer, commands: Vec>) { - let e = cb.blit_encoder(OnFault::Return).unwrap().unwrap(); - for command in commands { - e.encode(OnFault::Return, command).unwrap(); - } - e.encode(OnFault::Return, BlitCmd::EndEncoding).unwrap(); -} - -/// A fill of `buffer`'s 16 bytes at `at` with `value`. -fn fill(buffer: &P::Buffer, at: u64, value: u8) -> BlitCmd<'_, P> { - BlitCmd::FillBuffer { - buffer, - range: NsRange::new(at, 16), - value, - } -} - -/// A copy of `texture`'s first row of 16 pixels to the start of `buffer`. -fn copy_out<'a, P: Platform>(texture: &'a P::Texture, buffer: &'a P::Buffer) -> BlitCmd<'a, P> { - BlitCmd::CopyTextureToBuffer { - source_texture: texture, - source_slice: 0, - source_level: 0, - source_origin: MtlOrigin::new(0, 0, 0), - source_size: MtlSize::new(16, 1, 1), - destination_buffer: buffer, - destination_offset: 0, - destination_bytes_per_row: 256, - destination_bytes_per_image: 256, - } -} - -/// A 2D RGBA8Unorm texture of 64 by 4 pixels, Shared, rows of 256 bytes. -fn texture_desc(p: &P) -> P::TextureDescriptor { - p.texture_descriptor(&TextureDesc { - width: 64, - height: 4, - resource_options: Some(0), - ..TextureDesc::default() - }) -} - -/// `cb` committed and waited for: its status and its error's code (0 for none). -fn finish(cb: &P::CommandBuffer) -> Vec { - cb.commit(OnFault::Return).unwrap(); - cb.wait_until_completed(OnFault::Return).unwrap(); - vec![ - cb.status().0, - cb.error().map_or(0, |e| u64::try_from(e.code).unwrap()), - ] -} - -/// A command buffer of `queue`. -fn command_buffer(queue: &P::CommandQueue) -> P::CommandBuffer { - queue.command_buffer(OnFault::Return).unwrap().unwrap() -} - -/// Command buffers that use a detached buffer or heap: what runs of them, what they signal and -/// report, and where the guest's pages change. -fn detached_use(p: &P, dev: &P::Device) -> Steps { - let mut steps: Steps = Vec::new(); - let queue = dev.new_command_queue().unwrap(); - let byte = |buffer: &P::Buffer, at: u64| u64::from(read(buffer.contents(), at)); - - // One submission: a fill of another buffer before the detached one's, in one encoder. - let detached = detached_buffer::

(dev, 1); - let other = plain_buffer::

(dev); - let signaled = dev.new_shared_event().unwrap(); - let scheduled = dev.new_shared_event().unwrap(); - let cb = command_buffer::

(&queue); - let (seen, handler) = mpsc::channel(); - cb.add_completed_handler( - OnFault::Return, - Box::new(move |info| { - let code = info.error.map_or(0, |e| u64::try_from(e.code).unwrap()); - let _ = seen.send(vec![info.status.0, code]); - }), - ) - .unwrap(); - cb.encode_signal_when_scheduled(Some(&scheduled), 1) - .unwrap(); - blit::

( - &cb, - vec![fill::

(&other, 0, 0x11), fill::

(&detached, 0, 0x5a)], - ); - cb.encode_signal(Some(EventRef::Shared(&signaled)), 3) - .unwrap(); - let mut seen = finish::

(&cb); - seen.push(byte(&other, 0)); - seen.push(u64::from(signaled.wait_until_signaled_value(3, 1000))); - seen.push(u64::from(scheduled.wait_until_signaled_value(1, 1000))); - seen.extend(handler.recv().unwrap()); - steps.push(("one submission", seen)); - - // A texture over the detached buffer, and a view of it. - let texture = detached - .new_texture(OnFault::Return, &texture_desc(p), 0, 256) - .unwrap() - .unwrap(); - let view = texture.new_texture_view(70).unwrap().unwrap(); - let mut seen = Vec::new(); - for texture in [&texture, &view] { - let cb = command_buffer::

(&queue); - blit::

(&cb, vec![copy_out::

(texture, &other)]); - seen.extend(finish::

(&cb)); - } - steps.push(("a texture over it, a view of that", seen)); - - // Replaced, it runs. - let guest = pages(1, 0x01); - let array = p.new_address_range_array(&[range(guest, 0, PAGE)]).unwrap(); - assert!(detached.replace_backing(&array, false).unwrap()); - let cb = command_buffer::

(&queue); - blit::

(&cb, vec![fill::

(&detached, 0, 0x5a)]); - let mut seen = finish::

(&cb); - seen.push(u64::from(read(guest, 0))); - steps.push(("replaced", seen)); - - // A buffer and a texture placed in a detached heap, then the heap replaced. - let size = 4 * PAGE; - let dummy = pages(4, 0); - let array = p.new_address_range_array(&[range(dummy, 0, size)]).unwrap(); - let made = dev - .new_heap(&HeapDesc { - size, - heap_type: 1, - options: vec![OptionSet::StorageMode(0), OptionSet::HazardTrackingMode(0)], - address_ranges: Some(&array), - pinned_gpu_address: None, - }) - .unwrap(); - let heap = made.heap.unwrap(); - let placed = heap - .new_buffer_of_length(PAGE, made.descriptor_resource_options, 0) - .unwrap() - .unwrap(); - let placed_texture = heap - .new_texture(&texture_desc(p), 2 * PAGE) - .unwrap() - .unwrap(); - heap.detach_backing().unwrap(); - let mut seen = Vec::new(); - for commands in [ - vec![fill::

(&placed, 0, 0x44)], - vec![copy_out::

(&placed_texture, &other)], - ] { - let cb = command_buffer::

(&queue); - blit::

(&cb, commands); - seen.extend(finish::

(&cb)); - } - let heap_guest = pages(4, 0x02); - let array = p - .new_address_range_array(&[range(heap_guest, 0, size)]) - .unwrap(); - assert!(heap.replace_backing(&array, false).unwrap()); - assert!(vm_free(dummy, size)); - let cb = command_buffer::

(&queue); - blit::

(&cb, vec![fill::

(&placed, 0, 0x44)]); - seen.extend(finish::

(&cb)); - seen.push(u64::from(read(heap_guest, 0))); - steps.push(("placed in a detached heap, then replaced", seen)); - - // Another submission, past an event signal on each side of the detached buffer's encoder: - // both run. - let detached = detached_buffer::

(dev, 1); - let other = plain_buffer::

(dev); - let signaled = dev.new_shared_event().unwrap(); - let cb = command_buffer::

(&queue); - blit::

(&cb, vec![fill::

(&other, 0, 0x11)]); - cb.encode_signal(Some(EventRef::Shared(&signaled)), 1) - .unwrap(); - blit::

(&cb, vec![fill::

(&detached, 0, 0x5a)]); - cb.encode_signal(Some(EventRef::Shared(&signaled)), 2) - .unwrap(); - blit::

(&cb, vec![fill::

(&other, 16, 0x22)]); - let mut seen = finish::

(&cb); - seen.extend([byte(&other, 0), byte(&other, 16)]); - steps.push(("other submissions", seen)); - - // Released detached after its use is encoded, before the commit. - let detached = detached_buffer::

(dev, 1); - let other = plain_buffer::

(dev); - let cb = command_buffer::

(&queue); - blit::

( - &cb, - vec![fill::

(&other, 0, 0x11), fill::

(&detached, 0, 0x5a)], - ); - drop(detached); - let mut seen = finish::

(&cb); - seen.push(byte(&other, 0)); - steps.push(("released before the commit", seen)); - - // A texture over a buffer released detached, used by a command buffer made after the - // release: it fails. - let detached = detached_buffer::

(dev, 1); - let texture = detached - .new_texture(OnFault::Return, &texture_desc(p), 0, 256) - .unwrap() - .unwrap(); - drop(detached); - let cb = command_buffer::

(&queue); - blit::

(&cb, vec![copy_out::

(&texture, &other)]); - steps.push(( - "a texture over a buffer released detached", - finish::

(&cb), - )); - steps -} - -/// The tests' kernel that reads the word at an address it loads, and writes the word after it -/// (`src/gpu/reach.metal`). -const REACH: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/reach.metallib")); - -/// The reach of `buffer` through an address the kernel loads, naming nothing of it: the command -/// buffer's status and error code, the word read, and whether the guest's word at `written` -/// took the write. -fn reach( - dev: &P::Device, - queue: &P::CommandQueue, - buffer: &P::Buffer, - written: HostPtr, -) -> Vec { - reach_at::

(dev, queue, buffer, 0, written) -} - -/// [`reach`] of `buffer`'s bytes from `offset` on: the kernel reads the word there and writes -/// the one after it, whose host word at `written` (plus 4) shows whether it took the write. -fn reach_at( - dev: &P::Device, - queue: &P::CommandQueue, - buffer: &P::Buffer, - offset: u64, - written: HostPtr, -) -> Vec { - let library = dev.new_library(REACH).unwrap().unwrap().unwrap(); - let function = library - .new_function(OnFault::Return, "reach") - .unwrap() - .unwrap(); - let pipeline = dev - .new_compute_pipeline_state_for_function(Some(&function)) - .unwrap() - .unwrap(); - let addresses = plain_buffer::

(dev); - let words = plain_buffer::

(dev); - // SAFETY: both are the device's own Shared buffers of a page. - unsafe { - addresses - .contents() - .as_ptr::() - .write(buffer.gpu_address() + offset); - words.contents().as_ptr::().add(1).write(MARKER); - } - let cb = command_buffer::

(queue); - let e = cb.compute_encoder(OnFault::Return).unwrap().unwrap(); - for command in [ - ComputeCmd::SetComputePipelineState { - state: Some(&pipeline), - }, - ComputeCmd::SetBuffers { - buffers: &[Some(&addresses), Some(&words)], - offsets: &[0, 0], - range: NsRange::new(0, 2), - }, - ComputeCmd::DispatchThreadgroups { - threadgroups_per_grid: MtlSize::new(1, 1, 1), - threads_per_threadgroup: MtlSize::new(1, 1, 1), - }, - ComputeCmd::EndEncoding, - ] { - e.encode(OnFault::Return, command).unwrap(); - } - let mut seen = finish::

(&cb); - // SAFETY: the words buffer's own contents, and the guest's mapped page. - let (read, landed) = unsafe { - ( - words.contents().as_ptr::().read_volatile(), - written.as_ptr::().add(1).read_volatile(), - ) - }; - seen.extend([u64::from(read), u64::from(landed == MARKER)]); - seen -} - -/// The word [`reach`] writes. -const MARKER: u32 = 0xc0de_5eed; - -/// A buffer, and a buffer placed in a heap, over the guest's pages and used, reached through an -/// address a kernel loads, attached, then detached, then replaced by new pages, before and after -/// a use: what the platform does where nothing names the buffer. -fn detached_reach(p: &P, dev: &P::Device) -> Steps { - let mut steps: Steps = Vec::new(); - let queue = dev.new_command_queue().unwrap(); - let use_ = |buffer: &P::Buffer| { - let cb = command_buffer::

(&queue); - blit::

(&cb, vec![fill::

(buffer, 256, 0x77)]); - finish::

(&cb) - }; - - let buffer = detached_buffer::

(dev, 1); - let guest = pages(1, 0xa1); - let array = p.new_address_range_array(&[range(guest, 0, PAGE)]).unwrap(); - assert!(buffer.replace_backing(&array, false).unwrap()); - let mut seen = use_(&buffer); - seen.extend(reach::

(dev, &queue, &buffer, guest)); - for offset in 4..8 { - write(guest, offset, 0xa1); - } - retire(); - let contents = buffer.contents(); - buffer.detach_backing().unwrap(); - seen.extend(reach::

(dev, &queue, &buffer, guest)); - seen.push(u64::from(buffer.contents() == contents)); - steps.push(("a buffer", seen)); - let fresh = pages(1, 0xb1); - let array = p.new_address_range_array(&[range(fresh, 0, PAGE)]).unwrap(); - assert!(buffer.replace_backing(&array, false).unwrap()); - let mut seen = reach::

(dev, &queue, &buffer, fresh); - seen.push(u64::from(word(guest, 1) == MARKER)); - seen.extend(use_(&buffer)); - seen.extend(reach::

(dev, &queue, &buffer, fresh)); - steps.push(("a buffer used, detached, replaced", seen)); - - let size = 4 * PAGE; - let dummy = pages(4, 0); - let array = p.new_address_range_array(&[range(dummy, 0, size)]).unwrap(); - let made = dev - .new_heap(&HeapDesc { - size, - heap_type: 1, - options: vec![OptionSet::StorageMode(0), OptionSet::HazardTrackingMode(0)], - address_ranges: Some(&array), - pinned_gpu_address: None, - }) - .unwrap(); - let heap = made.heap.unwrap(); - let second = heap - .new_buffer_of_length(PAGE, made.descriptor_resource_options, 2 * PAGE) - .unwrap() - .unwrap(); - heap.detach_backing().unwrap(); - let guest = pages(4, 0xa2); - let array = p.new_address_range_array(&[range(guest, 0, size)]).unwrap(); - assert!(heap.replace_backing(&array, false).unwrap()); - assert!(vm_free(dummy, size)); - let at = guest.wrapping_add(2 * PAGE); - let mut seen = use_(&second); - seen.extend(reach::

(dev, &queue, &second, at)); - for offset in 4..8 { - write(at, offset, 0xa2); - } - retire(); - let contents = second.contents(); - heap.detach_backing().unwrap(); - seen.extend(reach::

(dev, &queue, &second, at)); - seen.push(u64::from(second.contents() == contents)); - steps.push(("a buffer placed in a heap", seen)); - let fresh = pages(4, 0xb2); - let array = p.new_address_range_array(&[range(fresh, 0, size)]).unwrap(); - assert!(heap.replace_backing(&array, false).unwrap()); - let new_at = fresh.wrapping_add(2 * PAGE); - let mut seen = reach::

(dev, &queue, &second, new_at); - seen.push(u64::from(word(at, 1) == MARKER)); - seen.extend(use_(&second)); - seen.extend(reach::

(dev, &queue, &second, new_at)); - steps.push(("a heap used, detached, replaced", seen)); - steps -} - -/// What Metal and this crate's platform do in [`detached_reach`]: attached, the kernel reads the -/// guest's word and its write lands there; detached, it reads 0 and its write is dropped, the -/// command buffer completing with no error; `contents` stays. Replaced after the detach, the kernel -/// reads 0 and its write lands neither in the new pages nor in the old, until a command buffer uses -/// the buffer, or a resource of its heap, again; then it reads and writes the new pages. -fn expected_reach() -> Steps { - vec![ - ("a buffer", vec![4, 0, 4, 0, 0xa1a1_a1a1, 1, 4, 0, 0, 0, 1]), - ( - "a buffer used, detached, replaced", - vec![4, 0, 0, 0, 0, 4, 0, 4, 0, 0xb1b1_b1b1, 1], - ), - ( - "a buffer placed in a heap", - vec![4, 0, 4, 0, 0xa2a2_a2a2, 1, 4, 0, 0, 0, 1], - ), - ( - "a heap used, detached, replaced", - vec![4, 0, 0, 0, 0, 4, 0, 4, 0, 0xb2b2_b2b2, 1], - ), - ] -} - -/// Buffers placed in a heap over address ranges, and in a plain placement heap: one's detach, -/// then fills of it and of another of the heap, its replace, and the heap's detach; then a -/// buffer, and a texture, each placed in a heap of its own released detached, used by a command -/// buffer made after the release. -fn placed_detach(p: &P, dev: &P::Device) -> Steps { - let mut steps: Steps = Vec::new(); - let queue = dev.new_command_queue().unwrap(); - let fill_one = |buffer: &P::Buffer, value: u8| { - let cb = command_buffer::

(&queue); - blit::

(&cb, vec![fill::

(buffer, 0, value)]); - finish::

(&cb) - }; - let size = 4 * PAGE; - let heap_over = |over_ranges: bool| { - let memory = pages(4, 0x31); - let array = p - .new_address_range_array(&[range(memory, 0, size)]) - .unwrap(); - let made = dev - .new_heap(&HeapDesc { - size, - heap_type: 1, - options: vec![OptionSet::StorageMode(0), OptionSet::HazardTrackingMode(0)], - address_ranges: over_ranges.then_some(&array), - pinned_gpu_address: None, - }) - .unwrap(); - (made.heap.unwrap(), made.descriptor_resource_options) - }; - for (name, over_ranges) in [ - ("placed in a heap over address ranges", true), - ("placed in a plain placement heap", false), - ] { - let (heap, options) = heap_over(over_ranges); - let first = heap - .new_buffer_of_length(PAGE, options, 0) - .unwrap() - .unwrap(); - let second = heap - .new_buffer_of_length(PAGE, options, 2 * PAGE) - .unwrap() - .unwrap(); - let mut seen = fill_one(&first, 0x11); - retire(); - first.detach_backing().unwrap(); - seen.extend(fill_one(&first, 0x22)); - seen.extend(fill_one(&second, 0x33)); - let guest = pages(1, 0x01); - let array = p.new_address_range_array(&[range(guest, 0, PAGE)]).unwrap(); - seen.push(u64::from(first.replace_backing(&array, false).unwrap())); - seen.extend(fill_one(&first, 0x44)); - heap.detach_backing().unwrap(); - seen.extend(fill_one(&second, 0x55)); - steps.push((name, seen)); - } - // Each in a heap of its own, so that the texture's heap is held by nothing else. - let (heap, options) = heap_over(true); - let buffer = heap - .new_buffer_of_length(PAGE, options, 0) - .unwrap() - .unwrap(); - heap.detach_backing().unwrap(); - drop(heap); - let (heap, _) = heap_over(true); - let texture = heap.new_texture(&texture_desc(p), 0).unwrap().unwrap(); - heap.detach_backing().unwrap(); - drop(heap); - let other = plain_buffer::

(dev); - let mut seen = fill_one(&buffer, 0x66); - let cb = command_buffer::

(&queue); - blit::

(&cb, vec![copy_out::

(&texture, &other)]); - seen.extend(finish::

(&cb)); - steps.push(( - "a buffer, and a texture, placed in a heap released detached", - seen, - )); - steps -} - -/// What Metal and this crate's platform do in [`placed_detach`]. -fn expected_placed() -> Steps { - vec![ - ( - "placed in a heap over address ranges", - vec![4, 0, 5, 8, 5, 8, 0, 5, 8, 5, 8], - ), - ( - "placed in a plain placement heap", - vec![4, 0, 4, 0, 4, 0, 0, 4, 0, 4, 0], - ), - ( - "a buffer, and a texture, placed in a heap released detached", - vec![5, 8, 5, 8], - ), - ] -} - -/// Frees `length` bytes of the test's pages at `at`. -fn vm_free(at: HostPtr, length: u64) -> bool { - VulkanVm::new().deallocate(at, length).is_success() -} - -/// What Metal and this crate's platform do in [`detached_use`]. -fn expected_use() -> Steps { - vec![ - ("one submission", vec![5, 8, 0, 1, 1, 5, 8]), - ("a texture over it, a view of that", vec![5, 8, 5, 8]), - ("replaced", vec![4, 0, 0x5a]), - ( - "placed in a detached heap, then replaced", - vec![5, 8, 5, 8, 4, 0, 0x44], - ), - ("other submissions", vec![5, 8, 0x11, 0x22]), - ("released before the commit", vec![5, 8, 0]), - ("a texture over a buffer released detached", vec![5, 8]), - ] -} - -/// What Metal and this crate's platform do ([`buffer_life`], [`heap_life`], [`edges`]). -fn expected() -> Vec { - vec![ - vec![ - ("refused replaces", vec![0, 0, 0, 0]), - ("deallocator runs", vec![0]), - ("replace, then again", vec![1, 0]), - ("the dummy's deallocator ran", vec![1]), - ("same GPU address", vec![1]), - ("contents", vec![0xa1, 0xa1, 0xb2]), - ("the GPU's fill", vec![4, 0x5c, 0x5c]), - ("the guest's pages", vec![0x5c, 0x5c, 0xa1, 0x5c, 0xa1]), - ("the GPU reads the guest's write", vec![4, 0x6d]), - ("contents stays while detached", vec![1]), - ("replace by other pages", vec![1]), - ("the GPU's fill", vec![4, 0x7e, 0x7e]), - ("the other pages", vec![0xc3, 0xc3]), - ("the GPU's next read", vec![4, 0xc3, 0xc3]), - ("replace by other pages", vec![1]), - ("the GPU's fill", vec![4, 0x7f, 0x7f]), - ("the other pages", vec![0x7f, 0x7f]), - ("the GPU's next read", vec![4, 0x7f, 0x7f]), - ("the first pages", vec![0x5c, 0x5c]), - ], - vec![ - ("replaces", vec![0, 0, 0, 1, 0]), - ("same GPU address", vec![1]), - ("the GPU's fill", vec![4, 0x5c, 0x5c]), - ("the guest's pages", vec![0x5c, 0xa1, 0x5c]), - ("the GPU reads the guest's write", vec![4, 0x33]), - ("read-only replace", vec![1]), - ("the GPU's fill", vec![4, 0x7e, 0x7e]), - ("the other pages", vec![0xc3, 0xc3]), - ("the GPU's next read", vec![4, 0xc3, 0xc3]), - ], - vec![ - ("heaps", vec![1, 1, 0, 0, 0]), - ("a buffer of length 0, its deallocator's runs", vec![0, 0]), - ], - ] -} - -#[test] -fn detached_buffers_and_heaps_on_vulkan() { - let Some(dev) = VulkanPlatform::system_default_device() else { - return; - }; - let p = VulkanPlatform::new(); - let seen = vec![buffer_life(&p, &dev), heap_life(&p, &dev), edges(&p, &dev)]; - assert_eq!(seen, expected()); - assert_eq!(detached_use(&p, &dev), expected_use()); - assert_eq!(placed_detach(&p, &dev), expected_placed()); - assert_eq!(detached_reach(&p, &dev), expected_reach()); -} - -/// The cases of [`behind_a_wait`]. -const BEHIND_A_WAIT: [&str; 5] = [ - "detached", - "replaced", - "detached, then replaced", - "detached, used past a split", - "detached, another replaced past a split", -]; - -/// Case `case` of [`BEHIND_A_WAIT`]: a buffer over guest pages (detached over a temporary -/// allocation, for `replaced`) whose fill a command buffer commits behind an event wait (past a -/// fill of another buffer and an event signal, which splits its submissions, for `used past a -/// split`), then detached, replaced by other pages, or both, before the wait's signal. For -/// `another replaced past a split`, the fill is followed by an event signal and a fill of a -/// second buffer over guest pages, and before the wait's signal the first buffer is detached and -/// the second detached and replaced by other pages. What shows: the command buffer's status and -/// error code, and the first byte of the guest's pages the first buffer was over and of those a -/// buffer was replaced by. -fn behind_a_wait(p: &P, dev: &P::Device, case: &str) -> Vec { - let queue = dev.new_command_queue().unwrap(); - let buffer = detached_buffer::

(dev, 1); - let over = pages(1, 0x01); - if case != "replaced" { - let array = p.new_address_range_array(&[range(over, 0, PAGE)]).unwrap(); - assert!(buffer.replace_backing(&array, false).unwrap()); - } - let another = case.contains("another").then(|| { - let second = detached_buffer::

(dev, 1); - let array = p - .new_address_range_array(&[range(pages(1, 0x02), 0, PAGE)]) - .unwrap(); - assert!(second.replace_backing(&array, false).unwrap()); - second - }); - let gate = dev.new_shared_event().unwrap(); - let cb = command_buffer::

(&queue); - cb.encode_wait(Some(EventRef::Shared(&gate)), 1).unwrap(); - let other = plain_buffer::

(dev); - if case.ends_with("used past a split") { - let split = dev.new_shared_event().unwrap(); - blit::

(&cb, vec![fill::

(&other, 0, 0x11)]); - cb.encode_signal(Some(EventRef::Shared(&split)), 1).unwrap(); - } - blit::

(&cb, vec![fill::

(&buffer, 0, 0x5c)]); - if let Some(second) = &another { - let split = dev.new_shared_event().unwrap(); - cb.encode_signal(Some(EventRef::Shared(&split)), 1).unwrap(); - blit::

(&cb, vec![fill::

(second, 0, 0x5c)]); - } - cb.commit(OnFault::Return).unwrap(); - if case.starts_with("detached") { - buffer.detach_backing().unwrap(); - } - let new = pages(1, 0x03); - if case.starts_with("replaced") || case.ends_with("then replaced") { - let array = p.new_address_range_array(&[range(new, 0, PAGE)]).unwrap(); - assert!(buffer.replace_backing(&array, false).unwrap()); - } - if let Some(second) = &another { - second.detach_backing().unwrap(); - let array = p.new_address_range_array(&[range(new, 0, PAGE)]).unwrap(); - assert!(second.replace_backing(&array, false).unwrap()); - } - gate.set_signaled_value(1).unwrap(); - cb.wait_until_completed(OnFault::Return).unwrap(); - vec![ - cb.status().0, - cb.error().map_or(0, |e| u64::try_from(e.code).unwrap()), - u64::from(read(over, 0)), - u64::from(read(new, 0)), - ] -} - -/// Metal's answers in [`behind_a_wait`] (measured on the M3 Max, macOS 26.7): it decides each -/// submission as it submits it, so it fails one that uses the buffer detached then (code 8), -/// running the others, and runs one that uses a buffer replaced then over the new pages, also -/// after a submission of the same command buffer failed. -fn expected_behind_a_wait() -> [Vec; 5] { - [ - vec![5, 8, 0x01, 0x03], - vec![4, 0, 0x01, 0x5c], - vec![4, 0, 0x01, 0x5c], - vec![5, 8, 0x01, 0x03], - vec![5, 8, 0x01, 0x5c], - ] -} - -/// The case of [`BEHIND_A_WAIT`] a child copy of this test binary runs. -const CHILD_CASE: &str = "RVG_BEHIND_A_WAIT"; - -/// This crate in [`behind_a_wait`], each case in a child copy of this test binary under strict -/// mode (`REIMS_VGPU_STRICT=1`), where a death ends the process as in production, on whatever thread it comes: each case answers Metal's, -/// and nothing dies. A use detached behind the wait, in the first submission or a later one, -/// fails with Metal's code 8 (the runtime decides each submission after the submission check -/// and keeps the code the check gave). A use replaced behind it, or detached and then replaced, -/// runs over the new pages: the runtime encodes the command buffer's encoders again over the -/// rebound buffer before its first submission -#[test] -fn behind_a_wait_on_vulkan() { - if let Ok(case) = std::env::var(CHILD_CASE) { - reims_vgpu_vulkan::core::testkit::capture::set_capture_enabled(false); - let dev = VulkanPlatform::system_default_device().unwrap(); - let p = VulkanPlatform::new(); - println!("seen {:?}", behind_a_wait(&p, &dev, &case)); - std::process::exit(0); - } - if VulkanPlatform::system_default_device().is_none() { - return; - } - for (case, metal) in BEHIND_A_WAIT.into_iter().zip(expected_behind_a_wait()) { - let out = std::process::Command::new(std::env::current_exe().unwrap()) - .args(["--exact", "behind_a_wait_on_vulkan", "--nocapture"]) - .args(["--test-threads=1"]) - .env(CHILD_CASE, case) - .env("REIMS_VGPU_STRICT", "1") - .output() - .unwrap(); - let (stdout, stderr) = ( - String::from_utf8_lossy(&out.stdout), - String::from_utf8_lossy(&out.stderr), - ); - let death = stderr - .lines() - .find(|l| l.starts_with("reims-vgpu: fatal: ")); - assert!(out.status.success() && death.is_none(), "{case}: {out:?}"); - assert!( - stdout.contains(&format!("seen {metal:?}")), - "{case}: {stdout}" - ); - } -} - -/// A buffer over guest pages whose kernel's dispatch a command buffer commits behind an event -/// wait, then detached and replaced by other pages before the wait's signal, its kernel the spin kernel of no -/// rounds ([`SPIN`]), which writes [`SPUN`] to the buffer's second word: of a pipeline state made -/// for it, so cold (the state's first dispatch, whose pipeline the runtime may still be making -/// as it is encoded, as it hands a state's first dispatch's making to its pool), where `warm` is -/// false, and of one a completed command buffer dispatched once first where it is true. What -/// shows: the command buffer's status and error code, and the second word of the pages the -/// buffer was over and of those it was replaced by. -fn dispatch_behind_a_wait(p: &P, dev: &P::Device, warm: bool) -> Vec { - let queue = dev.new_command_queue().unwrap(); - let library = dev.new_library(SPIN).unwrap().unwrap().unwrap(); - let function = library - .new_function(OnFault::Return, "spin") - .unwrap() - .unwrap(); - let pipeline = dev - .new_compute_pipeline_state_for_function(Some(&function)) - .unwrap() - .unwrap(); - let dispatch = |cb: &P::CommandBuffer, words: &P::Buffer| { - let e = cb.compute_encoder(OnFault::Return).unwrap().unwrap(); - for command in [ - ComputeCmd::SetComputePipelineState { - state: Some(&pipeline), - }, - ComputeCmd::SetBuffers { - buffers: &[Some(words)], - offsets: &[0], - range: NsRange::new(0, 1), - }, - ComputeCmd::DispatchThreadgroups { - threadgroups_per_grid: MtlSize::new(1, 1, 1), - threads_per_threadgroup: MtlSize::new(1, 1, 1), - }, - ComputeCmd::EndEncoding, - ] { - e.encode(OnFault::Return, command).unwrap(); - } - }; - if warm { - let first = plain_buffer::

(dev); - let cb = command_buffer::

(&queue); - dispatch(&cb, &first); - assert_eq!(finish::

(&cb), [4, 0]); - } - let buffer = detached_buffer::

(dev, 1); - let over = pages(1, 0); - let array = p.new_address_range_array(&[range(over, 0, PAGE)]).unwrap(); - assert!(buffer.replace_backing(&array, false).unwrap()); - let gate = dev.new_shared_event().unwrap(); - let cb = command_buffer::

(&queue); - cb.encode_wait(Some(EventRef::Shared(&gate)), 1).unwrap(); - dispatch(&cb, &buffer); - cb.commit(OnFault::Return).unwrap(); - buffer.detach_backing().unwrap(); - let new = pages(1, 0); - let array = p.new_address_range_array(&[range(new, 0, PAGE)]).unwrap(); - assert!(buffer.replace_backing(&array, false).unwrap()); - gate.set_signaled_value(1).unwrap(); - cb.wait_until_completed(OnFault::Return).unwrap(); - vec![ - cb.status().0, - cb.error().map_or(0, |e| u64::try_from(e.code).unwrap()), - u64::from(word(over, 1)), - u64::from(word(new, 1)), - ] -} - -/// Metal's answer in [`dispatch_behind_a_wait`], cold and warm (measured on the M3 Max, macOS -/// 27.0.1): the dispatch runs over the new pages, the command buffer completing with no error. -const DISPATCH_BEHIND_A_WAIT: [u64; 4] = [4, 0, 0, SPUN as u64]; - -/// This crate in [`dispatch_behind_a_wait`], cold and warm, each in a child copy of this test -/// binary under strict mode (`REIMS_VGPU_STRICT=1`), where a death ends the process as in -/// production, on whatever thread it comes: each answers Metal's, and nothing dies. The rebind -/// encodes the compute encoder again over the new pages before the command buffer's first -/// submission, the cold dispatch's too, whose recording waits for its pipeline -#[test] -fn a_dispatch_behind_a_wait_on_vulkan() { - const CHILD: &str = "RVG_DISPATCH_BEHIND_A_WAIT"; - if let Ok(warm) = std::env::var(CHILD) { - reims_vgpu_vulkan::core::testkit::capture::set_capture_enabled(false); - let dev = VulkanPlatform::system_default_device().unwrap(); - let p = VulkanPlatform::new(); - println!("seen {:?}", dispatch_behind_a_wait(&p, &dev, warm == "1")); - std::process::exit(0); - } - if VulkanPlatform::system_default_device().is_none() { - return; - } - for warm in ["0", "1"] { - let out = std::process::Command::new(std::env::current_exe().unwrap()) - .args([ - "--exact", - "a_dispatch_behind_a_wait_on_vulkan", - "--nocapture", - ]) - .args(["--test-threads=1"]) - .env(CHILD, warm) - .env("REIMS_VGPU_STRICT", "1") - .output() - .unwrap(); - let (stdout, stderr) = ( - String::from_utf8_lossy(&out.stdout), - String::from_utf8_lossy(&out.stderr), - ); - let death = stderr - .lines() - .find(|l| l.starts_with("reims-vgpu: fatal: ")); - assert!( - out.status.success() && death.is_none(), - "warm {warm}: {out:?}" - ); - assert!( - stdout.contains(&format!("seen {DISPATCH_BEHIND_A_WAIT:?}")), - "warm {warm}: {stdout}" - ); - } -} - -/// Two fresh pages of the host after `case`: 0 leaves them readable and writable, 1 takes all -/// access from the second, 2 from both, 3 unmaps the second, 4 leaves both read-only. -fn pages_after(case: u8) -> HostPtr { - let vm = VulkanVm::new(); - let at = pages(2, 0x5a); - let second = at.wrapping_add(PAGE); - match case { - 1 => vm.protect_max(second, PAGE, VmProt(0)).unwrap(), - 2 => vm.protect_max(at, 2 * PAGE, VmProt(0)).unwrap(), - 3 => assert!(vm.deallocate(second, PAGE).is_success()), - 4 => vm.protect_max(at, 2 * PAGE, VmProt::READ).unwrap(), - _ => {} - } - at -} - -/// Lets go of what [`pages_after`] left mapped of its two pages at `at` for `case`: both -/// pages, but only the first after case 3, whose second page it already unmapped. Unmapping -/// that second page again would unmap whatever the process has mapped there since, as a new -/// thread's malloc cache or the GPU driver's shared memory, and the process's next touch of it -/// faults. -fn let_go_pages_after(case: u8, at: HostPtr) { - let length = if case == 3 { PAGE } else { 2 * PAGE }; - let _ = VulkanVm::new().deallocate(at, length); -} - -/// The heaps cases' options: Shared, and read-only (resource option bit 24) or not. -fn heap_options(read_only: bool) -> Vec { - let mut options = vec![OptionSet::StorageMode(0)]; - if read_only { - options.push(OptionSet::ResourceOptionsOr(0x100_0000)); - } - options -} - -/// What a platform makes over the two pages of each of [`pages_after`]'s cases: a heap over -/// their address range, read-only or not, and a replace of a detached buffer's and a detached -/// heap's memory by them, read-only or not; 1 for each made, by case. -fn without_access(p: &P, dev: &P::Device) -> Steps { - let cases = [0, 1, 2, 3, 4]; - let vm = VulkanVm::new(); - let mut steps: Steps = Vec::new(); - for read_only in [false, true] { - let heaps = cases.map(|case| { - let at = pages_after(case); - let array = p - .new_address_range_array(&[range(at, 0, 2 * PAGE)]) - .unwrap(); - let made = dev - .new_heap(&HeapDesc { - size: 2 * PAGE, - heap_type: 1, - options: heap_options(read_only), - address_ranges: Some(&array), - pinned_gpu_address: None, - }) - .unwrap(); - let made = u64::from(made.heap.is_some()); - let_go_pages_after(case, at); - made - }); - steps.push(( - if read_only { - "read-only heaps" - } else { - "heaps" - }, - heaps.to_vec(), - )); - } - for read_only in [false, true] { - let replaced = cases.map(|case| { - let buffer = detached_buffer::

(dev, 2); - let at = pages_after(case); - let array = p - .new_address_range_array(&[range(at, 0, 2 * PAGE)]) - .unwrap(); - let replaced = u64::from(buffer.replace_backing(&array, read_only).unwrap()); - drop(buffer); - let_go_pages_after(case, at); - replaced - }); - steps.push(( - if read_only { - "read-only buffer replaces" - } else { - "buffer replaces" - }, - replaced.to_vec(), - )); - } - for read_only in [false, true] { - let replaced = cases.map(|case| { - let dummy = pages(2, 0); - let array = p - .new_address_range_array(&[range(dummy, 0, 2 * PAGE)]) - .unwrap(); - let heap = dev - .new_heap(&HeapDesc { - size: 2 * PAGE, - heap_type: 1, - options: heap_options(false), - address_ranges: Some(&array), - pinned_gpu_address: None, - }) - .unwrap() - .heap - .unwrap(); - heap.detach_backing().unwrap(); - let at = pages_after(case); - let array = p - .new_address_range_array(&[range(at, 0, 2 * PAGE)]) - .unwrap(); - let replaced = u64::from(heap.replace_backing(&array, read_only).unwrap()); - drop(heap); - let_go_pages_after(case, at); - let _ = vm.deallocate(dummy, 2 * PAGE); - replaced - }); - steps.push(( - if read_only { - "read-only heap replaces" - } else { - "heap replaces" - }, - replaced.to_vec(), - )); - } - steps -} - -/// What Metal makes over pages without access, measured on -/// `AppleM3Max-40c-25G229`: nothing over a page mapped without access or unmapped, as over -/// read-only pages what it makes over readable and writable ones. -fn expected_without_access() -> Steps { - vec![ - ("heaps", vec![1, 0, 0, 0, 1]), - ("read-only heaps", vec![1, 0, 0, 0, 1]), - ("buffer replaces", vec![1, 0, 0, 0, 1]), - ("read-only buffer replaces", vec![1, 0, 0, 0, 1]), - ("heap replaces", vec![1, 0, 0, 0, 1]), - ("read-only heap replaces", vec![1, 0, 0, 0, 1]), - ] -} - -/// What a platform makes as a heap of one page over ranges of two pages, read-only or not, the -/// second page past its size: one range over both of [`pages_after`]'s pages, then one range -/// of a page each, with the second readable and writable, without access, and unmapped (its -/// cases 0, 1 and 3), and a first range followed by a NULL one; 1 for each made. -fn past_the_size(p: &P, dev: &P::Device) -> Steps { - let vm = VulkanVm::new(); - let mut steps: Steps = Vec::new(); - for read_only in [false, true] { - let mut made = Vec::new(); - for split in [false, true] { - for case in [0, 1, 3] { - let at = pages_after(case); - let ranges = match split { - false => vec![range(at, 0, 2 * PAGE)], - true => vec![range(at, 0, PAGE), range(at, PAGE, PAGE)], - }; - made.push(heap_over::

(p, dev, &ranges, read_only)); - let_go_pages_after(case, at); - } - } - let at = pages(1, 0x5a); - let null = ResourceAddressRange { - address: 0, - length: PAGE, - }; - made.push(heap_over::

( - p, - dev, - &[range(at, 0, PAGE), null], - read_only, - )); - let _ = vm.deallocate(at, PAGE); - let name = match read_only { - false => "heaps past the size", - true => "read-only heaps past the size", - }; - steps.push((name, made)); - } - steps -} - -/// 1 where a platform makes a Shared heap of one page over `ranges`, read-only or not, else 0. -fn heap_over( - p: &P, - dev: &P::Device, - ranges: &[ResourceAddressRange], - read_only: bool, -) -> u64 { - let array = p.new_address_range_array(ranges).unwrap(); - let made = dev - .new_heap(&HeapDesc { - size: PAGE, - heap_type: 1, - options: heap_options(read_only), - address_ranges: Some(&array), - pinned_gpu_address: None, - }) - .unwrap(); - u64::from(made.heap.is_some()) -} - -/// What Metal makes past a heap's size, measured on `AppleM3Max-40c-25G229`: as -/// within it, nothing where a page of the ranges past it is mapped without access or unmapped, -/// in one range or a range of its own, and nothing after a NULL range. -fn expected_past_the_size() -> Steps { - vec![ - ("heaps past the size", vec![1, 0, 0, 1, 0, 0, 0]), - ("read-only heaps past the size", vec![1, 0, 0, 1, 0, 0, 0]), - ] -} - -/// This crate in [`past_the_size`], in a child copy of this test binary under strict mode -/// (`REIMS_VGPU_STRICT=1`), where a death ends the process as in production: Metal's heaps, and -/// nothing dies. The read-only ones (resource option bit 24) are made as Metal makes them: the -/// runtime imports their pages through a read-only view of them, which drops the GPU's writes as -/// Metal's memory of the option does -#[test] -fn pages_past_the_size_on_vulkan() { - const CHILD: &str = "RVG_PAGES_PAST_THE_SIZE"; - if std::env::var_os(CHILD).is_some() { - reims_vgpu_vulkan::core::testkit::capture::set_capture_enabled(false); - let dev = VulkanPlatform::system_default_device().unwrap(); - let p = VulkanPlatform::new(); - println!("made {:?}", past_the_size(&p, &dev)); - std::process::exit(0); - } - if VulkanPlatform::system_default_device().is_none() { - return; - } - let out = std::process::Command::new(std::env::current_exe().unwrap()) - .args(["--exact", "pages_past_the_size_on_vulkan", "--nocapture"]) - .args(["--test-threads=1"]) - .env(CHILD, "1") - .env("REIMS_VGPU_STRICT", "1") - .output() - .unwrap(); - let (stdout, stderr) = ( - String::from_utf8_lossy(&out.stdout), - String::from_utf8_lossy(&out.stderr), - ); - let death = stderr - .lines() - .find(|l| l.starts_with("reims-vgpu: fatal: ")); - assert!(out.status.success() && death.is_none(), "{out:?}"); - let metal = expected_past_the_size(); - assert!(stdout.contains(&format!("made {metal:?}")), "{stdout}"); -} - -/// This crate in [`without_access`], in a child copy of this test binary under strict mode -/// (`REIMS_VGPU_STRICT=1`), where a death ends the process as in production: Metal's heaps, and -/// nothing dies. The read-only ones (resource option bit 24) are made as Metal makes them: the -/// runtime imports their pages through a read-only view of them, which drops the GPU's writes as -/// Metal's memory of the option does -#[test] -fn pages_without_access_on_vulkan() { - const CHILD: &str = "RVG_PAGES_WITHOUT_ACCESS"; - if std::env::var_os(CHILD).is_some() { - reims_vgpu_vulkan::core::testkit::capture::set_capture_enabled(false); - let dev = VulkanPlatform::system_default_device().unwrap(); - let p = VulkanPlatform::new(); - println!("made {:?}", without_access(&p, &dev)); - std::process::exit(0); - } - if VulkanPlatform::system_default_device().is_none() { - return; - } - let out = std::process::Command::new(std::env::current_exe().unwrap()) - .args(["--exact", "pages_without_access_on_vulkan", "--nocapture"]) - .args(["--test-threads=1"]) - .env(CHILD, "1") - .env("REIMS_VGPU_STRICT", "1") - .output() - .unwrap(); - let (stdout, stderr) = ( - String::from_utf8_lossy(&out.stdout), - String::from_utf8_lossy(&out.stderr), - ); - let death = stderr - .lines() - .find(|l| l.starts_with("reims-vgpu: fatal: ")); - assert!(out.status.success() && death.is_none(), "{out:?}"); - let metal = expected_without_access(); - assert!(stdout.contains(&format!("made {metal:?}")), "{stdout}"); -} - -/// How many shapes [`unaligned_shape`] holds. -const UNALIGNED: usize = 8; - -/// The address ranges off whole pages [`unaligned`] takes, by index, over guest pages whose -/// 32-bit words hold their own offset there, top bit set, and the pages of the heap or buffer -/// over them: -/// 0. one range from 0x40 into a page, of two pages; -/// 1. one from 0x1000 into a page, of two pages; -/// 2. a range of 0x1000 bytes before one of two pages; -/// 3. a range of a page and 0x40 bytes before one of a page; -/// 4. a range of a page before one of a page from 0x40 into its page; -/// 5. the same before a third range, of a page, over three pages: whether the second takes the -/// pages its bytes lie in (pages 2 and 3, the third range past the size) or its length rounded -/// up (page 2, then the third range's page 5); -/// 6. a range of a page and 0x40 bytes before one whose bytes follow on from it, to the end of -/// page 2, over three pages: whether the two are one run of bytes (pages 0 to 2) or each takes -/// its own pages (pages 0 and 1, then 1 again); -/// 7. a range of a page, one of 0x1000 bytes from a page's start and one of a page, over three -/// pages. -/// -/// A replace of shapes 2, 3 and 7, whose lengths total other than the buffer's, answers NO. -fn unaligned_shape(guest: HostPtr, index: usize) -> (Vec, u64) { - let r = |offset, length| range(guest, offset, length); - match index { - 0 => (vec![r(0x40, 2 * PAGE)], 2), - 1 => (vec![r(0x1000, 2 * PAGE)], 2), - 2 => (vec![r(0, 0x1000), r(2 * PAGE, 2 * PAGE)], 2), - 3 => (vec![r(0, PAGE + 0x40), r(3 * PAGE, PAGE)], 2), - 4 => (vec![r(0, PAGE), r(2 * PAGE + 0x40, PAGE)], 2), - 5 => ( - vec![r(0, PAGE), r(2 * PAGE + 0x40, PAGE), r(5 * PAGE, PAGE)], - 3, - ), - 6 => (vec![r(0, PAGE + 0x40), r(PAGE + 0x40, 2 * PAGE - 0x40)], 3), - _ => (vec![r(0, PAGE), r(2 * PAGE, 0x1000), r(4 * PAGE, PAGE)], 3), - } -} - -/// The guest pages [`unaligned`] lies over. -const UNALIGNED_PAGES: u64 = 8; - -/// What `P` does with the shape `index` ([`unaligned_shape`]) as a placement heap's address -/// ranges (`heap` true) or as a detached buffer's replace: whether it is made (or answers YES); -/// then, of a buffer of the shape's pages (the replaced one, or one placed at 0 in a heap of that -/// size), the words `contents` reads and those a GPU copy reads at the start, 0x40 and 0x1000 -/// into each page and its last word, and the runs of the guest's words a GPU fill of the whole -/// buffer reached, as guest offsets. -fn unaligned(p: &P, dev: &P::Device, index: usize, heap: bool) -> Steps { - let guest = pages(UNALIGNED_PAGES, 0); - for at in (0..UNALIGNED_PAGES * PAGE).step_by(4) { - // SAFETY: a word of the test's own pages, which no GPU work uses yet. - unsafe { - guest - .wrapping_add(at) - .as_ptr::() - .write(0x8000_0000 | u32::try_from(at).unwrap()); - } - } - let (ranges, count) = unaligned_shape(guest, index); - let array = p.new_address_range_array(&ranges).unwrap(); - let length = count * PAGE; - let mut steps: Steps = Vec::new(); - let (buffer, heap) = match heap { - true => { - let made = dev - .new_heap(&HeapDesc { - size: length, - heap_type: 1, - options: vec![OptionSet::StorageMode(0)], - address_ranges: Some(&array), - pinned_gpu_address: None, - }) - .unwrap(); - steps.push(("heap made", vec![u64::from(made.heap.is_some())])); - let Some(h) = made.heap else { - assert!(vm_free(guest, UNALIGNED_PAGES * PAGE)); - return steps; - }; - let b = h.new_buffer_of_length(length, 0, 0).unwrap(); - steps.push(("placed", vec![u64::from(b.is_some())])); - let Some(b) = b else { - drop(h); - assert!(vm_free(guest, UNALIGNED_PAGES * PAGE)); - return steps; - }; - (b, Some(h)) - } - false => { - let b = detached_buffer::

(dev, count); - let answer = b.replace_backing(&array, false).unwrap(); - steps.push(("replaced", vec![u64::from(answer)])); - if !answer { - drop(b); - assert!(vm_free(guest, UNALIGNED_PAGES * PAGE)); - return steps; - } - (b, None) - } - }; - let offsets: Vec = (0..count) - .flat_map(|page| [0, 0x40, 0x1000, PAGE - 4].map(|at| page * PAGE + at)) - .collect(); - let words = |at: HostPtr| -> Vec { - offsets - .iter() - .map(|&offset| u64::from(word(at.wrapping_add(offset), 0))) - .collect() - }; - steps.push(("contents", words(buffer.contents()))); - let out = dev - .new_buffer_of_length(OnFault::Return, length, 0) - .unwrap() - .unwrap(); - let queue = dev.new_command_queue().unwrap(); - let cb = command_buffer::

(&queue); - let copy = BlitCmd::CopyBufferToBuffer { - source_buffer: Some(&buffer), - source_offset: 0, - destination_buffer: Some(&out), - destination_offset: 0, - size: length, - }; - blit::

(&cb, vec![copy]); - steps.push(("copy", finish::

(&cb))); - steps.push(("the GPU read", words(out.contents()))); - let cb = command_buffer::

(&queue); - let fill = BlitCmd::FillBuffer { - buffer: &buffer, - range: NsRange::new(0, length), - value: 0x5c, - }; - blit::

(&cb, vec![fill]); - steps.push(("fill", finish::

(&cb))); - let mut runs: Vec = Vec::new(); - for at in (0..UNALIGNED_PAGES * PAGE).step_by(4) { - let filled = word(guest.wrapping_add(at), 0) == 0x5c5c_5c5c; - match (filled, runs.len() % 2) { - (true, 0) | (false, 1) => runs.push(at), - _ => {} - } - } - if runs.len() % 2 == 1 { - runs.push(UNALIGNED_PAGES * PAGE); - } - steps.push(("filled guest runs", runs)); - drop((cb, queue, out, buffer, heap)); - assert!(vm_free(guest, UNALIGNED_PAGES * PAGE)); - steps -} - -/// Address ranges off whole pages ([`unaligned_shape`]), as a heap's and as a replace's, on this -/// platform as on Metal, which runs first: shapes 2 to 7 alike, step by step. A first range -/// starting off its page (shapes 0 and 1) dies at the creator here, where Metal's `contents` -/// answers its bytes from the range's own address and its GPU reads them from its page's start -/// (`src/gpu/backing.rs`'s `off_the_page`), which Metal's first words show -#[test] -fn unaligned_ranges_on_vulkan_are_metals() { - use reims_vgpu_vulkan::core::raise::death::DeathKind; - use reims_vgpu_vulkan::core::testkit::capture::catch_death; - let cases: Vec<(usize, bool)> = (0..UNALIGNED) - .flat_map(|index| [(index, true), (index, false)]) - .collect(); - let dev = VulkanPlatform::system_default_device().unwrap(); - let p = VulkanPlatform::new(); - for &(index, heap) in &cases { - let (case, sel) = match heap { - true => (format!("heap {index}"), "newHeapWithDescriptor:"), - false => ( - format!("replace {index}"), - "replaceBackingWithRanges:readOnly:", - ), - }; - if index < 2 { - let site = catch_death(|| unaligned(&p, &dev, index, heap)).unwrap_err(); - assert_eq!((site.kind, site.file), (DeathKind::Abort, sel), "{case}"); - continue; - } - let ours = unaligned(&p, &dev, index, heap); - reims_vgpu_vulkan::metal_check!(&case, ours); - } -} - -/// The kernel that keeps the GPU busy (`src/gpu/spin.metal`): its first word's count of rounds, -/// about 60 µs each on the M3 Max, then [`SPUN`] in its second word. -const SPIN: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/spin.metallib")); - -/// What [`SPIN`]'s kernel writes to its second word once it ran. -const SPUN: u32 = 0x600d; - -/// The rounds [`spinning`]'s kernel runs: about 120 ms on the M3 Max, past the detach and the -/// replace a test makes while it runs, each well under a millisecond, and past a late -/// scheduling. Another process's GPU fault can end the kernel's command buffer with an error as -/// its victim, on Metal as here, so the tests that run it are run again alone before a failure -/// counts. -const ROUNDS: u32 = 2000; - -/// A command buffer of `queue` whose kernel spins over `words`, whose first word holds the -/// rounds it runs, committed and scheduled: submitted, and running for the rounds' time. -fn spinning( - dev: &P::Device, - queue: &P::CommandQueue, - words: &P::Buffer, -) -> P::CommandBuffer { - let library = dev.new_library(SPIN).unwrap().unwrap().unwrap(); - let function = library - .new_function(OnFault::Return, "spin") - .unwrap() - .unwrap(); - let pipeline = dev - .new_compute_pipeline_state_for_function(Some(&function)) - .unwrap() - .unwrap(); - let cb = command_buffer::

(queue); - let e = cb.compute_encoder(OnFault::Return).unwrap().unwrap(); - for command in [ - ComputeCmd::SetComputePipelineState { - state: Some(&pipeline), - }, - ComputeCmd::SetBuffers { - buffers: &[Some(words)], - offsets: &[0], - range: NsRange::new(0, 1), - }, - ComputeCmd::DispatchThreadgroups { - threadgroups_per_grid: MtlSize::new(1, 1, 1), - threads_per_threadgroup: MtlSize::new(1, 1, 1), - }, - ComputeCmd::EndEncoding, - ] { - e.encode(OnFault::Return, command).unwrap(); - } - cb.commit(OnFault::Return).unwrap(); - cb.wait_until_scheduled().unwrap(); - cb -} - -/// Guest pages of `count` pages whose first word holds [`ROUNDS`], for [`spinning`]. -fn rounds(count: u64) -> HostPtr { - let guest = pages(count, 0); - // SAFETY: the test's own mapped, writable page. - unsafe { guest.as_ptr::().write_volatile(ROUNDS) }; - guest -} - -/// A buffer, or a heap and a buffer of a page placed in it, as core makes them (over a temporary -/// allocation or range, detached at once), replaced by the 4 pages at `guest`: the buffer, and the -/// heap where there is one. -fn over_guest_pages( - p: &P, - dev: &P::Device, - heap: bool, - guest: HostPtr, -) -> (P::Buffer, Option) { - let size = 4 * PAGE; - let array = p.new_address_range_array(&[range(guest, 0, size)]).unwrap(); - if heap { - let dummy = pages(4, 0); - let ranges = p.new_address_range_array(&[range(dummy, 0, size)]).unwrap(); - let made = dev - .new_heap(&HeapDesc { - size, - heap_type: 1, - options: vec![OptionSet::StorageMode(0), OptionSet::HazardTrackingMode(0)], - address_ranges: Some(&ranges), - pinned_gpu_address: None, - }) - .unwrap(); - let options = made.descriptor_resource_options; - let heap = made.heap.unwrap(); - let words = heap - .new_buffer_of_length(PAGE, options, 0) - .unwrap() - .unwrap(); - heap.detach_backing().unwrap(); - assert!(heap.replace_backing(&array, false).unwrap()); - assert!(vm_free(dummy, size)); - (words, Some(heap)) - } else { - let buffer = detached_buffer::

(dev, 4); - assert!(buffer.replace_backing(&array, false).unwrap()); - (buffer, None) - } -} - -/// A buffer or a heap, as core makes them (over a temporary allocation or range, detached at -/// once, replaced by the guest's pages), detached while a command buffer submitted and not yet -/// completed runs a kernel over it (over a buffer placed in the heap): whether the kernel had -/// ended as the detach returned, and the answer of a replace after it; the command buffer's -/// status, error code and whether the kernel's write landed in the guest's pages, once it -/// completed; then, once Metal retired its use ([`retire`]), the answer of a replace after a -/// second detach. -fn in_flight(p: &P, dev: &P::Device, heap: bool) -> Steps { - let queue = dev.new_command_queue().unwrap(); - let size = 4 * PAGE; - let guest = rounds(4); - let (words, made) = over_guest_pages(p, dev, heap, guest); - let detach = || match &made { - Some(heap) => heap.detach_backing().unwrap(), - None => words.detach_backing().unwrap(), - }; - let fresh = pages(4, 0); - let array = p.new_address_range_array(&[range(fresh, 0, size)]).unwrap(); - let replace = || match &made { - Some(heap) => heap.replace_backing(&array, false).unwrap(), - None => words.replace_backing(&array, false).unwrap(), - }; - let cb = spinning::

(dev, &queue, &words); - detach(); - let ended = word(guest, 1) == SPUN; - let mut steps: Steps = vec![( - "detached in flight: ended, replaced", - vec![u64::from(ended), u64::from(replace())], - )]; - cb.wait_until_completed(OnFault::Return).unwrap(); - steps.push(( - "completed: status, error, the kernel's write", - vec![ - cb.status().0, - cb.error().map_or(0, |e| u64::try_from(e.code).unwrap()), - u64::from(word(guest, 1) == SPUN), - ], - )); - retire(); - detach(); - steps.push(( - "detached once it completed: replaced", - vec![u64::from(replace())], - )); - drop((cb, queue, words, made)); - assert!(vm_free(guest, size) && vm_free(fresh, size)); - steps -} - -/// What Metal does in [`in_flight`] (measured on the M3 Max, macOS 26.7, 25G229, 28 runs of each -/// on a GPU nothing else used): a heap's detach answers NO at once, the kernel still running, and -/// a buffer's returns once the command buffer completed, the kernel's write landed, and answers -/// NO (in most runs, below); so the object stays attached, the replace after it answers NO, and -/// the command buffer completes over the guest's pages. Once it completed and its use retired, a -/// detach detaches. The status a buffer's command buffer reads as the detach returns is -/// `Completed` or, in some runs, still `Scheduled`, so it is not compared. -/// -/// A buffer's answer is not decided by the state the test drives: Metal answers NO in most runs -/// and YES in some, the object then detached and the replace after it answering YES. Its detach -/// is one call into the kernel driver (`IOGPUResourceDetachBacking`, a single -/// `IOConnectCallMethod`), which waits until every submitted GPU use of the buffer completed, -/// then answers NO where the kernel has not yet retired that use and YES where it has, the -/// kernel's own completion racing the waiting call. Measured on 2026-10-11, `detachBacking`'s own -/// answer, driven as here: YES in 13 of 150 runs and in 3 of 40. Nothing the caller does decides -/// it: a completed handler held blocked until after the replace (YES in 8 of 60), more GPU work -/// after the kernel in its command buffer (9 of 80), the command buffer held in flight past the -/// detach by an event wait after the kernel (8 of 150, and 1 of 150 where the work behind the -/// wait uses the buffer too), and a second queue's command buffer using the buffer (5 of 60) -/// each left both answers. This crate's NO, with the replace's NO after it, is one of Metal's two -/// answers, and [`detached_in_flight_on_vulkan`] compares it. -fn expected_in_flight() -> [Steps; 2] { - let completed = ( - "completed: status, error, the kernel's write", - vec![4, 0, 1], - ); - let after = ("detached once it completed: replaced", vec![1]); - [ - vec![ - ("detached in flight: ended, replaced", vec![0, 0]), - completed.clone(), - after.clone(), - ], - vec![ - ("detached in flight: ended, replaced", vec![1, 0]), - completed, - after, - ], - ] -} - -/// [`in_flight`] on this crate, as on Metal ([`expected_in_flight`]): a detach answers NO while a -/// command buffer the runtime submitted took the object, a buffer's once each such command -/// buffer completed (`src/gpu/backing.rs`'s `in_flight`) -#[test] -fn detached_in_flight_on_vulkan() { - let Some(dev) = VulkanPlatform::system_default_device() else { - return; - }; - let p = VulkanPlatform::new(); - let seen = [true, false].map(|heap| in_flight(&p, &dev, heap)); - assert_eq!(seen, expected_in_flight()); -} - -/// A detach of `heap`, or of `words` where there is none, then a replace of it by `array`: the -/// replace's answer. -fn detach_then_replace( - words: &P::Buffer, - heap: Option<&P::Heap>, - array: &P::AddressRangeArray, -) -> bool { - match heap { - Some(heap) => { - heap.detach_backing().unwrap(); - heap.replace_backing(array, false).unwrap() - } - None => { - words.detach_backing().unwrap(); - words.replace_backing(array, false).unwrap() - } - } -} - -/// A buffer or a heap, as core makes them, over the guest's pages ([`over_guest_pages`]), filled -/// by a blit (through a buffer placed in the heap) in a command buffer that fails as `failing` -/// says, if it does, and detached inside the completed handler of that command buffer, at once, -/// or where `retired` once Metal retired the use ([`retire`]): the answer of a replace after it, -/// in the handler too, and the status and error code the handler sees; then, once Metal retired -/// the use, the answer of a replace after a second detach, and the fill's byte in the guest's -/// pages. -fn in_a_completed_handler( - p: &P, - dev: &P::Device, - heap: bool, - failing: Failing, - retired: bool, -) -> Steps { - let queue = dev.new_command_queue().unwrap(); - let size = 4 * PAGE; - let guest = pages(4, 0); - let (words, made) = over_guest_pages(p, dev, heap, guest); - let fresh = pages(4, 0); - let array = p.new_address_range_array(&[range(fresh, 0, size)]).unwrap(); - let cb = command_buffer::

(&queue); - let other = matches!( - failing, - Failing::BeforeOther(_) | Failing::AfterOther(_) | Failing::NotSplit - ) - .then(|| plain_buffer::

(dev)); - let detached = (failing == Failing::DetachedAfter).then(|| detached_buffer::

(dev, 1)); - let signaled = matches!(failing, Failing::DetachedAfter | Failing::NotSplit) - .then(|| dev.new_shared_event().unwrap()); - let (seen, handler) = mpsc::channel(); - let held = ( - words.clone_ref(), - made.as_ref().map(Handle::clone_ref), - array.clone_ref(), - ); - cb.add_completed_handler( - OnFault::Return, - Box::new(move |info| { - let (words, made, array) = held; - if retired { - retire(); - } - let replaced = detach_then_replace::

(&words, made.as_ref(), &array); - let code = info.error.map_or(0, |e| u64::try_from(e.code).unwrap()); - let _ = seen.send(vec![u64::from(replaced), info.status.0, code]); - }), - ) - .unwrap(); - let protect = |options| cb.set_protection_options(OnFault::Return, options).unwrap(); - let object = || blit::

(&cb, vec![fill::

(&words, 0, 0x5a)]); - let another = |buffer: &Option| { - blit::

(&cb, vec![fill::

(buffer.as_ref().unwrap(), 0, 0x33)]); - }; - let signal = || { - cb.encode_signal(Some(EventRef::Shared(signaled.as_ref().unwrap())), 1) - .unwrap(); - }; - match failing { - Failing::Not => object(), - Failing::NotSplit => { - object(); - signal(); - another(&other); - } - Failing::Fill(options) => { - protect(options); - object(); - } - Failing::AfterFill(options) => { - object(); - protect(options); - } - Failing::BeforeOther(options) => { - object(); - protect(options); - another(&other); - } - Failing::AfterOther(options) => { - another(&other); - protect(options); - object(); - } - Failing::DetachedAfter => { - object(); - signal(); - another(&detached); - } - } - finish::

(&cb); - let mut steps: Steps = vec![( - "detached in its completed handler: replaced, status, error", - handler.recv().unwrap(), - )]; - retire(); - steps.push(( - "detached once it completed: replaced", - vec![u64::from(detach_then_replace::

( - &words, - made.as_ref(), - &array, - ))], - )); - steps.push(( - "the fill in the guest's pages", - vec![u64::from(read(guest, 0))], - )); - drop((cb, queue, words, made, other, detached, signaled)); - assert!(vm_free(guest, size) && vm_free(fresh, size)); - steps -} - -/// How [`in_a_completed_handler`]'s command buffer fails, if it does: by protection options -/// (`setProtectionOptions:`), under which an encoder made runs nothing, nor does any after it -/// (code 16 below 0x10, 1 from 0x10 up), and from 0x10 up with no encoder made under them, every -/// encoder running (code 1; `src/gpu/command.rs`'s docs); or by a use of a detached buffer -/// (code 8), in a submission of its own. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Failing { - /// It does not: it completes. - Not, - /// It does not, and the object's fill is not in its last submission: the object's fill, an - /// event's signal, which ends Metal's submission, then a fill of another buffer. - NotSplit, - /// The object's fill is made under the options: it runs nothing. - Fill(u64), - /// The options are set once the object's fill ended, nothing made under them: the fill runs. - AfterFill(u64), - /// The object's fill, then a fill of another buffer made under the options: the object's - /// runs, the other's runs nothing. - BeforeOther(u64), - /// A fill of another buffer, then the object's made under the options: the other's runs, - /// the object's runs nothing. - AfterOther(u64), - /// The object's fill, an event's signal, which ends Metal's submission, then a fill of a - /// detached buffer, whose submission fails with code 8: the object's runs. - DetachedAfter, -} - -/// The ways [`in_a_completed_handler`]'s command buffer was measured to complete: with the -/// object's fill in its only submission, and in its first. -const COMPLETING: [Failing; 2] = [Failing::Not, Failing::NotSplit]; - -/// What Metal does in [`in_a_completed_handler`] where its command buffer completes -/// ([`COMPLETING`]), a heap's and a buffer's alike, the replace after the detach in the handler -/// answering `replaced`: YES where the detach is made once the use retired ([`retire`]); where it -/// is made at once, NO in some runs, the object staying attached, and YES in the others. Metal -/// lets go of what the command buffer took as it processes its completion, which races the start -/// of its completed handlers (measured on the M3 Max, macOS 27.0.1, 26A434, on 2026-10-23, -/// `src/gpu/backing.rs`'s docs, "In flight": made at once, NO in 257 of 1132 runs, from 1 in 50 -/// to 40 in 40 per batch with the host's load, and 197 of 200 on macOS 26.7; made 20 µs or more -/// into the handler, YES in all 684, 104 of them 20 ms in; every NO detached when made again, -/// within 101 µs). Once the use retired, a detach detaches; the fill landed in the guest's pages. -fn expected_in_a_completed_handler(replaced: u64) -> Steps { - vec![ - ( - "detached in its completed handler: replaced, status, error", - vec![replaced, 4, 0], - ), - ("detached once it completed: replaced", vec![1]), - ("the fill in the guest's pages", vec![0x5a]), - ] -} - -/// The ways [`expected_in_a_failed_completed_handler`] was measured to fail a command buffer: -/// with code 1 by protection options 0x10, the object's fill made under them or before them; -/// with code 16 by options 0x2, the object's fill made before a fill of another buffer made under -/// them, or made under them after it; and with code 8 by a detached buffer's use. -const FAILING: [Failing; 5] = [ - Failing::Fill(0x10), - Failing::AfterFill(0x10), - Failing::BeforeOther(0x2), - Failing::AfterOther(0x2), - Failing::DetachedAfter, -]; - -/// What Metal does in [`in_a_completed_handler`] where its command buffer fails as `failing` -/// says, a heap's and a buffer's alike: the detach in the handler detaches, so the replace after -/// it answers YES, in all but a few runs, as Metal lets go of what a command buffer that -/// completes with an error took before its completed handlers run (measured on the M3 Max, -/// macOS 27.0.1, 26A434: YES in 2796 of 2800 runs over these and other layouts, NO in 4 of the -/// 1400 where the object's fill ran and in none of the 1400 where it ran nothing; the handler of -/// one that completed answered NO in 248 of 800 the same day, [`expected_in_a_completed_handler`]); -/// the handler sees status `Error` and the failure's code; once the use retired, a detach -/// detaches; the fill landed in the guest's pages where its encoder ran. -fn expected_in_a_failed_completed_handler(failing: Failing) -> Steps { - let (code, filled) = match failing { - Failing::Fill(0x10) => (1, 0), - Failing::AfterFill(0x10) => (1, 0x5a), - Failing::BeforeOther(0x2) => (16, 0x5a), - Failing::AfterOther(0x2) => (16, 0), - Failing::DetachedAfter => (8, 0x5a), - failing => panic!("not measured: {failing:?}"), - }; - vec![ - ( - "detached in its completed handler: replaced, status, error", - vec![1, 5, code], - ), - ("detached once it completed: replaced", vec![1]), - ("the fill in the guest's pages", vec![filled]), - ] -} - -/// [`in_a_completed_handler`] on this crate where its command buffer completes, each way of -/// [`COMPLETING`], a heap and a buffer, the detach in the handler made at once and once the use -/// retired: YES in both, Metal's once the use retired and one of its two at once -/// ([`expected_in_a_completed_handler`]), as neither a noted submission of a command buffer that -/// completed nor the runtime, which lets go of what it took as it processes its completion, -/// holds the object in its handlers (`src/gpu/backing.rs`'s docs, "In flight") -#[test] -fn detached_in_a_completed_handler_on_vulkan() { - let Some(dev) = VulkanPlatform::system_default_device() else { - return; - }; - let p = VulkanPlatform::new(); - for failing in COMPLETING { - for heap in [true, false] { - for retired in [false, true] { - let seen = in_a_completed_handler(&p, &dev, heap, failing, retired); - assert_eq!( - seen, - expected_in_a_completed_handler(1), - "{failing:?}, heap {heap}, retired {retired}" - ); - } - } - } -} - -/// [`in_a_completed_handler`] on this crate where its command buffer fails, each way of -/// [`FAILING`], a heap and a buffer: Metal's YES in the handler -/// ([`expected_in_a_failed_completed_handler`]), as neither a noted submission of a command -/// buffer that completed with an error nor the runtime, which lets go of what it took, those of -/// encoders its commit failed included, as it processes its completion, holds the object in its -/// handlers (`src/gpu/backing.rs`'s docs, "In flight") -#[test] -fn detached_in_a_failed_completed_handler_on_vulkan() { - let Some(dev) = VulkanPlatform::system_default_device() else { - return; - }; - let p = VulkanPlatform::new(); - for failing in FAILING { - for heap in [true, false] { - let seen = in_a_completed_handler(&p, &dev, heap, failing, false); - assert_eq!( - seen, - expected_in_a_failed_completed_handler(failing), - "{failing:?}, heap {heap}" - ); - } - } -} - -/// A buffer, or a buffer placed in a heap, as core makes them, over the guest's pages, used by a -/// command buffer that completed, then used by one not yet committed (its encoder ended, or still -/// open where `open`), and detached: what a kernel that reaches it through an address it loads -/// does ([`reach`]), and then the holder's status and error code, committed -/// ([`expected_held`]). -fn held(p: &P, dev: &P::Device, heap: bool, open: bool) -> Steps { - let queue = dev.new_command_queue().unwrap(); - let size = if heap { 4 * PAGE } else { PAGE }; - let guest = pages(size / PAGE, 0xa1); - let array = p.new_address_range_array(&[range(guest, 0, size)]).unwrap(); - let (target, made) = if heap { - let dummy = pages(4, 0); - let ranges = p.new_address_range_array(&[range(dummy, 0, size)]).unwrap(); - let made = dev - .new_heap(&HeapDesc { - size, - heap_type: 1, - options: vec![OptionSet::StorageMode(0), OptionSet::HazardTrackingMode(0)], - address_ranges: Some(&ranges), - pinned_gpu_address: None, - }) - .unwrap(); - let options = made.descriptor_resource_options; - let heap = made.heap.unwrap(); - let target = heap - .new_buffer_of_length(PAGE, options, 0) - .unwrap() - .unwrap(); - heap.detach_backing().unwrap(); - assert!(heap.replace_backing(&array, false).unwrap()); - assert!(vm_free(dummy, size)); - (target, Some(heap)) - } else { - let buffer = detached_buffer::

(dev, 1); - assert!(buffer.replace_backing(&array, false).unwrap()); - (buffer, None) - }; - let used = command_buffer::

(&queue); - blit::

(&used, vec![fill::

(&target, 256, 0x77)]); - assert_eq!(finish::

(&used), [4, 0]); - retire(); - let holder = command_buffer::

(&queue); - let e = holder.blit_encoder(OnFault::Return).unwrap().unwrap(); - e.encode(OnFault::Return, fill::

(&target, 512, 0x66)) - .unwrap(); - if !open { - e.encode(OnFault::Return, BlitCmd::EndEncoding).unwrap(); - } - match &made { - Some(heap) => heap.detach_backing().unwrap(), - None => target.detach_backing().unwrap(), - } - let mut steps: Steps = vec![( - "reached unnamed after the detach", - reach::

(dev, &queue, &target, guest), - )]; - if open { - e.encode(OnFault::Return, BlitCmd::EndEncoding).unwrap(); - } - steps.push(("the holder, committed", finish::

(&holder))); - steps -} - -/// What Metal does in [`held`], a buffer and a heap, the holder's encoder ended or open alike -/// (measured on the M3 Max, macOS 26.7, 25G229): the detach detaches, a kernel that reaches the -/// object unnamed reads 0 and its write is dropped, its command buffer completing with no error, -/// and the holder fails with code 8 as it is submitted. -fn expected_held() -> Steps { - vec![ - ("reached unnamed after the detach", vec![4, 0, 0, 0]), - ("the holder, committed", vec![5, 8]), - ] -} - -/// The cases of [`held`]: a heap or a buffer, the holder's encoder open or ended. -const HELD: [(bool, bool); 4] = [(false, false), (false, true), (true, false), (true, true)]; - -/// [`held`] on this crate, as on Metal ([`expected_held`]): the runtime's detach detaches the -/// object while a command buffer not yet committed used it, which fails as it is submitted, and -/// leaves it in no memory, which an unnamed reach reads as 0 (`src/gpu/backing.rs`'s docs) -#[test] -fn detached_while_held_on_vulkan() { - let Some(dev) = VulkanPlatform::system_default_device() else { - return; - }; - let p = VulkanPlatform::new(); - for (heap, open) in HELD { - assert_eq!( - held(&p, &dev, heap, open), - expected_held(), - "heap {heap}, open {open}" - ); - } -} - -/// A buffer, or a buffer placed in a heap, made as core makes them over a temporary allocation -/// or range of its own whose words are 0xd0d0d0d0, detached at once and never replaced: a command -/// buffer that names it, then a kernel that reaches it through an address it loads ([`reach`]), -/// and one that reads the word that kernel wrote, both naming nothing of it; whether `contents` -/// and the temporary memory's words stayed; and, for the buffer, whether its deallocator ran -/// before its release and once it went. -fn never_replaced(p: &P, dev: &P::Device, heap: bool) -> Steps { - let queue = dev.new_command_queue().unwrap(); - let size = 4 * PAGE; - let dummy = pages(4, 0xd0); - let (ran, runs) = mpsc::channel(); - let (target, made, contents) = if heap { - let ranges = p.new_address_range_array(&[range(dummy, 0, size)]).unwrap(); - let made = dev - .new_heap(&HeapDesc { - size, - heap_type: 1, - options: vec![OptionSet::StorageMode(0), OptionSet::HazardTrackingMode(0)], - address_ranges: Some(&ranges), - pinned_gpu_address: None, - }) - .unwrap(); - let options = made.descriptor_resource_options; - let heap = made.heap.unwrap(); - let target = heap - .new_buffer_of_length(PAGE, options, 0) - .unwrap() - .unwrap(); - let contents = target.contents(); - heap.detach_backing().unwrap(); - (target, Some(heap), contents) - } else { - // SAFETY: the dummy's pages stay mapped until the deallocator, which frees them, runs. - let contents = unsafe { HostRange::new(dummy, size) }; - let buffer = dev - .new_buffer(BufferDesc { - length: size, - options: vec![OptionSet::StorageMode(0)], - pinned_gpu_address: None, - contents: Some(contents), - no_copy: true, - deallocator: Some(Box::new(move |at, length| { - let _ = ran.send(at == dummy); - let _ = VulkanVm::new().deallocate(at, length); - })), - }) - .unwrap() - .unwrap(); - let contents = buffer.contents(); - buffer.detach_backing().unwrap(); - (buffer, None, contents) - }; - let named = command_buffer::

(&queue); - blit::

(&named, vec![fill::

(&target, 256, 0x77)]); - let mut steps: Steps = vec![("named", finish::

(&named))]; - steps.push(("reached", reach::

(dev, &queue, &target, dummy))); - steps.push(( - "the written word read", - reach_at::

(dev, &queue, &target, 4, dummy.wrapping_add(4)), - )); - steps.push(( - "contents and the temporary memory stay", - vec![ - u64::from(target.contents() == contents), - u64::from((0..3).all(|at| word(dummy, at) == 0xd0d0_d0d0)), - ], - )); - if made.is_none() { - steps.push(( - "the deallocator ran before the release", - vec![u64::try_from(runs.try_iter().count()).unwrap()], - )); - drop(target); - let ran = runs - .recv_timeout(std::time::Duration::from_secs(2)) - .is_ok_and(|over_dummy| over_dummy); - steps.push(("the deallocator ran once it went", vec![u64::from(ran)])); - } else { - drop((target, made)); - assert!(vm_free(dummy, size)); - } - steps -} - -/// What Metal does in [`never_replaced`], a buffer and a heap (measured on the M3 Max, macOS -/// 26.7, 25G229): the command buffer that names the object fails with code 8; a kernel that -/// reaches it unnamed reads 0 and its write is dropped, its command buffer completing with no -/// error, and a later one reads 0 where it wrote; `contents` stays, and the temporary memory -/// keeps its words; and the buffer's deallocator runs once it went, not before. -fn expected_never_replaced(heap: bool) -> Steps { - let mut steps = vec![ - ("named", vec![5, 8]), - ("reached", vec![4, 0, 0, 0]), - ("the written word read", vec![4, 0, 0, 0]), - ("contents and the temporary memory stay", vec![1, 1]), - ]; - if !heap { - steps.push(("the deallocator ran before the release", vec![0])); - steps.push(("the deallocator ran once it went", vec![1])); - } - steps -} - -/// [`never_replaced`] on this crate, as on Metal: the runtime's detach leaves the object in no -/// memory, and the buffer's deallocator is held until its release (`src/gpu/backing.rs`'s -/// `Held`) -#[test] -fn never_replaced_on_vulkan() { - let Some(dev) = VulkanPlatform::system_default_device() else { - return; - }; - let p = VulkanPlatform::new(); - for heap in [false, true] { - assert_eq!( - never_replaced(&p, &dev, heap), - expected_never_replaced(heap), - "heap {heap}" - ); - } -} diff --git a/crates/reims-vgpu-vulkan/tests/metal_answers/detach_backing.unaligned_ranges_on_vulkan_are_metals.txt b/crates/reims-vgpu-vulkan/tests/metal_answers/address_ranges.unaligned_ranges_on_vulkan_are_metals.txt similarity index 66% rename from crates/reims-vgpu-vulkan/tests/metal_answers/detach_backing.unaligned_ranges_on_vulkan_are_metals.txt rename to crates/reims-vgpu-vulkan/tests/metal_answers/address_ranges.unaligned_ranges_on_vulkan_are_metals.txt index 5b099887f..917793cf3 100644 --- a/crates/reims-vgpu-vulkan/tests/metal_answers/detach_backing.unaligned_ranges_on_vulkan_are_metals.txt +++ b/crates/reims-vgpu-vulkan/tests/metal_answers/address_ranges.unaligned_ranges_on_vulkan_are_metals.txt @@ -1,13 +1,7 @@ # Metal's answers, recorded from the Metal platform on an M3 Max, macOS 27.0.1, 2026-11-07. Never rewrite them from this library's own output. heap 2 [("heap made", [1]), ("placed", [1]), ("contents", [2147483648, 2147483712, 2147487744, 2147500028, 2147516416, 2147516480, 2147520512, 2147532796]), ("copy", [4, 0]), ("the GPU read", [2147483648, 2147483712, 2147487744, 2147500028, 2147516416, 2147516480, 2147520512, 2147532796]), ("fill", [4, 0]), ("filled guest runs", [0, 16384, 32768, 49152])] -replace 2 [("replaced", [0])] heap 3 [("heap made", [1]), ("placed", [1]), ("contents", [2147483648, 2147483712, 2147487744, 2147500028, 2147500032, 2147500096, 2147504128, 2147516412]), ("copy", [4, 0]), ("the GPU read", [2147483648, 2147483712, 2147487744, 2147500028, 2147500032, 2147500096, 2147504128, 2147516412]), ("fill", [4, 0]), ("filled guest runs", [0, 32768])] -replace 3 [("replaced", [0])] heap 4 [("heap made", [1]), ("placed", [1]), ("contents", [2147483648, 2147483712, 2147487744, 2147500028, 2147516416, 2147516480, 2147520512, 2147532796]), ("copy", [4, 0]), ("the GPU read", [2147483648, 2147483712, 2147487744, 2147500028, 2147516416, 2147516480, 2147520512, 2147532796]), ("fill", [4, 0]), ("filled guest runs", [0, 16384, 32768, 49152])] -replace 4 [("replaced", [1]), ("contents", [2147483648, 2147483712, 2147487744, 2147500028, 2147516416, 2147516480, 2147520512, 2147532796]), ("copy", [4, 0]), ("the GPU read", [2147483648, 2147483712, 2147487744, 2147500028, 2147516416, 2147516480, 2147520512, 2147532796]), ("fill", [4, 0]), ("filled guest runs", [0, 16384, 32768, 49152])] heap 5 [("heap made", [1]), ("placed", [1]), ("contents", [2147483648, 2147483712, 2147487744, 2147500028, 2147516416, 2147516480, 2147520512, 2147532796, 2147532800, 2147532864, 2147536896, 2147549180]), ("copy", [4, 0]), ("the GPU read", [2147483648, 2147483712, 2147487744, 2147500028, 2147516416, 2147516480, 2147520512, 2147532796, 2147532800, 2147532864, 2147536896, 2147549180]), ("fill", [4, 0]), ("filled guest runs", [0, 16384, 32768, 65536])] -replace 5 [("replaced", [1]), ("contents", [2147483648, 2147483712, 2147487744, 2147500028, 2147516416, 2147516480, 2147520512, 2147532796, 2147532800, 2147532864, 2147536896, 2147549180]), ("copy", [4, 0]), ("the GPU read", [2147483648, 2147483712, 2147487744, 2147500028, 2147516416, 2147516480, 2147520512, 2147532796, 2147532800, 2147532864, 2147536896, 2147549180]), ("fill", [4, 0]), ("filled guest runs", [0, 16384, 32768, 65536])] heap 6 [("heap made", [1]), ("placed", [1]), ("contents", [2147483648, 2147483712, 2147487744, 2147500028, 2147500032, 2147500096, 2147504128, 2147516412, 2147516416, 2147516480, 2147520512, 2147532796]), ("copy", [4, 0]), ("the GPU read", [2147483648, 2147483712, 2147487744, 2147500028, 2147500032, 2147500096, 2147504128, 2147516412, 2147516416, 2147516480, 2147520512, 2147532796]), ("fill", [4, 0]), ("filled guest runs", [0, 49152])] -replace 6 [("replaced", [1]), ("contents", [2147483648, 2147483712, 2147487744, 2147500028, 2147500032, 2147500096, 2147504128, 2147516412, 2147516416, 2147516480, 2147520512, 2147532796]), ("copy", [4, 0]), ("the GPU read", [2147483648, 2147483712, 2147487744, 2147500028, 2147500032, 2147500096, 2147504128, 2147516412, 2147516416, 2147516480, 2147520512, 2147532796]), ("fill", [4, 0]), ("filled guest runs", [0, 49152])] heap 7 [("heap made", [1]), ("placed", [1]), ("contents", [2147483648, 2147483712, 2147487744, 2147500028, 2147516416, 2147516480, 2147520512, 2147532796, 2147549184, 2147549248, 2147553280, 2147565564]), ("copy", [4, 0]), ("the GPU read", [2147483648, 2147483712, 2147487744, 2147500028, 2147516416, 2147516480, 2147520512, 2147532796, 2147549184, 2147549248, 2147553280, 2147565564]), ("fill", [4, 0]), ("filled guest runs", [0, 16384, 32768, 49152, 65536, 81920])] -replace 7 [("replaced", [0])] diff --git a/docs/accuracy-ledger.md b/docs/accuracy-ledger.md index bd735ec43..6eefbade0 100644 --- a/docs/accuracy-ledger.md +++ b/docs/accuracy-ledger.md @@ -123,7 +123,7 @@ process there instead. | A colour texture over a plane of a surface with planes keeps its texels past the surface, and a 2D array's slices past its first, in a tail of its own, zero when made, read and written alike by every path, where Metal's blits read zeros there, its kernels zeros and, 32 KiB past the plane, the plane's rows again, and its writes change no byte of the surface (`surface-texels-tail`); a colour 2D texture of more than one level, a 3D texture and a 2D multisample one over such a plane keep their texels in memory of their own, zero when made, where Metal lays them out in no one place (`surface-texels-apart`) | surfaces | | A draw under the last provoking vertex that the runtime draws otherwise than Metal: a line from its last vertex to its first (`provoking-vertex-lines`); flat inputs, a computed primitive ID or a selected layer or viewport from another vertex, barycentric weights beside flat inputs Metal's but for rounding, and, at a mode from 2 up (its top bit set or not), which it draws as mode 1 and patches as mode 0, a draw whose shape Metal's third way draws otherwise as far as its state reads it: a triangle strip, lines, sized points, the triangles of a state that selects a layer or viewport, and mesh draws, not measured there (`provoking-vertex-unmatched`, at the draw) | the runtime's provoking vertex | | A command predication record of the runtime's whose condition word lies past its buffer, the 256 bytes Metal rounds a lone buffer up to, or its heap reads zero, where Metal reads what its address space holds there (`predication-word-past-buffer`). No record reaches the runtime's predication yet: this platform's own carries it | the runtime's predication | -| A no-copy buffer, heap or rebind over pages the process maps read-only is made over a copy of its pages whose GPU writes the runtime drops, on every device, with or without a dma-buf source, so after its writes the CPU reads the pages as they were, as after Metal's (`read-only-pages-written`, read from metal2vulkan's code at 158f7220ff, which removed the degradation that once announced writes reaching such pages). What this platform answers for writes into read-only memory instead, on Linux: **a surface's read-only alias** is imported through a writable twin of its pages, in place, so a command that may write through an object over one dies where it is encoded: a draw or dispatch through one bound at a slot its functions may store through, by the runtime's slot writes, or made resident for writing; a blit into one; a pass whose attachment lies in one, whatever its actions, or that resolves into one or keeps its visibility results in one; a CPU write of a texture over one. Metal completes such a draw, dispatch, fill or pass's visibility results and drops their writes, fails the command buffer of a pass that stores an attachment back to one, and completes one that does not; a draw through one bound only at slots its functions cannot store through runs. **The guest's read-only objects** (a replace `readOnly:YES`, a heap over address ranges or a no-copy buffer or heap made with `MTLResourceOptions` bit 24, a no-copy buffer or heap over pages mapped read-only) are made over a copy of their pages whose GPU writes the runtime drops, as Metal's GPU drops them: a shader's store into a buffer there (through a slot or a loaded address), a blit's fill into one and a pass's visibility results there are sent and dropped, and so is a blit's copy into one, which no probe made on Metal; a pass that stores an attachment there (`Store`, `StoreAndMultisampleResolve`) fails its command buffer with Metal's page fault (`MTLCommandBufferErrorPageFault`), from that pass on, every event signal firing, as a type-9 draw's page fault does (which encoders run and whether signals fire are unmeasured for this fault), and the commit of every later command buffer of its task dies, where Metal fails each with a code nothing recorded; one that does not store it (`DontCare`, `MultisampleResolve`, under any load action) completes, as Metal's does. A resolve into such memory (unknown on Metal: no verdict over 520 processes), a pass that keeps an attachment there by `CustomSampleDepthStore`, a texture's write there by a shader or a blit (no probe made one), and a CPU write of such a texture (Metal ends the process) die where they are encoded. Metal measured on the M3 Max, macOS 27.0.1, by metal2vulkan's `probes/readonly_gpu_writes.m`. On macOS none of this is taken: MoltenVK hands Metal the pages, or a read-only view of them, and Metal answers | host imports (Linux) | +| A no-copy buffer or heap over pages the process maps read-only is made over a copy of its pages whose GPU writes the runtime drops, on every device, with or without a dma-buf source, so after its writes the CPU reads the pages as they were, as after Metal's (`read-only-pages-written`, read from metal2vulkan's code at 158f7220ff, which removed the degradation that once announced writes reaching such pages). What this platform answers for writes into read-only memory instead, on Linux: **a surface's read-only alias** is imported through a writable twin of its pages, in place, so a command that may write through an object over one dies where it is encoded: a draw or dispatch through one bound at a slot its functions may store through, by the runtime's slot writes, or made resident for writing; a blit into one; a pass whose attachment lies in one, whatever its actions, or that resolves into one or keeps its visibility results in one; a CPU write of a texture over one. Metal completes such a draw, dispatch, fill or pass's visibility results and drops their writes, fails the command buffer of a pass that stores an attachment back to one, and completes one that does not; a draw through one bound only at slots its functions cannot store through runs. **The guest's read-only objects** (a heap over address ranges or a no-copy buffer or heap made with `MTLResourceOptions` bit 24, a no-copy buffer or heap over pages mapped read-only) are made over a copy of their pages whose GPU writes the runtime drops, as Metal's GPU drops them: a shader's store into a buffer there (through a slot or a loaded address), a blit's fill into one and a pass's visibility results there are sent and dropped, and so is a blit's copy into one, which no probe made on Metal; a pass that stores an attachment there (`Store`, `StoreAndMultisampleResolve`) fails its command buffer with Metal's page fault (`MTLCommandBufferErrorPageFault`), from that pass on, every event signal firing, as a type-9 draw's page fault does (which encoders run and whether signals fire are unmeasured for this fault), and the commit of every later command buffer of its task dies, where Metal fails each with a code nothing recorded; one that does not store it (`DontCare`, `MultisampleResolve`, under any load action) completes, as Metal's does. A resolve into such memory (unknown on Metal: no verdict over 520 processes), a pass that keeps an attachment there by `CustomSampleDepthStore`, a texture's write there by a shader or a blit (no probe made one), and a CPU write of such a texture (Metal ends the process) die where they are encoded. Metal measured on the M3 Max, macOS 27.0.1, by metal2vulkan's `probes/readonly_gpu_writes.m`. On macOS none of this is taken: MoltenVK hands Metal the pages, or a read-only view of them, and Metal answers | host imports (Linux) | | Under `textureWriteRoundingMode` 2, a pipeline that covers by alpha, whose function writes a `float` alpha to a half-float colour 0 stored as written, covers by the alpha rounded to the `half` Metal stores, where Metal's coverage reads it before rounding: a fragment within half a `half` step of a threshold may cover one sample more or fewer (`coverage-reads-rounded-alpha`) | render states | | A multisampled pipeline's fragment function that reads `[[sample_mask]]`, which Metal runs once per covered sample (it reads `[[sample_id]]` or a sample-qualified varying, or writes memory), and returns an output runs once per pixel, its body once per covered sample, and writes the last pass's outputs to every sample Metal's runs keep, where Metal writes each sample's from its own run: equal where every pass computes the same outputs. On MoltenVK a function that writes memory runs as written, exact (`looped-sample-outputs`) | render states | | A blend the fragment function computes, of an attachment it reads through the pixel interlock (MoltenVK, RADV, ANV), in a format whose Metal blend arithmetic the runtime has not built (32-bit float, 16-bit normalized, 8-bit snorm, 10-bit, packed float, `A8Unorm`, an 8-bit unorm one written by fewer than four lanes, or a 16-bit float or 8-bit unorm one under a blend of the second source), is the shader's generic blend in `float`, and a four-channel 8-bit `_sRGB` one's under a blend of the second source in a module compiled with fast math is the 8-bit unorm blend's rounded forms over the decoded texel, where Metal's for these is not measured (`unmeasured-fetch-blend`) | draw encoding | diff --git a/docs/lessons.md b/docs/lessons.md index a66c51887..ecee175d8 100644 --- a/docs/lessons.md +++ b/docs/lessons.md @@ -43,7 +43,7 @@ one. A new trap found the same way goes here. - A Metal comparison run after MoltenVK has worked on Metal's device, in the same process, sees Metal let go late. A test of texture ID reuse that ran the Vulkan platform's sequence first and Metal's second found Metal's texture, released while a command buffer held it, still held when `waitUntilCompleted` returned, in 3 runs of 3. Metal run alone frees it by the time the wait returns (5 runs of 5), and 300 ms after the wait it was free in both runs that waited (**measured** on the M3 Max). Metal lets go of a command buffer's resources asynchronously, and once MoltenVK's work shares its device, that release loses the race with the waiter; it looks like the runtime freeing IDs too early. Run Metal's side of a comparison first, before the Vulkan platform makes anything in the process, wherever what is compared depends on when Metal lets go of something (IDs, addresses, retain and use counts, reuse): `texture_identifiers_are_reused_as_metals`, `a_command_buffer_holds_a_surface_as_metals_does` and `holds_as_metals` do. When Metal's side of a comparison disagrees with a plain-Metal probe of the same sequence, run it again with Metal's side alone in its process. - A rule that covers a list of shapes is only as whole as its list, and the list must come from every scenario that makes one, not from the cases the change already knows. A death at a depth or stencil texture whose size Metal's was not measured for exempted the shape of the two cases it named, a 2D `Depth32Float_Stencil8` texture of two levels, and missed the `Depth32Float_Stencil8` cube arrays and an `X32_Stencil8` texture other scenarios make: the full suite died in all three, in every setup, where the change's own check had run a subset picked by name. Unit tests could not show it either: only the guest's serialized descriptors turn `allowGPUOptimizedContents` off. The scenarios build without a device, so the list can be exact: build every one with its descriptor builders wrapped, and list each descriptor of the formats in question with the scenarios whose ops carry its bytes. How to spot the next one: a new death at a creation call, checked by a suite subset rather than the full suite. - A copy of raw bytes carries the layout of every object over them. Core pages a legacy heap's bytes to and from the guest's pages through its buffer over all of the heap, so the guest's pages hold, and a texture of the heap reads after a page-in, whatever layout the platform keeps there. On the Vulkan platform that was the driver's: a native driver's own tiling, or on MoltenVK Metal's layout of MoltenVK's texture, whose usage can differ from the guest's and with it whether Metal compresses the texture (**measured**, `legacy_heap_textures_are_metals_where_metal_keeps_them_plain`). Nothing died or announced it, and no test or suite case read a heap's bytes over a texture. How to spot the next one: for any path that copies an object's bytes whole (paging, a buffer over a heap, an alias of the same memory), list every object that shares those bytes and ask whose layout each one's bytes are in. -- A device test that builds its objects another way than core builds them checks another flow than the one the guest drives. Tests of objects over the guest's pages under a heap's texture (`gpu::over_pages`, a registry since deleted) made their heaps over the guest's pages at once, where core makes a detached heap over memory of its own, places the guest's textures in it, and gives it the guest's pages only at its first prepare, by a replace (`resources/heap/detach.rs`): in core's flow every check compared the guest's pages with core's temporary allocation. The same test replaced a buffer without the detach core makes first, which Metal refuses, so it died at its first line on its first GPU run and had never reached its assertions. Followed through core's flow, the registry never fired at all: core makes each detached heap's cover, its buffer over all of the heap, first and never releases it, so every texture the registry kept apart died at its placement beside the cover first, and the registry, which every command paid a check for, was deleted. Make test objects as core does (`detached_heap`, `replace_heap` in `gpu::resource`'s tests), ask of a check whether core's flow can reach it at all, and for a check of where an object lies, ask what changes where it lies after it is made: a replace, a detach, a discard. +- A device test that builds its objects another way than core builds them checks another flow than the one the guest drives. Tests of objects over the guest's pages under a heap's texture (`gpu::over_pages`, a registry since deleted) made their heaps over the guest's pages at once, where core makes a detached heap over memory of its own, places the guest's textures in it, and gives it the guest's pages only at its first prepare, by a replace (`resources/heap/detach.rs`): in core's flow every check compared the guest's pages with core's temporary allocation. The same test replaced a buffer without the detach core makes first, which Metal refuses, so it died at its first line on its first GPU run and had never reached its assertions. Followed through core's flow, the registry never fired at all: core makes each detached heap's cover, its buffer over all of the heap, first and never releases it, so every texture the registry kept apart died at its placement beside the cover first, and the registry, which every command paid a check for, was deleted. Make test objects as the guest's flow makes them, ask of a check whether core's flow can reach it at all, and for a check of where an object lies, ask what changes where it lies after it is made: a replace, a detach, a discard. - A sweep shows a rule only where it holds an input on which two rules part. The colour fill packer (`crate::gpu::fill`) was compared with Metal over thousands of colours, but its NaNs were only `f64::NAN` and `-f64::NAN`, and no double lay strictly between two integer edges, so three of Metal's rules went unmeasured and the packer missed all three: a signalling NaN into an integer channel stores the largest value, a NaN's payload survives into a half or float channel, and an `R32Uint` double strictly between 2^31 - 1 and 2^31 stores 2^31. How to spot the next one: a sweep of an encoding whose NaNs are all default quiet NaNs, or whose edge values are all exact integers; it must also hold signalling NaNs, payload bits at the positions each target format keeps and drops, and values strictly between representable edges. - An option of a release can move what the release does first. Without a keep-alive, the runtime frees a no-copy buffer's import and then runs the deallocator; given one (its D822), it runs the deallocator first, at Metal's moment, frees the import, and only then drops the keep-alive. A keep-alive holding nothing would have moved every unmap a deallocator of core's makes before the free, on every release, and a driver that validates host-pointer imports at each submission fails on unmapped pages. The platform gives the keep-alive what must outlive the import: the aliases and twins it imports, and a hold that makes core's unmaps through `VulkanVm` wait for the free (`reims-vgpu-vulkan`'s `remap`). How to spot the next one: when a dependency adds an argument that changes when a callback runs, read the code that runs it for the order of everything else it does, not just the callback's moment. - A copy of a Vulkan handle keeps nothing alive. Shared shader modules each held a clone of `ash::Device`, a table of function pointers around a raw handle, which a review passed as harmless; a module released after the device's teardown then destroyed itself through the dead device, and runs on a software rasterizer (llvmpipe) crashed every time. A raw `VkRenderPass` copied into a pool's closure was the same slip. How to spot the next one: in a change that shares or caches a Vulkan object, or moves one into a closure, list every holder and check that each ends before the device and the loader do. diff --git a/docs/qemu.md b/docs/qemu.md index a25c6ae3d..2d56d9a8a 100644 --- a/docs/qemu.md +++ b/docs/qemu.md @@ -425,10 +425,10 @@ through dma-bufs"). How the GPU then takes those pages depends on its driver: log, and its objects take the ways below. - Views are mapped from their files while they fit 8,192 mappings short of the budget (`budget.rs`, `HEADROOM`), and through dma-bufs past that. Any - other import of a view's pages (a no-copy buffer's, a heap's or a - rebind's) maps them from their files while they fit short of those 8,192 - mappings too, as does the writable twin an import of read-only pages - needs. Past that line the library's import gate refuses the pages, and + other import of a view's pages (a no-copy buffer's or a heap's) maps + them from their files while they fit short of those 8,192 mappings too, + as does the writable twin an import of read-only pages needs. Past that + line the library's import gate refuses the pages, and the runtime makes the object over a copy of them, which takes no mapping (metal2vulkan's `HostMemory::with_import_gate`, announced `copied-host-pages`; with `REIMS_VGPU_STRICT=1` it ends the process), @@ -494,7 +494,7 @@ What gets logged: within the headroom of the budget, with the `sysctl -w vm.max_map_count=...` value that covers them (2^23, 8,388,608, for a 16 GiB guest): past that, buffers and heaps not bound in a chunk are copied. -- Each buffer, heap or rebind copied for want of mappings is counted with +- Each buffer or heap copied for want of mappings is counted with its bytes, logged at the first and at each power of two (after the first at debug), and written to the trace (`nrcopy` for pages left in dma-bufs, `notwin` for read-only