From 3eb84d76c6def74c517c8f3ff6aa8fc5c5371b8d Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sat, 7 Nov 2026 06:37:03 -0800 Subject: [PATCH] Off macOS, drop the GPU's writes to bit-24 no-copy memory through a copy Metal drops what a shader or the blit engine writes into no-copy memory made with its private option bit 24: the write completes with no error, a later command of the same command buffer may read it back, and neither a later command buffer nor the CPU sees it (probes/readonly_gpu_writes.m, an M3 Max under macOS 27.0.1; the owner's ruling of 10-23: drop, never refuse, on every driver). macOS imports the pages through a read-only view of them. Elsewhere the import was of the caller's own pages, so the GPU's writes reached the pages, the CPU and later command buffers (host-page-writes-kernel-store-read-only and host-page-writes-visibility-read-only diverged on llvmpipe and the RTX 5080), announced as private-resource-option. No import can keep the writes out there: Linux drivers pin imported pages for writing, and ANV lost the device and RADV failed every submission over read-only imported pages. So off macOS such a buffer, heap or rebind is made over a copy of the pages whose GPU writes are dropped, the mechanism copied.rs already has for pages the process maps read-only: each commit copies in what the CPU changed, later commands of the batch read the GPU's writes, and the batch's completion puts every byte the GPU changed back, writing nothing to the pages. The gate is not asked (nothing is imported), the copy joins no other buffer over the bytes, and a rebind whose bytes moved in their page is now a copy laid out at the old offset rather than refused. - buffer_descriptor.rs: buffer_over_host_memory makes the copy (CopiedFor::ReadOnly) where drops_writes and the system maps no read-only view; the rebind path copies the same way (read_only_copy); copied_buffer takes why it copies, and passes read_only to CopiedBuffers::add and drops_writes to the buffer's HostCell. no_copy_options moves here from degradation.rs and no longer announces private-resource-option off macOS (that notice stays for a heap of the runtime's memory and an indirect command buffer). - copied.rs: add() takes read_only, which drops the copy's GPU writes whatever the pages' protection. - buffer.rs: BufferParts carries drops_writes into host_lie. - New: CopiedBecause::ReadOnly, WorkCounts::copied_read_only_memory. - Docs: read_only_view.rs, copied.rs, capabilities.rs (the answer stays no off macOS), values.rs, host_backing.rs, interop.rs, host_aliases.rs, error.rs (RebindTextures is macOS-only now), degradation.rs, docs/API.md (private-resource-option, copied-host-pages), docs/HOWTO.md and the docs/FAST-PATHS.md known gap: off macOS a command buffer committed while the writer is in flight still reads its writes, and a render pass's store-out into the copy completes where Metal's faults. - Tests: degrade_notices' bit-24 lane tests assert the writes are dropped on every driver and count the copies (3 and 1 off macOS, 0 on it) and the kinds (copied-host-pages off macOS, none on it); copied_surfaces' dropping buffer is a copy of its own off macOS. - host-page-writes read-only rows declare copied-host-pages in place of private-resource-option; their 8 ledger rows are removed. - api_signatures.tsv blessed for the new field. Verified: see the replay and lane-test jobs named in the branch report (lavapipe, the RTX 5080 through b5080, MoltenVK on the M3). (cherry picked from commit 1f24b1f035d61f093ecf2c76fae4b9c2e4b541d9) --- .../metal2vulkan-conformance/known-gaps.tsv | 8 - .../src/cases/host_page_writes.rs | 25 ++- crates/metal2vulkan-runtime/src/buffer.rs | 30 +++- .../src/buffer_descriptor.rs | 143 +++++++++++++----- .../metal2vulkan-runtime/src/capabilities.rs | 9 +- crates/metal2vulkan-runtime/src/copied.rs | 23 +-- .../metal2vulkan-runtime/src/degradation.rs | 41 ++--- crates/metal2vulkan-runtime/src/error.rs | 7 +- crates/metal2vulkan-runtime/src/heap.rs | 3 +- .../metal2vulkan-runtime/src/host_aliases.rs | 4 +- .../metal2vulkan-runtime/src/host_backing.rs | 5 +- crates/metal2vulkan-runtime/src/interop.rs | 3 +- .../src/read_only_view.rs | 12 +- .../metal2vulkan-runtime/src/tests/copied.rs | 2 +- crates/metal2vulkan-runtime/src/values.rs | 6 +- .../metal2vulkan-runtime/src/work_counts.rs | 10 ++ .../src/wrapped_buffer.rs | 1 + .../src/runtime_lane/copied_surfaces.rs | 26 ++-- .../src/runtime_lane/degrade_notices.rs | 113 ++++++++------ .../src/runtime_lane/host_memory.rs | 2 +- crates/metal2vulkan/tests/api_signatures.tsv | 1 + docs/API.md | 21 ++- docs/FAST-PATHS.md | 37 ++--- docs/HOWTO.md | 13 +- 24 files changed, 333 insertions(+), 212 deletions(-) diff --git a/crates/metal2vulkan-conformance/known-gaps.tsv b/crates/metal2vulkan-conformance/known-gaps.tsv index e491eef49..8d891a96f 100644 --- a/crates/metal2vulkan-conformance/known-gaps.tsv +++ b/crates/metal2vulkan-conformance/known-gaps.tsv @@ -442,14 +442,6 @@ vertex-format-instance-step llvmpipe divergent case/MTLVertexFormatUChar4Normali vertex-format-instance-step llvmpipe divergent case/MTLVertexFormatUChar4Normalized/rows 24 elements differ (F32), the largest difference 0.00000005960464477539063 Metal converts a normalized vertex field as `c / (2^b - 1)`, correctly rounded, and this device's fixed-function vertex input is one ULP high: at the first differing element Metal answers 0x3EFEFEFF, the nearest `float` to 127/255, and we answer 0x3EFEFF00, the next `float` up, and the site's bound is that one ULP (5.96e-8, or 2.98e-8 where the differing lanes are smaller). Under the native-arithmetic contract the device's conversion is the answer: the pipeline records `device-vertex-conversion` for a normalized attribute that fixed-function vertex input fetches, and its recorded bound names exactly this, lavapipe's reciprocal product reading some 8-bit unsigned codes one ulp high. Validation derives no tolerance from it. Open: nothing. vertex-format-instance-step llvmpipe divergent case/MTLVertexFormatHalf4/rows 12 elements differ (F32), the largest difference NaN A NaN of a narrow float attribute (`half`, or a small float of `FloatRG11B10`) fetched by fixed-function vertex input: Metal answers its canonical `0x7FC00000`, and ours keeps the device's widening of the NaN, its payload included (0x7FC02000, or 0x7FFE0000 for the small float, at the first differing element). Under the native-arithmetic contract the device's widening is the answer: `device-nan-encoding` records a fixed-function attribute of a float format narrower than 32 bits, whose NaN Metal widens to `0x7FC00000` and the device's widening need not, and validation derives no tolerance from it. Open: nothing. vertex-format-instance-step NVIDIA GeForce RTX 5080 Laptop GPU divergent case/MTLVertexFormatHalf4/rows 12 elements differ (F32), the largest difference NaN A NaN of a narrow float attribute (`half`, or a small float of `FloatRG11B10`): the first differing element is Metal 0x7FC00000 against our 0x7FC02000, the device's widening of the NaN, its payload included, where Metal answers its canonical `0x7FC00000`. Under the native-arithmetic contract the device's widening is the answer: `device-nan-encoding` records an attribute of a float format narrower than 32 bits, fetched or pulled, whose NaN Metal widens to `0x7FC00000` and the device's widening need not; validation derives no tolerance from it. Open: nothing. -host-page-writes-kernel-store-read-only llvmpipe divergent case/bytes-in-a-later-command-buffer-bytes 256 elements differ (U8), the largest difference 171 Metal DROPS what a shader or the blit engine writes into memory whose backing is read-only, silently and with no error, and we land the write. Metal's rule is measured, not assumed: `probes/readonly_gpu_writes.m` ran eleven shapes on an Apple M3 Max under macOS 27.0.1, one shape a process, eight runs a shape, each against a writable twin of the same program, and a kernel's stores and a pass's visibility result both complete with no error while neither a later command buffer nor the CPU sees any of it -- the writable twin landing its write in all three places is what makes 'dropped' a measurement. The two read-only states agree: bit 24 of `MTLResourceOptions` (what this case states, `ResourceOptions::PRIVATE_BIT`) and the production SPI pair `detachBacking` plus `replaceBackingWithRanges:readOnly:YES` answer alike on all ten shapes measurable under both. The owner's standing rule is that where Metal drops such a write we drop it too, on EVERY driver, with no refusal. We do it on macOS alone: crates/metal2vulkan-runtime/src/read_only_view.rs imports the pages through a read-only view of them (`mach_vm_remap` then `mprotect`), and `VIEWS_DROP_WRITES` is `cfg!(target_os = "macos")`, so on a Linux driver the import is of the caller's own pages, the GPU's writes reach them, and the difference is announced as `Degradation::PrivateResourceOption`. The announcement is not a justification here: the case declares nothing of it and the bytes differ. What the exact form is on a Linux driver is NOT established -- the module's own measurement is that those drivers pin imported pages for writing and refuse or fault on read-only ones (`host_memory.rs`), so the read-only-view trick does not carry over -- and finding one is the work this row waits on. The read taken in the SAME command buffer is exact here, which is the module's recorded reading that a dropped write may be read back from the GPU's caches and is not a contract; the two sites that move are the later command buffer's read and the CPU's. Open: runtime work, on the orchestrator's todo list. -host-page-writes-kernel-store-read-only llvmpipe divergent case/bytes-the-cpu-reads-bytes 256 elements differ (U8), the largest difference 171 Metal DROPS what a shader or the blit engine writes into memory whose backing is read-only, silently and with no error, and we land the write. Metal's rule is measured, not assumed: `probes/readonly_gpu_writes.m` ran eleven shapes on an Apple M3 Max under macOS 27.0.1, one shape a process, eight runs a shape, each against a writable twin of the same program, and a kernel's stores and a pass's visibility result both complete with no error while neither a later command buffer nor the CPU sees any of it -- the writable twin landing its write in all three places is what makes 'dropped' a measurement. The two read-only states agree: bit 24 of `MTLResourceOptions` (what this case states, `ResourceOptions::PRIVATE_BIT`) and the production SPI pair `detachBacking` plus `replaceBackingWithRanges:readOnly:YES` answer alike on all ten shapes measurable under both. The owner's standing rule is that where Metal drops such a write we drop it too, on EVERY driver, with no refusal. We do it on macOS alone: crates/metal2vulkan-runtime/src/read_only_view.rs imports the pages through a read-only view of them (`mach_vm_remap` then `mprotect`), and `VIEWS_DROP_WRITES` is `cfg!(target_os = "macos")`, so on a Linux driver the import is of the caller's own pages, the GPU's writes reach them, and the difference is announced as `Degradation::PrivateResourceOption`. The announcement is not a justification here: the case declares nothing of it and the bytes differ. What the exact form is on a Linux driver is NOT established -- the module's own measurement is that those drivers pin imported pages for writing and refuse or fault on read-only ones (`host_memory.rs`), so the read-only-view trick does not carry over -- and finding one is the work this row waits on. The read taken in the SAME command buffer is exact here, which is the module's recorded reading that a dropped write may be read back from the GPU's caches and is not a contract; the two sites that move are the later command buffer's read and the CPU's. Open: runtime work, on the orchestrator's todo list. -host-page-writes-kernel-store-read-only NVIDIA GeForce RTX 5080 Laptop GPU divergent case/bytes-in-a-later-command-buffer-bytes 256 elements differ (U8), the largest difference 171 Metal DROPS what a shader or the blit engine writes into memory whose backing is read-only, silently and with no error, and we land the write. Metal's rule is measured, not assumed: `probes/readonly_gpu_writes.m` ran eleven shapes on an Apple M3 Max under macOS 27.0.1, one shape a process, eight runs a shape, each against a writable twin of the same program, and a kernel's stores and a pass's visibility result both complete with no error while neither a later command buffer nor the CPU sees any of it -- the writable twin landing its write in all three places is what makes 'dropped' a measurement. The two read-only states agree: bit 24 of `MTLResourceOptions` (what this case states, `ResourceOptions::PRIVATE_BIT`) and the production SPI pair `detachBacking` plus `replaceBackingWithRanges:readOnly:YES` answer alike on all ten shapes measurable under both. The owner's standing rule is that where Metal drops such a write we drop it too, on EVERY driver, with no refusal. We do it on macOS alone: crates/metal2vulkan-runtime/src/read_only_view.rs imports the pages through a read-only view of them (`mach_vm_remap` then `mprotect`), and `VIEWS_DROP_WRITES` is `cfg!(target_os = "macos")`, so on a Linux driver the import is of the caller's own pages, the GPU's writes reach them, and the difference is announced as `Degradation::PrivateResourceOption`. The announcement is not a justification here: the case declares nothing of it and the bytes differ. What the exact form is on a Linux driver is NOT established -- the module's own measurement is that those drivers pin imported pages for writing and refuse or fault on read-only ones (`host_memory.rs`), so the read-only-view trick does not carry over -- and finding one is the work this row waits on. The read taken in the SAME command buffer is exact here, which is the module's recorded reading that a dropped write may be read back from the GPU's caches and is not a contract; the two sites that move are the later command buffer's read and the CPU's. Open: runtime work, on the orchestrator's todo list. -host-page-writes-kernel-store-read-only NVIDIA GeForce RTX 5080 Laptop GPU divergent case/bytes-the-cpu-reads-bytes 256 elements differ (U8), the largest difference 171 Metal DROPS what a shader or the blit engine writes into memory whose backing is read-only, silently and with no error, and we land the write. Metal's rule is measured, not assumed: `probes/readonly_gpu_writes.m` ran eleven shapes on an Apple M3 Max under macOS 27.0.1, one shape a process, eight runs a shape, each against a writable twin of the same program, and a kernel's stores and a pass's visibility result both complete with no error while neither a later command buffer nor the CPU sees any of it -- the writable twin landing its write in all three places is what makes 'dropped' a measurement. The two read-only states agree: bit 24 of `MTLResourceOptions` (what this case states, `ResourceOptions::PRIVATE_BIT`) and the production SPI pair `detachBacking` plus `replaceBackingWithRanges:readOnly:YES` answer alike on all ten shapes measurable under both. The owner's standing rule is that where Metal drops such a write we drop it too, on EVERY driver, with no refusal. We do it on macOS alone: crates/metal2vulkan-runtime/src/read_only_view.rs imports the pages through a read-only view of them (`mach_vm_remap` then `mprotect`), and `VIEWS_DROP_WRITES` is `cfg!(target_os = "macos")`, so on a Linux driver the import is of the caller's own pages, the GPU's writes reach them, and the difference is announced as `Degradation::PrivateResourceOption`. The announcement is not a justification here: the case declares nothing of it and the bytes differ. What the exact form is on a Linux driver is NOT established -- the module's own measurement is that those drivers pin imported pages for writing and refuse or fault on read-only ones (`host_memory.rs`), so the read-only-view trick does not carry over -- and finding one is the work this row waits on. The read taken in the SAME command buffer is exact here, which is the module's recorded reading that a dropped write may be read back from the GPU's caches and is not a contract; the two sites that move are the later command buffer's read and the CPU's. Open: runtime work, on the orchestrator's todo list. -host-page-writes-visibility-read-only llvmpipe divergent case/bytes-in-a-later-command-buffer-bytes 8 elements differ (U8), the largest difference 171 Metal DROPS what a shader or the blit engine writes into memory whose backing is read-only, silently and with no error, and we land the write. Metal's rule is measured, not assumed: `probes/readonly_gpu_writes.m` ran eleven shapes on an Apple M3 Max under macOS 27.0.1, one shape a process, eight runs a shape, each against a writable twin of the same program, and a kernel's stores and a pass's visibility result both complete with no error while neither a later command buffer nor the CPU sees any of it -- the writable twin landing its write in all three places is what makes 'dropped' a measurement. The two read-only states agree: bit 24 of `MTLResourceOptions` (what this case states, `ResourceOptions::PRIVATE_BIT`) and the production SPI pair `detachBacking` plus `replaceBackingWithRanges:readOnly:YES` answer alike on all ten shapes measurable under both. The owner's standing rule is that where Metal drops such a write we drop it too, on EVERY driver, with no refusal. We do it on macOS alone: crates/metal2vulkan-runtime/src/read_only_view.rs imports the pages through a read-only view of them (`mach_vm_remap` then `mprotect`), and `VIEWS_DROP_WRITES` is `cfg!(target_os = "macos")`, so on a Linux driver the import is of the caller's own pages, the GPU's writes reach them, and the difference is announced as `Degradation::PrivateResourceOption`. The announcement is not a justification here: the case declares nothing of it and the bytes differ. What the exact form is on a Linux driver is NOT established -- the module's own measurement is that those drivers pin imported pages for writing and refuse or fault on read-only ones (`host_memory.rs`), so the read-only-view trick does not carry over -- and finding one is the work this row waits on. The read taken in the SAME command buffer is exact here, which is the module's recorded reading that a dropped write may be read back from the GPU's caches and is not a contract; the two sites that move are the later command buffer's read and the CPU's. Open: runtime work, on the orchestrator's todo list. -host-page-writes-visibility-read-only llvmpipe divergent case/bytes-the-cpu-reads-bytes 8 elements differ (U8), the largest difference 171 Metal DROPS what a shader or the blit engine writes into memory whose backing is read-only, silently and with no error, and we land the write. Metal's rule is measured, not assumed: `probes/readonly_gpu_writes.m` ran eleven shapes on an Apple M3 Max under macOS 27.0.1, one shape a process, eight runs a shape, each against a writable twin of the same program, and a kernel's stores and a pass's visibility result both complete with no error while neither a later command buffer nor the CPU sees any of it -- the writable twin landing its write in all three places is what makes 'dropped' a measurement. The two read-only states agree: bit 24 of `MTLResourceOptions` (what this case states, `ResourceOptions::PRIVATE_BIT`) and the production SPI pair `detachBacking` plus `replaceBackingWithRanges:readOnly:YES` answer alike on all ten shapes measurable under both. The owner's standing rule is that where Metal drops such a write we drop it too, on EVERY driver, with no refusal. We do it on macOS alone: crates/metal2vulkan-runtime/src/read_only_view.rs imports the pages through a read-only view of them (`mach_vm_remap` then `mprotect`), and `VIEWS_DROP_WRITES` is `cfg!(target_os = "macos")`, so on a Linux driver the import is of the caller's own pages, the GPU's writes reach them, and the difference is announced as `Degradation::PrivateResourceOption`. The announcement is not a justification here: the case declares nothing of it and the bytes differ. What the exact form is on a Linux driver is NOT established -- the module's own measurement is that those drivers pin imported pages for writing and refuse or fault on read-only ones (`host_memory.rs`), so the read-only-view trick does not carry over -- and finding one is the work this row waits on. The read taken in the SAME command buffer is exact here, which is the module's recorded reading that a dropped write may be read back from the GPU's caches and is not a contract; the two sites that move are the later command buffer's read and the CPU's. Open: runtime work, on the orchestrator's todo list. -host-page-writes-visibility-read-only NVIDIA GeForce RTX 5080 Laptop GPU divergent case/bytes-in-a-later-command-buffer-bytes 8 elements differ (U8), the largest difference 171 Metal DROPS what a shader or the blit engine writes into memory whose backing is read-only, silently and with no error, and we land the write. Metal's rule is measured, not assumed: `probes/readonly_gpu_writes.m` ran eleven shapes on an Apple M3 Max under macOS 27.0.1, one shape a process, eight runs a shape, each against a writable twin of the same program, and a kernel's stores and a pass's visibility result both complete with no error while neither a later command buffer nor the CPU sees any of it -- the writable twin landing its write in all three places is what makes 'dropped' a measurement. The two read-only states agree: bit 24 of `MTLResourceOptions` (what this case states, `ResourceOptions::PRIVATE_BIT`) and the production SPI pair `detachBacking` plus `replaceBackingWithRanges:readOnly:YES` answer alike on all ten shapes measurable under both. The owner's standing rule is that where Metal drops such a write we drop it too, on EVERY driver, with no refusal. We do it on macOS alone: crates/metal2vulkan-runtime/src/read_only_view.rs imports the pages through a read-only view of them (`mach_vm_remap` then `mprotect`), and `VIEWS_DROP_WRITES` is `cfg!(target_os = "macos")`, so on a Linux driver the import is of the caller's own pages, the GPU's writes reach them, and the difference is announced as `Degradation::PrivateResourceOption`. The announcement is not a justification here: the case declares nothing of it and the bytes differ. What the exact form is on a Linux driver is NOT established -- the module's own measurement is that those drivers pin imported pages for writing and refuse or fault on read-only ones (`host_memory.rs`), so the read-only-view trick does not carry over -- and finding one is the work this row waits on. The read taken in the SAME command buffer is exact here, which is the module's recorded reading that a dropped write may be read back from the GPU's caches and is not a contract; the two sites that move are the later command buffer's read and the CPU's. Open: runtime work, on the orchestrator's todo list. -host-page-writes-visibility-read-only NVIDIA GeForce RTX 5080 Laptop GPU divergent case/bytes-the-cpu-reads-bytes 8 elements differ (U8), the largest difference 171 Metal DROPS what a shader or the blit engine writes into memory whose backing is read-only, silently and with no error, and we land the write. Metal's rule is measured, not assumed: `probes/readonly_gpu_writes.m` ran eleven shapes on an Apple M3 Max under macOS 27.0.1, one shape a process, eight runs a shape, each against a writable twin of the same program, and a kernel's stores and a pass's visibility result both complete with no error while neither a later command buffer nor the CPU sees any of it -- the writable twin landing its write in all three places is what makes 'dropped' a measurement. The two read-only states agree: bit 24 of `MTLResourceOptions` (what this case states, `ResourceOptions::PRIVATE_BIT`) and the production SPI pair `detachBacking` plus `replaceBackingWithRanges:readOnly:YES` answer alike on all ten shapes measurable under both. The owner's standing rule is that where Metal drops such a write we drop it too, on EVERY driver, with no refusal. We do it on macOS alone: crates/metal2vulkan-runtime/src/read_only_view.rs imports the pages through a read-only view of them (`mach_vm_remap` then `mprotect`), and `VIEWS_DROP_WRITES` is `cfg!(target_os = "macos")`, so on a Linux driver the import is of the caller's own pages, the GPU's writes reach them, and the difference is announced as `Degradation::PrivateResourceOption`. The announcement is not a justification here: the case declares nothing of it and the bytes differ. What the exact form is on a Linux driver is NOT established -- the module's own measurement is that those drivers pin imported pages for writing and refuse or fault on read-only ones (`host_memory.rs`), so the read-only-view trick does not carry over -- and finding one is the work this row waits on. The read taken in the SAME command buffer is exact here, which is the module's recorded reading that a dropped write may be read back from the GPU's caches and is not a contract; the two sites that move are the later command buffer's read and the CPU's. Open: runtime work, on the orchestrator's todo list. pixel-samplers-rgba16f-nearest-border NVIDIA GeForce RTX 5080 Laptop GPU divergent case/output/norm the digest is 3288187d8ade9557ef4b727bf31750abd8136d15c98b6d29b17ccf6423c0d497 on Metal and 18ed16e2998cc7c3d87dee548216bd6f3bdff85329f9a3ce3025330f3bcd0c0f here Metal's 800 sampled results of this case's `norm` source digest to one value and ours to another; the row holds both. `norm` is the case's control: a normalized sampler state of the same filter and address mode inside an argument buffer, sampled at the coordinate divided by the texture's size, which the runtime hands to the device's own sampler. What moves is the nearest-texel selection and not the filtering: the three `nearest` cases of each format diverge at this site and the `linear` ones do not. The texture is 5 by 3 -- a power of two on neither axis -- so a coordinate divided by the size lands within an ulp of a texel boundary at many of the 800 coordinates, and the `zero` and `border` address modes answer the same digest as each other on both sides, so the out-of-bounds answer is not in it. Under the native-arithmetic contract the device's sampler is the answer: `device-sampling` records that a nearest sample within the device's sub-texel precision of a texel boundary may read the neighbouring texel (0.1% of the deviation probe's coordinates on NVIDIA), and validation derives no tolerance from it. Which coordinates differ is not established by this run, which compares the site as a digest. Open: an element-by-element read of the site against the note's recorded bound. pixel-samplers-rgba16f-nearest-edge NVIDIA GeForce RTX 5080 Laptop GPU divergent case/output/norm the digest is e28b6390ff83ff95e1c5d00dae0fcf2f7b51ad9c20c68e88223e25cfc18700bd on Metal and 05a10e769736e671ff2e1d30f120e417523306fc2281aa0c2be5aa2cea44f3fb here Metal's 800 sampled results of this case's `norm` source digest to one value and ours to another; the row holds both. `norm` is the case's control: a normalized sampler state of the same filter and address mode inside an argument buffer, sampled at the coordinate divided by the texture's size, which the runtime hands to the device's own sampler. What moves is the nearest-texel selection and not the filtering: the three `nearest` cases of each format diverge at this site and the `linear` ones do not. The texture is 5 by 3 -- a power of two on neither axis -- so a coordinate divided by the size lands within an ulp of a texel boundary at many of the 800 coordinates, and the `zero` and `border` address modes answer the same digest as each other on both sides, so the out-of-bounds answer is not in it. Under the native-arithmetic contract the device's sampler is the answer: `device-sampling` records that a nearest sample within the device's sub-texel precision of a texel boundary may read the neighbouring texel (0.1% of the deviation probe's coordinates on NVIDIA), and validation derives no tolerance from it. Which coordinates differ is not established by this run, which compares the site as a digest. Open: an element-by-element read of the site against the note's recorded bound. pixel-samplers-rgba16f-nearest-zero NVIDIA GeForce RTX 5080 Laptop GPU divergent case/output/norm the digest is 3288187d8ade9557ef4b727bf31750abd8136d15c98b6d29b17ccf6423c0d497 on Metal and 18ed16e2998cc7c3d87dee548216bd6f3bdff85329f9a3ce3025330f3bcd0c0f here Metal's 800 sampled results of this case's `norm` source digest to one value and ours to another; the row holds both. `norm` is the case's control: a normalized sampler state of the same filter and address mode inside an argument buffer, sampled at the coordinate divided by the texture's size, which the runtime hands to the device's own sampler. What moves is the nearest-texel selection and not the filtering: the three `nearest` cases of each format diverge at this site and the `linear` ones do not. The texture is 5 by 3 -- a power of two on neither axis -- so a coordinate divided by the size lands within an ulp of a texel boundary at many of the 800 coordinates, and the `zero` and `border` address modes answer the same digest as each other on both sides, so the out-of-bounds answer is not in it. Under the native-arithmetic contract the device's sampler is the answer: `device-sampling` records that a nearest sample within the device's sub-texel precision of a texel boundary may read the neighbouring texel (0.1% of the deviation probe's coordinates on NVIDIA), and validation derives no tolerance from it. Which coordinates differ is not established by this run, which compares the site as a digest. Open: an element-by-element read of the site against the note's recorded bound. diff --git a/crates/metal2vulkan-conformance/src/cases/host_page_writes.rs b/crates/metal2vulkan-conformance/src/cases/host_page_writes.rs index f3e6a6fc1..f9395e948 100644 --- a/crates/metal2vulkan-conformance/src/cases/host_page_writes.rs +++ b/crates/metal2vulkan-conformance/src/cases/host_page_writes.rs @@ -441,28 +441,25 @@ impl Case for HostPageWrite { // vertex function, which is the fixture, not this family's subject) is the suite's // (`crate::replay::NATIVE_NOTES`), declared by no row. // - // `private-resource-option` **has** its venue now, which is what the earlier reading of - // this comment was waiting for. On macOS a no-copy buffer with bit 24 announces nothing: - // the runtime imports the pages through a read-only alias of them and - // `Device::no_copy_options` returns without announcing. Off macOS the GPU's writes reach - // the pages and the notice fires, and it fired on two drivers at once -- the RTX 5080 - // Laptop (615.71.09) and llvmpipe (Mesa 26.2.4) -- for - // `host-page-writes-visibility-read-only` and `host-page-writes-kernel-store-read-only` - // and for neither writable row (replay-nvidia.log, replay-llvmpipe.log). So it is declared - // from `Row::read_only`, which is the bit it is about. + // `copied-host-pages` is the read-only rows' alone, declared from `Row::read_only`, which + // is the bit it is about. On macOS a no-copy buffer with bit 24 announces nothing: the + // runtime imports the pages through a read-only view of them. Off macOS no import keeps + // the GPU's writes out, so the buffer is made over a copy of the pages whose GPU writes are + // dropped at each batch's completion (the runtime's `copied.rs`), and that copy is + // announced. It never fires on MoltenVK, which is why it is declared rather than relied + // on. // // `shared-in-system-memory` is every row's and belongs to the venue, not to this family: // each row reads its pages back through a `Shared` buffer // (`crate::replay::shared_memory_notice`). Announced by all four on the 5080. // - // **None of these loosens a byte**, and that matters most here: the read-only rows' pages - // really do differ on both drivers (`case/bytes-the-cpu-reads-bytes`, 8 bytes, Metal 171 - // against ours 16), which is this family's whole subject. Those bytes stay compared - // exactly and those rows stay divergent on them. + // **None of these loosens a byte**, and that matters most here: the read-only rows' pages, + // and what a later command buffer reads of them, are this family's whole subject. Those + // bytes stay compared exactly. let mut named = vec![crate::replay::shared_memory_notice()]; if self.row.read_only { named.push(crate::replay::notice_allowance( - metal2vulkan_runtime::Degradation::PrivateResourceOption.code(), + metal2vulkan_runtime::Degradation::CopiedHostPages.code(), )); } named diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index eae663107..f01abf898 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -174,8 +174,8 @@ pub(super) struct HostCell { /// (`WorkCounts::no_copy_lies_read`). device: Device, /// The GPU's writes to the buffer are dropped, as Metal's private option bit 24 drops them: - /// its pages are imported through a read-only view of them (`read_only_view.rs`), which a - /// rebind's are too. + /// its pages are imported through a read-only view of them (`read_only_view.rs`), or copied, + /// the copy's GPU writes never written back (`copied.rs`), and a rebind's are too. drops_writes: bool, /// The deallocator of the pages its last detach let go of (`detach.rs`), held back until its /// next rebind or its release, as Metal runs it then ([`Release::hold_back`]). @@ -373,7 +373,7 @@ impl Detached { } impl HostCell { - /// Whether the GPU's writes to the buffer are dropped (`read_only_view.rs`). + /// Whether the GPU's writes to the buffer are dropped (`read_only_view.rs`, `copied.rs`). pub(super) fn drops_writes(&self) -> bool { self.drops_writes } @@ -1867,6 +1867,10 @@ pub(super) struct BufferParts { pub(super) release: Option, /// The buffer is a heap's own (`heap.rs`): `Default` hazard tracking resolves to untracked. pub(super) of_heap: bool, + /// The GPU's writes to a no-copy buffer's pages are dropped, as Metal's private option bit 24 + /// drops them: they are imported through a read-only view of them (`read_only_view.rs`), or + /// copied, the copy's GPU writes never written back (`copied.rs`), and a rebind's are too. + pub(super) drops_writes: bool, /// A `Managed` buffer's host copy, on a device without unified memory. pub(super) mirror: Option>, /// What imports a no-copy buffer's dma-bufs again, where the device may release its import @@ -2315,6 +2319,7 @@ impl Device { owner: Owner::Runtime, release: None, of_heap, + drops_writes: false, mirror, #[cfg(unix)] again: None, @@ -2460,6 +2465,7 @@ impl Device { owner: Owner::Runtime, release: None, of_heap: false, + drops_writes: false, mirror: None, #[cfg(unix)] again: None, @@ -2481,6 +2487,7 @@ impl Device { owner, release, of_heap, + drops_writes, mirror, #[cfg(unix)] again, @@ -2501,7 +2508,7 @@ impl Device { let import = self.host_import(pages, again, kept); #[cfg(not(unix))] let import = Arc::new(HostImport::new(self, pages, kept)); - self.host_lie(identity.key, import, release) + self.host_lie(identity.key, import, release, drops_writes) } Owner::Runtime | Owner::Vulkan => Lie::Fixed(Arc::new(FixedPages { device: self.clone(), @@ -2560,7 +2567,7 @@ impl Device { ) -> Buffer { let identity = Identity::new(modes.hazard, false); let own = OwnBytes { - lie: self.host_lie(identity.key, import, release), + lie: self.host_lie(identity.key, import, release, false), reserved, identity, owner: Owner::Caller, @@ -2571,9 +2578,16 @@ impl Device { } /// A no-copy buffer's lie, of `key`: pages of its own in `import`, released to `release` - /// once nothing holds them, which a rebind replaces (`rebind.rs`). - fn host_lie(&self, key: ResourceKey, import: Arc, release: Option) -> Lie { - let drops_writes = import.drops_writes(); + /// once nothing holds them, which a rebind replaces (`rebind.rs`); the GPU's writes to it + /// dropped where `drops_writes`, or where `import` is of a read-only view of the pages. + fn host_lie( + &self, + key: ResourceKey, + import: Arc, + release: Option, + drops_writes: bool, + ) -> Lie { + let drops_writes = drops_writes || import.drops_writes(); let host = HostPages::new(import); if let Some(release) = release { host.release_to(release); diff --git a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs index 978b33dba..8822f2dcc 100644 --- a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs +++ b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs @@ -230,7 +230,7 @@ impl Device { (None, None) => Place::At(placement), }; let (resource_options, drops_writes) = match contents { - BufferContents::NoCopy { .. } => self.no_copy_options(CALL, resource_options), + BufferContents::NoCopy { .. } => no_copy_options(resource_options), _ => (self.own_memory_options(CALL, resource_options)?, false), }; let buffer = match contents { @@ -306,7 +306,10 @@ impl Device { /// the pages are imported instead. With Metal's private option bit 24 /// ([`ResourceOptions::PRIVATE_BIT`]), the GPU's writes to the pages are dropped, as Metal's /// are: on macOS the pages are imported through a read-only view of them, by their pointer - /// alone; elsewhere the GPU's writes reach them, announced (`private-resource-option`). + /// alone; elsewhere the buffer is made over a copy of them whose GPU writes are dropped, + /// announced (`copied-host-pages`): each commit copies in the bytes the CPU changed, the + /// command buffers already submitted read what the GPU wrote, and each batch's completion + /// puts the copy back to the caller's bytes, which the GPU never writes. /// /// Where the caller's gate refuses the import ([`HostMemory::with_import_gate`]), or the import /// the device and the gate admitted fails (out of memory, another Vulkan error), of the pointer @@ -340,7 +343,7 @@ impl Device { deallocator: Option, ) -> Result { const CALL: &str = "new_buffer_with_bytes_no_copy"; - let (options, drops_writes) = self.no_copy_options(CALL, options); + let (options, drops_writes) = no_copy_options(options); // SAFETY: the caller's contract. let buffer = unsafe { self.buffer_over_host_memory( @@ -448,9 +451,11 @@ impl Device { /// must start at a multiple of the import's unit, the larger of the host page and the /// device's `minImportedHostPointerAlignment`, so that the heap's offsets are its memory's /// (`Invalid`, `HeapProblem::HostMemoryAlignment`, elsewhere). Where `drops_writes` (Metal's - /// private option bit 24, [`Device::no_copy_options`]), the pages are imported through a - /// read-only view of them, which drops the GPU's writes (`read_only_view.rs`): an import of - /// its own, which no other buffer lies in or joins, and which the device keeps imported. + /// private option bit 24, [`no_copy_options`]), the pages are imported through a read-only + /// view of them, which drops the GPU's writes (`read_only_view.rs`): an import of its own, + /// which no other buffer lies in or joins, and which the device keeps imported. Where the + /// system maps no such view, the buffer is a copy of the pages whose GPU writes are dropped + /// instead (`copied.rs`), placed but joined by no other buffer. /// /// # Safety /// @@ -505,7 +510,8 @@ impl Device { // buffer and no import of the class lives (`host_aliases.rs`, `copied.rs`): one // `VkBuffer`, one snapshot and one key, its dma-buf source dropped uncalled and the gate // unasked, as no page is mapped for it. A heap's own buffer imports or copies its own, as - // does one whose GPU writes are dropped (its import is a read-only view of the pages). + // does one whose GPU writes are dropped (its import is a read-only view of the pages, or + // its copy drops them). let made_over = (pointer.as_ptr() as u64, length); let release = release.of(pointer, length); let shares = (!of_heap && !drops_writes) @@ -554,7 +560,8 @@ impl Device { // once, here, holding no lock of the runtime's, before the gate. One run inside one chunk // is bound in the chunk's import, with no import of its own: no pin, no kernel mapping, // no gate. Others take the paths below, the runs kept with the buffer. A buffer whose GPU - // writes are dropped is never routed: it imports a read-only view of its pages. + // writes are dropped is never routed: it imports a read-only view of its pages, or is a + // copy of them. let routed = match (&runs, drops_writes) { (Some(resolver), false) => self.route_runs(call, importer, resolver, &window)?, _ => None, @@ -582,6 +589,21 @@ impl Device { // drops the GPU's writes to pages the process cannot write); or where the import it // admitted fails, of the pointer or of the caller's dma-bufs. let copyable = !drops_writes; + let copy = (call, pointer, length, modes, placement, of_heap); + // Memory whose GPU writes Metal's private option bit 24 drops, where the system + // maps no read-only view of the pages (`read_only_view.rs`): a copy of them whose + // GPU writes are dropped, the gate unasked and no page pinned. It joins no other + // buffer over the bytes, nor does one lie in it. + if drops_writes && !crate::read_only_view::VIEWS_DROP_WRITES { + // SAFETY: the caller's contract. + let copied = + unsafe { self.copied_buffer(copy, release, dirty, CopiedFor::ReadOnly) }; + return copied.map(|buffer| { + let buffer = kept(buffer, log, kept_runs); + shared.aliases.place(buffer.identity().key, made_over); + buffer + }); + } let refused_by_host = copyable && host.by_pointer && gate.as_ref().is_some_and(|gate| { @@ -591,11 +613,11 @@ impl Device { }; !gate(request) }); - let copy = (call, pointer, length, modes, placement, of_heap); if refused_by_host { shared.counts.host_import_refused_by_host(); // SAFETY: the caller's contract. - let copied = unsafe { self.copied_buffer(copy, release, dirty, None) }; + let copied = + unsafe { self.copied_buffer(copy, release, dirty, CopiedFor::Refused) }; return copied.map(|buffer| noted(kept(buffer, log, kept_runs))); } // Only a buffer that imports its pages pins them, and so has their writability @@ -640,8 +662,9 @@ impl Device { // announced. Err(error) if copyable && copies_after(&error) => { // SAFETY: the caller's contract. - let copied = - unsafe { self.copied_buffer(copy, release, dirty, Some(error)) }; + let copied = unsafe { + self.copied_buffer(copy, release, dirty, CopiedFor::Failed(error)) + }; return copied.map(|buffer| noted(kept(buffer, log, kept_runs))); } Err(error) => return Err(error), @@ -672,6 +695,7 @@ impl Device { owner: Owner::Caller, release, of_heap, + drops_writes, mirror: None, #[cfg(unix)] again, @@ -769,10 +793,13 @@ impl Device { // where Metal lays their texels out, which keeps their alignment only at that offset. New // bytes at another offset in their page are given a copy of them laid out at the old // offset (`copied.rs`), as no import lays them there: the gate is not asked, as nothing is - // imported. A buffer whose GPU writes are dropped is never a copy, and is refused so. + // imported. A buffer whose GPU writes are dropped is a copy of the new pages where the + // system maps no read-only view of them (`read_only_view.rs`), as at its making, and is + // never one where it imports such a view, which refuses bytes that moved. let texels = cell.texels(); let in_place = cell.in_place_images(); - let copyable = !drops_writes; + let read_only_copy = drops_writes && !crate::read_only_view::VIEWS_DROP_WRITES; + let copyable = !drops_writes || read_only_copy; let moved = (!texels.is_empty() || !in_place.is_empty()) && window.offset != cell.offset(); if moved && !copyable { return Err(Error::NotImplemented(RuntimeGap::RebindTextures)); @@ -864,7 +891,9 @@ impl Device { // permission is asked (a copy pins no page, and drops the GPU's writes to pages the // process cannot write); or where the import it admitted fails, of the pointer or // of the caller's dma-bufs. Bytes moved in their page are a copy, the gate unasked. - let gate = gate.filter(|_| copyable && host.by_pointer && !moved && !chunk_bound); + let gate = gate.filter(|_| { + copyable && !read_only_copy && host.by_pointer && !moved && !chunk_bound + }); let refused_by_host = match gate { Some(gate) => { // Asked with no lock of the runtime's held: the textures over detached @@ -886,7 +915,7 @@ impl Device { shared.counts.host_import_refused_by_host(); } // Only pages imported here are pinned, and so have their writability asked. - let imports = !chunk_bound && !refused_by_host && !moved; + let imports = !chunk_bound && !refused_by_host && !moved && !read_only_copy; let host = match imports { true => writability_settled(host, writable, &shared.counts)?, false => host, @@ -901,7 +930,16 @@ impl Device { let copy = |failed: Option| { let window = ©_window; // SAFETY: the caller's contract. - unsafe { self.copied_pages(pointer, length, window, images, own_pages, failed) } + unsafe { + self.copied_pages( + pointer, + length, + window, + (images, own_pages), + failed, + read_only_copy, + ) + } }; let imported = match (in_chunk, imports) { (Some(bound), _) => Ok(Ok(bound)), @@ -1006,6 +1044,7 @@ impl Device { let cause = match (moved, &failed) { (true, _) => CopiedBecause::Moved, (false, Some(_)) => CopiedBecause::Failed, + (false, None) if read_only_copy => CopiedBecause::ReadOnly, (false, None) => CopiedBecause::Refused, }; let (host, placement, copied) = copy(failed)?; @@ -1377,7 +1416,8 @@ impl Device { /// Where images in place ride on it (`own_pages`), the copy is fresh pages the runtime maps and /// imports by their pointer where the device takes them ([`Device::fresh_page_buffer`]), so /// each image is made for host allocations, as over the caller's pages, under the device's - /// check for fresh pages (`in_place.rs`); else memory the device allocates. Refused as + /// check for fresh pages (`in_place.rs`); else memory the device allocates. The GPU's writes + /// to the copy are dropped where `read_only` (Metal's private option bit 24). Refused as /// [`Device::copied_buffer`] refuses its copy. /// /// # Safety @@ -1388,9 +1428,9 @@ impl Device { pointer: NonNull, length: u64, window: &ImportWindow, - images: Option, - own_pages: bool, + (images, own_pages): (Option, bool), failed: Option, + read_only: bool, ) -> Result<(HostBuffer, Placement, crate::copied::Copied), Error> { let shared = self.shared(); let raw_device = shared.vk(); @@ -1428,7 +1468,7 @@ impl Device { // SAFETY: the copy is the placement's `length` bytes past the window's offset, mapped, // which nothing uses yet and which stay mapped while the import holds them; the caller's // bytes stay mapped as long (the caller's contract). - let copied = match unsafe { shared.copied.add(pointer, copy, bytes) } { + let copied = match unsafe { shared.copied.add(pointer, copy, bytes, read_only) } { Ok(copied) => copied, Err(why) => { discard(&memory); @@ -1532,13 +1572,21 @@ impl Device { "they lie at another offset in their page than the buffer's old bytes, \ where a texture over the buffer was planned, which no import lays them at" } + CopiedBecause::ReadOnly => { + "Metal's private option bit 24 (0x1000000) makes them memory the GPU's \ + writes do not reach, and no import of them here keeps the GPU's writes out" + } }; - let dropped = match drops { - true => { + let dropped = match (drops, cause) { + (true, CopiedBecause::ReadOnly) => { + ", whose GPU writes are dropped, as Metal drops them, and never written to \ + the pages" + } + (true, _) => { ", whose GPU writes are dropped, as Metal drops them, since the process maps \ some of their pages read-only" } - false => "", + (false, _) => "", }; ( format!("{call} over {length:#x} bytes at {pointer:p}"), @@ -1581,10 +1629,11 @@ impl Device { /// A copied host buffer over the `length` bytes at `pointer` (`copied.rs`), of `modes`, at /// `placement`, for `call`, a heap's own buffer where `of_heap` (laid where the heap's /// textures could lie, its hazard identity a heap's), given back to `release`, its caller's - /// log `dirty` kept with it: - /// made where the caller's gate refused the pointer's import (`failed` is `None`), or where - /// the import the gate and the device admitted failed with `failed`. Announced - /// (`copied-host-pages`) and counted either way. Refused where its own memory cannot be had + /// log `dirty` kept with it, made `why` says: where the caller's gate refused the pointer's + /// import, where the import the gate and the device admitted failed, or for memory whose GPU + /// writes Metal's private option bit 24 drops where the system maps no read-only view of the + /// pages (`read_only_view.rs`), whose GPU writes the copy drops. Announced + /// (`copied-host-pages`) and counted each way. Refused where its own memory cannot be had /// (typed as the allocation answers), and where the process cannot read every page (memory /// Metal makes no buffer over): with the import's failure where there was one, else as not /// importable. @@ -1604,8 +1653,14 @@ impl Device { ), release: Option, dirty: Option>, - failed: Option, + why: CopiedFor, ) -> Result { + let read_only = matches!(why, CopiedFor::ReadOnly); + let (cause, failed) = match why { + CopiedFor::Refused => (CopiedBecause::Refused, None), + CopiedFor::Failed(failed) => (CopiedBecause::Failed, Some(failed)), + CopiedFor::ReadOnly => (CopiedBecause::ReadOnly, None), + }; let shared = self.shared(); let raw_device = shared.vk(); // The pages' refusal where they cannot be copied: the import's failure, or a refusal of @@ -1661,7 +1716,7 @@ impl Device { // SAFETY: the copy is the placement's `length` bytes, mapped, which nothing uses yet and // which stay mapped while the import holds them; the caller's bytes stay mapped as long // (the caller's contract). - let copied = match unsafe { shared.copied.add(pointer, copy, bytes) } { + let copied = match unsafe { shared.copied.add(pointer, copy, bytes, read_only) } { Ok(copied) => copied, Err(why) => { discard(&memory); @@ -1686,6 +1741,7 @@ impl Device { owner: Owner::Caller, release, of_heap, + drops_writes: read_only, mirror: None, #[cfg(unix)] again: None, @@ -1698,10 +1754,6 @@ impl Device { pages.keep_dirty(dirty); } } - let cause = match failed { - Some(_) => CopiedBecause::Failed, - None => CopiedBecause::Refused, - }; shared.counts.copied_host_buffer_made(cause); if of_heap { shared.counts.copied_heap_made(); @@ -1935,7 +1987,8 @@ fn pages_log( /// ([`host_window`]). struct HostWindow { /// The GPU's writes to them are dropped: they are imported through a read-only view of them - /// (`read_only_view.rs`), by their pointer alone. + /// (`read_only_view.rs`), by their pointer alone, or where the system maps no such view, they + /// are copied (`copied.rs`). drops_writes: bool, /// The pages: the range rounded out to the host page. window: ImportWindow, @@ -1975,6 +2028,26 @@ fn writability_settled( } } +/// `options` of a no-copy buffer or heap over the caller's bytes without +/// [`ResourceOptions::PRIVATE_BIT`], and whether its memory drops the GPU's writes, as Metal's does +/// where the options set the bit: on macOS the runtime imports the pages through a read-only view +/// of them (`read_only_view.rs`); elsewhere it makes the object over a copy of them whose GPU +/// writes it never writes back (`copied.rs`, announced as `copied-host-pages`). +pub(super) fn no_copy_options(options: ResourceOptions) -> (ResourceOptions, bool) { + options.without_private_bit() +} + +/// Why a no-copy buffer or heap is made over a copy of the caller's pages (`Device::copied_buffer`). +enum CopiedFor { + /// The caller's gate refused their import (`HostMemory::with_import_gate`). + Refused, + /// The import the device and the gate admitted failed, with this. + Failed(Error), + /// Metal's private option bit 24 drops the GPU's writes to the memory, and the system maps + /// no read-only view of the pages (`read_only_view.rs`): the copy drops them. + ReadOnly, +} + /// Whether `error`, an import's failure that is not the device's refusal of the pages, leaves the /// no-copy buffer a copy of them (`copied.rs`): out of memory, another Vulkan error, or the /// runtime's refusal of pages the kernel cannot pin, made for a driver whose failed import of them diff --git a/crates/metal2vulkan-runtime/src/capabilities.rs b/crates/metal2vulkan-runtime/src/capabilities.rs index 3b4f9085b..f52ba1e1c 100644 --- a/crates/metal2vulkan-runtime/src/capabilities.rs +++ b/crates/metal2vulkan-runtime/src/capabilities.rs @@ -483,9 +483,12 @@ impl DeviceProperties { /// visibility result all complete and leave the pages as they were, and a colour attachment with /// [`StoreAction::Store`](crate::StoreAction::Store), a resolve target or a depth or stencil /// attachment over such memory ends its command buffer in error. On macOS, where the device - /// imports the pages through a read-only view of them, that is yes; elsewhere the import is of - /// the caller's own pages and this answers no, with the difference announced - /// ([`Degradation::PrivateResourceOption`](crate::Degradation::PrivateResourceOption)). + /// imports the pages through a read-only view of them, that is yes. Elsewhere the memory is a + /// copy of the pages whose GPU writes are dropped, announced + /// ([`Degradation::CopiedHostPages`](crate::Degradation::CopiedHostPages)), and this answers + /// no: the CPU and the command buffers committed after a writer's completion read the pages' + /// own bytes, but a command buffer committed before it may read the GPU's writes, and a render + /// pass's store-out into the copy completes. pub fn drops_gpu_writes_to_read_only_memory(&self) -> bool { crate::read_only_view::VIEWS_DROP_WRITES } diff --git a/crates/metal2vulkan-runtime/src/copied.rs b/crates/metal2vulkan-runtime/src/copied.rs index 353e13cd1..a17b25855 100644 --- a/crates/metal2vulkan-runtime/src/copied.rs +++ b/crates/metal2vulkan-runtime/src/copied.rs @@ -54,8 +54,10 @@ //! `WorkCounts::copied_copy_in_bytes_skipped`. //! - **Pages the process cannot write** (read-only pages, as a consumer's alias of a read-only //! replace, `replaceBackingWithRanges:readOnly:`, maps them), asked of the system as the copy is -//! made ([`mapped_writable`]): the GPU's writes to the copy are dropped, as Metal drops the GPU's -//! writes to read-only memory (`read_only_view.rs`). At each batch's completion every byte the +//! made ([`mapped_writable`]), and memory of Metal's private option bit 24 where the system maps +//! no read-only view of the pages (`read_only_view.rs`, copied whatever the gate would answer): +//! the GPU's writes to the copy are dropped, as Metal drops the GPU's writes to read-only +//! memory. At each batch's completion every byte the //! GPU changed in the copy takes back the byte the pages and the copy last agreed on //! ([`CopiedBuffers::merge_back`]), and nothing is written to the pages: later commands of the //! same batch read the write back, and a later command buffer the pages' bytes. The CPU's writes @@ -98,8 +100,9 @@ //! textures bound to its bytes and the images in place over the buffer are made again over the //! copy: in fresh pages the runtime imported where an image in place rides on it, made as over //! the caller's pages; else linear images of its memory that start `PREINITIALIZED`. -//! - **What is not copied.** Memory whose GPU writes Metal's private option bit 24 drops imports as -//! before. A texture made over a copied buffer is a shadow of its bytes (`shadowed-texture`). +//! - **What is not copied.** On macOS, memory whose GPU writes Metal's private option bit 24 drops +//! imports a read-only view of its pages (`read_only_view.rs`). A texture made over a copied +//! buffer is a shadow of its bytes (`shadowed-texture`). use crate::device::lock; use crate::dirty_pages::{new_writer, DirtySource, DirtyTally, PagesLog}; @@ -338,10 +341,10 @@ impl CopiedBuffers { /// Register the copy at `copy` of the `length` bytes at `pages`, its bytes read from the pages /// now ([`read_caller`]: through the kernel, or where it fails, with plain loads of pages - /// mapped readable). Where the process cannot write every page ([`mapped_writable`]), the - /// GPU's writes to the copy are dropped (the module docs). Refused, registering nothing, where - /// the process cannot read every page, or the host has no memory for the bytes the copy and - /// the pages last agreed on. + /// mapped readable). Where the process cannot write every page ([`mapped_writable`]), or + /// `read_only` (memory of Metal's private option bit 24), the GPU's writes to the copy are + /// dropped (the module docs). Refused, registering nothing, where the process cannot read + /// every page, or the host has no memory for the bytes the copy and the pages last agreed on. /// /// # Safety /// @@ -354,6 +357,7 @@ impl CopiedBuffers { pages: NonNull, copy: NonNull, length: usize, + read_only: bool, ) -> Result { let read = |pages: NonNull, into: &mut [u8]| { // SAFETY: the caller's bytes, read with plain loads only where the process maps them @@ -361,7 +365,8 @@ impl CopiedBuffers { unsafe { read_caller(pages, into, read_pages, mapped_readable) } }; let start = pages.as_ptr() as u64; - let drops_writes = !mapped_writable(start, start.saturating_add(length as u64)); + let drops_writes = + read_only || !mapped_writable(start, start.saturating_add(length as u64)); // SAFETY: the caller's. unsafe { self.add_reading(pages, copy, length, read, drops_writes) } } diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index 2103b79aa..9f553d0da 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -1039,8 +1039,8 @@ degradations! { placed one"; /// A heap of the runtime's memory or an indirect command buffer made with /// `MTLResourceOptions` bit 24 - /// ([`ResourceOptions::PRIVATE_BIT`](crate::ResourceOptions::PRIVATE_BIT)), or off macOS a - /// no-copy buffer or heap over the caller's bytes, which Metal makes and keeps the GPU's + /// ([`ResourceOptions::PRIVATE_BIT`](crate::ResourceOptions::PRIVATE_BIT)), which Metal + /// makes and keeps the GPU's /// writes from the memory of (the M3 Max under macOS 27.0.1, `read_only_view.rs`: what a /// shader or the blit engine writes reaches neither the CPU nor a later command buffer, /// which read the memory's bytes -- a blit's fill, a kernel's stores, a vertex- or @@ -1050,9 +1050,10 @@ degradations! { /// machinery writes **faults** the command buffer -- a colour attachment over that memory, /// a resolve into it, a depth or stencil attachment in a heap of the bit, and a blit into a /// texture over or in it), is - /// made as without it, and reports its options without it, as Metal's does. On macOS a - /// no-copy buffer or heap with the bit drops the GPU's writes as Metal's does, its pages - /// imported through a read-only view of them (`read_only_view.rs`), announcing nothing. + /// made as without it, and reports its options without it, as Metal's does. A no-copy + /// buffer or heap with the bit drops the GPU's writes as Metal's does: on macOS its pages + /// imported through a read-only view of them (`read_only_view.rs`), announcing nothing; + /// elsewhere made over a copy of them that drops them (`copied-host-pages`). /// A buffer of the runtime's memory or a texture descriptor with the bit is refused, as /// Metal ends the process there; a buffer placed in a heap without the bit is made as /// without it, as Metal's is, announcing nothing. @@ -1973,9 +1974,12 @@ degradations! { /// memory, or another Vulkan error, such as a driver out of the mappings the host kernel /// allows), or the runtime kept pages the kernel cannot pin from a driver whose failed /// import of them breaks it (`RuntimeDriverDefect::UnpinnablePagesBreakHostMemory`) and no - /// dma-buf of them served. A copy of pages the process maps read-only drops the GPU's - /// writes, as Metal drops them: never written to the pages - /// (`WorkCounts::copied_dropped_bytes`; the detail says so). A copy whose own allocation + /// dma-buf of them served; or, off macOS, the memory is of Metal's private option bit 24 + /// (`ResourceOptions::PRIVATE_BIT`), which no import there keeps the GPU's writes from, and + /// which is copied without asking the gate (`WorkCounts::copied_read_only_memory`). A copy + /// of pages the process maps read-only, or of bit-24 memory, drops the GPU's writes, as + /// Metal drops them: never written to the pages (`WorkCounts::copied_dropped_bytes`; the + /// detail says so). A copy whose own allocation /// fails refuses the call (`OutOfMemory`). /// Announced once per device, by the call that makes it, or at each such call where /// `DeviceOptions::announce_each` asks. Counted: `WorkCounts::copied_host_buffers_made`. @@ -3404,27 +3408,10 @@ impl Device { } } - /// `options` of `call`'s no-copy buffer or heap over the caller's bytes without - /// [`ResourceOptions::PRIVATE_BIT`], and whether its memory drops the GPU's writes, as Metal's - /// does where the options set the bit: on macOS, where the runtime imports the pages through - /// a read-only view of them (`read_only_view.rs`). Elsewhere the GPU's writes reach the - /// pages, announced once ([`Degradation::PrivateResourceOption`]). - pub(super) fn no_copy_options( - &self, - call: &'static str, - options: ResourceOptions, - ) -> (ResourceOptions, bool) { - if !crate::read_only_view::VIEWS_DROP_WRITES { - return (self.take_options(call, options), false); - } - options.without_private_bit() - } - /// `options` as the runtime makes `call`'s resource of them where Metal makes it with /// [`ResourceOptions::PRIVATE_BIT`] and keeps the GPU's writes from its memory (a heap of - /// the runtime's memory; a no-copy buffer or heap off macOS, [`Device::no_copy_options`]; an - /// indirect command buffer, whose GPU-written records under it are not measured): without the - /// bit, announced once ([`Degradation::PrivateResourceOption`]). + /// the runtime's memory; an indirect command buffer, whose GPU-written records under it are + /// not measured): without the bit, announced once ([`Degradation::PrivateResourceOption`]). pub(super) fn take_options( &self, call: &'static str, diff --git a/crates/metal2vulkan-runtime/src/error.rs b/crates/metal2vulkan-runtime/src/error.rs index 22c55e270..41b4eb218 100644 --- a/crates/metal2vulkan-runtime/src/error.rs +++ b/crates/metal2vulkan-runtime/src/error.rs @@ -1712,9 +1712,10 @@ pub enum RuntimeGap { EmptyFillPattern, /// `Buffer::rebind_bytes_no_copy` of a no-copy buffer whose GPU writes are dropped (Metal's /// private option bit 24) with a live texture over its bytes, given memory at another offset - /// in its page than the old: the texture's copies and texel views are planned at the bytes' - /// offset in their `VkBuffer` (`rebind.rs`), and such a buffer is never a copy laid out there, - /// as any other buffer's moved bytes are. Also a rebind of a no-copy buffer or heap with a + /// in its page than the old, on macOS: the texture's copies and texel views are planned at the + /// bytes' offset in their `VkBuffer` (`rebind.rs`), and such a buffer imports a read-only view + /// of its pages there, never a copy laid out there, as any other buffer's moved bytes are + /// (elsewhere such a buffer is a copy, laid out there). Also a rebind of a no-copy buffer or heap with a /// texture whose image is bound to its bytes, where the device makes no such image over the /// new memory: over memory it imports by its pointer, one that takes the import's type and /// lies where the texture's texels do, its rows (and slices) as far apart as the old image's, diff --git a/crates/metal2vulkan-runtime/src/heap.rs b/crates/metal2vulkan-runtime/src/heap.rs index f9c125ea0..c89af499a 100644 --- a/crates/metal2vulkan-runtime/src/heap.rs +++ b/crates/metal2vulkan-runtime/src/heap.rs @@ -628,7 +628,8 @@ impl Device { token: Option, ) -> Result { const CALL: &str = "new_heap_with_bytes_no_copy"; - let (options, drops_writes) = self.no_copy_options(CALL, descriptor.resource_options); + let (options, drops_writes) = + super::buffer_descriptor::no_copy_options(descriptor.resource_options); let modes = Modes::of(options)?; if modes.storage != StorageMode::Shared || descriptor.heap_type == HeapType::Sparse { return Err(invalid(CALL, Problem::StorageMode)); diff --git a/crates/metal2vulkan-runtime/src/host_aliases.rs b/crates/metal2vulkan-runtime/src/host_aliases.rs index a97491f70..0138fadad 100644 --- a/crates/metal2vulkan-runtime/src/host_aliases.rs +++ b/crates/metal2vulkan-runtime/src/host_aliases.rs @@ -49,8 +49,8 @@ //! the shadow copy in again, as a write through its own buffer does. //! - **Not joined.** Buffers over memory that overlaps without being the same range, a heap's //! bytes (a heap's own copy too), and the memory a rebound buffer takes, keep their own keys, -//! and a buffer whose GPU writes are dropped imports a read-only view of its own (a copy shared -//! with it would take its writes): Metal orders no two +//! and a buffer whose GPU writes are dropped imports a read-only view of its own, or is a copy +//! of its own (a copy shared with it would take its writes): Metal orders no two //! no-copy buffers over one allocation (the same probe's `host` cases read stale or mixed //! texels), so the runtime's joining of the same range is the IOSurface's ordering, which a //! race over plain no-copy buffers may also give. A rebound buffer leaves the memory it was diff --git a/crates/metal2vulkan-runtime/src/host_backing.rs b/crates/metal2vulkan-runtime/src/host_backing.rs index ae35b59bc..db88d813a 100644 --- a/crates/metal2vulkan-runtime/src/host_backing.rs +++ b/crates/metal2vulkan-runtime/src/host_backing.rs @@ -35,8 +35,9 @@ pub enum HostBacking { /// A copy of the pages in memory of the device's own, which the GPU reads and writes in their /// place: the caller's gate refused their import /// ([`HostMemory::with_import_gate`](crate::HostMemory::with_import_gate)), the import the - /// device and the gate admitted failed, or a rebind's new bytes lie at another offset in - /// their page than the old under a texture over the buffer. Announced as the + /// device and the gate admitted failed, a rebind's new bytes lie at another offset in their + /// page than the old under a texture over the buffer, or off macOS the memory is of Metal's + /// private option bit 24, whose GPU writes the copy drops. Announced as the /// [`copied-host-pages`](crate::Degradation::CopiedHostPages) degradation: each commit writes /// into the copy the bytes the CPU changed in the pages, and each batch's completion writes /// back the bytes the GPU changed, where Metal's GPU uses the pages themselves. diff --git a/crates/metal2vulkan-runtime/src/interop.rs b/crates/metal2vulkan-runtime/src/interop.rs index f609be4fd..db96250aa 100644 --- a/crates/metal2vulkan-runtime/src/interop.rs +++ b/crates/metal2vulkan-runtime/src/interop.rs @@ -224,7 +224,8 @@ impl Buffer { /// a copied host buffer ([`HostBacking::Copied`](crate::HostBacking::Copied)), whose memory is /// a copy the runtime brings in step with the pages only at its own commits and completions; /// pages imported as dma-bufs (several allocations, sparsely bound); pages of Metal's private - /// option bit 24, whose import is of a read-only view that drops the GPU's writes; a detached + /// option bit 24, whose import is of a read-only view that drops the GPU's writes (on macOS; + /// elsewhere they are a copied host buffer); a detached /// buffer; and an import the device released while idle and could not make again (the device /// is then lost). As [`vk_buffer`](Self::vk_buffer) does, the call keeps an import the device /// would release while idle imported for good. diff --git a/crates/metal2vulkan-runtime/src/read_only_view.rs b/crates/metal2vulkan-runtime/src/read_only_view.rs index 6e8a46b66..b84b146fe 100644 --- a/crates/metal2vulkan-runtime/src/read_only_view.rs +++ b/crates/metal2vulkan-runtime/src/read_only_view.rs @@ -79,10 +79,14 @@ //! the import's 11 to 20 ms per GiB. //! - **Freed.** The view is unmapped once the memory imported from it is freed (`memory.rs`'s //! `Block`), as the import requires it mapped for its whole life. -//! - **Elsewhere** the import is of the caller's pages: Linux drivers pin imported pages for -//! writing and refuse or fault on read-only ones (`host_memory.rs`), so there the GPU's writes -//! reach the pages, and the difference is announced -//! ([`Degradation::PrivateResourceOption`](crate::Degradation::PrivateResourceOption)). +//! - **Elsewhere** no import keeps the GPU's writes out: Linux drivers pin imported pages for +//! writing and refuse or fault on read-only ones (`host_memory.rs`; ANV lost the device and RADV +//! failed every submission over read-only imported pages). So there such memory is a copy of the +//! pages whose GPU writes are dropped (`copied.rs`, announced as +//! [`Degradation::CopiedHostPages`](crate::Degradation::CopiedHostPages)): each commit copies in +//! what the CPU wrote, later commands of a batch read its GPU writes back, and its completion +//! puts the copy back to the pages' bytes, which the GPU never writes. A render pass's +//! store-out into it completes there, where Metal's faults its command buffer. use std::ptr::NonNull; diff --git a/crates/metal2vulkan-runtime/src/tests/copied.rs b/crates/metal2vulkan-runtime/src/tests/copied.rs index 6872f2445..3241aca9d 100644 --- a/crates/metal2vulkan-runtime/src/tests/copied.rs +++ b/crates/metal2vulkan-runtime/src/tests/copied.rs @@ -312,7 +312,7 @@ fn copied_pages_of_a_dma_buf_mapping_are_copied() { let mut copy = vec![0_u8; length]; // SAFETY: the copy is the test's; the mapping is `length` bytes, readable, live past the // answer. - let copied = unsafe { buffers.add(mapping.pages, at(&mut copy), length) }; + let copied = unsafe { buffers.add(mapping.pages, at(&mut copy), length, false) }; assert!(copied.is_ok(), "copied"); assert!(copy == pattern, "the copy holds the dma-buf's bytes"); } diff --git a/crates/metal2vulkan-runtime/src/values.rs b/crates/metal2vulkan-runtime/src/values.rs index 8a01807fe..b012cbfa7 100644 --- a/crates/metal2vulkan-runtime/src/values.rs +++ b/crates/metal2vulkan-runtime/src/values.rs @@ -134,7 +134,11 @@ impl ResourceOptions { /// pass's visibility result -- and reaches neither the CPU nor a later command buffer. What a /// render pass's own machinery writes faults the command buffer: a colour attachment over /// that memory, a resolve into it, a depth or stencil attachment in a heap of the bit, and a - /// blit into a texture over or in it. The runtime makes them as without it, and announces + /// blit into a texture over or in it. The runtime drops the GPU's writes to a no-copy + /// buffer's or heap's memory with it, as Metal does: on macOS its pages are imported through + /// a read-only view of them, announcing nothing; elsewhere it is made over a copy of them + /// whose GPU writes are dropped, announced as `metal2vulkan-degrade-copied-host-pages`. A + /// heap of the runtime's memory with it is made as without it, announcing /// `metal2vulkan-degrade-private-resource-option` once; so does an indirect command buffer /// made with it, which Metal makes and whose GPU-written records under it are not measured; /// - a buffer placed in a heap without it is made as without it, as Metal's is, announcing diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 4b55a73ce..c0d0b87ec 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -326,6 +326,7 @@ pub(crate) struct Counters { copied_host_buffers_refused: AtomicU64, copied_host_buffers_degraded: AtomicU64, copied_rebind_pages_moved: AtomicU64, + copied_read_only_memory: AtomicU64, copied_rebind_pages_made: AtomicU64, copied_rebind_images_made: AtomicU64, copied_heaps_made: AtomicU64, @@ -2701,6 +2702,7 @@ impl Counters { CopiedBecause::Failed => &self.copied_host_buffers_degraded, CopiedBecause::Refused => &self.copied_host_buffers_refused, CopiedBecause::Moved => &self.copied_rebind_pages_moved, + CopiedBecause::ReadOnly => &self.copied_read_only_memory, } .fetch_add(1, Ordering::Relaxed); } @@ -5646,6 +5648,10 @@ pub struct WorkCounts { /// page than the old, where a texture over the buffer was planned at the old offset /// (`Buffer::rebind_bytes_no_copy`): the copy keeps the bytes at the old offset. pub copied_rebind_pages_moved: u64, + /// Of `copied_host_buffers_made`: no-copy buffers, heaps and rebinds of memory whose GPU writes + /// Metal's private option bit 24 drops, made over a copy that drops them where the system + /// maps no read-only view of the pages (`copied.rs`, `read_only_view.rs`). + pub copied_read_only_memory: u64, /// Of the copies made, those a rebind gave a buffer as its new pages /// (`Buffer::rebind_bytes_no_copy`), in `copied_host_buffers_made` and its kin too. pub copied_rebind_pages_made: u64, @@ -6995,6 +7001,7 @@ impl Device { .copied_host_buffers_degraded .load(Ordering::Relaxed), copied_rebind_pages_moved: counters.copied_rebind_pages_moved.load(Ordering::Relaxed), + copied_read_only_memory: counters.copied_read_only_memory.load(Ordering::Relaxed), copied_rebind_pages_made: counters.copied_rebind_pages_made.load(Ordering::Relaxed), copied_rebind_images_made: counters.copied_rebind_images_made.load(Ordering::Relaxed), copied_heaps_made: counters.copied_heaps_made.load(Ordering::Relaxed), @@ -7319,4 +7326,7 @@ pub(crate) enum CopiedBecause { /// A rebind's new bytes lie at another offset in their page than the old, where a texture /// over the buffer was planned at the old offset: no import lays them there. Moved, + /// Metal's private option bit 24 drops the GPU's writes to the memory, and the system maps no + /// read-only view of the pages (`read_only_view.rs`): the copy drops them. + ReadOnly, } diff --git a/crates/metal2vulkan-runtime/src/wrapped_buffer.rs b/crates/metal2vulkan-runtime/src/wrapped_buffer.rs index 13e3e7de7..d938da403 100644 --- a/crates/metal2vulkan-runtime/src/wrapped_buffer.rs +++ b/crates/metal2vulkan-runtime/src/wrapped_buffer.rs @@ -297,6 +297,7 @@ impl Device { owner: Owner::Vulkan, release: None, of_heap: false, + drops_writes: false, mirror: None, #[cfg(unix)] again: None, diff --git a/crates/metal2vulkan-validation/src/runtime_lane/copied_surfaces.rs b/crates/metal2vulkan-validation/src/runtime_lane/copied_surfaces.rs index ca389a68b..38965406a 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/copied_surfaces.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/copied_surfaces.rs @@ -436,18 +436,17 @@ fn a_shared_and_a_managed_buffer_over_one_refused_surface_share_its_copy() { }); } -/// Whether the GPU's writes to no-copy memory made with Metal's private option bit 24 are dropped -/// here (`degrade_notices`'s `DROPS_WRITES`): on macOS, where the runtime imports its pages through a -/// read-only view of them. -const DROPS_WRITES: bool = cfg!(target_os = "macos"); +/// Whether the runtime imports the pages of no-copy memory made with Metal's private option bit 24 +/// through a read-only view of them here (`degrade_notices`'s `VIEWS_DROP_WRITES`): on macOS. Else +/// such memory is a copy of its own whose GPU writes are dropped. +const VIEWS_DROP_WRITES: bool = cfg!(target_os = "macos"); /// A buffer made with Metal's private option bit 24 over a refused surface's pages stays apart from -/// the surface's copy, where the device drops such a buffer's writes (macOS): Metal drops the GPU's -/// writes to that memory, and the runtime imports a read-only view of the pages for it, never a -/// copy (the gate is not asked), where a copy shared with the surface's buffer would take its -/// writes and merge them back. No copy is made or shared for it, and its fill is dropped, while it -/// reads the surface buffer's write once that completed. Where the device does not drop them, it -/// is a plain buffer, which lies in the surface's copy. +/// the surface's copy: Metal drops the GPU's writes to that memory, and a copy shared with the +/// surface's buffer would take its writes and merge them back. On macOS the runtime imports a +/// read-only view of the pages for it, making no copy; elsewhere it makes a copy of its own that +/// drops its writes, sharing none. The gate is not asked either way. Its fill is dropped, while it +/// reads the surface buffer's write once that completed. #[test] fn a_buffer_whose_writes_are_dropped_stays_apart_from_a_copy() { on_device(|device| { @@ -462,9 +461,9 @@ fn a_buffer_whose_writes_are_dropped_stays_apart_from_a_copy() { // SAFETY: as above. let dropping = unsafe { refused(device, memory.pointer(), bit) }; let counts = copy_counts(&before, &device.work_counts()); - let expected = match DROPS_WRITES { + let expected = match VIEWS_DROP_WRITES { true => [0, 0, 0, 0], - false => [0, 0, 1, 0], + false => [1, 0, 0, 0], }; assert_eq!( counts, expected, @@ -480,8 +479,7 @@ fn a_buffer_whose_writes_are_dropped_stays_apart_from_a_copy() { blit.end_encoding().unwrap(); command_buffer.commit().unwrap(); finish(&command_buffer); - let kept = if DROPS_WRITES { 0x11 } else { 0x5a }; - assert_eq!(memory.read(0..LEN as usize), vec![kept; LEN as usize]); + assert_eq!(memory.read(0..LEN as usize), vec![0x11; LEN as usize]); // The surface buffer's write, once completed, is what it reads. let command_buffer = queue.command_buffer().unwrap(); let mut blit = command_buffer.blit_command_encoder().unwrap(); diff --git a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs index bf6399957..26787eadb 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs @@ -44,7 +44,7 @@ //! texture views of another component layout shadowed in `view_reinterpretation` //! ([`VIEW_SHADOWS`]), executions of an indirect command buffer from one command //! with two lengths in `visibility` ([`REPEATED_STARTS`]), passes writing a `Boolean` visibility -//! result there ([`BOOLEANS`]), resources made with Metal's private +//! result there ([`BOOLEANS`]), heaps of the runtime's memory made with Metal's private //! option bit here ([`PRIVATE_OPTION`]), indexed indirect draws of bytes a draw wrote with no //! barrier in `indirect_draws` ([`UNORDERED_DRAWS`]), pipeline states whose functions read an //! argument their function constants removed in `absent_reads` ([`ABSENT_READS`]), a slot's @@ -453,7 +453,8 @@ pub(super) fn on_device_with( /// reconvergence; no kind is in two lists, and no list names a kind twice. `misplaced-notice` /// ([`MISPLACED`]), `copied-host-pages` ([`COPIED_PAGES`]) and `device-memory-overflow` /// ([`OVERFLOWED`]) are taken by the runtime's own tests instead, as no lane can meet the first, -/// only a refusing gate meets the second, and only a full device-local heap the third. +/// only a refusing gate or, off macOS, Metal's private option bit 24 meets the second, and only a +/// full device-local heap the third. /// /// This module compiles only under the device cfgs, so a kind that lands with no site leaves this /// test red where the ordinary gate cannot read it. The runtime crate's @@ -796,10 +797,11 @@ const STILL_MAKING: [Degradation; 3] = [ /// The kind a no-copy buffer takes whose import of the caller's pages the caller's gate /// (`HostMemory::with_import_gate`) refused, or whose import the gate and the device admitted and -/// that then failed, so the pages are copied. Only `copied_surfaces` meets it, behind its refusing -/// gate, where its notices are not its subject; no venue's driver fails an admitted import on -/// demand (NVIDIA's runs out of the host kernel's mappings only past `vm.max_map_count`). The -/// runtime's own tests +/// that then failed, so the pages are copied; off macOS, also no-copy memory of Metal's private +/// option bit 24 ([`read_only_kinds`]), which is a copy that drops the GPU's writes. Beside those, +/// only `copied_surfaces` meets it, behind its refusing gate, where its notices are not its +/// subject; no venue's driver fails an admitted import on demand (NVIDIA's runs out of the host +/// kernel's mappings only past `vm.max_map_count`). The runtime's own tests /// `copied_buffer_is_made_where_the_caller_s_gate_refuses_the_import` and /// `copied_buffer_is_made_where_an_admitted_import_fails_announced` take its site, the import /// failed by the runtime's test hook. @@ -814,8 +816,7 @@ const COPIED_PAGES: [Degradation; 1] = [Degradation::CopiedHostPages]; const OVERFLOWED: [Degradation; 1] = [Degradation::DeviceMemoryOverflow]; /// The kind Metal's private option bit takes where the GPU's writes reach the memory here -/// ([`the_private_option_bit_is_announced_on_a_heap_of_the_runtime_s_memory`], -/// [`the_private_option_bit_drops_the_gpu_s_writes_to_no_copy_memory`]). +/// ([`the_private_option_bit_is_announced_on_a_heap_of_the_runtime_s_memory`]). const PRIVATE_OPTION: [Degradation; 1] = [Degradation::PrivateResourceOption]; /// `options` with Metal's private option bit 24 (0x1000000). @@ -896,10 +897,25 @@ fn the_private_option_bit_is_announced_on_a_heap_of_the_runtime_s_memory() { }); } -/// Whether the GPU's writes to no-copy memory made with Metal's private option bit 24 are -/// dropped here, as Metal drops them: on macOS, where the runtime imports its pages through a -/// read-only view of them (the runtime's `read_only_view.rs`). -const DROPS_WRITES: bool = cfg!(target_os = "macos"); +/// Whether the runtime imports the pages of no-copy memory made with Metal's private option bit +/// 24 through a read-only view of them here (the runtime's `read_only_view.rs`): on macOS. Else it +/// makes the memory over a copy of the pages whose GPU writes it drops (`copied.rs`). +const VIEWS_DROP_WRITES: bool = cfg!(target_os = "macos"); + +/// The kinds no-copy memory made with Metal's private option bit 24 announces here: none where a +/// read-only view of its pages drops the GPU's writes, else the copy's (`copied-host-pages`). +fn read_only_kinds() -> &'static [Degradation] { + match VIEWS_DROP_WRITES { + true => &[], + false => &COPIED_PAGES, + } +} + +/// The no-copy objects made over a copy of memory of Metal's private option bit 24 since `before` +/// (`WorkCounts::copied_read_only_memory`). +fn read_only_copies(device: &Device, before: &metal2vulkan_runtime::WorkCounts) -> u64 { + device.work_counts().copied_read_only_memory - before.copied_read_only_memory +} /// Of `buffer`, a no-copy buffer over host pages whose bytes are its `contents`: the CPU writes /// 0x11 to its first 16 bytes, a command buffer fills them with 0x5a, and later command buffers @@ -951,12 +967,14 @@ fn drops_the_fill(device: &Device, buffer: &Buffer) -> bool { /// A no-copy buffer, a buffer placed in a no-copy heap and that buffer rebound to other pages, /// made with Metal's private option bit 24, which Metal makes and keeps the GPU's writes from the /// memory of (the M3 Max under macOS 27.0.1: a blit's fill reaches neither the CPU nor a later -/// command buffer, which reads the CPU's bytes): on macOS each drops a fill so, and nothing is -/// announced; elsewhere the fill reaches the pages, announced once. Each reports its options -/// without the bit, as Metal's does. +/// command buffer, which reads the CPU's bytes): each drops a fill so. On macOS their pages are +/// imported through a read-only view of them and nothing is announced; elsewhere each is made over +/// a copy of the pages that drops the GPU's writes, counted and announced once. Each reports its +/// options without the bit, as Metal's does. #[test] fn the_private_option_bit_drops_the_gpu_s_writes_to_no_copy_memory() { on_device(|device, messages| { + let before = device.work_counts(); let bit = ResourceOptions::PRIVATE_BIT; let shared = with_private_bit(ResourceOptions::shared()); let plain = device @@ -982,13 +1000,19 @@ fn the_private_option_bit_drops_the_gpu_s_writes_to_no_copy_memory() { no_copy => no_copy.unwrap(), }; assert_eq!(no_copy.resource_options(), plain); - assert_eq!(drops_the_fill(device, &no_copy), DROPS_WRITES); + assert!( + drops_the_fill(device, &no_copy), + "the no-copy buffer took the fill" + ); // Rebound to other pages, it drops the GPU's writes to them too. // SAFETY: the other mapping outlives the buffer, and no other thread encodes or commits. unsafe { no_copy.rebind_bytes_no_copy(HostMemory::new(other.pointer()), None, None) } .unwrap(); assert_eq!(no_copy.contents(), Some(other.pointer())); - assert_eq!(drops_the_fill(device, &no_copy), DROPS_WRITES); + assert!( + drops_the_fill(device, &no_copy), + "the rebound buffer took the fill" + ); let heap_memory = Mapping::anonymous(HEAP); let descriptor = HeapDescriptor::new(HeapType::Automatic, HEAP as u64, shared); // SAFETY: the mapping outlives the heap, which is dropped first. @@ -1003,14 +1027,17 @@ fn the_private_option_bit_drops_the_gpu_s_writes_to_no_copy_memory() { .unwrap(); assert_eq!(heap.resource_options().raw() & bit, 0); let placed = heap.new_buffer(256, ResourceOptions::shared()).unwrap(); - assert_eq!(drops_the_fill(device, &placed), DROPS_WRITES); + assert!( + drops_the_fill(device, &placed), + "the heap's buffer took the fill" + ); drop((placed, heap, no_copy)); + // The buffer, its rebind and the heap: each a copy where no view drops the writes. + let copies = read_only_copies(device, &before); + eprintln!("PRIVATEBIT: views drop writes {VIEWS_DROP_WRITES}; copies made {copies}"); + assert_eq!(copies, if VIEWS_DROP_WRITES { 0 } else { 3 }); // Beside them, what the `Shared` resources force on the device. - let kinds: &[Degradation] = match DROPS_WRITES { - true => &[], - false => &PRIVATE_OPTION, - }; - assert_made_once(messages, kinds, &shared_kinds(device)); + assert_made_once(messages, read_only_kinds(), &shared_kinds(device)); }); } @@ -1116,12 +1143,14 @@ fn kernel_store_reads(device: &Device, memory: &Buffer) -> KernelStoreReads { /// conformance suite's `host-page-writes-kernel-store-read-only`), a later command of the same /// command buffer reads the stored words back from the GPU's caches, every run, while a later /// command buffer and the CPU read the pages' own bytes. On macOS the runtime imports the pages -/// through a read-only view of them, which answers as Metal does at all three sites and announces -/// nothing; elsewhere the stores reach the pages and are read at all three, announced once. Every byte of -/// the window the stores do not name keeps the pages' own byte at every site. +/// through a read-only view of them, and elsewhere makes the buffer over a copy of them that drops +/// the GPU's writes at the batch's completion (counted and announced once): either answers as +/// Metal does at all three sites. Every byte of the window the stores do not name keeps the pages' +/// own byte at every site. #[test] fn a_kernel_s_stores_into_private_bit_memory_reach_only_its_own_command_buffer() { on_device(|device, messages| { + let before = device.work_counts(); let memory = Mapping::anonymous(GUEST_PAGE); // SAFETY: the mapping's `GUEST_PAGE` bytes are this process's and nothing else uses them. unsafe { std::ptr::write_bytes(memory.pointer().as_ptr(), PAD, GUEST_PAGE) }; @@ -1150,46 +1179,32 @@ fn a_kernel_s_stores_into_private_bit_memory_reach_only_its_own_command_buffer() stored[at..at + 4].copy_from_slice(&word.to_le_bytes()); } let kept = vec![PAD; WINDOW]; - let past = match DROPS_WRITES { - true => &kept, - false => &stored, - }; + let copies = read_only_copies(device, &before); eprintln!( - "PRIVATEBIT-KERNEL: drops writes {DROPS_WRITES}; same command buffer stored {}, later \ - command buffer stored {}, CPU stored {}", + "PRIVATEBIT-KERNEL: views drop writes {VIEWS_DROP_WRITES}; copies made {copies}; same \ + command buffer stored {}, later command buffer stored {}, CPU stored {}", reads.same == stored, reads.later == stored, reads.cpu == stored ); + assert_eq!(copies, u64::from(!VIEWS_DROP_WRITES)); assert!( reads.same == stored, "a later command of the dispatch's command buffer reads the stored words, as Metal's \ does" ); assert!( - reads.later == *past, - "a later command buffer reads {}", - match DROPS_WRITES { - true => "the pages' own bytes: the stores were dropped", - false => "the stores, which reached the pages", - } + reads.later == kept, + "a later command buffer reads the pages' own bytes: the stores were dropped" ); assert!( - reads.cpu == *past, - "the CPU reads {}", - match DROPS_WRITES { - true => "the pages' own bytes: the stores were dropped", - false => "the stores, which reached the pages", - } + reads.cpu == kept, + "the CPU reads the pages' own bytes: the stores were dropped" ); drop(no_copy); let mut first = shared_kinds(device); first.extend(reads.made); - let kinds: &[Degradation] = match DROPS_WRITES { - true => &[], - false => &PRIVATE_OPTION, - }; - assert_made_once(messages, kinds, &first); + assert_made_once(messages, read_only_kinds(), &first); }); } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/host_memory.rs b/crates/metal2vulkan-validation/src/runtime_lane/host_memory.rs index b3d6d1871..f9b3d46d2 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/host_memory.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/host_memory.rs @@ -1992,7 +1992,7 @@ fn memory_metal_makes_no_buffer_over_is_refused_when_it_is_made() { /// Metal answers nil for (`Nil`: length 0, and its descriptor form, and a length past /// `max_buffer_length`). (The private option bit the consumer's detached buffers /// send, 0x1000000, is taken: `degrade_notices`' -/// `the_private_option_bit_is_announced_where_the_gpu_s_writes_reach_the_memory`.) +/// `the_private_option_bit_drops_the_gpu_s_writes_to_no_copy_memory`.) #[test] fn refused_no_copy_buffers_never_run_their_deallocator() { on_device(|device| { diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index f4561dc1e..851463f4f 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2580,6 +2580,7 @@ field metal2vulkan-runtime::WorkCounts.copied_host_buffers_shared pub copied_hos field metal2vulkan-runtime::WorkCounts.copied_merge_back_bytes pub copied_merge_back_bytes: u64 field metal2vulkan-runtime::WorkCounts.copied_merges_compared pub copied_merges_compared: u64 field metal2vulkan-runtime::WorkCounts.copied_merges_skipped pub copied_merges_skipped: u64 +field metal2vulkan-runtime::WorkCounts.copied_read_only_memory pub copied_read_only_memory: u64 field metal2vulkan-runtime::WorkCounts.copied_rebind_images_made pub copied_rebind_images_made: u64 field metal2vulkan-runtime::WorkCounts.copied_rebind_pages_made pub copied_rebind_pages_made: u64 field metal2vulkan-runtime::WorkCounts.copied_rebind_pages_moved pub copied_rebind_pages_moved: u64 diff --git a/docs/API.md b/docs/API.md index c6f47780d..bcfc91fd4 100644 --- a/docs/API.md +++ b/docs/API.md @@ -2133,11 +2133,11 @@ bound. Metal placed one. - `metal2vulkan-degrade-private-resource-option` (precision). `PrivateResourceOption`: A heap of the runtime's memory or an indirect command buffer made with `MTLResourceOptions` bit 24 - (`ResourceOptions::PRIVATE_BIT`), or off macOS a no-copy buffer or heap over the caller's bytes, - which Metal makes and keeps the GPU's writes from the memory of, is made as without it, and - reports its options without it, as Metal's does. On macOS a no-copy buffer or heap with the bit - drops the GPU's writes as Metal's does, its pages imported through a read-only view of them, - announcing nothing. A buffer of the runtime's memory or a texture descriptor with the bit is + (`ResourceOptions::PRIVATE_BIT`), which Metal makes and keeps the GPU's writes from the memory + of, is made as without it, and reports its options without it, as Metal's does. A no-copy + buffer or heap with the bit drops the GPU's writes as Metal's does: on macOS its pages are + imported through a read-only view of them, announcing nothing; elsewhere it is made over a copy + of them that drops the GPU's writes (`copied-host-pages`). A buffer of the runtime's memory or a texture descriptor with the bit is refused, as Metal ends the process there; a buffer placed in a heap without the bit is made as without it, announcing nothing. Cost: the GPU's writes reach the resource's memory, the CPU and later command buffers, where Metal's never reach them. @@ -2812,7 +2812,12 @@ bound. with plain loads where the process maps every page readable. Pages not mapped, or mapped without read permission, are never copied: the buffer is refused, as their import is. A copy whose own allocation fails refuses the call (`OutOfMemory`). Memory whose GPU writes Metal's - private option bit 24 drops is never copied. A buffer's or heap's rebind is copied the same way, + private option bit 24 drops is copied off macOS alone, where no import keeps the GPU's writes + out of the pages, the gate not asked (`copied_read_only_memory`): the copy drops the GPU's writes + as a copy of read-only pages does, though a command buffer committed before the writer's batch + completed may still read them, and a render pass's store-out into it completes where Metal's + faults its command buffer. On macOS the pages are imported through a read-only view of them. A + buffer's or heap's rebind is copied the same way, its heap's bound textures and its images in place made again over the copy, and a buffer's rebind to bytes at another offset in their page under a texture planned at the old one is a copy laid out there (the detail says which). A buffer made over exactly the bytes (the same first @@ -2823,8 +2828,8 @@ bound. accesses; a rebind to them does too where its textures were planned at the copy's offset and no image in place rides on it. A heap's own buffer and memory whose GPU writes are dropped keep their own. Counted: `WorkCounts::copied_host_buffers_made`, of them - `copied_host_buffers_refused`, `copied_host_buffers_degraded` and `copied_rebind_pages_moved` - (and `copied_heaps_made`, `copied_rebind_pages_made`, `copied_rebind_images_made`); each such + `copied_host_buffers_refused`, `copied_host_buffers_degraded`, `copied_rebind_pages_moved` and + `copied_read_only_memory` (and `copied_heaps_made`, `copied_rebind_pages_made`, `copied_rebind_images_made`); each such buffer, and each buffer placed in such a heap, answers `Buffer::host_backing` with `HostBacking::Copied` until its next rebind or detach. Cost: the GPU uses a copy of diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index b0dc10315..4077fa270 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -411,24 +411,25 @@ driver's. Each is open work. families of one queue, a single-graphics-queue device -- still shares, and the sharing is counted (`WorkCounts::queues_sharing_a_vk_queue`). Not announced. -- **GPU writes into read-only memory reach it off macOS.** Metal drops what a shader or the blit - engine writes into memory whose backing is read-only (no-copy memory of its private option bit 24, - or pages replaced read-only): a kernel's or a draw stage's stores, through a bound slot or an - address loaded out of an argument buffer, a blit fill and a visibility result complete, and - neither a later command buffer nor the CPU sees them, though a later command of the same command - buffer may read them back from the GPU's caches; what its atomics do there is unmeasured. A render - pass's store-out over such memory (`storeAction = Store`, or a multisample primary stored there) - ends its command buffer in error (`MTLCommandBufferErrorDomain` / - `kIOGPUCommandBufferCallbackErrorPageFault`), while attachments at `storeAction = DontCare` or - `loadAction = Load` complete; resolving *into* such memory is unknown (no page fault in 520 - processes, almost all of them recovery victims). On macOS the runtime imports such pages through a - read-only view of them (`read_only_view.rs`), which takes the GPU's writes nowhere as Metal's - memory does. Elsewhere the import is of the caller's own pages and the GPU's writes reach them - (a copy of pages the process maps read-only, where the caller's gate refused their import or it - failed, drops them as Metal does, `copied.rs`): honouring bit 24 there means a read-only import (`Device::no_copy_options`, `host_lie`'s - `drops_writes`) and measuring what the drivers then do, since ANV lost the device and RADV failed - every submission over read-only imported pages. Announced meanwhile as `private-resource-option` - and `read-only-pages-written`. +- **Off macOS, GPU writes into read-only memory are dropped only at the writer's completion.** + Metal drops what a shader or the blit engine writes into memory whose backing is read-only + (no-copy memory of its private option bit 24, or pages replaced read-only): a kernel's or a draw + stage's stores, through a bound slot or an address loaded out of an argument buffer, a blit fill + and a visibility result complete, and neither a later command buffer nor the CPU sees them, + though a later command of the same command buffer may read them back from the GPU's caches; what + its atomics do there is unmeasured. A render pass's store-out over such memory (`storeAction = + Store`, or a multisample primary stored there) ends its command buffer in error + (`MTLCommandBufferErrorDomain` / `kIOGPUCommandBufferCallbackErrorPageFault`), while attachments + at `storeAction = DontCare` or `loadAction = Load` complete; resolving *into* such memory is + unknown (no page fault in 520 processes, almost all of them recovery victims). On macOS the + runtime imports such pages through a read-only view of them (`read_only_view.rs`), which takes the + GPU's writes nowhere as Metal's memory does. Elsewhere no import keeps them out (ANV lost the + device and RADV failed every submission over read-only imported pages), so the memory is a copy + of the pages whose GPU writes each batch's completion takes back out (`copied.rs`, announced as + `copied-host-pages`): the CPU and a command buffer committed after that completion read the + pages' bytes, as Metal's do, but one committed before it, while the writer is in flight, reads + the writes, and a render pass's store-out into the copy completes where Metal's faults its + command buffer. - **A function linked from a module that declares function constants** is refused (`Unsupported{Linking; NotImplemented}` at a surviving call to the stub, `canon::link`), keyed on diff --git a/docs/HOWTO.md b/docs/HOWTO.md index 25adf9866..effef9e98 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -369,7 +369,11 @@ happens where: - on NVIDIA's driver, the pages are a mapping the kernel cannot pin (a dma-buf's), which the runtime never hands that driver (`RuntimeDriverDefect::UnpinnablePagesBreakHostMemory`, `WorkCounts::host_imports_unpinnable`), and no dma-buf of the caller's source served them - (`copied_host_buffers_degraded`). + (`copied_host_buffers_degraded`); +- off macOS, the memory is of Metal's private option bit 24 (`ResourceOptions::PRIVATE_BIT`), + whose GPU writes Metal drops: no import there keeps the GPU's writes out of the pages, so the + copy is made without asking the gate and drops them (below; `copied_read_only_memory`). On macOS + such pages are imported through a read-only view of them instead. A buffer made over exactly the bytes (the same first byte and length) a live copied buffer was made over lies in that copy, of either storage mode, as a buffer over a live import's bytes lies in @@ -419,8 +423,11 @@ maximum protection lowered to read) are copied the same way, and the copy drops as Metal drops them: each batch's completion takes the bytes the GPU changed back out of the copy and writes nothing to the pages (`copied_dropped_bytes`), so later commands of the same command buffer read the writes back and a later command buffer reads the pages' bytes. The runtime asks -the system whether the process can write the pages as it makes the copy. The announcement's detail -says so. +the system whether the process can write the pages as it makes the copy. The copy of memory of +Metal's private option bit 24 drops the GPU's writes the same way, whatever the pages' protection. +A command buffer committed before the writer's batch completed may still read the writes, where +Metal's never does, and a render pass's store-out into such a copy completes, where Metal's faults +its command buffer. The announcement's detail says so. A no-copy heap's own buffer is copied the same way (`copied_heaps_made`): its buffers lie in the copy, and its textures are shadows of its bytes. `Buffer::rebind_bytes_no_copy` and