🔥 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.
This commit is contained in:
Anees Iqbal committed 2026-11-12 23:10:01 -08:00
1 parent cf8e05b9f7
commit ff837ae87d
30 files changed
+784 -4623

No files matched your search

+2 -2
View File
@@ -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)'
@@ -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"
Binary file not shown.
+15 -28
View File
@@ -367,27 +367,12 @@ pub fn created_or_decided<T>(
/// 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<T>(
/// 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<T>(
/// 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<T>(
/// 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<T>(
/// 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
@@ -42,9 +42,6 @@ pub trait Buffer<P: Platform>: GpuResource<P> {
/// 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<P: Platform>: GpuResource<P> {
descriptor: &P::TextureDescriptor,
plane: SurfacePlane,
) -> RaiseResult<Option<P::Texture>>;
/// sel: replaceBackingWithRanges:readOnly: SPI
/// `false` makes core throw "Failed to replace buffer backing".
fn replace_backing(&self, ranges: &P::AddressRangeArray, read_only: bool) -> RaiseResult<bool>;
/// 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<P: Platform>: GpuResource<P> {
/// `MTLHeap` (with `MTLHeapSPI`). Not an `MTLResource`: its purgeable state, storage mode and
/// options are its own selectors.
pub trait Heap<P: Platform>: 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<P: Platform>: Handle {
descriptor: &P::TextureDescriptor,
offset: u64,
) -> RaiseResult<Option<P::Texture>>;
/// sel: replaceBackingWithRanges:readOnly: SPI
/// `false` makes core throw "Failed to replace heap backing".
fn replace_backing(&self, ranges: &P::AddressRangeArray, read_only: bool) -> RaiseResult<bool>;
/// sel: resourceOptions
fn resource_options(&self) -> u64;
/// sel: setPurgeableState:
@@ -115,14 +115,6 @@ impl Buffer<FakePlatform> for Fk<kind::Buffer> {
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<FakePlatform> for Fk<kind::Buffer> {
|w| Some(new_texture(w, desc, None, 0, Some(parent), false)),
)
}
fn replace_backing(
&self,
ranges: &<FakePlatform as Platform>::AddressRangeArray,
read_only: bool,
) -> RaiseResult<bool> {
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<FakePlatform> for Fk<kind::Texture> {
@@ -512,10 +486,6 @@ impl Texture<FakePlatform> for Fk<kind::Texture> {
}
impl Heap<FakePlatform> for Fk<kind::Heap> {
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<FakePlatform> for Fk<kind::Heap> {
)
}
fn replace_backing(
&self,
ranges: &<FakePlatform as Platform>::AddressRangeArray,
read_only: bool,
) -> RaiseResult<bool> {
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)
}
@@ -213,10 +213,6 @@ pub struct BufferModel {
pub deallocator: Option<NoCopyDeallocator>,
/// A descriptor-made buffer's deallocator `(contents, length)`, run when the buffer dies.
pub desc_deallocator: Option<DescDeallocator>,
/// `detachBacking` was sent.
pub detached: bool,
/// The address ranges it was re-backed with (retained).
pub ranges: Option<AnyHandle>,
/// 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<Arc<RawRegion>>,
/// The address ranges it was made over or re-backed with.
/// The address ranges it was made over.
pub ranges: Option<AnyHandle>,
/// Common resource state.
pub common: ResourceCommon,
File diff suppressed because it is too large. Load diff
+5 -5
View File
@@ -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.
+50 -218
View File
@@ -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<Option<Arc<Progress>>>,
/// Its command predication.
pub(crate) predication: Arc<Predication>,
/// Its place among the releases of detached objects until it commits, which its submission
/// check then holds ([`backing::submission_check`]).
opened: Mutex<Option<Opened>>,
/// 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<rt::CommitFailure> {
/// ([`CommandBufferObject::fails_at_type_9`]). Two different ways at once, which nothing
/// measured, die.
fn failure(&self, sel: &'static str) -> Option<rt::CommitFailure> {
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<VulkanPlatform> 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<rt::CommandBufferError> {
/// 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<rt::CommandBufferError> {
/// 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<String>) -> 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<VulkanPlatform> 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<VulkanPlatform> 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<VulkanPlatform> 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<VulkanPlatform> 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<Option<VulkanCommandBuffer>> {
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<VulkanPlatform> 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
+18 -33
View File
@@ -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<Arc<OsSurface>>) -> 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<VulkanPlatform> 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<Option<VulkanBuffer>> {
let sel = "newBufferWithDescriptor:";
@@ -1944,9 +1941,6 @@ impl GpuDevice<VulkanPlatform> 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<VulkanPlatform> 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<VulkanPlatform> 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<VulkanPlatform> 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<VulkanPlatform> 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<VulkanPlatform> 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<VulkanPlatform> 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<VulkanPlatform> 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<VulkanPlatform> 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,
@@ -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()
}
+1 -18
View File
@@ -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<bool> = 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
+2 -2
View File
@@ -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 <metal_stdlib>
using namespace metal;
+30 -155
View File
@@ -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<Arc<OsSurface>>,
/// 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<VulkanHeap>,
/// 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<TextureObject>;
/// 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<MTLHeap>`.
@@ -1058,36 +1051,13 @@ impl Buffer<VulkanPlatform> 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<u8>| 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<VulkanPlatform> 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<bool> {
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<ExportedMemory, String> {
@@ -1939,13 +1874,6 @@ fn placed<T>(sel: &'static str, made: Result<T, rt::Error>) -> Result<T, rt::Err
}
impl Heap<VulkanPlatform> 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<VulkanPlatform> 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<VulkanPlatform> 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<bool> {
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: Platform>(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: Platform>(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: Platform>(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`
+21 -35
View File
@@ -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<Pages>),
/// 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<Pages>),
}
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<u64>) -> 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<u64>) -> 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<u64>) -> 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<u64>) -> 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);
}
@@ -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`]).
+15 -19
View File
@@ -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<u8>, 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,
@@ -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();
@@ -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<u64>], 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<Alias> {
@@ -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]
+5 -6
View File
@@ -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<HostAddr, KernReturn> {
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(),
+1 -1
View File
@@ -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)]
+1 -1
View File
@@ -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.
+9 -10
View File
@@ -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
@@ -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::<u8>(),
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::<u32>().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<u64>)>;
/// A blit encoder of `cb` with `commands`, ended.
fn blit<P: Platform>(cb: &P::CommandBuffer, commands: Vec<BlitCmd<'_, P>>) {
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<P: Platform>(cb: &P::CommandBuffer) -> Vec<u64> {
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<P: Platform>(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<OptionSet> {
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: Platform>(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: Platform>(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>(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>(
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: Platform>(
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<ResourceAddressRange>, 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: Platform>(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::<u32>()
.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<u64> = (0..count)
.flat_map(|page| [0, 0x40, 0x1000, PAGE - 4].map(|at| page * PAGE + at))
.collect();
let words = |at: HostPtr| -> Vec<u64> {
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::<P>(&queue);
let copy = BlitCmd::CopyBufferToBuffer {
source_buffer: Some(&buffer),
source_offset: 0,
destination_buffer: Some(&out),
destination_offset: 0,
size: length,
};
blit::<P>(&cb, vec![copy]);
steps.push(("copy", finish::<P>(&cb)));
steps.push(("the GPU read", words(out.contents())));
let cb = command_buffer::<P>(&queue);
let fill = BlitCmd::FillBuffer {
buffer: &buffer,
range: NsRange::new(0, length),
value: 0x5c,
};
blit::<P>(&cb, vec![fill]);
steps.push(("fill", finish::<P>(&cb)));
let mut runs: Vec<u64> = 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);
}
}
File diff suppressed because it is too large. Load diff
@@ -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])]
+1 -1
View File
@@ -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 |
+1 -1
View File
@@ -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.
+5 -5
View File
@@ -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