From d0a424060a887171fd0a67a9a01f0ca21bca787c Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Wed, 2 Dec 2026 03:01:42 -0800 Subject: [PATCH] Runtime: each submission that uses memory another API shares hands it over; the release calls are gone A consumer's video path showed green frames. Its paths call external_writes_done before each picture and a release only in their encode fills, so every acquire of an exported block or surface after the first had no release of the runtime's to match (VUID-vkQueueSubmit2-commandBuffer-03879), and whether memory another API wrote was acquired, or discarded, depended on the order the consumer's calls arrived in. f6fe21431c's test shows it: no submission released the surface. Now one form serves every kind of memory another API shares, the form Direct3D 11 planes already took (crate::handed): each vkQueueSubmit2 part whose command buffers or uploads use an exported block, an exported surface's planes in place or its buffer, or a Direct3D 11 plane acquires all of it from the other API's queue family in one barrier, in a runtime command buffer at the part's head after a global barrier, and releases it in one barrier in another at the part's end, which takes the part's last signals. Per such part: 3 barriers and 2 runtime command buffers; no submission, VkSubmitInfo2 or semaphore wait is added. The uploads' copies into textures over a buffer in an exported block go with the first part, which hands that block over too. Exported memory is the runtime's until its making (Work::create): an exported block's buffer is released, and an exported surface's planes in place move out of the undefined layout and are released in the same barrier, in a runtime command buffer at the head of the submission that takes the make's upload, ahead of any acquire. The upload owes the making by weak reference, so a surface or block dropped first owes nothing and holds nothing. The making's submission is the ready point: Surface::wait_until_ready waits for it in both forms (the copy form's is its block's), and the new Block::wait_until_ready is its twin (Metal counterpart none; refuses a block that is not exported; has the submission go at once, so it returns with no command buffer committed). One barrier at the making, nothing per frame beyond the per-part hand-over. external_writes_done keeps only its host-side mark: on a block (and a copy-form surface) the textures over it take its bytes again; in place and on a Direct3D 11 import it records nothing. Surface::buffer records nothing at its make. A block that is not exported is still refused. Deleted, with no replacement: BlitCommandEncoder::release_to_external and BlitCommandEncoder::release_surface_to_external, and Building::release_command, which only they used. Consumer uses (the consumer's checkout, searched for main): release_to_external at vaapi/fill.rs:599 and nvidia/encode/fill.rs:289, each followed by EndEncoding, commit and the consumer's CPU wait; its wrapper trait method BlitEncoder::release_to_external (core/platform/blit.rs:395, a cfg(unix) no-op default) and the RtPlatform impl (rt_platform/blit.rs:992-999); doc mentions at rt_platform/export.rs:33, vaapi/fill.rs:30 and nvidia/encode/fill.rs:18. release_surface_to_external: zero uses. The consumer drops them all in the pin that takes this commit. The guard the planner asked for: a plane's image in place takes its tiling from InPlaceTiling alone, whose values are LINEAR and the DRM_FORMAT_MOD_LINEAR modifier, never OPTIMAL; the device-free test no_plane_in_place_takes_the_optimal_tiling pins it. The order test every_device_completes_a_surface_s_making_before_its_ready_wait_returns checks that each plane owes its move at the make and none once the wait returns, with the device's completed progress at or past the ready point. The export, surface and Direct3D 11 tests now count one acquire and one release per submission and one release at the making, with no release call. The runtime README states the contract (The hand-over contract): nothing another API writes may be handed memory of ours before that memory's ready point; the other API's next write must not begin before the submissions that used the memory have completed; who waits by kind and what a reader gets where no write landed; no optimal image in memory another API writes in place (section 12.11), the Direct3D 11 import being the documented case (section 12.10.1, Table 17). Its known gaps carry the planner's line on host-pointer memory. docs/REFUSALS.md is regenerated and the signature table blessed (one added, two removed). Checked before this commit: clippy of the runtime, all targets, plain and under --cfg m2v_cpu_icd, on this commit's code less its doc changes (job m3-max-77874). The device runs at this commit (lavapipe, the Radeon 780M, the UHD 630) follow and are reported with the lane's tip. The dma-buf import half is not built. --- crates/metal2vulkan-runtime/README.md | 184 ++++++---- crates/metal2vulkan-runtime/src/blit.rs | 167 +-------- crates/metal2vulkan-runtime/src/block.rs | 19 +- crates/metal2vulkan-runtime/src/command.rs | 71 ++-- crates/metal2vulkan-runtime/src/counters.rs | 58 +-- crates/metal2vulkan-runtime/src/d3d11.rs | 6 +- crates/metal2vulkan-runtime/src/error.rs | 9 +- crates/metal2vulkan-runtime/src/export.rs | 117 +++--- crates/metal2vulkan-runtime/src/handed.rs | 159 +++++++++ crates/metal2vulkan-runtime/src/import.rs | 5 +- crates/metal2vulkan-runtime/src/lib.rs | 1 + crates/metal2vulkan-runtime/src/memory.rs | 21 +- crates/metal2vulkan-runtime/src/submit.rs | 256 ++++++++++---- crates/metal2vulkan-runtime/src/surface.rs | 307 +++++++--------- .../metal2vulkan-runtime/src/tests/d3d11.rs | 8 +- .../metal2vulkan-runtime/src/tests/export.rs | 96 +++-- .../metal2vulkan-runtime/src/tests/surface.rs | 334 ++++++++++++------ crates/metal2vulkan-runtime/src/texture.rs | 117 ++++-- .../src/replay/new_runtime/videos.rs | 7 +- crates/metal2vulkan/tests/api_signatures.tsv | 3 +- docs/REFUSALS.md | 12 +- 21 files changed, 1129 insertions(+), 828 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/handed.rs diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index ac4867914..6e4313c42 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -822,40 +822,39 @@ address of the block's memory goes out only as `Buffer::gpu_address` of a buffer counts in `Metrics::exported_blocks_addressed` (Textures over a buffer, the exported block's rule). -Once the other API's work that accessed the block has completed (work that wrote it, or that read it -after a release; the consumer's own wait on the decoder), the consumer calls -`Block::external_writes_done()` before it commits the command buffers that use the block. The call -records the block's acquire from the other API's queue family (`VK_QUEUE_FAMILY_EXTERNAL` for an -opaque handle, `VK_QUEUE_FAMILY_FOREIGN_EXT` for a dma-buf) in the upload, ahead of every command -buffer committed after it, without waiting for the GPU: one buffer barrier, counted in -`Metrics::external_acquires`. A block that is not exported is `Refusal::NotExported`. The contract -has three parts: between `external_writes_done` and the other API's next write, the other API does -not access the block, unless a release (`release_to_external`, below) comes between, from whose -completion it may read the whole block, the runtime's writes and its own earlier ones; when it -writes again, it reads nothing of the block but what it has itself written since and what a release -since handed it; and after each acquire, a byte the other API has not written since the previous -acquire is undefined to the runtime, unless a release came between the two: a release and the -acquire after it transfer ownership, which keeps the bytes the other API did not write (section -7.7.6). The acquire is not followed by a release of its own: without one, Vulkan leaves the block's -contents undefined to the other API's reads (section 7.7.6). +**The making and the ready point.** The block is the runtime's until its making: the release of +its buffer from the runtime's queue family to the other API's (`VK_QUEUE_FAMILY_EXTERNAL` for an +opaque handle, `VK_QUEUE_FAMILY_FOREIGN_EXT` for a dma-buf), one buffer barrier counted in +`Metrics::external_releases`, in a command buffer of the runtime's own at the head of the +runtime's submission that carries the next commit, ahead of every command buffer committed after +the make. The make submits nothing and waits for nothing. Before the other API's first access, +the consumer calls `Block::wait_until_ready()` on its own thread: it returns once that submission +has completed, and has it go at once where it is not yet made, so it returns with no command +buffer committed. It counts in `Metrics::surface_waits` as a surface's wait does (Exported +surfaces). A block that is not exported is `Refusal::NotExported`. -Where the other API is to read the block after the runtime's commands (a video encoder reading the -frames a blit wrote, or a decoder reading again, as a reference, a picture the runtime read), the -consumer calls `BlitCommandEncoder::release_to_external(&buffer)`, with a buffer in the block, after -the encoder's last command that uses it. The call records the whole block's release from the -runtime's queue family to the other API's (the acquire's family) into that command buffer, after -every command before it: one buffer barrier, counted in `Metrics::external_releases`, with no -submission of its own and no wait. The barrier that orders the release before later commands is -owed, and the command buffer's end barrier pays it where nothing follows. A buffer whose block is -not exported is `Refusal::NotExported`. The contract of this direction: the other API reads the -block from that command buffer's completion, which the consumer waits for; from the call until the -consumer's next write into the block through the runtime or the next `external_writes_done`, the -runtime does not read the block and the consumer encodes no read of it. That next write, once the -other API's reads have completed, needs no acquire: after a release, Vulkan lets the releasing queue -use the resource again without one, its contents written anew (section 7.7.6). Where the other API -writes the block in between, `external_writes_done` comes first, as above; where it only reads the -block and the runtime is to read it again, `external_writes_done` comes first too, once those reads -have completed: the acquire after the release, which keeps the block's bytes (section 7.7.6). +**Each submission hands it over.** From its making the other API owns the block between the +runtime's submissions. Each `vkQueueSubmit2` whose command buffers or uploads use the block +acquires it from the other API's queue family in a command buffer of the runtime's own ahead of +everything in the call, after a global barrier from and to every stage, and releases it to that +family in another after everything in the call, which takes the call's last signals, its progress +value among them: one barrier each, counted in `Metrics::external_acquires` and +`Metrics::external_releases`, and the two command buffers in `Metrics::runtime_command_buffers`. +Everything one call uses of memory another API shares goes in those two barriers. No submission, +`VkSubmitInfo2` or semaphore wait is added, and a command buffer that uses the block is seen +complete only once the release has run. A group rt sends member by member, one `vkQueueSubmit2` a +member, hands over in each member's call what that member uses; the uploads' copies go with the +first. So every acquire has a release before it, the making's or a submission's of the runtime's +or the other API's own (`VUID-vkQueueSubmit2-commandBuffer-03879`), whatever order the consumer's +calls arrive in. + +**The consumer's calls.** Once the other API's work that wrote the block has completed (the +consumer's own wait on the decoder), the consumer calls `Block::external_writes_done()` before it +commits the command buffers that read what that work wrote. The call records nothing and waits for +nothing: it marks the other API's writes on the host side alone, so a texture over a buffer in the +block in an image of its own takes the block's bytes again before its next use. A block that is +not exported is `Refusal::NotExported`. There is no release call: each submission that uses the +block releases it at its end. The contract is below (The hand-over contract). ### Exported surfaces @@ -939,9 +938,8 @@ a texture: the textures a consumer makes over a plane are its views. A plane's i formats of the texture's own list that its tiling samples, and none where the device refuses that list; a view of another format it does not list is `Gap::TextureView` of `TextureViewKind::SurfacePixelFormat`. The make submits nothing and waits for nothing: the -images move out of the undefined layout into the general one in the runtime's submission that -carries the next commit, or at once where `Surface::wait_until_ready` asks first, and stay in it -through every copy. +images move out of the undefined layout into the general one at the surface's making (below), and +stay in it through every copy. A plane whose texture's usage holds both `ShaderRead` and `RenderTarget` takes, on a device with the attachment feedback loop, the feedback usage beside the rest where the handle's image format @@ -956,42 +954,46 @@ counted copy a device without the loop takes (Known gaps of render encoders). Th linear image on the surface's own memory, at the pitch and starts the export states. A Direct3D 11 plane asks its import's query the same. -**The ready point.** That move may discard what the memory holds, so the other API writes an -in-place surface's memory only once it has completed: before the other API's first write, the -consumer calls `Surface::wait_until_ready()` on its own thread, which returns once the move's -submission has completed and has that submission go at once where it is not yet made. The -runtime's own commands need no wait: the move goes ahead of every command buffer committed after -the make. In the copy form the call returns at once. Each call in place is counted in -`Metrics::surface_waits`, with its time in `surface_wait_nanos`, the longest in -`surface_wait_max_nanos`, and in `surface_wait_submissions` the runtime's submissions it waited -for: those not yet complete as it began, the one that moves the planes among them unless it -completed first (a submission made after the make, for any command buffer, takes the moves). A -wait far longer than those submissions' GPU times waited behind work the runtime did not submit. +**The making and the ready point.** The surface is the runtime's until its making: in place, each +plane's image moves out of the undefined layout into the general one and is released to the other +API's queue family, in one barrier of the planes counted in `Metrics::external_releases`; in the +copy form the block's buffer is released, as an exported block's is (above). The making goes in a +command buffer of the runtime's own at the head of the runtime's submission that carries the next +commit, ahead of every command buffer committed after the make and of any acquire. That move may +discard what the memory holds, so the other API accesses the surface's memory only once the +making has completed: before the other API's first access, the consumer calls +`Surface::wait_until_ready()` on its own thread, which returns once the making's submission has +completed and has that submission go at once where it is not yet made. The runtime's own commands +need no wait. Each call that waits, in either form, is counted in `Metrics::surface_waits`, with +its time in `surface_wait_nanos`, the longest in `surface_wait_max_nanos`, and in +`surface_wait_submissions` the runtime's submissions it waited for: those not yet complete as it +began, the one that carries the making among them unless it completed first (a submission made +after the make, for any command buffer, takes the making). A wait far longer than those +submissions' GPU times waited behind work the runtime did not submit. `Block::wait_until_ready()` +counts in the same metrics. **The copy form** is taken where any of that fails, and the answer's `SurfaceForm::Copy` names why (`SurfaceCopy`): `NoModifier`, `Tiling`, `Dedicated`, `Pitch`, `Start` or `MemoryType`. The surface is then an exported block (as above) laid by the same rule at the tightest pitch the multiples allow, and each plane's texture is a texture over a buffer in it, an image of its own that the submissions copy the bytes into and back (`Metrics::over_copies`): in, once after each -acquire or other change of the bytes (Textures over a buffer, the exported block's rule). A start or pitch the +`external_writes_done` or other change of the bytes (Textures over a buffer, the exported block's +rule). A start or pitch the driver cannot take falls to the copy form with no error: the answer's `form` is the only sign. `Metrics::surfaces_in_place` and `Metrics::surfaces_copied` count each form made. -One contract for both forms, the exported block's above, after the ready point. Once the other API's -work that accessed the surface has completed (work that wrote it, or that read it after a release), -the consumer calls `Surface::external_writes_done()` before it commits the command buffers that use -the surface: in place, each plane's image's acquire from the other API's queue family, the general -layout kept, one barrier in the upload; in the copy form the block's acquire. Where the other API is -to read the surface after the runtime's commands (what they wrote, or a reference picture they -read), the consumer calls `BlitCommandEncoder::release_surface_to_external(&surface)` after the last -command that uses the planes: in place, each plane's image's release, one barrier; in the copy form -the block's release, the planes' images copied back first. Both count in -`Metrics::external_acquires` and `Metrics::external_releases`. From a release until the consumer's -next write into the surface through the runtime or the next `external_writes_done`, the consumer -encodes no read of its planes. The surface's memory is freed once the surface, its planes' -handles and every command buffer that used it are gone. An acquire that no command buffer's -submission has carried yet goes as the last of them lets go of a plane or of the exported block, -in a submission of its own, with no wait, so the memory waits for no later call. +One contract for both forms, the exported block's, after the ready point (The hand-over +contract). Each `vkQueueSubmit2` whose command buffers or uploads use the surface acquires it from +the other API's queue family at its head and releases it at its end, as an exported block's +submission does (above): in place, each plane's image, the general layout kept, and the surface's +buffer where `Surface::buffer` has made it, in one barrier each way; in the copy form, the block, +the planes' images copied back into it at each segment's end, before the release. Once the other +API's work that wrote the surface has completed, the consumer calls +`Surface::external_writes_done()` before it commits the command buffers that read what it wrote: +in the copy form it is the block's call, and in place it records nothing and changes nothing. +There is no release call. The surface's memory is freed once the surface, its planes' handles and +every command buffer that used it are gone; the making's upload holds none of it, so a surface let +go of before its making's submission is freed with no submission. **The surface's buffer.** `Surface::buffer()` answers a buffer over the surface's own memory, the counterpart of an IOSurface-backed buffer: from the memory's first byte, its bytes at the layout @@ -1006,11 +1008,10 @@ on one more import of the dma-buf, into the memory type the planes' imports took keeps its own fd of the dma-buf for that import. The call imports only where the device's buffers import a dma-buf (`vkGetPhysicalDeviceExternalBufferProperties`) and the fd's query and the buffer's requirements list that type. Either form counts in `Gauges::surface_buffers`, and a -dma-buf's also in `Gauges::surface_imports`. The first call records the buffer's acquire from the -other API's queue family. From then on, `external_writes_done` acquires the buffer with the planes -and `release_surface_to_external` releases it with them, writing back first the copies of the -textures the consumer made over it. In the copy form the buffer is the block's, which the planes -are textures over. +dma-buf's also in `Gauges::surface_imports`. The call records nothing: from then on each +submission that uses the buffer acquires and releases it with the planes, and the copies of the +textures the consumer made over it go back into it at each segment's end, before the release. In +the copy form the buffer is the block's, which the planes are textures over. Vulkan's memory aliasing makes the buffer and the planes in place aliases that read each other's writes: a buffer and linear images in the general layout are host-accessible, and two @@ -1075,9 +1076,8 @@ command buffers rt sends member by member, one `vkQueueSubmit2` a member, each s progress value, hands each member's planes over in that member's call, so a member ahead of the last is seen complete after its own planes' release and not before it; each such call counts in `Metrics::d3d11_plane_parts` too. Direct3D 11 thus owns the planes' memory between rt's -submissions. `Surface::external_writes_done()` and -`BlitCommandEncoder::release_surface_to_external(&surface)` record nothing and change nothing for -such a surface. So the consumer's precondition is that Direct3D 11's work that accesses a plane has +submissions. `Surface::external_writes_done()` records nothing and changes nothing for such a +surface. So the consumer's precondition is that Direct3D 11's work that accesses a plane has completed before the consumer commits the command buffers that use it, and that rt's command buffers that use a plane have completed before Direct3D 11 accesses it again. No keyed mutex is used, by rt or on the textures: each is made with `D3D11_RESOURCE_MISC_SHARED | D3D11_RESOURCE_MISC_SHARED_NTHANDLE`, not @@ -1085,12 +1085,50 @@ buffers that use a plane have completed before Direct3D 11 accesses it again. No device that opens it must acquire before rendering to it; the consumer orders the two APIs' work by its waits. A plane nothing wrote has undefined contents, as a Metal texture nothing wrote does. The surface has no buffer: `Surface::buffer()` is `Gap::D3d11SurfaceBuffer`, as its planes lie in memories of their own, and `Surface::handle()` is -`None`. No upload's move goes ahead of the planes' first use, so `Surface::wait_until_ready()` -returns at once. The planes' imports are freed as an exported surface's memory is (above); rt keeps +`None`. Direct3D 11 made the planes' memory, so the import has no making and +`Surface::wait_until_ready()` returns at once. The planes' imports are freed as an exported surface's memory is (above); rt keeps no handle of its own, and each import holds the Direct3D 11 texture's payload until it is freed. +### The hand-over contract + +Metal has no counterpart: an IOSurface needs no hand-over between APIs. What follows holds for an +exported block, an exported surface in either form, and a Direct3D 11 import. + +- Nothing another API writes may be handed memory of ours before that memory's ready point: the + other API's first access of an exported block or surface comes after `Block::wait_until_ready()` + or `Surface::wait_until_ready()` has returned. A Direct3D 11 import has no ready point, as + Direct3D 11 made its memory. +- The other API's next write must not begin before the submissions that used the memory have + completed: the consumer waits for the runtime's command buffers that used it, and the release at + each submission's end, which those command buffers complete only after, hands the memory back. +- The runtime's commands read what the other API wrote once the work that wrote it has completed + before the consumer commits them, and the consumer has called `external_writes_done` (a host + mark for an exported block and a copy-form surface; nothing in place and on a Direct3D 11 + import). +- Who waits, by kind. An exported block: the consumer waits for the ready point before the other + API's first access, for the other API's work before the runtime's commit, and for the runtime's + command buffers before the other API's next access; where no write landed, either side reads + undefined bytes, as a taken block's are until written. An exported surface in place: the same + waits; the making's move out of the undefined layout leaves the planes' texels undefined until + written, as a Metal texture nothing wrote is. An exported surface in the copy form: the block's + waits; the planes' images take the block's bytes at their next use after + `external_writes_done`, undefined where no write landed. A Direct3D 11 import: no ready point; + the consumer waits for Direct3D 11's work before the runtime's commit and for the runtime's + command buffers before Direct3D 11 accesses the planes again; a plane nothing wrote has + undefined contents. +- No path places an optimal image in memory another API writes in place. A surface's planes in + place take their tiling from one type (`InPlaceTiling`): `VK_IMAGE_TILING_LINEAR`, or the + `DRM_FORMAT_MOD_LINEAR` modifier for a dma-buf, linear images that section 12.11 takes as + host-accessible aliases, which "interpret the contents of the memory in consistent ways", and an + exported block holds no image. The Direct3D 11 import is the documented import case: its planes + are images of the texture Direct3D 11 made, in the layout Table 17 gives the handle type + outside Vulkan, `VK_IMAGE_LAYOUT_GENERAL` (section 12.5.2), which each acquire, the first + included, takes as the image's true initial layout (section 12.10.1). + ### Known gaps of memory blocks +- Vulkan promises host access only; a write by another device into host-pointer memory is taken as a host write once that API reports the copy complete. + - On a device whose Shared type is not host-coherent (Shared memory's coherence), the flushes and invalidates are that device's cost: before each submission over what its command buffers reach, and at each completion and each shared event's GPU-raised value seen over what they may write, on diff --git a/crates/metal2vulkan-runtime/src/blit.rs b/crates/metal2vulkan-runtime/src/blit.rs index 4254b7d12..8dd00dd4e 100644 --- a/crates/metal2vulkan-runtime/src/blit.rs +++ b/crates/metal2vulkan-runtime/src/blit.rs @@ -44,10 +44,8 @@ use crate::error::{Error, Gap, Refusal}; use crate::fence::Fence; use crate::hazard::Access; use crate::indirect::{reset_regions, IndirectCommandBuffer}; -use crate::memory::Own; use crate::over::Reached; use crate::record::{memory_barrier, Reach}; -use crate::surface::Surface; use crate::texture::{ copy_unit, place, BytesPlace, CopyUnit, Placed, Region, Rows, Texture, TextureDescriptor, TextureObject, @@ -117,9 +115,7 @@ enum Way { /// A copy runs after every earlier command of its command buffer, and every later command runs /// after it, with the writes on either side visible across it: a blit needs no hazard tracking of /// its own and leaves none for the encoders after it. Each texture's level and slice leaves its -/// home layout for the copy and comes back in the same call; no element of set 1 is rewritten. A -/// release to another API ([`release_to_external`](Self::release_to_external)) leaves the barrier -/// after it owed. +/// home layout for the copy and comes back in the same call; no element of set 1 is rewritten. /// /// Owned: one thread encodes at a time. Dropping it ends it, as /// [`end_encoding`](Self::end_encoding) does. @@ -1186,167 +1182,6 @@ impl BlitCommandEncoder { Ok(()) } - /// No Metal counterpart: releases `buffer`'s exported block - /// ([`Device::new_exported_block`](crate::Device::new_exported_block)) to the other API, which - /// reads the block once this command buffer has completed: what its commands wrote (a video - /// encoder that reads the frames a blit wrote, for one), or what the other API wrote before - /// and the commands only read (a decoder that reads a reference picture again). The consumer - /// calls it after the encoder's last command that uses the block, and has the other API read - /// the block after its own wait on the command buffer's completion. - /// - /// The call records the whole block's release from the runtime's queue family to the other - /// API's (`VK_QUEUE_FAMILY_EXTERNAL` for an opaque handle, `VK_QUEUE_FAMILY_FOREIGN_EXT` for - /// a dma-buf) into this command buffer, after every command before it, whose writes it makes - /// available: one buffer barrier, counted in - /// [`Metrics::external_releases`](crate::Metrics::external_releases). It is no submission of - /// its own and waits for nothing. A texture over a buffer in the block, in an image of its - /// own, is copied back into it first, as before any command that writes the buffer. The - /// barrier that orders the release before later commands is owed: the command buffer's next - /// command records it, or its end barrier where none follows. - /// - /// The contract: from the call until the consumer's next write into the block through the - /// runtime or the next [`Block::external_writes_done`](crate::Block::external_writes_done), - /// the consumer encodes no read of the block (of a buffer in it, or of a texture over one), - /// and the runtime reads none of it. That next write, once the other API's reads have - /// completed, needs no acquire: Vulkan lets the releasing queue use the block again without - /// one, its contents written anew ("It is valid to never call the acquire operation after a - /// release, and instead simply start using the resource on any queue (even the releasing - /// queue), but the contents should be reinitialized before being read"). Where the other API - /// writes the block in between, `external_writes_done` comes before the runtime's commands - /// use what it wrote; where it only reads the block and the runtime is to read it again, - /// `external_writes_done` comes first too, once those reads have completed: the acquire after - /// the release, which keeps the block's bytes. - /// - /// Err: [`Refusal::OtherDevice`] for another device's buffer; [`Refusal::NotExported`] for - /// a buffer whose block is not exported; [`Error::Vulkan`] where the command buffer cannot - /// record. - pub fn release_to_external(&mut self, buffer: &Buffer) -> Result<(), Error> { - let (core, building) = self.parts(); - if !buffer.is_of(core) { - return Err(Error::Refused(Refusal::OtherDevice)); - } - let (block, _) = buffer.held(); - let Some(Own::Export { handle, .. }) = block.memory.own else { - return Err(Error::Refused(Refusal::NotExported { - block: block.memory.id, - })); - }; - let (whole, _) = block.memory.range(0); - building.keep(buffer); - // The textures over a buffer in the block go back to it first, as before a write of it. - let overs = [(Reached::Buffer(buffer.span()), Access::Write)]; - building.overs_before(overs, false)?; - let command = building.release_command()?; - building.overs_after(overs, false); - let release = [vk::BufferMemoryBarrier2::default() - .src_stage_mask(vk::PipelineStageFlags2::ALL_COMMANDS) - .src_access_mask(vk::AccessFlags2::MEMORY_WRITE) - .src_queue_family_index(core.family) - .dst_queue_family_index(handle.family()) - .buffer(whole) - .offset(0) - .size(vk::WHOLE_SIZE)]; - let dependency = vk::DependencyInfo::default().buffer_memory_barriers(&release); - // SAFETY: the command buffer records outside any render pass and keeps the buffer, so its - // block, until it retires; the barrier spans the block's own allocation, its buffer's, - // and a dma-buf's foreign family is enabled (`Device::new_exported_block`). - unsafe { core.device.cmd_pipeline_barrier2(command, &dependency) }; - building.count(Metric::OtherBarriers); - building.count(Metric::ExternalReleases); - Ok(()) - } - - /// No Metal counterpart: releases `surface` - /// ([`Device::new_exported_surface`](crate::Device::new_exported_surface)) to the other API, - /// which reads its planes once this command buffer has completed: what its commands wrote (a - /// video encoder that reads the pictures a pass rendered, for one), or what the other API - /// wrote before and the commands only read (a decoder that reads a reference picture again). - /// The consumer calls it after the encoder's last command that uses the planes, and has the - /// other API read the surface after its own wait on the command buffer's completion. - /// - /// In place, the call records each plane's image's release from the runtime's queue family to - /// the other API's (`VK_QUEUE_FAMILY_EXTERNAL` for an opaque handle, - /// `VK_QUEUE_FAMILY_FOREIGN_EXT` for a dma-buf), the general layout kept, and the surface's - /// buffer's where [`Surface::buffer`] has made it, its textures over it in images of their own - /// copied back into it first, after every command before it: one barrier of the planes and - /// the buffer, counted in - /// [`Metrics::external_releases`](crate::Metrics::external_releases). In the copy form it is - /// the block's release ([`release_to_external`](Self::release_to_external)), the planes' - /// images copied back into the block first. The contract is the block's: from the call until - /// the consumer's next write into the surface through the runtime or the next - /// [`Surface::external_writes_done`](crate::Surface::external_writes_done), the consumer - /// encodes no read of its planes. For a Direct3D 11 import (`Device::import_d3d11_surface`, - /// on Windows) the call records nothing: each `vkQueueSubmit2` that uses its planes releases - /// them itself, after its last command and before its signals - /// ([`Metrics::d3d11_plane_submissions`](crate::Metrics::d3d11_plane_submissions)). - /// - /// Err: [`Refusal::OtherDevice`] for another device's surface; [`Error::Vulkan`] where the - /// command buffer cannot record. - pub fn release_surface_to_external(&mut self, surface: &Surface) -> Result<(), Error> { - if let Some(buffer) = surface.copied() { - return self.release_to_external(buffer); - } - let (core, building) = self.parts(); - if !surface.is_of(core) { - return Err(Error::Refused(Refusal::OtherDevice)); - } - // Each `vkQueueSubmit2` that uses a Direct3D 11 import's planes releases them itself. - if surface.handle().is_none() { - return Ok(()); - } - for texture in surface.planes() { - building.keep_texture(texture); - } - let buffer = surface.made_buffer(); - let overs = - || (buffer.iter()).map(|buffer| (Reached::Buffer(buffer.span()), Access::Write)); - if let Some(buffer) = &buffer { - building.keep(buffer); - // The textures over the buffer go back to it first, as before a write of it. - building.overs_before(overs(), false)?; - } - let command = building.release_command()?; - if buffer.is_some() { - building.overs_after(overs(), false); - } - let family = surface.family(); - let buffers: Vec> = (buffer.iter()) - .map(|buffer| { - vk::BufferMemoryBarrier2::default() - .src_stage_mask(vk::PipelineStageFlags2::ALL_COMMANDS) - .src_access_mask(vk::AccessFlags2::MEMORY_WRITE) - .src_queue_family_index(core.family) - .dst_queue_family_index(family) - .buffer(buffer.device_range().0) - .offset(0) - .size(vk::WHOLE_SIZE) - }) - .collect(); - let releases: Vec> = (surface.planes().iter()) - .map(|texture| { - vk::ImageMemoryBarrier2::default() - .src_stage_mask(vk::PipelineStageFlags2::ALL_COMMANDS) - .src_access_mask(vk::AccessFlags2::MEMORY_WRITE) - .old_layout(vk::ImageLayout::GENERAL) - .new_layout(vk::ImageLayout::GENERAL) - .src_queue_family_index(core.family) - .dst_queue_family_index(family) - .image(texture.image()) - .subresource_range(texture.whole()) - }) - .collect(); - let dependency = vk::DependencyInfo::default() - .image_memory_barriers(&releases) - .buffer_memory_barriers(&buffers); - // SAFETY: the command buffer records outside any render pass and keeps the planes and the - // buffer until it retires; each image is in its home layout, general, between commands, - // the buffer spans the surface's memory, and a dma-buf's foreign family is enabled. - unsafe { core.device.cmd_pipeline_barrier2(command, &dependency) }; - building.count(Metric::OtherBarriers); - building.count(Metric::ExternalReleases); - Ok(()) - } - /// `updateFence:`: encoders that wait on `fence` after this one, of any queue, see what this /// encoder and the ones before it wrote. It records nothing ([`Fence`]): each copy's own /// barrier already reaches every command submitted after it. diff --git a/crates/metal2vulkan-runtime/src/block.rs b/crates/metal2vulkan-runtime/src/block.rs index 0ac77ecac..10a94fe0a 100644 --- a/crates/metal2vulkan-runtime/src/block.rs +++ b/crates/metal2vulkan-runtime/src/block.rs @@ -6,7 +6,8 @@ use crate::error::Error; use crate::memory::{self, BlockInfo}; use std::fmt; use std::ops::Deref; -use std::sync::{Arc, Mutex, PoisonError, Weak}; +use std::sync::atomic::AtomicU64; +use std::sync::{Arc, Mutex, OnceLock, PoisonError, Weak}; /// No Metal counterpart: rt's own handle of a block of memory the consumer places buffers in, as /// a placement `MTLHeap`'s buffers sit in its memory @@ -39,6 +40,9 @@ pub(crate) struct Claim { core: Weak, /// The block, until the last handle drops or the device's teardown takes it. block: Mutex>>, + /// An exported block's: where its making completes, the point the other API's first access + /// waits for ([`Block::wait_until_ready`]); unset for every other block. + ready: OnceLock>, } impl Block { @@ -49,6 +53,7 @@ impl Block { info, core: Arc::downgrade(core), block: Mutex::new(Some(Arc::new(block))), + ready: OnceLock::new(), }); lock(&core.claims).insert(info.id, Arc::downgrade(&claim)); Block { claim } @@ -59,6 +64,18 @@ impl Block { Weak::as_ptr(&self.claim.core) == Arc::as_ptr(core) } + /// An exported block's point where its making completes ([`Block::wait_until_ready`]); + /// `None` for every other block. + pub(crate) fn ready(&self) -> Option> { + self.claim.ready.get().cloned() + } + + /// Sets an exported block's `ready` point, once, at its make + /// ([`Device::new_exported_block`](crate::Device::new_exported_block)). + pub(crate) fn set_ready(&self, ready: Arc) { + self.claim.ready.get_or_init(|| ready); + } + /// Its device and the block, while the claim holds it. /// /// Err: [`Error::Quiesced`] once the device's teardown took the block. diff --git a/crates/metal2vulkan-runtime/src/command.rs b/crates/metal2vulkan-runtime/src/command.rs index b996f4f23..60a1d2035 100644 --- a/crates/metal2vulkan-runtime/src/command.rs +++ b/crates/metal2vulkan-runtime/src/command.rs @@ -11,6 +11,7 @@ use crate::error::{Error, Refusal}; use crate::event::{Event, EventInner}; use crate::fault::DeviceFault; use crate::fence::Fences; +use crate::handed::Handed; use crate::hazard::{Access, Hazards}; use crate::kept::{Lent, Objects}; use crate::memory::Block; @@ -211,8 +212,8 @@ pub(crate) enum Owed { Unbound, /// A dispatch over a Private arena records a piece after its first. ArenaPiece, - /// A memory barrier was asked for, a block was released to another API, or a concurrent - /// encoder began after commands that touched anything. + /// A memory barrier was asked for, or a concurrent encoder began after commands that touched + /// anything. Other, } @@ -247,12 +248,12 @@ pub(crate) struct Building { stamps: Option, /// A barrier owed before the next command, by the first of its causes in [`Owed`]'s order: an /// encoder that wrote ended, a memory barrier was asked for, a dispatch wrote through an - /// address outside its resources, a render pass ended, or a block was released to another - /// API. The segment's own end barrier pays it too. + /// address outside its resources, or a render pass ended. The segment's own end barrier pays + /// it too. owed: Option, - /// The barrier owed orders a render pass ([`Building::owe_pass`]) or a release - /// ([`Building::release_command`]) before what follows it: it reaches every later command - /// ([`Reach::Commands`]), whatever the command that pays it names. + /// The barrier owed orders a render pass ([`Building::owe_pass`]) before what follows it: it + /// reaches every later command ([`Reach::Commands`]), whatever the command that pays it + /// names. owed_all: bool, /// A dispatch wrote since the last barrier that reached indirect argument reads: a barrier /// between dispatches leaves them out unless the dispatch after it is indirect, so an @@ -423,11 +424,11 @@ pub(crate) struct Segment { /// upload that leads its submission takes the copies back owed to them by writes submitted /// before it (`crate::over::ManagedOvers`). pub(crate) managed_reached: Vec>, - /// The images of the Direct3D 11 planes its commands use (`Device::import_d3d11_surface`, on - /// Windows): the `vkQueueSubmit2` that carries it acquires them from - /// `VK_QUEUE_FAMILY_EXTERNAL` at its start and releases them to it at its end, before its - /// signals (`crate::submit::parts`). - pub(crate) planes: Vec>, + /// What its commands use of memory another API shares (`crate::handed`): the + /// `vkQueueSubmit2` part that carries it acquires each from the other API's queue family at + /// its start and releases it to that family at its end, before its signals + /// (`crate::submit::parts`). + pub(crate) handed: Vec, /// The checks at its head and its writes of heap placements with links (`crate::alias`), /// where it has any: staged, a command buffer of moves leads it where the checks find one /// owed. @@ -1204,15 +1205,15 @@ impl Building { } } - /// Starts a new segment after the last one. A segment that signals passes its Direct3D 11 - /// planes on: one kept after the signal is kept for the command that splits + /// Starts a new segment after the last one. A segment that signals passes what it hands over + /// on: one kept after the signal is kept for the command that splits /// ([`keep_texture`](Self::keep_texture)). fn split(&mut self) -> Result<(), Error> { self.close(&[], None)?; let last = self.last(); let mut next = Segment::default(); if !last.signals.is_empty() { - next.planes.clone_from(&last.planes); + next.handed.clone_from(&last.handed); } self.gpu.segments.push(next); Ok(()) @@ -1454,21 +1455,6 @@ impl Building { self.owed_all = true; } - /// The current segment's command buffer, for a release of a block to another API's queue - /// family, which the caller records next. A release's own barrier orders every earlier - /// command before it, and nothing after it: Vulkan ignores its second scope, and only a - /// barrier from every stage waits for it (`VK_PIPELINE_STAGE_ALL_COMMANDS_BIT`, the queue - /// family ownership transfer). So the barrier that orders it before later commands is owed, - /// as a render pass's is ([`owe_pass`](Self::owe_pass)): recorded first by the segment's next - /// command, reaching every later command, or paid by the segment's end barrier where none - /// follows. - pub(crate) fn release_command(&mut self) -> Result { - let command = self.current()?; - self.owe(Owed::Other); - self.owed_all = true; - Ok(command) - } - /// Whether the next command opens a command buffer of the segments: the last segment has /// none begun, or a signal ends it first. Every command before it is then in a command buffer /// that ended on the queue, whose end barrier orders it before every later command @@ -1643,9 +1629,19 @@ impl Building { } /// Keeps `buffer`, with its block and its device copy where it has one, until the command - /// buffer retires. + /// buffer retires. A block another API shares is handed over by the current segment's + /// submission part too ([`Segment::handed`]). pub(crate) fn keep(&mut self, buffer: &Buffer) { self.gpu.kept.buffers.hold(buffer); + self.hand_block(buffer.held().0); + } + + /// Adds `block` to the current segment's hand-overs where another API shares it + /// ([`Segment::handed`]). + fn hand_block(&mut self, block: &Arc) { + if block.memory.handed_family().is_some() { + Handed::Block(Arc::clone(block)).keep(&mut self.last().handed); + } } /// Keeps `buffer` as [`keep`](Self::keep) does, and lends it for a binding slot: no count @@ -1659,6 +1655,7 @@ impl Building { { self.buffer_lends += 1; } + self.hand_block(buffer.held().0); // SAFETY: the caller uses the borrow only before the commit, and the lists are cleared // only once the command buffer retired. unsafe { self.gpu.kept.buffers.keep(buffer) } @@ -1682,8 +1679,10 @@ impl Building { self.pushed = Pushed::default(); } - /// Keeps `block` until the command buffer retires. + /// Keeps `block` until the command buffer retires, handed over by the current segment's + /// submission part where another API shares it ([`Segment::handed`]). pub(crate) fn keep_block(&mut self, block: &Arc) { + self.hand_block(block); let blocks = &mut self.gpu.blocks; if !blocks.iter().rev().any(|kept| Arc::ptr_eq(kept, block)) { blocks.push(Arc::clone(block)); @@ -1729,14 +1728,14 @@ impl Building { } /// Keeps `texture` until the command buffer retires, as Metal's command buffer retains every - /// object its encoders bind: each object once, a view apart from its parent. A Direct3D 11 - /// plane's image is kept by the current segment too, whose `vkQueueSubmit2` hands it over - /// ([`Segment::planes`]). + /// object its encoders bind: each object once, a view apart from its parent. What of it lies + /// in memory another API shares is kept by the current segment too, whose `vkQueueSubmit2` + /// part hands it over ([`Segment::handed`]). pub(crate) fn keep_texture(&mut self, texture: &Texture) { if self.gpu.kept.textures.hold(texture) { self.gpu.managed |= texture.managed_over().is_some(); } - texture.keep_plane(&mut self.last().planes); + texture.keep_handed(&mut self.last().handed); } /// Keeps `texture` as [`keep_texture`](Self::keep_texture) does, and lends it for a binding diff --git a/crates/metal2vulkan-runtime/src/counters.rs b/crates/metal2vulkan-runtime/src/counters.rs index 7a7034eb9..51e4e95e5 100644 --- a/crates/metal2vulkan-runtime/src/counters.rs +++ b/crates/metal2vulkan-runtime/src/counters.rs @@ -2534,9 +2534,10 @@ pub struct Metrics { /// feedback layout, one at a draw that reads an attachment after a memory barrier owed to it, /// and two around the copies a draw that reads an attachment makes into its image's shadow /// ([`attachment_read_copies`](Self::attachment_read_copies)), or the clear of the shadow - /// that stands for a copy of what its pass cleared, one for each acquire of an exported - /// block ([`external_acquires`](Self::external_acquires)), and one for each release of one - /// ([`external_releases`](Self::external_releases)). Any other draw takes none. An upload + /// that stands for a copy of what its pass cleared. Any other draw takes none. The hand-overs + /// of memory another API shares are the runtime's own command buffers' barriers + /// ([`external_acquires`](Self::external_acquires), + /// [`external_releases`](Self::external_releases)). An upload /// adds one where it moves new textures' images to their home layouts, one more after the /// zeroing of those it zeroes ([`texture_clear_barriers`](Self::texture_clear_barriers)), two /// around each copy between a texture's image and the staging region or a named buffer @@ -3248,25 +3249,26 @@ pub struct Metrics { /// value, the order Vulkan defines for what the guest then reads; this counts a driver whose /// counter runs ahead of its wait. pub waits_behind_counter: u64, - /// Acquires of another API's writes into exported blocks recorded - /// ([`Block::external_writes_done`](crate::Block::external_writes_done)) and into exported - /// surfaces ([`Surface::external_writes_done`](crate::Surface::external_writes_done), and an - /// in-place surface's buffer at the [`Surface::buffer`](crate::Surface::buffer) call that - /// makes it): one barrier each, in the upload, also counted in [`barriers`](Self::barriers). - /// Also one for each texture in place over a buffer in a dma-buf's import - /// (`Device::import_dma_buf`, on Unix), whose move home acquires its image and the buffer's - /// range under it from the foreign queue family, in the barrier of the upload's moves home. - /// Also one for each `vkQueueSubmit2` that uses a Direct3D 11 plane - /// ([`d3d11_plane_submissions`](Self::d3d11_plane_submissions)), in a command buffer of its - /// own. + /// Acquires of memory another API shares, one for each `vkQueueSubmit2` whose command buffers + /// or uploads use any (an exported block, an exported surface's planes in place or its buffer, + /// a Direct3D 11 plane, `Device::import_d3d11_surface` on Windows): one barrier of everything + /// the call uses of it, from the other API's queue family, in a command buffer of the + /// runtime's own ahead of everything in the call, after a global barrier from and to every + /// stage; both counted in [`barriers`](Self::barriers). A group sent member by member acquires + /// in each of its calls that uses any. Also one for each texture in place over a buffer in a + /// dma-buf's import (`Device::import_dma_buf`, on Unix), whose move home acquires its image + /// and the buffer's range under it from the foreign queue family, in the barrier of the + /// upload's moves home. No Metal counterpart: an IOSurface needs no hand-over between APIs. pub external_acquires: u64, - /// Releases of exported blocks and surfaces to another API recorded - /// ([`BlitCommandEncoder::release_to_external`](crate::BlitCommandEncoder::release_to_external), - /// [`BlitCommandEncoder::release_surface_to_external`](crate::BlitCommandEncoder::release_surface_to_external)): - /// one barrier each, in the command buffer's work, also counted in - /// [`barriers`](Self::barriers). Also one for each `vkQueueSubmit2` that uses a Direct3D 11 - /// plane ([`d3d11_plane_submissions`](Self::d3d11_plane_submissions)), in a command buffer of - /// its own. + /// Releases of memory another API shares: one for each `vkQueueSubmit2` that acquired it + /// ([`external_acquires`](Self::external_acquires)), one barrier of what it acquired, in a + /// command buffer of the runtime's own after everything in the call, which takes the call's + /// last signals; and one for each submission that carries the making of exported memory + /// ([`Device::new_exported_block`](crate::Device::new_exported_block), + /// [`Device::new_exported_surface`](crate::Device::new_exported_surface)), one barrier of + /// what was made, a plane's first move out of the undefined layout among it, in a command + /// buffer at the submission's head, ahead of any acquire. Each counted in + /// [`barriers`](Self::barriers). No Metal counterpart, as above. pub external_releases: u64, /// `vkQueueSubmit2` calls whose command buffers keep a plane of a Direct3D 11 surface /// (`Device::import_d3d11_surface`, on Windows), or whose uploads copy into or out of one: @@ -3307,10 +3309,12 @@ pub struct Metrics { /// address went out; 0 where none went out, as for a surface's block in the copy form whose /// buffer's address nothing read. pub exported_blocks_addressed: u64, - /// Waits of surfaces made in place for the submission that moves their planes to the general - /// layout ([`Surface::wait_until_ready`](crate::Surface::wait_until_ready)), on the - /// consumer's thread: one per call. The make - /// ([`Device::new_exported_surface`](crate::Device::new_exported_surface)) waits for none. + /// Waits for the submission that carries the making of an exported surface or block + /// ([`Surface::wait_until_ready`](crate::Surface::wait_until_ready), + /// [`Block::wait_until_ready`](crate::Block::wait_until_ready)), on the consumer's thread: + /// one per call that waits (a Direct3D 11 import's waits for nothing). The makes + /// ([`Device::new_exported_surface`](crate::Device::new_exported_surface), + /// [`Device::new_exported_block`](crate::Device::new_exported_block)) wait for none. pub surface_waits: u64, /// The nanoseconds of [`host_time`](crate::host_time) the surface waits took, in total. pub surface_wait_nanos: u64, @@ -3318,9 +3322,9 @@ pub struct Metrics { /// difference of two reads does not apply to it. pub surface_wait_max_nanos: u64, /// The runtime's submissions the surface waits waited for, in total: at each wait's start, - /// those of the device not yet complete, through the one that moves the planes, which is + /// those of the device not yet complete, through the one that carries the making, which is /// among them unless it had completed before the wait began (a submission made after the - /// make, for any command buffer, takes the moves). Another API's work is not counted: a wait + /// make, for any command buffer, takes the making). Another API's work is not counted: a wait /// much longer than these submissions' GPU times waited behind work the runtime did not /// submit. pub surface_wait_submissions: u64, diff --git a/crates/metal2vulkan-runtime/src/d3d11.rs b/crates/metal2vulkan-runtime/src/d3d11.rs index 81ef4ce71..5a96b4503 100644 --- a/crates/metal2vulkan-runtime/src/d3d11.rs +++ b/crates/metal2vulkan-runtime/src/d3d11.rs @@ -142,9 +142,8 @@ impl Device { /// ([`Metrics::d3d11_plane_parts`](crate::Metrics::d3d11_plane_parts)). The acquire follows /// a global barrier from and to every stage, so an earlier submission's release on rt's one /// queue happens before it (Vulkan 1.4, section 7.7.6). - /// [`Surface::external_writes_done`] and - /// [`release_surface_to_external`](crate::BlitCommandEncoder::release_surface_to_external) - /// record nothing for such a surface and change nothing. No keyed mutex is used, by rt or on + /// [`Surface::external_writes_done`] records nothing for such a surface and changes nothing. + /// No keyed mutex is used, by rt or on /// the textures: each is made with /// `D3D11_RESOURCE_MISC_SHARED | D3D11_RESOURCE_MISC_SHARED_NTHANDLE`, not /// `D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX`, whose mutex the device that makes the texture and @@ -449,6 +448,7 @@ impl Device { view_formats: list, block: None, d3d11: true, + family: vk::QUEUE_FAMILY_EXTERNAL, linear_attachment: false, }; self.surface_texture(d, plane.index, made, unit) diff --git a/crates/metal2vulkan-runtime/src/error.rs b/crates/metal2vulkan-runtime/src/error.rs index a8e8a4014..a33f369ea 100644 --- a/crates/metal2vulkan-runtime/src/error.rs +++ b/crates/metal2vulkan-runtime/src/error.rs @@ -211,11 +211,10 @@ pub enum Refusal { /// The block named. block: BlockId, }, - /// An acquire of another API's writes into a block that is not exported - /// ([`Block::external_writes_done`](crate::Block::external_writes_done)), or a release to - /// another API of a buffer whose block is not exported - /// ([`BlitCommandEncoder::release_to_external`](crate::BlitCommandEncoder::release_to_external)). - /// Metal has no counterpart. + /// A call about another API's access of a block that is not exported: the mark of its writes + /// ([`Block::external_writes_done`](crate::Block::external_writes_done)) or the wait for the + /// block's making ([`Block::wait_until_ready`](crate::Block::wait_until_ready)). Metal has no + /// counterpart. /// /// Basis: ours (only an exported block's memory is another API's to write or read). NotExported { diff --git a/crates/metal2vulkan-runtime/src/export.rs b/crates/metal2vulkan-runtime/src/export.rs index 1509e7e2c..bd23c0dd1 100644 --- a/crates/metal2vulkan-runtime/src/export.rs +++ b/crates/metal2vulkan-runtime/src/export.rs @@ -10,12 +10,12 @@ //! buffers export it (`vkGetPhysicalDeviceExternalBufferProperties`), and refused elsewhere. use crate::block::Block; -use crate::counters::{Metric, Part}; +use crate::counters::Part; use crate::device::Device; use crate::error::{Error, Limit, Refusal}; use crate::floor; +use crate::handed::Handed; use crate::memory::{self, Own}; -use crate::submit::Held; use ash::vk; use std::ffi::CStr; use std::sync::Arc; @@ -208,13 +208,23 @@ impl Device { /// it, which counts in /// [`Metrics::exported_blocks_addressed`](crate::Metrics::exported_blocks_addressed). /// + /// The call makes no submission and waits for nothing. The block is the runtime's until its + /// making, the release of its buffer to the other API's queue family in one barrier, at the + /// head of the runtime's submission that carries the next commit, ahead of every command + /// buffer committed after the make. The other API's first access waits for that submission + /// ([`Block::wait_until_ready`]), which has it go at once where none has. From then the other + /// API owns the block between the runtime's submissions: each `vkQueueSubmit2` that uses it + /// acquires it at its head and releases it at its end + /// ([`Block::external_writes_done`]). + /// /// Err: [`Limit::NoExport`] where the device does not export the handle; /// [`Limit::ExportType`] for a dma-buf on a device without the foreign queue family, or where /// the buffer's memory requirements do not list the Private type; /// [`Limit::BlockLen`] past the device's longest allocation or /// buffer; [`Limit::MemoryAllocations`]; /// [`Limit::BlockIds`]; [`Error::Vulkan`] where the buffer, the - /// allocation, its binding or the handle fails; [`Error::Quiesced`]. + /// allocation, its binding, the handle or the upload's command buffer fails; + /// [`Error::Quiesced`]. pub fn new_exported_block( &self, handle: ExportHandle, @@ -240,6 +250,10 @@ impl Device { let raw = memory.device_memory(); let claiming = crate::host_time(); let block = Block::claim(core, info, memory::Block::new(memory, Arc::clone(core))); + // Its buffer goes to the other API in the next commit's submission, which the make does + // not wait for: the consumer waits for it on its own thread (`Block::wait_until_ready`). + let (_, made) = block.held()?; + block.set_ready(core.work.create(core, &[Handed::Block(made)])?); let exporting = crate::host_time(); (core.counters).timed(Part::ExportClaim, size, exporting - claiming, false); // A failure here gives the block back with its memory as `block` drops. @@ -257,66 +271,65 @@ impl Device { } impl Block { - /// No Metal counterpart: the other API's accesses of this exported block - /// ([`Device::new_exported_block`]) are done, and the runtime's commands may now read and - /// write it. The consumer calls it once the other API's work that accessed the block (work - /// that wrote it, or that read it after a release) has completed (its own wait on the - /// decoder, for one), and before it commits the command buffers that use the block. + /// No Metal counterpart: the other API's writes into this exported block + /// ([`Device::new_exported_block`]) are done, and the runtime's commands may now read them. + /// The consumer calls it once the other API's work that wrote the block has completed (its + /// own wait on the decoder, for one), and before it commits the command buffers that read + /// what it wrote. /// - /// The call records the block's acquire from the other API's queue family: the whole - /// block, from `VK_QUEUE_FAMILY_EXTERNAL` for an opaque handle, or from - /// `VK_QUEUE_FAMILY_FOREIGN_EXT` for a dma-buf, to the runtime's, made visible to every - /// later command. It goes in the upload, as [`Device::zero_block_range`]'s fill does: - /// submitted ahead of every command buffer committed after this call, holding the block until - /// it completes. The call never waits for the GPU. One call is one buffer barrier, - /// counted in [`Metrics::external_acquires`](crate::Metrics::external_acquires). - /// - /// The contract has three parts: between this call and the other API's next write, the other - /// API does not access the block, unless a release - /// ([`release_to_external`](crate::BlitCommandEncoder::release_to_external)) comes between, - /// from whose completion it may read the whole block, the runtime's writes and its own - /// earlier ones; when it writes again, it reads nothing of the block but what it has itself - /// written since and what a release since handed it; and after each acquire, a byte the other - /// API has not written since the previous acquire is undefined to the runtime, unless a - /// release came between the two: a release and the acquire after it transfer ownership, and - /// Vulkan leaves contents undefined only where "no ownership transfer is defined", so the - /// bytes the other API did not write keep what the release handed it. The acquire is not - /// followed by a release of its own: without one, Vulkan leaves the block's contents undefined - /// to the other API's reads ("the contents of that resource are undefined for any read - /// accesses performed by the second queue family"). + /// The call records nothing and waits for nothing: each `vkQueueSubmit2` that uses the block + /// acquires it from the other API's queue family at its head and releases it to that family + /// at its end ([`Metrics::external_acquires`](crate::Metrics::external_acquires), + /// [`Metrics::external_releases`](crate::Metrics::external_releases)), whether the call + /// comes before or after the commit. It marks what the other API wrote on the host side + /// alone: each texture over a buffer in the block in an image of its own + /// ([`Buffer::new_texture`](crate::Buffer::new_texture)) takes the block's bytes again + /// before its next use. /// /// Err: [`Refusal::NotExported`] for a block that is not exported; - /// [`Refusal::InScheduledHandler`] in a scheduled handler; [`Error::Quiesced`]; and - /// [`Error::Vulkan`] where the upload's command buffer cannot be made. + /// [`Refusal::InScheduledHandler`] in a scheduled handler; [`Error::Quiesced`]. pub fn external_writes_done(&self) -> Result<(), Error> { crate::command::not_in_scheduled_handler()?; let (core, block) = self.held()?; - let Some(Own::Export { handle, .. }) = block.memory.own else { + if !matches!(block.memory.own, Some(Own::Export { .. })) { return Err(Error::Refused(Refusal::NotExported { block: self.id })); - }; - let (buffer, _) = block.memory.range(0); - let acquire = [vk::BufferMemoryBarrier2::default() - .dst_stage_mask(vk::PipelineStageFlags2::ALL_COMMANDS) - .dst_access_mask(vk::AccessFlags2::MEMORY_READ | vk::AccessFlags2::MEMORY_WRITE) - .src_queue_family_index(handle.family()) - .dst_queue_family_index(core.family) - .buffer(buffer) - .offset(0) - .size(vk::WHOLE_SIZE)]; - let held = [Held::Block(Arc::clone(&block))]; - core.work.upload(&core, None, held, |device, command| { - let dependency = vk::DependencyInfo::default().buffer_memory_barriers(&acquire); - // SAFETY: the upload's command buffer is recording, under the work lock; the buffer - // spans the block's allocation, which the upload holds, and a dma-buf's foreign - // family is enabled (`Device::new_exported_block`). - unsafe { device.cmd_pipeline_barrier2(command, &dependency) }; - })?; + } // The other API's writes change the bytes of the textures over the block // (`crate::over::ExportedOvers`). core.work .exported_changed(block.memory.id, (0, block.memory.len)); - core.counters.count(Metric::UploadBarriers); - core.counters.count(Metric::ExternalAcquires); + Ok(()) + } + + /// No Metal counterpart: waits until this exported block ([`Device::new_exported_block`]) is + /// the other API's to access, on the calling thread, the consumer's own. Metal has no such + /// wait, as it has no exports. The twin of + /// [`Surface::wait_until_ready`](crate::Surface::wait_until_ready). + /// + /// The block is the runtime's until its making: the release of its buffer to the other API's + /// queue family, which [`Device::new_exported_block`] records for the runtime's first + /// submission after the make and does not wait for. The other API's first access of the + /// block comes after that submission. The call returns once it has completed, and has it go + /// at once where it is not yet made, so it returns with no command buffer committed. The + /// runtime's own commands need no such wait: the making goes ahead of every command buffer + /// committed after the make. Each call counts in + /// [`Metrics::surface_waits`](crate::Metrics::surface_waits), with its time and the + /// submissions it waited for. + /// + /// Err: [`Refusal::NotExported`] for a block that is not exported; + /// [`Refusal::InScheduledHandler`] in a scheduled handler; [`Error::Quiesced`]; + /// [`Error::Vulkan`] where the device is lost first or the progress semaphore cannot be read. + pub fn wait_until_ready(&self) -> Result<(), Error> { + crate::command::not_in_scheduled_handler()?; + let (core, _) = self.held()?; + let Some(ready) = self.ready() else { + return Err(Error::Refused(Refusal::NotExported { block: self.id })); + }; + if core.closed() { + return Err(Error::Quiesced); + } + let (waited, submissions) = core.work.wait_ready(&core, &ready)?; + core.counters.surface_wait(waited, submissions); Ok(()) } } diff --git a/crates/metal2vulkan-runtime/src/handed.rs b/crates/metal2vulkan-runtime/src/handed.rs new file mode 100644 index 000000000..252e894cc --- /dev/null +++ b/crates/metal2vulkan-runtime/src/handed.rs @@ -0,0 +1,159 @@ +//! Memory another API shares with rt, which every `vkQueueSubmit2` part that uses it hands over +//! (`crate::submit::parts`): a Direct3D 11 plane's image (`Device::import_d3d11_surface`, on +//! Windows), an exported surface's plane in place and its buffer +//! ([`Device::new_exported_surface`](crate::Device::new_exported_surface)), and an exported block +//! ([`Device::new_exported_block`](crate::Device::new_exported_block)), a copy-form surface's +//! among them. Each part acquires every one it uses from the other API's queue family at its head +//! and releases it to that family at its end, so the other API owns the memory between rt's +//! submissions. Memory rt exported is also released once at its making, after an image's first +//! move, in a command buffer at the head of the submission that takes the make's upload +//! ([`Work::create`](crate::submit::Work::create)): every acquire of it has a release before it +//! (`VUID-vkQueueSubmit2-commandBuffer-03879`). A Direct3D 11 plane is Direct3D 11's from its +//! making, the import's documented case (section 12.10.1, Table 17). + +use crate::memory::Block; +use crate::submit::Held; +use crate::texture::Image; +use ash::vk; +use std::sync::{Arc, Weak}; + +/// Which of a resource's hand-overs a barrier records. +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum Hand { + /// Its making: its release to the other API's queue family, an image's first move out of the + /// undefined layout in it ([`Image::making`]). + Make, + /// Its acquire from the other API's queue family at a part's head. + Acquire, + /// Its release to the other API's queue family at a part's end. + Release, +} + +/// One resource in memory another API shares, as a part hands it over. +#[derive(Clone)] +pub(crate) enum Handed { + /// A plane's image: a Direct3D 11 texture's, or an exported surface's in place. + Image(Arc), + /// An exported block, or an exported surface's buffer, whose one buffer spans it. + Block(Arc), +} + +/// A [`Handed`] an upload owes its making's release to, not held: one gone before the upload's +/// submission owes nothing. +pub(crate) enum Owed { + Image(Weak), + Block(Weak), +} + +impl Owed { + /// Whether the resource still lives. + pub(crate) fn lives(&self) -> bool { + match self { + Owed::Image(image) => image.strong_count() > 0, + Owed::Block(block) => block.strong_count() > 0, + } + } + + /// The resource, where it still lives. + pub(crate) fn upgrade(&self) -> Option { + match self { + Owed::Image(image) => image.upgrade().map(Handed::Image), + Owed::Block(block) => block.upgrade().map(Handed::Block), + } + } +} + +impl Handed { + /// Whether `self` and `other` are the same resource. + fn is(&self, other: &Handed) -> bool { + match (self, other) { + (Handed::Image(a), Handed::Image(b)) => Arc::ptr_eq(a, b), + (Handed::Block(a), Handed::Block(b)) => Arc::ptr_eq(a, b), + _ => false, + } + } + + /// Adds it to `list` where it is not there yet. + pub(crate) fn keep(&self, list: &mut Vec) { + if !list.iter().any(|kept| kept.is(self)) { + list.push(self.clone()); + } + } + + /// Not held, for an upload that owes its making's release. + pub(crate) fn owed(&self) -> Owed { + match self { + Handed::Image(image) => Owed::Image(Arc::downgrade(image)), + Handed::Block(block) => Owed::Block(Arc::downgrade(block)), + } + } + + /// Whether it is a Direct3D 11 plane's image (`Metrics::d3d11_plane_submissions`). + pub(crate) fn d3d11(&self) -> bool { + matches!(self, Handed::Image(image) if image.d3d11_plane()) + } + + /// It, as a command buffer of the runtime's holds it until it retires. + pub(crate) fn held(&self) -> Held { + match self { + Handed::Image(image) => Held::Texture(Arc::clone(image)), + Handed::Block(block) => Held::Block(Arc::clone(block)), + } + } +} + +/// A block's hand-over between the other API's queue family `other` and the runtime's `family`: +/// the whole of its buffer, acquired (`acquire`) and made visible to every later command, or +/// released after every earlier command's writes. +fn block_barrier( + block: &Block, + other: u32, + family: u32, + acquire: bool, +) -> vk::BufferMemoryBarrier2<'static> { + let (buffer, _) = block.memory.range(0); + let barrier = vk::BufferMemoryBarrier2::default() + .buffer(buffer) + .offset(0) + .size(vk::WHOLE_SIZE); + let all = vk::PipelineStageFlags2::ALL_COMMANDS; + match acquire { + true => (barrier.src_queue_family_index(other)) + .dst_queue_family_index(family) + .dst_stage_mask(all) + .dst_access_mask(vk::AccessFlags2::MEMORY_READ | vk::AccessFlags2::MEMORY_WRITE), + false => (barrier.src_queue_family_index(family)) + .dst_queue_family_index(other) + .src_stage_mask(all) + .src_access_mask(vk::AccessFlags2::MEMORY_WRITE), + } +} + +/// The barriers of `handed`'s hand-over `hand` to or from the runtime's queue family `family`: +/// its images' and its blocks'. A block's making is its release. +pub(crate) fn barriers( + handed: &[Handed], + family: u32, + hand: Hand, +) -> ( + Vec>, + Vec>, +) { + let mut images = Vec::new(); + let mut buffers = Vec::new(); + for item in handed { + match item { + Handed::Image(image) => images.push(match hand { + Hand::Make => image.making(family), + _ => image.handed(family, hand == Hand::Acquire), + }), + Handed::Block(block) => { + if let Some(other) = block.memory.handed_family() { + let acquire = hand == Hand::Acquire; + buffers.push(block_barrier(block, other, family, acquire)); + } + } + } + } + (images, buffers) +} diff --git a/crates/metal2vulkan-runtime/src/import.rs b/crates/metal2vulkan-runtime/src/import.rs index 2ce31437b..3496616d5 100644 --- a/crates/metal2vulkan-runtime/src/import.rs +++ b/crates/metal2vulkan-runtime/src/import.rs @@ -962,7 +962,10 @@ pub(crate) fn surface_import( .memory_type_index(index) .push_next(&mut import) .push_next(&mut flags); - let own = Own::Surface { import: true }; + let own = Own::Surface { + import: true, + family: vk::QUEUE_FAMILY_FOREIGN_EXT, + }; // SAFETY: an import of the dma-buf into a type its query offered, its buffers list and its // planes' imports took, of at least the buffer's size. match unsafe { memory::import(core, &info, handle.vk(), None, own) } { diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs index a2d59cc6f..c56e0006f 100644 --- a/crates/metal2vulkan-runtime/src/lib.rs +++ b/crates/metal2vulkan-runtime/src/lib.rs @@ -37,6 +37,7 @@ mod fence; mod fill; pub mod floor; mod function_table; +mod handed; mod hazard; mod host_bytes; mod import; diff --git a/crates/metal2vulkan-runtime/src/memory.rs b/crates/metal2vulkan-runtime/src/memory.rs index 173e0858f..bb2190e45 100644 --- a/crates/metal2vulkan-runtime/src/memory.rs +++ b/crates/metal2vulkan-runtime/src/memory.rs @@ -390,6 +390,8 @@ pub(crate) enum Own { Surface { /// Its memory is an import of its own, freed with it. import: bool, + /// The other API's queue family, which its hand-overs name (`crate::handed`). + family: u32, }, /// An import over several dma-bufs ([`crate::Device::import_dma_bufs`]): its sparse buffer, /// bound to its chunks' imports by the bind that signals `bind` on the binds' timeline @@ -448,6 +450,18 @@ impl Memory { matches!(self.own, Some(Own::Export { .. })) } + /// The other API's queue family, where another API shares the memory and each submission + /// part that uses it hands it over (`crate::handed`): an exported block's, an exported + /// surface's buffer's (a dma-buf's on its own import of the surface's dma-buf). `None` for + /// every other block, an import of another API's memory among them. + pub(crate) fn handed_family(&self) -> Option { + match self.own { + Some(Own::Export { handle, .. }) => Some(handle.family()), + Some(Own::Surface { family, .. }) => Some(family), + _ => None, + } + } + pub(crate) fn info(&self) -> BlockInfo { BlockInfo { id: self.id, @@ -2675,7 +2689,10 @@ pub(crate) unsafe fn surface_view( mapping: None, device_local: under.memory.device_local, spilled: false, - own: Some(Own::Surface { import: false }), + own: Some(Own::Surface { + import: false, + family: handle.family(), + }), }; Ok(Block::over(memory, Arc::clone(core), Arc::clone(under))) } @@ -2713,7 +2730,7 @@ fn free_own(core: &Core, memory: &Memory, release: Option) { } // A surface's buffer on the opaque handle's allocation frees no memory: the block under it, // given back after it, does. - if memory.own == Some(Own::Surface { import: false }) { + if matches!(memory.own, Some(Own::Surface { import: false, .. })) { core.counters.fall(Gauge::SurfaceBuffers); return; } diff --git a/crates/metal2vulkan-runtime/src/submit.rs b/crates/metal2vulkan-runtime/src/submit.rs index 03748b521..bb66bb051 100644 --- a/crates/metal2vulkan-runtime/src/submit.rs +++ b/crates/metal2vulkan-runtime/src/submit.rs @@ -72,6 +72,7 @@ use crate::error::Error; use crate::event::EventInner; use crate::fault; use crate::fill; +use crate::handed::{self, Hand, Handed, Owed}; use crate::memory::{Block, BlockId, Internal}; use crate::over::{self, ExportedOvers, Leans}; use crate::queue::QueueInner; @@ -165,7 +166,8 @@ pub(crate) const UPLOAD_ENTRIES: usize = 4096; /// one call larger than it goes alone. pub(crate) const UPLOAD_BYTES: u64 = 64 << 20; -/// The new textures awaiting their home layout at which the dead among them are first dropped. +/// The new textures awaiting their home layout, or the resources awaiting their making, at which +/// the dead among them are first dropped. pub(crate) const HOMES_PRUNE: usize = 64; /// For the device tests: the nanoseconds this thread waited for the work lock @@ -333,9 +335,14 @@ pub(crate) struct Upload { /// The staging region's spans its copies use, and their bytes. spans: Vec, span_bytes: u64, - /// Where a surface waits for the moves this upload records ([`Work::ready_point`]): set to - /// the progress value of the submission that takes it, 0 until then. + /// Where the consumer waits for the makings this upload owes ([`Work::create`]): set to the + /// progress value of the submission that takes it, 0 until then. ready: Option>, + /// What was made in memory another API shares while it recorded, not held: the submission + /// that takes it records the making of each that still lives at its head ([`Work::create`]). + created: Vec, + /// The length of `created` at which the dead are dropped from it. + created_prune_at: usize, /// The textures made while it recorded, not held: the submission that takes it moves each /// that still lives to its home layout ([`Work::home`]). homes: Vec>, @@ -400,6 +407,8 @@ impl Upload { spans: Vec::new(), span_bytes: 0, ready: None, + created: Vec::new(), + created_prune_at: HOMES_PRUNE, homes: Vec::new(), prune_at: HOMES_PRUNE, filled: Vec::new(), @@ -458,19 +467,20 @@ impl Upload { core.counters.count(Metric::TextureClearBarriers); } - /// A new upload that hands `planes`, Direct3D 11 planes' images, over ([`Image::handed`]) in - /// one barrier counted in `core`'s counters, its command buffer ended; with the first failed - /// call, which loses the device. An acquire follows a global barrier from and to every stage: - /// an acquire's own first synchronization scope does not apply, and the release before it, - /// an earlier submission's on the one queue, must happen before it (Vulkan 1.4, section - /// 7.7.6: "VK_PIPELINE_STAGE_ALL_COMMANDS_BIT is the only valid stage to wait on or wait for - /// these operations"). + /// A new upload that hands `handed`, resources in memory another API shares, over + /// (`crate::handed`) as `hand` says, in one barrier counted in `core`'s counters, its command + /// buffer ended; with the first failed call, which loses the device. An acquire follows a + /// global barrier from and to every stage: an acquire's own first synchronization scope does + /// not apply, and the release before it, an earlier submission's on the one queue or the + /// making's at its own submission's head, must happen before it (Vulkan 1.4, section 7.7.6: + /// "VK_PIPELINE_STAGE_ALL_COMMANDS_BIT is the only valid stage to wait on or wait for these + /// operations"). A release or a making holds what it hands over until it retires. fn hand_over( core: &Core, - planes: &[Arc], - acquire: bool, + handed: &[Handed], + hand: Hand, ) -> (Option, Result<(), DeviceLoss>) { - let upload = match Upload::begin(core, 0) { + let mut upload = match Upload::begin(core, 0) { Ok(upload) => upload, Err(Error::Vulkan { call, result }) => { return (None, Err(DeviceLoss::of(call)(result))) @@ -478,29 +488,39 @@ impl Upload { Err(error) => unreachable!("an upload's begin fails only in a Vulkan call: {error}"), }; let device = &core.device; + let acquire = hand == Hand::Acquire; if acquire { record::barrier(device, upload.command, Reach::Commands); core.counters.count(Metric::UploadBarriers); } - let barriers: Vec<_> = (planes.iter()) - .map(|image| image.handed(core.family, acquire)) - .collect(); + let (images, buffers) = handed::barriers(handed, core.family, hand); #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] if acquire { - let recorded = (planes.iter().zip(&barriers)) - .map(|(image, barrier)| (Arc::as_ptr(image) as usize, barrier.old_layout)); + let recorded = (handed.iter()) + .filter_map(|item| match item { + Handed::Image(image) => Some(Arc::as_ptr(image) as usize), + Handed::Block(_) => None, + }) + .zip(&images) + .map(|(image, barrier)| (image, barrier.old_layout)); lock(&core.work.acquired).extend(recorded); } - let dependency = vk::DependencyInfo::default().image_memory_barriers(&barriers); + let dependency = vk::DependencyInfo::default() + .image_memory_barriers(&images) + .buffer_memory_barriers(&buffers); // SAFETY: the upload's command buffer is recording, and only the submit thread has it; - // each image is the device's, held by the submission until it retires, and general - // between commands. + // each image and block is the device's, held by the submission until it retires, each + // image general between commands or, at its making, undefined and not yet used, and a + // dma-buf's foreign family is enabled. unsafe { device.cmd_pipeline_barrier2(upload.command, &dependency) }; core.counters.count(Metric::UploadBarriers); core.counters.count(match acquire { true => Metric::ExternalAcquires, false => Metric::ExternalReleases, }); + if !acquire { + upload.held.extend(handed.iter().map(Handed::held)); + } times::end_own(device, upload.command, upload.stamps); // SAFETY: as above. let ended = unsafe { device.end_command_buffer(upload.command) } @@ -567,10 +587,10 @@ struct Batch { /// The Managed buffers with textures over their device copies its segments reach, to which /// its upload takes the copies back owed by writes submitted before (`crate::over`). reached: Vec>, - /// The images of the Direct3D 11 planes its segments use (`Segment::planes`), by the part - /// each segment is in where it goes member by member: the leads before it, 0 for the part - /// ahead of the first lead's ([`parts`]). Empty where none uses one. - planes: Vec>>, + /// What its segments use of memory another API shares (`Segment::handed`), by the part each + /// segment is in where it goes member by member: the leads before it, 0 for the part ahead of + /// the first lead's ([`parts`]). Empty where none uses any. + handed: Vec>, /// What it flushes before it is submitted, where the Shared type is not host-coherent and /// a command buffer with a segment in it or a copy-in it carries reaches Shared memory /// (`crate::coherence`); `None` where none does. @@ -1344,10 +1364,11 @@ impl Work { value } - /// The point at which every move to a home layout recorded so far has completed, with no - /// submission of its own: the last upload's not yet submitted, whose submission sets it, and - /// takes every one before it; where none is, the last submission that took one. - /// [`ready_value`](Self::ready_value) reads it. + /// For the device tests: the point at which everything recorded into uploads so far has + /// completed, with no submission of its own: the last upload's not yet submitted, whose + /// submission sets it, and takes every one before it; where none is, the last submission that + /// took one. [`ready_value`](Self::ready_value) reads it. + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] pub(crate) fn ready_point(&self) -> Arc { let mut guard = self.lock(); let state = &mut *guard; @@ -1362,7 +1383,53 @@ impl Work { } } - /// The progress value at which `point` ([`ready_point`](Self::ready_point)) is reached: the + /// `made`, just made in memory rt exports to another API (`crate::handed`), owes its making + /// to the upload of the next commit ([`WorkState::current`]): the submission that takes that + /// upload, which goes ahead of every command buffer committed after this call, records at + /// its head, ahead of any acquire, the release of each that still lives to the other API's + /// queue family, an image's first move out of the undefined layout in the same barrier + /// ([`Upload::make_handed`]). Nothing holds them until then. The point returned is set to + /// that submission's progress value ([`ready_value`](Self::ready_value)): the other API's + /// first access waits for it. + /// + /// Err: [`Error::Quiesced`]; [`Error::Vulkan`] where a command pool or buffer cannot be made. + pub(crate) fn create(&self, core: &Core, made: &[Handed]) -> Result, Error> { + let mut state = self.lock(); + if state.closed { + return Err(Error::Quiesced); + } + let upload = state.current(core)?; + if upload.created.len() >= upload.created_prune_at { + upload.created.retain(|owed| owed.lives()); + upload.created_prune_at = (upload.created.len() * 2).max(HOMES_PRUNE); + } + upload.created.extend(made.iter().map(Handed::owed)); + let ready = (upload.ready).get_or_insert_with(|| Arc::new(AtomicU64::new(0))); + Ok(Arc::clone(ready)) + } + + /// Waits on the calling thread until `point` ([`create`](Self::create)) is reached, having + /// its submission go at once where it is not yet made ([`ready_value`](Self::ready_value)): + /// the nanoseconds waited and the runtime's submissions not yet complete as the wait began, + /// through that one (`Metrics::surface_wait_submissions`). + /// + /// Err: [`Error::Vulkan`] where the device is lost first or the progress semaphore cannot be + /// read. + pub(crate) fn wait_ready(&self, core: &Core, point: &AtomicU64) -> Result<(u64, u64), Error> { + // The progress reached is read before `ready_value` can wake the submit thread: a + // submission it then makes, the making's among them, cannot have completed by the read, + // so it is counted. + let began = times::host_time(); + // SAFETY: the progress semaphore is the device's, live while the core is. + let reached = unsafe { core.device.get_semaphore_counter_value(core.done.progress) } + .map_err(Error::vulkan("vkGetSemaphoreCounterValue"))?; + let value = self.ready_value(point); + core.done.wait(core, value)?; + let waited = times::host_time().saturating_sub(began); + Ok((waited, value.saturating_sub(reached))) + } + + /// The progress value at which `point` ([`create`](Self::create)) is reached: the /// value of the submission that took its upload, or where that upload is not yet submitted, /// the next submission's, which this call has take it at once ([`flush`](Self::flush)). pub(crate) fn ready_value(&self, point: &AtomicU64) -> u64 { @@ -1953,7 +2020,7 @@ impl WorkState { written: Vec::new(), wrote: Vec::new(), reached: Vec::new(), - planes: Vec::new(), + handed: Vec::new(), flushes: None, lost: None, }); @@ -1993,13 +2060,13 @@ impl WorkState { group.overs.push(copy); } } - if !segment.planes.is_empty() { + if !segment.handed.is_empty() { let part = group.starts.len(); - if group.planes.len() <= part { - group.planes.resize_with(part + 1, Vec::new); + if group.handed.len() <= part { + group.handed.resize_with(part + 1, Vec::new); } - for image in &segment.planes { - image.keep_plane(&mut group.planes[part]); + for item in &segment.handed { + item.keep(&mut group.handed[part]); } } // The moves its checks find owed lead it, in its submit info (`crate::alias`). @@ -2557,7 +2624,7 @@ impl Batch { written: Vec::new(), wrote: Vec::new(), reached: Vec::new(), - planes: Vec::new(), + handed: Vec::new(), flushes: None, lost: None, } @@ -2595,9 +2662,9 @@ pub(crate) fn put_ahead( /// the parts left empty, and each part's one above the one before. A segment with no commands /// and no signals is left out, and so is a part left empty. /// -/// `planes[p]` holds the Direct3D 11 planes part `p` uses, and `hand` the command buffer that -/// acquires (`true`) or releases (`false`) such planes ([`Upload::hand_over`]), None where its -/// make failed: each part that uses planes acquires them at its head, ahead of its uploads +/// `handed[p]` holds what part `p` uses of memory another API shares, and `hand` the command +/// buffer that acquires (`true`) or releases (`false`) it ([`Upload::hand_over`]), None where its +/// make failed: each part that uses any acquires it at its head, ahead of its uploads /// where it has them, and releases them at its end, the release taking that part's last /// signals, its progress value among them, so it adds no submit info ([`infos`]) and the part's /// command buffers are seen complete only after it. A part that uses none takes neither. @@ -2606,7 +2673,7 @@ pub(crate) fn parts

( ahead: usize, leads: &[usize], (progress, value): (vk::Semaphore, u64), - planes: &[Vec

], + handed: &[Vec

], mut hand: impl FnMut(&[P], bool) -> Option, ) -> Vec<(u64, Vec)> { let staged = |command: vk::CommandBuffer| Staged { @@ -2623,7 +2690,7 @@ pub(crate) fn parts

( } parts.push((value - count as u64, segments)); parts.reverse(); - for ((_, part), used) in parts.iter_mut().zip(planes) { + for ((_, part), used) in parts.iter_mut().zip(handed) { part.retain(|staged| staged.command.is_some() || !staged.signals.is_empty()); if used.is_empty() { continue; @@ -2646,7 +2713,7 @@ pub(crate) fn parts

( part.extend([last, release]); } } - for (_, part) in parts.iter_mut().skip(planes.len()) { + for (_, part) in parts.iter_mut().skip(handed.len()) { part.retain(|staged| staged.command.is_some() || !staged.signals.is_empty()); } parts.retain(|(_, part)| !part.is_empty()); @@ -2704,7 +2771,7 @@ fn scheduled(joined: &mut Vec) { /// signalling the progress `value`, and where it goes member by member each part before it its /// own lower value. Whatever was passed to `vkQueueSubmit2` goes to the completion thread as in /// flight; a failed submission is taken as a loss. -fn submit(core: &Core, value: u64, uploads: Vec, batch: Batch) { +fn submit(core: &Core, value: u64, mut uploads: Vec, batch: Batch) { let Batch { mut segments, mut finished, @@ -2717,12 +2784,18 @@ fn submit(core: &Core, value: u64, uploads: Vec, batch: Batch) { apart, held, copy_ins, - mut planes, + mut handed, flushes, lost, .. } = batch; let device = &core.device; + // What the uploads owe their makings to that still lives (`Work::create`), whatever else they + // record. + let making: Vec = (uploads.iter_mut()) + .flat_map(|upload| upload.created.drain(..)) + .filter_map(|owed| owed.upgrade()) + .collect(); // An upload begun for textures gone before their move records nothing; one is kept, or begun, // for the copies into textures over a buffer in an image of their own. let sides = !overs.is_empty() || !backs.is_empty(); @@ -2783,28 +2856,57 @@ fn submit(core: &Core, value: u64, uploads: Vec, batch: Batch) { let ended = unsafe { device.end_command_buffer(last.command) }; ok = ok.and(ended.map_err(DeviceLoss::of("vkEndCommandBuffer"))); } - // Each Direct3D 11 plane a part's command buffers or uploads use is the runtime's from that - // part's start to its end: acquired from `VK_QUEUE_FAMILY_EXTERNAL` in a command buffer of its - // own ahead of everything in the part, and released to it in another after everything, which - // holds the images (`Metrics::d3d11_plane_submissions`). The uploads' planes go with the first - // part, and where the group goes as one part, every segment's go with it. - if !apart && planes.len() > 1 { + // Everything a part's command buffers or uploads use of memory another API shares is the + // runtime's from that part's start to its end: acquired from the other API's queue family in + // a command buffer of its own ahead of everything in the part, and released to it in another + // after everything, which holds it (`crate::handed`). The uploads' go with the first part, and + // where the group goes as one part, every segment's go with it. + if !apart && handed.len() > 1 { let mut one = Vec::new(); - for image in planes.iter().flatten() { - image.keep_plane(&mut one); + for item in handed.iter().flatten() { + item.keep(&mut one); } - planes = vec![one]; + handed = vec![one]; + } + // Where the group goes member by member, the uploads' copies into textures over a buffer in + // a block another API shares read that block in the first part, which hands it over too. + let read: Vec = (handed.iter().flatten()) + .filter(|item| match item { + Handed::Block(block) => (overs.iter()).any(|copy| copy.memory.block == block.memory.id), + Handed::Image(_) => false, + }) + .cloned() + .collect(); + for item in read { + item.keep(&mut handed[0]); } for upload in &uploads { for held in &upload.held { - if let Held::Texture(image) = held { - if planes.is_empty() { - planes.push(Vec::new()); + let item = match held { + Held::Texture(image) if image.surface() => Handed::Image(Arc::clone(image)), + Held::Block(block) if block.memory.handed_family().is_some() => { + Handed::Block(Arc::clone(block)) } - image.keep_plane(&mut planes[0]); + _ => continue, + }; + if handed.is_empty() { + handed.push(Vec::new()); } + item.keep(&mut handed[0]); } } + // The makings are recorded once, in a command buffer of their own at the submission's head, + // ahead of the first part's acquire (`crate::handed`). + let made = match making.is_empty() { + true => None, + false => { + let (upload, done) = Upload::hand_over(core, &making, Hand::Make); + if let (true, Err(loss)) = (ok.is_ok(), done) { + ok = Err(loss); + } + upload + } + }; segments.splice( 0..0, uploads.iter().map(|upload| Staged { @@ -2816,33 +2918,47 @@ fn submit(core: &Core, value: u64, uploads: Vec, batch: Batch) { true => &starts[..], false => &[][..], }; - let mut handed = Vec::new(); + let mut hands = Vec::new(); let mut parts = self::parts( segments, uploads.len(), leads, (core.done.progress, value), - &planes, - |planes, acquire| { - let (upload, done) = Upload::hand_over(core, planes, acquire); + &handed, + |handed, acquire| { + let hand = match acquire { + true => Hand::Acquire, + false => Hand::Release, + }; + let (upload, done) = Upload::hand_over(core, handed, hand); if let (true, Err(loss)) = (ok.is_ok(), done) { ok = Err(loss); } - let mut upload = upload?; - match (acquire, apart) { - (true, false) => core.counters.count(Metric::D3d11PlaneSubmissions), - (true, true) => { - core.counters.count(Metric::D3d11PlaneSubmissions); + let upload = upload?; + if acquire && handed.iter().any(Handed::d3d11) { + core.counters.count(Metric::D3d11PlaneSubmissions); + if apart { core.counters.count(Metric::D3d11PlaneParts); } - (false, _) => (upload.held).extend(planes.iter().cloned().map(Held::Texture)), } let command = upload.command; - handed.push(upload); + hands.push(upload); Some(command) }, ); - uploads.extend(handed); + // The making's releases lead the submission, ahead of its first part's acquire. + if let (Some(upload), Some((_, first))) = (&made, parts.first_mut()) { + let command = vk::CommandBufferSubmitInfo::default().command_buffer(upload.command); + first.insert( + 0, + Staged { + command: Some(command), + ..Staged::default() + }, + ); + } + uploads.extend(hands); + uploads.extend(made); if ok.is_ok() { // The host's writes to the Shared memory its command buffers and copy-ins reach are the // GPU's before it runs, where the Shared type is not host-coherent (`crate::coherence`). diff --git a/crates/metal2vulkan-runtime/src/surface.rs b/crates/metal2vulkan-runtime/src/surface.rs index da774a892..2250d0df2 100644 --- a/crates/metal2vulkan-runtime/src/surface.rs +++ b/crates/metal2vulkan-runtime/src/surface.rs @@ -22,17 +22,17 @@ //! Both forms lay the planes alike: one pitch for every plane, and each plane at an exact start. use crate::block::Block; -use crate::buffer::{Buffer, BufferObject}; +use crate::buffer::Buffer; #[cfg(unix)] use crate::counters::Gauge; use crate::counters::{Metric, Part}; use crate::device::{lock, Core, Device}; use crate::error::{Error, Gap, Limit, Refusal}; use crate::export::{Export, ExportHandle}; +use crate::handed::Handed; use crate::hazard::HeapId; use crate::memory; -use crate::submit::Held; -use crate::texture::{Backing, SurfaceImage, Texture, TextureDescriptor, TextureObject}; +use crate::texture::{Backing, SurfaceImage, Texture, TextureDescriptor}; use crate::times::host_time; use ash::vk; use std::sync::atomic::AtomicU64; @@ -101,6 +101,42 @@ const IN_PLACE_USAGE: vk::ImageUsageFlags = vk::ImageUsageFlags::from_raw( /// `DRM_FORMAT_MOD_LINEAR`. const MOD_LINEAR: u64 = 0; +/// The tiling of a plane's image in place, in memory another API writes in place: linear, whose +/// texel layout the subresource layout states and which Vulkan takes as a host-accessible alias +/// in the general layout (section 12.11). No value names `VK_IMAGE_TILING_OPTIMAL`, and +/// [`make_image`], the one maker of such an image, takes its tiling from this type alone, so no +/// path places an optimal image in that memory. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum InPlaceTiling { + /// `VK_IMAGE_TILING_LINEAR`: an opaque handle's planes. + Linear, + /// `VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT` of `DRM_FORMAT_MOD_LINEAR` alone: a dma-buf's + /// planes. + DrmLinear, +} + +impl InPlaceTiling { + /// For the tests: every value. + #[cfg(test)] + pub(crate) const ALL: [InPlaceTiling; 2] = [InPlaceTiling::Linear, InPlaceTiling::DrmLinear]; + + /// The tiling `handle`'s planes take in place. + pub(crate) fn of(handle: ExportHandle) -> InPlaceTiling { + match handle { + ExportHandle::DmaBuf => InPlaceTiling::DrmLinear, + _ => InPlaceTiling::Linear, + } + } + + /// Its Vulkan tiling. + pub(crate) fn vk(self) -> vk::ImageTiling { + match self { + InPlaceTiling::Linear => vk::ImageTiling::LINEAR, + InPlaceTiling::DrmLinear => vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT, + } + } +} + /// A plane's image in place, as `Query::plane` finds it. struct PlaneImage { /// Every bit of `IN_PLACE_USAGE`, storage and the plan's usage that its tiling holds @@ -221,9 +257,11 @@ pub struct Surface { handle: Option, planes: Vec, kind: Kind, - /// In place, where the planes' moves to the general layout complete - /// ([`Surface::wait_until_ready`]); `None` in the copy form, whose images the other API - /// never reaches, and for a Direct3D 11 import, whose images are general as imported. + /// Where its making completes, the point the other API's first access waits for + /// ([`Surface::wait_until_ready`]): in place, its planes' ([`Work::create`]); in the copy + /// form, its block's. `None` for a Direct3D 11 import, which Direct3D 11 made. + /// + /// [`Work::create`]: crate::submit::Work::create ready: Option>, } @@ -341,12 +379,9 @@ impl Query<'_> { } } - /// The tiling the handle's planes take in place. + /// The tiling the handle's planes take in place ([`InPlaceTiling`]). fn tiling(&self) -> vk::ImageTiling { - match self.handle { - ExportHandle::DmaBuf => vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT, - _ => vk::ImageTiling::LINEAR, - } + InPlaceTiling::of(self.handle).vk() } /// The external memory features of an image of `format`, `usage` and view-format `list` @@ -657,9 +692,10 @@ struct Made { } /// Makes a plane's image of `format`, `usage` and view-format `list`, external as `handle`, in -/// `tiling`: for a dma-buf, `DRM_FORMAT_MOD_LINEAR` with the implicit list where `at` is `None`, -/// else the explicit layout at `at` (offset, pitch). Its requirements and its subresource layout -/// come with it. Timed in [`Metrics::image_creates`](crate::Metrics::image_creates). +/// the handle's [`InPlaceTiling`]: for a dma-buf, `DRM_FORMAT_MOD_LINEAR` with the implicit list +/// where `at` is `None`, else the explicit layout at `at` (offset, pitch). Its requirements and +/// its subresource layout come with it. Timed in +/// [`Metrics::image_creates`](crate::Metrics::image_creates). /// /// # Safety /// @@ -671,7 +707,8 @@ unsafe fn make_image( handle: ExportHandle, at: Option<(u64, u64)>, ) -> Result { - let dma = handle == ExportHandle::DmaBuf; + let tiling = InPlaceTiling::of(handle); + let dma = tiling == InPlaceTiling::DrmLinear; let modifiers = [MOD_LINEAR]; let mut implicit = vk::ImageDrmFormatModifierListCreateInfoEXT::default().drm_format_modifiers(&modifiers); @@ -688,12 +725,9 @@ unsafe fn make_image( .plane_layouts(&layouts); let mut external = vk::ExternalMemoryImageCreateInfo::default().handle_types(handle.vk()); let mut formats = vk::ImageFormatListCreateInfo::default().view_formats(list); - let (tiling, aspect) = match dma { - true => ( - vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT, - vk::ImageAspectFlags::MEMORY_PLANE_0_EXT, - ), - false => (vk::ImageTiling::LINEAR, vk::ImageAspectFlags::COLOR), + let aspect = match dma { + true => vk::ImageAspectFlags::MEMORY_PLANE_0_EXT, + false => vk::ImageAspectFlags::COLOR, }; let mut info = vk::ImageCreateInfo::default() .image_type(vk::ImageType::TYPE_2D) @@ -706,7 +740,7 @@ unsafe fn make_image( .mip_levels(1) .array_layers(1) .samples(vk::SampleCountFlags::TYPE_1) - .tiling(tiling) + .tiling(tiling.vk()) .usage(usage) .sharing_mode(vk::SharingMode::EXCLUSIVE) // An external image is made undefined (`VUID-VkImageCreateInfo-pNext-01443`). @@ -799,10 +833,13 @@ impl Device { /// **Form.** In place where the device's queries and the images made hold the layout exactly /// (the crate's guide says what each handle asks); else the copy form, whose reason the /// answer names, laid alike at the tightest pitch the multiples allow. Decided at the make. - /// The call makes no submission and waits for nothing: each plane's image in place moves to - /// the general layout in the runtime's submission that carries the next commit, and the other - /// API's first write into the memory waits for it ([`Surface::wait_until_ready`]), which has - /// it go at once where none has. Each form counts in + /// The call makes no submission and waits for nothing. The memory is the runtime's until its + /// making: in place, each plane's image moves out of the undefined layout to the general one + /// and is released to the other API's queue family in one barrier, and in the copy form the + /// block's buffer is released, at the head of the runtime's submission that carries the next + /// commit, ahead of every command buffer committed after the make. The other API's first + /// access waits for that submission ([`Surface::wait_until_ready`]), which has it go at once + /// where none has. Each form counts in /// [`Metrics::surfaces_in_place`](crate::Metrics::surfaces_in_place) or /// [`Metrics::surfaces_copied`](crate::Metrics::surfaces_copied). /// @@ -900,10 +937,13 @@ impl Device { } } step!("textures"); - // The images move to the general layout in the next commit's submission, which the make - // does not wait for: the consumer waits for it on its own thread - // (`Surface::wait_until_ready`). - let ready = Some(core.work.ready_point()); + // The images move to the general layout and go to the other API in the next commit's + // submission, which the make does not wait for: the consumer waits for it on its own + // thread (`Surface::wait_until_ready`). + let images: Vec = (planes.iter()) + .map(|texture| Handed::Image(texture.held_image())) + .collect(); + let ready = Some(core.work.create(core, &images)?); step!("ready point"); core.counters.count(Metric::SurfacesInPlace); let view = View { @@ -959,12 +999,13 @@ impl Device { row_pitch: pitch, }) .collect(); + let ready = block.ready(); let surface = Surface { device: self.clone(), handle: Some(spec.handle), planes, kind: Kind::Copy(block, buffer), - ready: None, + ready, }; let export = SurfaceExport { export, @@ -1109,6 +1150,7 @@ impl Device { view_formats: m.list, block: Some(Arc::clone(&block)), d3d11: false, + family: spec.handle.family(), linear_attachment: linear, }) .collect(); @@ -1401,6 +1443,7 @@ impl Device { view_formats: m.list, block: None, d3d11: false, + family: spec.handle.family(), linear_attachment: linear, }); } @@ -1430,19 +1473,19 @@ impl Surface { &self.planes } + /// For the device tests: its ready point's progress value, 0 until the submission that takes + /// its making's upload sets it; `None` without one. + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + pub(crate) fn ready_for_test(&self) -> Option { + (self.ready.as_ref()).map(|ready| ready.load(std::sync::atomic::Ordering::Relaxed)) + } + /// The handle an exported surface's memory is shared through; `None` for an import of /// Direct3D 11 textures (`Device::import_d3d11_surface`, on Windows). pub fn handle(&self) -> Option { self.handle } - /// The other API's queue family, which the surface's acquires and releases name: the - /// export's handle's, and `VK_QUEUE_FAMILY_EXTERNAL` for an import of Direct3D 11 textures. - pub(crate) fn family(&self) -> u32 { - self.handle - .map_or(vk::QUEUE_FAMILY_EXTERNAL, ExportHandle::family) - } - /// The surface of Direct3D 11 textures' `planes`, each in memory of its own /// (`Device::import_d3d11_surface`). #[cfg(windows)] @@ -1456,34 +1499,6 @@ impl Surface { } } - /// The copy form's buffer, over the whole block; `None` in place. - pub(crate) fn copied(&self) -> Option<&Buffer> { - match &self.kind { - Kind::Copy(_, buffer) => Some(buffer), - Kind::InPlace(_) => None, - #[cfg(windows)] - Kind::Imported => None, - } - } - - /// The buffer in place, where [`buffer`](Self::buffer) has made it. - pub(crate) fn made_buffer(&self) -> Option { - match &self.kind { - Kind::InPlace(view) => match &*lock(&view.state) { - ViewState::Made(buffer) => Some(buffer.clone()), - ViewState::Source(_) => None, - }, - Kind::Copy(..) => None, - #[cfg(windows)] - Kind::Imported => None, - } - } - - /// Whether the surface is `core`'s. - pub(crate) fn is_of(&self, core: &Arc) -> bool { - Arc::ptr_eq(self.device.core(), core) - } - /// An IOSurface-backed buffer's counterpart (`MTLBuffer.h` speaks of a buffer "backed by an /// IOSurface"; `MTLDevice.h` makes a plane's texture from one, /// `newTextureWithDescriptor:iosurface:plane:`, and no buffer): a buffer over the surface's @@ -1501,15 +1516,14 @@ impl Surface { /// memory type the planes' imports took, which the call attempts only where the fd's query /// and the buffer's memory requirements list that type. Either counts in /// [`Gauges::surface_buffers`](crate::Gauges::surface_buffers) while it lives, a dma-buf's - /// also in [`Gauges::surface_imports`](crate::Gauges::surface_imports). The first call also - /// records the buffer's acquire from the other API's queue family, as - /// [`external_writes_done`](Self::external_writes_done) records the planes', into the upload - /// that goes ahead of every command buffer committed after it, counted in - /// [`Metrics::external_acquires`](crate::Metrics::external_acquires); from then each - /// [`external_writes_done`](Self::external_writes_done) acquires the buffer with the planes, - /// and each [`release_surface_to_external`](crate::BlitCommandEncoder::release_surface_to_external) - /// releases it with them. In the copy form the buffer is the block's, which the planes are - /// textures over, so the planes' copies carry the bytes between them. + /// also in [`Gauges::surface_imports`](crate::Gauges::surface_imports). The call records + /// nothing: the buffer is in memory the other API owns between the runtime's submissions, + /// and, as the planes are, it is acquired from the other API's queue family at the head of + /// each `vkQueueSubmit2` that uses it and released to it at that submission's end + /// ([`Metrics::external_acquires`](crate::Metrics::external_acquires), + /// [`Metrics::external_releases`](crate::Metrics::external_releases)). In the copy form the + /// buffer is the block's, which the planes are textures over, so the planes' copies carry the + /// bytes between them. /// /// **Order.** The surface, its planes (and their views) and its buffer are one resource in /// the runtime's ordering of reads and writes, as a heap's resources are: a write through the @@ -1546,8 +1560,8 @@ impl Surface { /// more than its length, or require an allocation of its own; /// [`Limit::NoImport`] for a dma-buf on a device whose buffers import /// none; [`Error::Fd`]; [`Limit::MemoryAllocations`]; [`Limit::BlockIds`]; [`Error::Vulkan`] - /// where the buffer, its import, its binding or the upload's command buffer cannot be made. - /// A refused call makes nothing, and a later call tries again. + /// where the buffer, its import or its binding cannot be made. A refused call makes nothing, + /// and a later call tries again. pub fn buffer(&self) -> Result { let view = match &self.kind { Kind::Copy(_, buffer) => return Ok(buffer.clone()), @@ -1575,18 +1589,6 @@ impl Surface { Source::DmaBuf(fd, index) => crate::import::surface_import(core, fd, view.len, *index)?, }; let block = Arc::new(block); - let (raw, _) = block.memory.range(0); - let acquire = [acquire(self.family(), core.family, raw)]; - let held = [Held::Block(Arc::clone(&block))]; - core.work.upload(core, None, held, |device, command| { - let dependency = vk::DependencyInfo::default().buffer_memory_barriers(&acquire); - // SAFETY: the upload's command buffer is recording, under the work lock; the buffer - // spans the surface's memory, which the upload holds, and a dma-buf's foreign family - // is enabled. - unsafe { device.cmd_pipeline_barrier2(command, &dependency) }; - })?; - core.counters.count(Metric::UploadBarriers); - core.counters.count(Metric::ExternalAcquires); let unit = Some(Arc::clone(&view.unit)); let buffer = self.device.buffer(block, 0, view.len, None, None, unit); *state = ViewState::Made(buffer.clone()); @@ -1597,15 +1599,16 @@ impl Surface { /// the calling thread, the consumer's own. Metal has no such wait: an IOSurface's planes are /// ready as it is made. /// - /// In place, each plane's image moves out of the undefined layout into the general one in - /// the runtime's first submission after the make, which - /// [`Device::new_exported_surface`] does not wait for; that move may discard what the memory - /// holds, so the other API's first write into the memory comes after it. The call returns - /// once that submission has completed, and has it go at once where it is not yet made. The - /// runtime's own commands need no such wait: the move goes ahead of every command buffer - /// committed after the make. In the copy form, whose planes' images the other API never - /// reaches, and for a Direct3D 11 import (`Device::import_d3d11_surface`, on Windows), whose - /// images are general as imported, the call returns at once. Each call in place counts in + /// The surface is the runtime's until its making, in the runtime's first submission after the + /// make, which [`Device::new_exported_surface`] does not wait for: in place, each plane's + /// image moves out of the undefined layout into the general one, a move that may discard + /// what the memory holds, and is released to the other API's queue family; in the copy form, + /// the block's buffer is released ([`Block::wait_until_ready`]). So the other API's first + /// access of the memory comes after that submission. The call returns once it has completed, + /// and has it go at once where it is not yet made. The runtime's own commands need no such + /// wait: the making goes ahead of every command buffer committed after the make. For a + /// Direct3D 11 import (`Device::import_d3d11_surface`, on Windows), which Direct3D 11 made, + /// the call returns at once. Each call that waits counts in /// [`Metrics::surface_waits`](crate::Metrics::surface_waits), with its time and the /// submissions it waited for. /// @@ -1620,106 +1623,36 @@ impl Surface { if core.closed() { return Err(Error::Quiesced); } - // The progress reached is read before `ready_value` can wake the submit thread: a - // submission it then makes, the moves' among them, cannot have completed by the read, so - // it is counted. - let began = host_time(); - // SAFETY: the progress semaphore is the device's, live while the core is. - let reached = unsafe { core.device.get_semaphore_counter_value(core.done.progress) } - .map_err(Error::vulkan("vkGetSemaphoreCounterValue"))?; - let value = core.work.ready_value(ready); - core.done.wait(core, value)?; - let waited = host_time().saturating_sub(began); - core.counters - .surface_wait(waited, value.saturating_sub(reached)); + let (waited, submissions) = core.work.wait_ready(core, ready)?; + core.counters.surface_wait(waited, submissions); Ok(()) } - /// No Metal counterpart: the other API's accesses of this surface are done, and the - /// runtime's commands may now read and write its planes, as - /// [`Block::external_writes_done`] is for a block. The consumer calls it once the other API's - /// work that accessed the surface (work that wrote it, or that read it after a release) has + /// No Metal counterpart: the other API's writes into this surface are done, and the + /// runtime's commands may now read its planes, as [`Block::external_writes_done`] is for a + /// block. The consumer calls it once the other API's work that wrote the surface has /// completed, and before it commits the command buffers that use the surface. /// - /// In place, the call records each plane's image's acquire from the other API's queue - /// family (`VK_QUEUE_FAMILY_FOREIGN_EXT` for a dma-buf, `VK_QUEUE_FAMILY_EXTERNAL` for an - /// opaque handle), the general layout kept, and the surface's buffer's where - /// [`buffer`](Self::buffer) has made it, into the upload that goes ahead of every command - /// buffer committed after it: one barrier of the planes and the buffer, counted in - /// [`Metrics::external_acquires`](crate::Metrics::external_acquires). In the copy form it is - /// the block's acquire, and the submissions copy the bytes into the planes' images. The - /// contract is the block's. For a Direct3D 11 import (`Device::import_d3d11_surface`, on - /// Windows) the call records nothing and changes nothing: each `vkQueueSubmit2` that uses - /// its planes acquires them itself, from the general layout, the first acquire included - /// ([`Metrics::d3d11_plane_submissions`](crate::Metrics::d3d11_plane_submissions)), so what - /// Direct3D 11 wrote is kept whether the call comes before or after the commit. + /// In the copy form it is the block's call: the planes' images take the block's bytes again + /// before their next use. In place, and for a Direct3D 11 import + /// (`Device::import_d3d11_surface`, on Windows), the call records nothing and changes + /// nothing: each `vkQueueSubmit2` that uses the planes, or the buffer, acquires them from the + /// other API's queue family at its head, the general layout kept, and releases them to it at + /// its end ([`Metrics::external_acquires`](crate::Metrics::external_acquires), + /// [`Metrics::external_releases`](crate::Metrics::external_releases)), so what the other API + /// wrote is kept whether the call comes before or after the commit. /// - /// Err: [`Refusal::InScheduledHandler`] in a scheduled handler; [`Error::Quiesced`]; and - /// [`Error::Vulkan`] where the upload's command buffer cannot be made. + /// Err: in the copy form, what [`Block::external_writes_done`] returns. pub fn external_writes_done(&self) -> Result<(), Error> { - if let Kind::Copy(block, _) = &self.kind { - return block.external_writes_done(); + match &self.kind { + Kind::Copy(block, _) => block.external_writes_done(), + Kind::InPlace(_) => Ok(()), + #[cfg(windows)] + Kind::Imported => Ok(()), } - // Each `vkQueueSubmit2` that uses a Direct3D 11 import's planes acquires them itself. - if self.handle.is_none() { - return Ok(()); - } - crate::command::not_in_scheduled_handler()?; - let core = self.device.core(); - if core.closed() { - return Err(Error::Quiesced); - } - let images: Vec<_> = self.planes.iter().map(Texture::held_image).collect(); - let family = self.family(); - let acquires: Vec> = (self.planes.iter()) - .map(|texture| { - vk::ImageMemoryBarrier2::default() - .dst_stage_mask(vk::PipelineStageFlags2::ALL_COMMANDS) - .dst_access_mask(vk::AccessFlags2::MEMORY_READ | vk::AccessFlags2::MEMORY_WRITE) - .old_layout(vk::ImageLayout::GENERAL) - .new_layout(vk::ImageLayout::GENERAL) - .src_queue_family_index(family) - .dst_queue_family_index(core.family) - .image(texture.image()) - .subresource_range(texture.whole()) - }) - .collect(); - let buffer = self.made_buffer(); - let buffers: Vec> = (buffer.iter()) - .map(|buffer| acquire(family, core.family, buffer.device_range().0)) - .collect(); - let held = std::array::from_fn::<_, { MAX_PLANES + 1 }, _>(|at| match &buffer { - Some(buffer) if at == MAX_PLANES => Held::Block(Arc::clone(buffer.held().0)), - _ => Held::Texture(Arc::clone(&images[at % images.len()])), - }); - core.work.upload(core, None, held, |device, command| { - let dependency = vk::DependencyInfo::default() - .image_memory_barriers(&acquires) - .buffer_memory_barriers(&buffers); - // SAFETY: the upload's command buffer is recording, under the work lock; it holds the - // images, which are in the general layout, and the buffer's memory, and a dma-buf's - // foreign family is enabled. - unsafe { device.cmd_pipeline_barrier2(command, &dependency) }; - })?; - core.counters.count(Metric::UploadBarriers); - core.counters.count(Metric::ExternalAcquires); - Ok(()) } } -/// The acquire of a surface's buffer `buffer` from the other API's queue family `from` to the -/// runtime's `to`, made visible to every later command. -fn acquire(from: u32, to: u32, buffer: vk::Buffer) -> vk::BufferMemoryBarrier2<'static> { - vk::BufferMemoryBarrier2::default() - .dst_stage_mask(vk::PipelineStageFlags2::ALL_COMMANDS) - .dst_access_mask(vk::AccessFlags2::MEMORY_READ | vk::AccessFlags2::MEMORY_WRITE) - .src_queue_family_index(from) - .dst_queue_family_index(to) - .buffer(buffer) - .offset(0) - .size(vk::WHOLE_SIZE) -} - /// The flags every allocation of a dma-buf surface's memory takes: device addresses, which its /// buffer needs (`VUID-vkBindBufferMemory-bufferDeviceAddress-03339`). #[cfg(unix)] diff --git a/crates/metal2vulkan-runtime/src/tests/d3d11.rs b/crates/metal2vulkan-runtime/src/tests/d3d11.rs index 61b08cf51..972aea00c 100644 --- a/crates/metal2vulkan-runtime/src/tests/d3d11.rs +++ b/crates/metal2vulkan-runtime/src/tests/d3d11.rs @@ -12,7 +12,7 @@ //! staging copies (`CopyResource`, `Map`). Each of rt's three submissions keeps the planes, //! acquires them from `VK_QUEUE_FAMILY_EXTERNAL` at its start and releases them at its end: three //! in `Metrics::d3d11_plane_submissions`, three acquires and three releases, the consumer's -//! `external_writes_done` and `release_surface_to_external` calls, still made, recording none. +//! `external_writes_done` calls, still made, recording none. //! Two reads committed back to back on queues of their own, the first not waited for before the //! second commits, read picture 1 exactly and count two plane-keeping submissions, two acquires //! and two releases; on an instance without the validation layer, 64 reads committed back to back @@ -381,8 +381,8 @@ mod on_device { .unwrap_or_else(|error| panic!("{name}: the import: {error}")) } - /// rt writes `bytes` (packed) into both planes and releases them to Direct3D 11, and - /// waits for the command buffer. + /// rt writes `bytes` (packed) into both planes, its submission releasing them to + /// Direct3D 11 at its end, and waits for the command buffer. fn rt_write(name: &str, device: &Device, surface: &Surface, bytes: &[u8]) { let len = bytes.len() as u64; let block = (device.take_block(MemoryClass::Shared, len)).expect("a block"); @@ -404,8 +404,6 @@ mod on_device { (encoder.copy_from_buffer(&from, layout, size, texture, TexturePlace::default())) .unwrap_or_else(|error| panic!("{name}: the write: {error}")); } - (encoder.release_surface_to_external(surface)) - .unwrap_or_else(|error| panic!("{name}: the release: {error}")); encoder.end_encoding(); command_buffer.commit().expect("a commit"); finished(name, &command_buffer); diff --git a/crates/metal2vulkan-runtime/src/tests/export.rs b/crates/metal2vulkan-runtime/src/tests/export.rs index 592140283..188c7140b 100644 --- a/crates/metal2vulkan-runtime/src/tests/export.rs +++ b/crates/metal2vulkan-runtime/src/tests/export.rs @@ -2,11 +2,12 @@ //! gives a Private block of its own, counted live in `Gauges::exports` and its allocation's bytes //! in `Gauges::export_bytes` until its memory is freed, its make timed whole and by step (`Metrics::export_makes`, `export_allocations`, //! `export_handles`, `export_claims`: one call each, of the allocation's bytes, the steps within -//! the whole), which rt writes and releases (`BlitCommandEncoder::release_to_external`) twice, with no acquire -//! between, and whose handle a second device of the same physical device imports, reading rt's -//! second bytes through it and writing the whole block, which rt acquires -//! (`Block::external_writes_done`) and reads; an acquire or a release of a block that is not -//! exported is refused; each handle the device does not export is +//! the whole), released to the other API once at its making (`Block::wait_until_ready`), which rt +//! writes twice, each submission acquiring and releasing it, and whose handle a second device of +//! the same physical device imports, reading rt's second bytes through it and writing the whole +//! block, which rt's next submission acquires and reads (`Block::external_writes_done` records +//! nothing); the mark and the wait of a block that is not exported are refused; each handle the +//! device does not export is //! refused typed; an exported block holds no image (a texture //! over a buffer in it is the counted copy, and a heap texture in it is refused); and submissions //! beside 64 live exports, whose cost the harness's own row `export_submit_cost` times. @@ -171,15 +172,18 @@ mod on_device { } /// Each handle the device exports gives a Private block of its own, counted live in - /// `Gauges::exports`, that rt fills and releases to the other API's queue family in one - /// command buffer (`BlitCommandEncoder::release_to_external`, counted), then fills and - /// releases again in a second with no acquire between, as Vulkan allows; a second device of - /// the same physical device imports it and reads rt's second bytes from it once both have - /// completed; the second device then fills the whole block and releases it, and rt's acquire - /// (`Block::external_writes_done`, counted) lets a blit read its bytes. The gauge is back - /// once the block is given back. An acquire of a taken block, and a release of a buffer in - /// one, are `Refusal::NotExported`. Each handle it does not export is `Limit::NoExport`, and - /// a dma-buf on a device without the foreign queue family `Limit::ExportType`. + /// `Gauges::exports`, whose making releases it to the other API's queue family once: the + /// wait for it (`Block::wait_until_ready`, counted in `Metrics::surface_waits`) returns with + /// no command buffer committed, the one release counted and no acquire. rt fills it in one + /// command buffer, then fills it again in a second, each submission acquiring it from the + /// other API's queue family at its head and releasing it at its end (counted); a second + /// device of the same physical device imports it and reads rt's second bytes from it once + /// both have completed; the second device then fills the whole block and releases it, + /// `Block::external_writes_done` records nothing (no count), and the blit that reads the + /// other API's bytes acquires and releases the block in its own submission. The gauge is back + /// once the block is given back. The mark and the wait of a taken block are + /// `Refusal::NotExported`. Each handle it does not export is `Limit::NoExport`, and a dma-buf + /// on a device without the foreign queue family `Limit::ExportType`. #[test] fn every_device_exports_each_offered_handle_and_refuses_the_rest() { each_device("export", |name, instance, device| { @@ -191,16 +195,11 @@ mod on_device { Err(Error::Refused(Refusal::NotExported { block })) if block == taken.id => {} other => panic!("{name}: an acquire of a taken block: {other:?}"), } - let in_taken = (device.new_buffer(taken.id, 0, LEN, None)).expect("a buffer"); - let queue = device.new_command_queue(4).expect("a queue"); - let unused = queue.command_buffer().expect("a command buffer"); - let mut encoder = unused.blit_command_encoder().expect("an encoder"); - match encoder.release_to_external(&in_taken) { + match taken.wait_until_ready() { Err(Error::Refused(Refusal::NotExported { block })) if block == taken.id => {} - other => panic!("{name}: a release of a buffer in a taken block: {other:?}"), + other => panic!("{name}: the wait of a taken block: {other:?}"), } - encoder.end_encoding(); - drop((unused, queue, in_taken, taken)); + drop(taken); let mut exported = 0; for handle in ExportHandle::ALL { if !device.core().exports.offers(handle) || (handle.foreign() && !foreign) { @@ -226,7 +225,8 @@ mod on_device { m.export_claims, ] }; - let made = timed(&counters.metrics()); + let made_metrics = counters.metrics(); + let made = timed(&made_metrics); let (block, export) = (device.new_exported_block(handle, LEN)) .unwrap_or_else(|error| panic!("{name}: {handle:?}: {error}")); let steps: Vec = (timed(&counters.metrics()).iter().zip(made)) @@ -272,11 +272,32 @@ mod on_device { "{name}: {handle:?}: the export and its allocation's bytes counted" ); - // rt writes the block and releases it to the other API, twice: the second write - // takes no acquire after the first release, and the other API reads its bytes. + // The block's making releases it to the other API once, with no command buffer + // committed: the wait has its submission go. + let handed = |m: &Metrics| [m.external_acquires, m.external_releases]; + let delta = |before: [u64; 2]| { + let after = handed(&counters.metrics()); + [after[0] - before[0], after[1] - before[1]] + }; + let (waits, start) = (counters.metrics().surface_waits, handed(&made_metrics)); + (block.wait_until_ready()) + .unwrap_or_else(|error| panic!("{name}: {handle:?}: the wait: {error}")); + assert_eq!( + counters.metrics().surface_waits, + waits + 1, + "{name}: {handle:?}: the wait, counted" + ); + assert_eq!( + delta(start), + [0, 1], + "{name}: {handle:?}: the making's one release and no acquire" + ); + + // rt writes the block twice, each submission acquiring and releasing it, and the + // other API reads its bytes. let buffer = (device.new_buffer(block.id, 0, LEN, None)).expect("a buffer"); let queue = device.new_command_queue(4).expect("a queue"); - let releases = counters.metrics().external_releases; + let writes = handed(&counters.metrics()); for (low, high) in [(0x11, 0x22), (0x5a, 0xa5)] { let command_buffer = queue.command_buffer().expect("a command buffer"); let mut encoder = command_buffer.blit_command_encoder().expect("an encoder"); @@ -284,17 +305,15 @@ mod on_device { .unwrap_or_else(|error| panic!("{name}: {error}")); (encoder.fill_buffer(&buffer, LEN / 2..LEN, high)) .unwrap_or_else(|error| panic!("{name}: {error}")); - (encoder.release_to_external(&buffer)) - .unwrap_or_else(|error| panic!("{name}: {handle:?}: {error}")); encoder.end_encoding(); command_buffer.commit().expect("a commit"); finished(name, &command_buffer); assert_eq!(command_buffer.error(), None, "{name}"); } assert_eq!( - counters.metrics().external_releases, - releases + 2, - "{name}: the releases, counted" + delta(writes), + [2, 2], + "{name}: {handle:?}: each write's submission acquires and releases the block" ); let external = handle.family(); @@ -364,13 +383,13 @@ mod on_device { write.commit().expect("a commit"); finished(name, &write); assert_eq!(write.error(), None, "{name}"); - let acquires = counters.metrics().external_acquires; + let marked = handed(&counters.metrics()); (block.external_writes_done()) - .unwrap_or_else(|error| panic!("{name}: {handle:?}: the acquire: {error}")); + .unwrap_or_else(|error| panic!("{name}: {handle:?}: the mark: {error}")); assert_eq!( - counters.metrics().external_acquires, - acquires + 1, - "{name}: the acquire, counted" + delta(marked), + [0, 0], + "{name}: {handle:?}: external_writes_done records nothing" ); let mine_block = (device.take_block(MemoryClass::Shared, LEN)) .unwrap_or_else(|error| panic!("{name}: {error}")); @@ -383,6 +402,11 @@ mod on_device { back.commit().expect("a commit"); finished(name, &back); assert_eq!(back.error(), None, "{name}"); + assert_eq!( + delta(marked), + [1, 1], + "{name}: {handle:?}: the read's submission acquires and releases the block" + ); let contents = mine.contents().expect("Shared"); // SAFETY: the buffer's bytes, which no command writes any more. let bytes = unsafe { std::slice::from_raw_parts(contents.as_ptr(), LEN as usize) }; diff --git a/crates/metal2vulkan-runtime/src/tests/surface.rs b/crates/metal2vulkan-runtime/src/tests/surface.rs index d84c9f96a..67f7f7726 100644 --- a/crates/metal2vulkan-runtime/src/tests/surface.rs +++ b/crates/metal2vulkan-runtime/src/tests/surface.rs @@ -5,20 +5,22 @@ //! 4K ones), its NVIDIA row (an opaque handle at a pitch multiple of 4, each plane directly below //! the one before) and a copy-form row (an opaque handle at a pitch multiple of 4096, which no //! driver's fixed pitch of these pictures meets). Each surface's layout is checked against the -//! rule (plane 0 at 0, one pitch, exact starts); a second device of the same physical device -//! imports the handle and writes three pictures, each acquired by rt and read through its plane +//! rule (plane 0 at 0, one pitch, exact starts); its ready wait waits once, for the submission of +//! its making, which releases it to the other API once; a second device of the same physical +//! device imports the handle and writes three pictures, each read by rt through its plane //! textures by a blit into a Shared buffer whose bytes the host compares (a consumer's CPU read of -//! a decoded picture); rt releases the third to the second device's read, which hands it back with -//! nothing written, then acquires and reads it again, each read from zeroed bytes and none a copy -//! in place (the reference round: a decoder's reference picture); rt copies a picture into the planes and releases them, and the second -//! device reads it through the handle (the encode round); rt clears each plane in a render pass, -//! reads it, and releases it to the second device's read (the render round). Then the buffer -//! round: the surface's buffer, made at its first call and counted in the surface gauges (none in -//! the copy form, whose buffer is its block's), reads two pictures the second device wrote (the -//! first through the buffer's own acquire at its make, the second through the next -//! `external_writes_done`), and a negative control of the layout (the same bytes read one byte -//! off) finds them wrong; a picture blitted into the buffer is read through the planes, and -//! released, through the handle. On the 1080p picture, where `llvm-as` assembles the examples' +//! a decoded picture), each read's submission acquiring the surface at its head and releasing it +//! at its end; the second device reads the third and hands it back with nothing written, and rt +//! reads it again, each read from zeroed bytes and none a copy in place (the reference round: a +//! decoder's reference picture); rt copies a picture into the planes and the second device reads +//! it through the handle (the encode round); rt clears each plane in a render pass and reads it, +//! and the second device reads it (the render round). Then the buffer round: the surface's +//! buffer, made at its first call with nothing recorded and counted in the surface gauges (none +//! in the copy form, whose buffer is its block's), reads two pictures the second device wrote, +//! and a negative control of the layout (the same bytes read one byte off) finds them wrong; a +//! picture blitted into the buffer is read through the planes and through the handle. Every +//! hand-over is the submission's own: no release call exists. On the 1080p picture, where +//! `llvm-as` assembles the examples' //! library, a kernel writes a picture through the buffer and the encoder's next kernel reads //! plane 0 through a view: its texels exact, and in place one barrier more than a control whose //! first kernel writes a buffer of its own, the ordering a resource outside the surface's unit @@ -29,6 +31,31 @@ //! //! The second device stands in for the other API, as in the export tests: a device of another //! instance cannot run under the validation layer. +//! +//! On every host, with no device: no plane's image in place is optimal (`InPlaceTiling`). + +use crate::surface::InPlaceTiling; +use ash::vk; + +/// No path places an optimal image in memory another API writes in place: a plane's image in +/// place takes its tiling from `InPlaceTiling` alone, and no value of it is +/// `VK_IMAGE_TILING_OPTIMAL`, whose texel layout Vulkan leaves to the implementation (section +/// 12.11 takes only linear images as host-accessible aliases). Each handle's tiling is one of +/// them: the dma-buf's the `DRM_FORMAT_MOD_LINEAR` modifier's, every other handle's linear. +#[test] +fn no_plane_in_place_takes_the_optimal_tiling() { + for tiling in InPlaceTiling::ALL { + assert!(tiling.vk() != vk::ImageTiling::OPTIMAL, "{tiling:?}"); + } + for handle in crate::ExportHandle::ALL { + let tiling = InPlaceTiling::of(handle); + let expected = match handle { + crate::ExportHandle::DmaBuf => vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT, + _ => vk::ImageTiling::LINEAR, + }; + assert!(tiling.vk() == expected, "{handle:?}: {tiling:?}"); + } +} #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod on_device { @@ -556,7 +583,7 @@ mod on_device { (before.submissions, before.surface_waits), "{label}: the make's submissions and waits" ); - // The other API's first write waits for the planes' moves. + // The other API's first write waits for the surface's making. let began = Instant::now(); (surface.wait_until_ready()) .unwrap_or_else(|error| panic!("{label}: the ready wait: {error}")); @@ -566,44 +593,42 @@ mod on_device { let wait_nanos = ready.surface_wait_nanos - after.surface_wait_nanos; let behind = ready.surface_wait_submissions - after.surface_wait_submissions; match form { - SurfaceForm::InPlace => { - assert_eq!( - after.surfaces_in_place, - before.surfaces_in_place + 1, - "{label}" - ); - // The ready wait waits once, for the submission of the moves, which - // it has go: nothing else submits here, so the moves are still - // pending at its flush, and their submission, made after the wait - // began, is counted, however fast the device completes it. - assert_eq!(waited, 1, "{label}: the ready wait counted"); - assert!(behind >= 1, "{label}: {behind} submissions waited for"); - assert!( - ready.submissions > after.submissions, - "{label}: the moves' submission made by the ready wait" - ); - assert!( - wait_nanos <= readied.as_nanos() as u64, - "{label}: the wait's {wait_nanos} ns within the call's {readied:?}" - ); - assert!( - ready.surface_wait_max_nanos >= wait_nanos, - "{label}: the longest wait" - ); - } + SurfaceForm::InPlace => assert_eq!( + after.surfaces_in_place, + before.surfaces_in_place + 1, + "{label}" + ), SurfaceForm::Copy(_) => { - assert_eq!( - after.surfaces_copied, - before.surfaces_copied + 1, - "{label}" - ); - assert_eq!( - (waited, wait_nanos, behind), - (0, 0, 0), - "{label}: the copy form's ready wait waits for nothing" - ); + assert_eq!(after.surfaces_copied, before.surfaces_copied + 1, "{label}") } } + // In either form the ready wait waits once, for the submission of the + // making, which it has go: nothing else submits here, so the making is still + // pending at its flush, and its submission, made after the wait began, is + // counted, however fast the device completes it. The making releases the + // surface's memory once and acquires nothing. + assert_eq!(waited, 1, "{label}: the ready wait counted"); + assert!(behind >= 1, "{label}: {behind} submissions waited for"); + assert!( + ready.submissions > after.submissions, + "{label}: the making's submission made by the ready wait" + ); + assert!( + wait_nanos <= readied.as_nanos() as u64, + "{label}: the wait's {wait_nanos} ns within the call's {readied:?}" + ); + assert!( + ready.surface_wait_max_nanos >= wait_nanos, + "{label}: the longest wait" + ); + assert_eq!( + ( + ready.external_acquires - after.external_acquires, + ready.external_releases - after.external_releases + ), + (0, 1), + "{label}: the making's one release" + ); let index = export.export.memory_type; let flags = flag_names(kinds.memory_types_as_slice()[index as usize].property_flags); @@ -651,13 +676,14 @@ mod on_device { [layout[0].row_pitch; 2], ); - // Three pictures, each written by the other API and read by rt. - let acquires = counters.metrics().external_acquires; + // Three pictures, each written by the other API and read by rt, each read's + // submission acquiring and releasing the surface. + let pictures = counters.metrics(); for seed in 1..=3 { fill(&theirs, |out| lay_picture(seed, planes, &layout, out)); other.write(&label, &theirs); (surface.external_writes_done()) - .unwrap_or_else(|error| panic!("{label}: the acquire: {error}")); + .unwrap_or_else(|error| panic!("{label}: the mark: {error}")); rt_read(&label, &queue, &surface, planes, &mine); assert_eq!( wrong(seed, planes, (offsets, pitches), bytes_of(&mine)), @@ -665,25 +691,22 @@ mod on_device { "{label}: picture {seed} read by rt" ); } + let read = counters.metrics(); assert_eq!( - counters.metrics().external_acquires, - acquires + 3, + ( + read.external_acquires - pictures.external_acquires, + read.external_releases - pictures.external_releases + ), + (3, 3), "{label}" ); - // The reference round: picture 3, which rt acquired and read, is released to - // the other API's read (a decoder reading its reference picture) and handed - // back with nothing written; rt acquires it again and reads it once more. - // Each read starts from zeroed bytes; in place the round copies nothing. + // The reference round: picture 3, which rt read and its submission released, + // is read by the other API (a decoder reading its reference picture) and + // handed back with nothing written; rt reads it once more, its submission + // acquiring it again. Each read starts from zeroed bytes; in place the round + // copies nothing. let held = counters.metrics(); - let command_buffer = queue.command_buffer().expect("a command buffer"); - let mut encoder = command_buffer.blit_command_encoder().expect("an encoder"); - (encoder.release_surface_to_external(&surface)) - .unwrap_or_else(|error| panic!("{label}: the reference release: {error}")); - encoder.end_encoding(); - command_buffer.commit().expect("a commit"); - finished(&label, &command_buffer); - assert_eq!(command_buffer.error(), None, "{label}"); fill(&theirs, |out| out.fill(0)); other.read(&label, &theirs, true); assert_eq!( @@ -692,13 +715,13 @@ mod on_device { "{label}: the reference picture read through the handle" ); (surface.external_writes_done()) - .unwrap_or_else(|error| panic!("{label}: the re-acquire: {error}")); + .unwrap_or_else(|error| panic!("{label}: the mark: {error}")); fill(&mine, |out| out.fill(0)); rt_read(&label, &queue, &surface, planes, &mine); assert_eq!( wrong(3, planes, (offsets, pitches), bytes_of(&mine)), None, - "{label}: picture 3 read by rt after the re-acquire" + "{label}: picture 3 read by rt again" ); let handed = counters.metrics(); assert_eq!( @@ -716,7 +739,8 @@ mod on_device { ); } - // The encode round: rt copies a picture into the planes and releases them. + // The encode round: rt copies a picture into the planes, its submission + // acquiring and releasing them, and the other API reads it. let (_source_block, source) = shared(&device, packed(planes).2); fill(&source, |out| { for (i, plane) in planes.iter().enumerate() { @@ -728,7 +752,7 @@ mod on_device { } } }); - let releases = counters.metrics().external_releases; + let encode = counters.metrics(); let command_buffer = queue.command_buffer().expect("a command buffer"); let mut encoder = command_buffer.blit_command_encoder().expect("an encoder"); for (i, (texture, plane)) in surface.planes().iter().zip(planes).enumerate() { @@ -746,16 +770,18 @@ mod on_device { )) .unwrap_or_else(|error| panic!("{label}: the encode copy: {error}")); } - (encoder.release_surface_to_external(&surface)) - .unwrap_or_else(|error| panic!("{label}: the release: {error}")); encoder.end_encoding(); command_buffer.commit().expect("a commit"); finished(&label, &command_buffer); assert_eq!(command_buffer.error(), None, "{label}"); + let encoded = counters.metrics(); assert_eq!( - counters.metrics().external_releases, - releases + 1, - "{label}" + ( + encoded.external_acquires - encode.external_acquires, + encoded.external_releases - encode.external_releases + ), + (1, 1), + "{label}: the encode's submission acquires and releases the surface" ); other.read(&label, &theirs, false); assert_eq!( @@ -764,8 +790,8 @@ mod on_device { "{label}: the encode round read through the handle" ); - // The render round: rt clears each plane in a render pass, reads it, and - // releases it to the other API's read. + // The render round: rt clears each plane in a render pass and reads it, and + // the other API reads it after the read's submission released it. let value = |plane: &Plane, i: usize| match plane.texel / u64::from(plane_channels(plane)) { @@ -812,13 +838,6 @@ mod on_device { "{label}: plane {i} rendered, read by rt" ); } - let command_buffer = queue.command_buffer().expect("a command buffer"); - let mut encoder = command_buffer.blit_command_encoder().expect("an encoder"); - (encoder.release_surface_to_external(&surface)) - .unwrap_or_else(|error| panic!("{label}: the release: {error}")); - encoder.end_encoding(); - command_buffer.commit().expect("a commit"); - finished(&label, &command_buffer); other.read(&label, &theirs, false); let read = bytes_of(&theirs); for (i, plane) in planes.iter().enumerate() { @@ -1003,12 +1022,13 @@ mod on_device { let (_mine_block, mine) = shared(device, packed(planes).2); let (offsets, pitches, _) = packed(planes); - // Picture 4, written before the buffer's make: its own acquire reads it. + // Picture 4, written before the buffer's make, which records nothing: the read's + // submission acquires the buffer with the planes. fill(&theirs, |out| lay_picture(4, planes, layout, out)); other.write(label, &theirs); (surface.external_writes_done()) - .unwrap_or_else(|error| panic!("{label}: the acquire: {error}")); - let (gauges, acquires) = (counters.gauges(), counters.metrics().external_acquires); + .unwrap_or_else(|error| panic!("{label}: the mark: {error}")); + let (gauges, metrics) = (counters.gauges(), counters.metrics()); let buffer = (surface.buffer()).unwrap_or_else(|error| panic!("{label}: the buffer: {error}")); // In place the export's size; in the copy form the block's length, which holds the planes. @@ -1048,10 +1068,11 @@ mod on_device { + u64::from(in_place && surface.handle() == Some(ExportHandle::DmaBuf)), "{label}: a dma-buf's buffer's import counted" ); + let made_metrics = counters.metrics(); assert_eq!( - counters.metrics().external_acquires, - acquires + u64::from(in_place), - "{label}: the buffer's acquire at its make" + (made_metrics.external_acquires, made_metrics.barriers), + (metrics.external_acquires, metrics.barriers), + "{label}: the buffer's make records nothing" ); assert!( buffer.contents().is_none(), @@ -1083,7 +1104,7 @@ mod on_device { fill(&theirs, |out| lay_picture(5, planes, layout, out)); other.write(label, &theirs); (surface.external_writes_done()) - .unwrap_or_else(|error| panic!("{label}: the acquire: {error}")); + .unwrap_or_else(|error| panic!("{label}: the mark: {error}")); read_whole(&buffer); assert_eq!( wrong(5, planes, at_layout, bytes_of(&whole)), @@ -1091,8 +1112,8 @@ mod on_device { "{label}: picture 5 read through the buffer" ); - // Picture 6, blitted into the buffer, read through the planes in the same encoder, then - // released and read through the handle. + // Picture 6, blitted into the buffer, read through the planes in the same encoder, and + // read through the handle once the submission released it. fill(&whole, |out| lay_picture(6, planes, layout, out)); let command_buffer = queue.command_buffer().expect("a command buffer"); let mut encoder = command_buffer.blit_command_encoder().expect("an encoder"); @@ -1113,8 +1134,6 @@ mod on_device { )) .unwrap_or_else(|error| panic!("{label}: the planes' read: {error}")); } - (encoder.release_surface_to_external(surface)) - .unwrap_or_else(|error| panic!("{label}: the release: {error}")); encoder.end_encoding(); command_buffer.commit().expect("a commit"); finished(label, &command_buffer); @@ -1180,9 +1199,9 @@ mod on_device { layout, } = *round; let counters = device.counters(); - // The surface is the runtime's again (the other API wrote nothing since its release). + // The other API wrote nothing since rt's last submission released the surface. (surface.external_writes_done()) - .unwrap_or_else(|error| panic!("{label}: the acquire: {error}")); + .unwrap_or_else(|error| panic!("{label}: the mark: {error}")); let total = buffer.length(); let words = u32::try_from(total / 4).expect("words"); let (_zeros_block, zeros) = shared(device, total); @@ -1308,18 +1327,16 @@ mod on_device { [metrics.submissions, metrics.held_release_starts] } - /// A surface let go of while its acquire is not yet submitted is freed with no later call. - /// For each row the device exports, on the 1080p picture: 32 surfaces, each acquired + /// A surface let go of while its making is not yet submitted is freed with no later call and + /// no submission: the upload that owes the making holds nothing (`Work::create`). For each + /// row the device exports, on the 1080p picture: 32 surfaces, each marked /// (`external_writes_done`) and never used, dropped together, their gauges back with no - /// other call, through one submission for the whole burst; a surface whose acquire the - /// submission of a command buffer that read it carried, dropped once that command buffer - /// completed, freed with no submission added; one acquired again after such a read and - /// dropped, freed through one submission; then 200 rounds of make, acquire, a read on every - /// other round and drop, each freed before the next, the gauges the same at rounds 100 and - /// 200. Without the drop's send the acquires' upload holds the planes until a later call, and - /// the waits for the frees time out. + /// submission; a surface a command buffer read, dropped once that command buffer completed, + /// freed with no submission added; one marked again after such a read and dropped, freed + /// with no submission; then 200 rounds of make, mark, a read on every other round and drop, + /// each freed before the next, the gauges the same at rounds 100 and 200. #[test] - fn every_device_frees_a_surface_at_its_drop_with_its_acquire_unsent() { + fn every_device_frees_a_surface_at_its_drop_with_its_making_unsent() { each_device("surface_drop", |name, _, device| { let counters = device.counters(); let queue = device.new_command_queue(4).expect("a queue"); @@ -1359,7 +1376,7 @@ mod on_device { .unwrap_or_else(|error| panic!("{label}: {error}")); form = Some(export.form); (surface.external_writes_done()) - .unwrap_or_else(|error| panic!("{label}: the acquire: {error}")); + .unwrap_or_else(|error| panic!("{label}: the mark: {error}")); surface }; let base = surface_gauges(&device); @@ -1386,11 +1403,11 @@ mod on_device { let burst = since(before); assert_eq!( burst, - [1, 1], - "{label}: one submission, one held release starting it, for the 32 drops" + [0, 0], + "{label}: no submission and no held release for the 32 drops" ); - // The acquire carried by a read's submission: the drop sends nothing. + // A surface a read's submission made and used: the drop sends nothing. let surface = acquired(); rt_read(&label, &queue, &surface, planes, &out); let before = sends(&device); @@ -1403,16 +1420,16 @@ mod on_device { "{label}: the drop of a surface read sends nothing" ); - // Acquired again after a read: the drop sends that acquire. + // Marked again after a read: the mark records nothing, and the drop sends nothing. let surface = acquired(); rt_read(&label, &queue, &surface, planes, &out); (surface.external_writes_done()) - .unwrap_or_else(|error| panic!("{label}: the second acquire: {error}")); + .unwrap_or_else(|error| panic!("{label}: the second mark: {error}")); let before = sends(&device); drop(surface); - freed("a surface acquired again after its read"); + freed("a surface marked again after its read"); let again = since(before); - assert_eq!(again, [1, 1], "{label}: the drop sends the second acquire"); + assert_eq!(again, [0, 0], "{label}: the drop sends nothing"); // 200 rounds, each freed before the next. let mut at = Vec::new(); @@ -1435,7 +1452,7 @@ mod on_device { println!( "surface-drop: {label}: form {form:?}; submissions and held releases that \ started one: 32 drops of surfaces never used {burst:?}, a read surface's \ - drop {used:?}, a drop after a second acquire {again:?}; 200 rounds: \ + drop {used:?}, a drop after a second mark {again:?}; 200 rounds: \ exports, their bytes, surface imports, theirs, surface buffers, textures \ {:?} at round 100 and {:?} at 200, blocks {} and {}; the device's held releases {} of {} bytes, \ {} starts", @@ -1451,6 +1468,91 @@ mod on_device { }); } + /// The order the contract states: the other API is handed none of the surface's memory before + /// its ready point. For each row the device exports, on the 1080p picture: at the make, the + /// ready point is not yet set and each plane in place still owes its move out of the undefined + /// layout; once the ready wait returns, the submission that carried the making has completed + /// (the device's completed progress is at or past the ready point) and no plane owes its move. + /// The copy form's ready point is its block's, and holds the same. + #[test] + fn every_device_completes_a_surface_s_making_before_its_ready_wait_returns() { + each_device("surface_ready_order", |name, _, device| { + let core = device.core(); + let planes = &PICTURES[0].1; + for row in &ROWS { + let handle = row.handle; + let foreign = device + .extensions() + .iter() + .any(|n| n.as_c_str() == ash::ext::queue_family_foreign::NAME); + let label = format!("{name}: {} {handle:?}", row.name); + if !device.core().exports.offers(handle) || (handle.foreign() && !foreign) { + println!("surface-order: {label}: not exported"); + continue; + } + let specs = [0, 1].map(|i| { + let p = planes[i]; + let mut descriptor = + TextureDescriptor::new(TextureType::Type2D, p.format, p.width, p.height); + descriptor.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + PlaneSpec { + descriptor, + index: None, + rows_below: row.rows_below(planes)[i], + } + }); + let spec = SurfaceSpec { + handle, + pitch_multiple: row.pitch_multiple, + start_multiple: row.start_multiple, + planes: &specs, + }; + let (surface, export) = (device.new_exported_surface(&spec)) + .unwrap_or_else(|error| panic!("{label}: {error}")); + let in_place = export.form == SurfaceForm::InPlace; + let images: Vec<_> = (surface.planes().iter()) + .map(|texture| texture.held_image()) + .collect(); + let owed = |images: &[std::sync::Arc]| -> Vec { + images.iter().map(|image| image.owes_home()).collect() + }; + assert_eq!( + surface.ready_for_test(), + Some(0), + "{label}: the making not yet submitted at the make" + ); + if in_place { + assert_eq!( + owed(&images), + [true, true], + "{label}: each plane owes its move at the make" + ); + } + (surface.wait_until_ready()) + .unwrap_or_else(|error| panic!("{label}: the ready wait: {error}")); + let ready = surface.ready_for_test().expect("a ready point"); + let completed = core.done.completed(); + println!( + "surface-order: {label}: form {:?}; the making at progress {ready}, the \ + device's completed progress {completed} as the wait returned", + export.form + ); + assert!( + ready > 0 && completed >= ready, + "{label}: the making's submission ({ready}) completed before the wait \ + returned ({completed})" + ); + if in_place { + assert_eq!( + owed(&images), + [false, false], + "{label}: no plane owes its move once ready" + ); + } + } + }); + } + /// A plane's texture viewed in another format of its own list, through a swizzle: for each /// row the device exports, on the 1080p picture, a surface whose luma's texture has /// `ShaderRead` and `PixelFormatView` usage, reached through its views alone, then a swizzled diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index ec7b018a1..d06757d4f 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -48,6 +48,7 @@ use crate::device::{lock, Core, Device}; use crate::error::{ Error, Gap, Limit, Refusal, RenderPassKind, StorageElementCase, TextureBacking, TextureViewKind, }; +use crate::handed::Handed; use crate::hazard::HeapId; use crate::host_bytes::HostBytes; use crate::memory::{self, Block, BlockId, MemoryClass, Own}; @@ -514,7 +515,8 @@ pub(crate) struct Image { foreign: Option<(vk::Buffer, u64, u64)>, /// An upload recorded its move from `first` to `home`. Read and set under the work lock. A /// Direct3D 11 plane is made with it set: it owes no move, as each acquire takes it from the - /// general layout ([`handed`](Self::handed)). + /// general layout ([`handed`](Self::handed)). An exported surface's plane in place is moved + /// by its making's command buffer instead, on the submit thread ([`made`](Self::made)). homed: AtomicBool, /// How the move home zeroes it, for an image the runtime places for a texture of its own /// (`Source::Plain` and `Source::Managed`); `None` for every other image. @@ -612,10 +614,12 @@ enum Under { Buffer { _buffer: Buffer }, /// A surface plane's image in place ([`Device::new_exported_surface`]): the opaque /// handle's allocation it is bound in, or none for a dma-buf's plane on its own import; or - /// a Direct3D 11 texture's plane (`d3d11`, `Device::import_d3d11_surface`, on Windows). + /// a Direct3D 11 texture's plane (`d3d11`, `Device::import_d3d11_surface`, on Windows). Its + /// hand-overs name the other API's queue family `family` (`crate::handed`). Surface { _block: Option>, d3d11: bool, + family: u32, }, } @@ -740,57 +744,89 @@ impl Zeroing { } impl Image { - /// Adds the image to `planes` where it is a Direct3D 11 texture's plane - /// (`Device::import_d3d11_surface`, on Windows) not yet there: each `vkQueueSubmit2` that - /// reaches such an image hands it over at its start and its end ([`handed`](Self::handed)). - pub(crate) fn keep_plane(self: &Arc, planes: &mut Vec>) { - if self.d3d11_plane() && !planes.iter().any(|kept| Arc::ptr_eq(kept, self)) { - planes.push(Arc::clone(self)); + /// Adds the image to `handed` where it is a surface's plane in memory another API shares (a + /// Direct3D 11 texture's, `Device::import_d3d11_surface` on Windows, or an exported + /// surface's in place) not yet there: each `vkQueueSubmit2` part that reaches such an image + /// hands it over at its start and its end ([`handed`](Self::handed)). + pub(crate) fn keep_handed(self: &Arc, handed: &mut Vec) { + if self.surface() { + Handed::Image(Arc::clone(self)).keep(handed); } } /// Whether it is a Direct3D 11 texture's plane (`Device::import_d3d11_surface`, on Windows). - fn d3d11_plane(&self) -> bool { + pub(crate) fn d3d11_plane(&self) -> bool { matches!(self._under, Some(Under::Surface { d3d11: true, .. })) } - /// A Direct3D 11 plane's hand-over between `VK_QUEUE_FAMILY_EXTERNAL` and the runtime's - /// queue family `family`, from and to the general layout, the first acquire included - /// (`VUID-VkImageMemoryBarrier-srcQueueFamilyIndex-12332`, `...-dstQueueFamilyIndex-12331`): - /// its acquire (`acquire`), made visible to every later command, or its release, after every - /// earlier command's writes. Direct3D 11 made the memory, so it is the existing owner the - /// first acquire takes it from, in the layout Vulkan implies for it outside Vulkan, general - /// (section 12.5.2, Table 17); the undefined layout the image is made in is "a placeholder" - /// (section 12.10.1), and naming it would let the move discard what Direct3D 11 wrote - /// (section 12.5.1). Recorded on the submit thread. + /// A surface plane's hand-over between the other API's queue family + /// (`VK_QUEUE_FAMILY_EXTERNAL`, or `VK_QUEUE_FAMILY_FOREIGN_EXT` for a dma-buf's plane) and + /// the runtime's queue family `family`, from and to the general layout, the first acquire + /// included (for a Direct3D 11 plane, `VUID-VkImageMemoryBarrier-srcQueueFamilyIndex-12332`, + /// `...-dstQueueFamilyIndex-12331`): its acquire (`acquire`), made visible to every later + /// command, or its release, after every earlier command's writes. Direct3D 11 made its + /// planes' memory, so it is the existing owner a first acquire takes it from, in the layout + /// Vulkan implies for it outside Vulkan, general (section 12.5.2, Table 17); the undefined + /// layout the image is made in is "a placeholder" (section 12.10.1), and naming it would let + /// the move discard what Direct3D 11 wrote (section 12.5.1). An exported surface's plane was + /// moved to the general layout and released at its making ([`made`](Self::made)), so its + /// every acquire follows a release of its own. Recorded on the submit thread. pub(crate) fn handed(&self, family: u32, acquire: bool) -> vk::ImageMemoryBarrier2<'static> { let (all, access) = ( vk::PipelineStageFlags2::ALL_COMMANDS, vk::AccessFlags2::MEMORY_READ | vk::AccessFlags2::MEMORY_WRITE, ); + let other = match self._under { + Some(Under::Surface { family, .. }) => family, + _ => vk::QUEUE_FAMILY_EXTERNAL, + }; let barrier = vk::ImageMemoryBarrier2::default() .old_layout(self.home) .new_layout(self.home) .image(self.image) .subresource_range(whole(self.aspects)); match acquire { - true => (barrier.src_queue_family_index(vk::QUEUE_FAMILY_EXTERNAL)) + true => (barrier.src_queue_family_index(other)) .dst_queue_family_index(family) .dst_stage_mask(all) .dst_access_mask(access), false => (barrier.src_queue_family_index(family)) - .dst_queue_family_index(vk::QUEUE_FAMILY_EXTERNAL) + .dst_queue_family_index(other) .src_stage_mask(all) .src_access_mask(vk::AccessFlags2::MEMORY_WRITE), } } + /// An exported surface's plane's making (`crate::handed`): its release from the runtime's + /// queue family `family` to the other API's, with its move from the undefined layout it is + /// made in to its home layout, general, where that move is still owed. Recorded once, in the + /// command buffer at the head of the submission that takes its make's upload, over memory rt + /// made that no other API has touched yet: the other API's first access waits for that + /// submission ([`Surface::wait_until_ready`](crate::Surface::wait_until_ready)), so the move + /// discards nothing. On the submit thread. + pub(crate) fn making(&self, family: u32) -> vk::ImageMemoryBarrier2<'static> { + let release = self.handed(family, false); + match self.homed.swap(true, Ordering::Relaxed) { + true => release, + false => release.old_layout(self.first), + } + } + + /// For the device tests: its move from the layout it is made in to its home layout is still + /// owed. + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + pub(crate) fn owes_home(&self) -> bool { + !self.homed.load(Ordering::Relaxed) + } + /// The image's move from the layout it is made in to its home layout, where no upload has /// recorded it yet: recorded once, by the upload that is to hold the image (a drawable's once /// for each acquire, [`Work::home`](crate::submit::Work::home)), with its zeroing between /// two moves where it has one ([`Zero`]). Under the work lock. pub(crate) fn homing(&self) -> Option { - if self.homed.swap(true, Ordering::Relaxed) { + // A surface's plane is moved, where it owes a move, by its making's command buffer + // ([`made`](Self::made)). + if self.surface() || self.homed.swap(true, Ordering::Relaxed) { return None; } // A drawable's image moves home at each acquire: from the present layout after a present. @@ -6472,6 +6508,9 @@ pub(crate) struct SurfaceImage { /// image, made undefined as a placeholder; each acquire takes it from the general layout, /// the layout Vulkan implies for it outside Vulkan (section 12.5.2, [`Image::handed`]). pub(crate) d3d11: bool, + /// The other API's queue family, which its hand-overs name (`crate::handed`): + /// `VK_QUEUE_FAMILY_EXTERNAL`, or `VK_QUEUE_FAMILY_FOREIGN_EXT` for a dma-buf's plane. + pub(crate) family: u32, /// The image is `LINEAR` and its format renders only through /// `VK_FORMAT_FEATURE_2_LINEAR_COLOR_ATTACHMENT_BIT_NV` (`crate::surface::Query::plane`): /// the image is marked ([`Image`]'s `linear_attachment`). @@ -6515,9 +6554,9 @@ impl Device { } /// The texture of a surface plane's image, at `index` as for [`Device::new_texture`]: its - /// home layout general, from undefined in the next upload, which goes ahead of every command - /// buffer committed after the make, or, a Direct3D 11 texture's, general as each acquire - /// takes it, with no move ([`Image::handed`]). Its format is the + /// home layout general, from undefined at its making, which the surface's make owes the + /// submission that takes its upload ([`Image::made`]), or, a Direct3D 11 texture's, general + /// as each acquire takes it, with no move ([`Image::handed`]). Its format is the /// descriptor's, a view of the image's own where they differ. The texture holds the image, /// which its drop frees with its memory. It takes `unit`'s id in the hazard sets, the /// surface's ([`HeapId::unit`]). @@ -6616,7 +6655,7 @@ impl Device { first: vk::ImageLayout::UNDEFINED, over: false, // A Direct3D 11 plane owes no move: each acquire takes it from the general layout - // (`Image::handed`). + // (`Image::handed`). An exported one's is its making's (`Image::made`). homed: AtomicBool::new(general), foreign: None, zero: None, @@ -6624,6 +6663,7 @@ impl Device { _under: Some(Under::Surface { _block: made.block, d3d11: general, + family: made.family, }), }); let shadow = ShadowView::of(&image, &plan, index, shape.view_type, whole); @@ -6634,8 +6674,8 @@ impl Device { let element = sampled.filter(|_| plan.read).map(|view| (view, home)); let looped = sampled.filter(|_| image.looped()); // SAFETY: the texture's views are live; its image is in its home layout whenever - // work uses it: the upload that moves it goes ahead of that work, or its acquire - // takes it general. + // work uses it: its making's command buffer moves it ahead of that work, or its + // acquire takes it general. let owner = unsafe { (core.arrays).place_texture( &core.device, @@ -6674,15 +6714,9 @@ impl Device { inner: Arc::new(inner), device: self.clone(), }; - // For the device tests: the plane's texture apart from its move home, which takes the work - // lock ([`crate::surface::steps`]). + // For the device tests: the plane's texture ([`crate::surface::steps`]). #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] crate::surface::steps::mark("plane texture"); - if !general { - core.work.home(core, texture.inner.imaged())?; - } - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - crate::surface::steps::mark("plane home"); Ok(texture) } } @@ -6693,10 +6727,19 @@ impl Texture { Arc::clone(self.inner.imaged()) } - /// Adds its image to `planes` where it is a Direct3D 11 plane's ([`Image::keep_plane`]). - pub(crate) fn keep_plane(&self, planes: &mut Vec>) { + /// Adds to `handed` what of it lies in memory another API shares (`crate::handed`): its + /// image, where it is a surface's plane ([`Image::keep_handed`]), or the exported block of + /// the buffer it lies over, where it is a texture over a buffer in one, whose copies in and + /// back read and write that block. + pub(crate) fn keep_handed(&self, handed: &mut Vec) { if let Some(image) = self.inner.image_of() { - image.keep_plane(planes); + image.keep_handed(handed); + } + if let Some(buffer) = self.inner.over() { + let (block, _) = buffer.held(); + if block.memory.handed_family().is_some() { + Handed::Block(Arc::clone(block)).keep(handed); + } } } } diff --git a/crates/metal2vulkan-validation/src/replay/new_runtime/videos.rs b/crates/metal2vulkan-validation/src/replay/new_runtime/videos.rs index 812d2d5e5..3c1f789ed 100644 --- a/crates/metal2vulkan-validation/src/replay/new_runtime/videos.rs +++ b/crates/metal2vulkan-validation/src/replay/new_runtime/videos.rs @@ -5,9 +5,10 @@ //! height), and every texture over a plane a view of that plane's texture at the texture's own //! index. The surface is waited for at its ready point (`rt::Surface::wait_until_ready`) once it is //! made, as the consumer waits before the other API's first write into it, so a picture lands -//! only after its planes' images left the undefined layout. A picture landed -//! (`m2v.externalWriteDone`) is the surface's acquire -//! (`rt::Surface::external_writes_done`). The stream holds no bytes of the pictures (the buffer is +//! only after its making (its planes' images out of the undefined layout and released to the other +//! API). A picture landed (`m2v.externalWriteDone`) is the surface's mark +//! (`rt::Surface::external_writes_done`); each submission that uses the planes acquires and +//! releases them itself. The stream holds no bytes of the pictures (the buffer is //! Private, and another API wrote it), so the play writes none: what the textures read is the //! surface's memory as it is, as the recorded buffer's was. The buffer stays, and the textures //! read nothing of it. diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 0a7440fef..89a17081b 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -5913,13 +5913,12 @@ method metal2vulkan-runtime::BlitCommandEncoder::end_encoding pub fn end_encodin method metal2vulkan-runtime::BlitCommandEncoder::fill_buffer pub fn fill_buffer(&mut self, buffer: &Buffer, range: Range, value: u8) -> Result<(), Error> method metal2vulkan-runtime::BlitCommandEncoder::generate_mipmaps pub fn generate_mipmaps(&mut self, texture: &Texture) -> Result<(), Error> method metal2vulkan-runtime::BlitCommandEncoder::optimize_indirect_command_buffer pub fn optimize_indirect_command_buffer(&mut self, buffer: &IndirectCommandBuffer, range: Range) -> Result<(), Error> -method metal2vulkan-runtime::BlitCommandEncoder::release_surface_to_external pub fn release_surface_to_external(&mut self, surface: &Surface) -> Result<(), Error> -method metal2vulkan-runtime::BlitCommandEncoder::release_to_external pub fn release_to_external(&mut self, buffer: &Buffer) -> Result<(), Error> method metal2vulkan-runtime::BlitCommandEncoder::reset_commands_in_buffer pub fn reset_commands_in_buffer(&mut self, buffer: &IndirectCommandBuffer, range: Range) -> Result<(), Error> method metal2vulkan-runtime::BlitCommandEncoder::synchronize_resource pub fn synchronize_resource(&mut self, resource: Resource<'_>) -> Result<(), Error> method metal2vulkan-runtime::BlitCommandEncoder::update_fence pub fn update_fence(&mut self, fence: &Fence) -> Result<(), Error> method metal2vulkan-runtime::BlitCommandEncoder::wait_for_fence pub fn wait_for_fence(&mut self, fence: &Fence) -> Result<(), Error> method metal2vulkan-runtime::Block::external_writes_done pub fn external_writes_done(&self) -> Result<(), Error> +method metal2vulkan-runtime::Block::wait_until_ready pub fn wait_until_ready(&self) -> Result<(), Error> method metal2vulkan-runtime::BlockId::get pub fn get(self) -> u32 method metal2vulkan-runtime::Buffer::block pub fn block(&self) -> BlockId method metal2vulkan-runtime::Buffer::contents pub fn contents(&self) -> Option> diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index 66d2a3eb8..e7b0d456a 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -238,13 +238,13 @@ Columns: | `ManagedCopyExported` | A Managed buffer whose device copy is placed in an exported block (`Device::new_managed_buffer`) | every device (a public call's own check of its arguments) | `ours`: Metal places a Managed buffer's second copy itself, so no Metal program puts it in memory another API shares | 1: `crates/metal2vulkan-runtime/src/buffer.rs (new_managed_buffer)` | `-` | | `ZeroRangePastBlock` | A zero fill whose range leaves its block (`Device::zero_block_range`), as a buffer placed there would | every device (a public call's own check of its arguments) | `ours`: the fill stands for the zeroed contents of a buffer placed in the range, and Metal answers nil for a buffer placed past the end of its heap | 1: `crates/metal2vulkan-runtime/src/buffer.rs (zero_block_range)` | `-` | | `ZeroRangeShared` | A zero fill of a Shared block (`Device::zero_block_range`) | every device (a public call's own check of its arguments) | `ours`: the host maps a Shared block, and its bytes are zeroed through the mapping, as a zeroed Shared buffer's are; the fill is for the memory the host does not map | 1: `crates/metal2vulkan-runtime/src/buffer.rs (zero_block_range)` | `-` | -| `NotExported` | An acquire of another API's writes into a block that is not exported (`Block::external_writes_done`), or a release to another API of a buffer... | every device (a public call's own check of its arguments) | `ours`: only an exported block's memory is another API's to write or read | 2: `crates/metal2vulkan-runtime/src/blit.rs (release_to_external)`, `crates/metal2vulkan-runtime/src/export.rs (external_writes_done)` | `-` | +| `NotExported` | A call about another API's access of a block that is not exported | every device (a public call's own check of its arguments) | `ours`: only an exported block's memory is another API's to write or read | 2: `crates/metal2vulkan-runtime/src/export.rs (external_writes_done)`, `crates/metal2vulkan-runtime/src/export.rs (wait_until_ready)` | `-` | | `SurfacePlanes` | A surface (`Device::new_exported_surface`) of no plane or of more than four, or whose pitch or start multiple is 0, or whose multiples and texels... | every device (a public call's own check of its arguments) | `ours`: a DRM format has at most four memory planes, and a layout needs a nonzero multiple | 3: `crates/metal2vulkan-runtime/src/d3d11.rs (import_d3d11_surface)`, `crates/metal2vulkan-runtime/src/surface.rs (new_exported_surface, 2 sites)` | `-` | | `ModifiedRange` | A changed range that leaves its buffer (`Buffer::did_modify_range`) | every device (a public call's own check of its arguments) | `ours`: the copy of such a range would write past the buffer's device copy | 1: `crates/metal2vulkan-runtime/src/buffer.rs (did_modify_range)` | `-` | | `Committed` | A call on a command buffer already committed | every device (a public call's own check of its arguments) | `metal-documented`: Metal's validation asserts "commit an already committed command buffer", "Completed handler provided after commit call" and "Scheduled handler provided after commit call" | 1: `crates/metal2vulkan-runtime/src/command.rs (open)` | `-` | | `InScheduledHandler` | A call a scheduled handler may not make (`CommandBuffer::add_scheduled_handler`) | every device (a public call's own check of its arguments) | `ours`: the consumer's scheduled handlers run on the submit thread, and the one consumer's make none of these calls; a guest's scheduled handler runs in the guest | 1: `crates/metal2vulkan-runtime/src/command.rs (not_in_scheduled_handler)` | `-` | | `WaitOnOwnThread` | A wait, in a handler or a listener, for what the runtime thread that runs it would have to do first, so it would never end | every device (a public call's own check of its arguments) | `ours`: no wait of the runtime's hangs by construction | 4: `crates/metal2vulkan-runtime/src/command.rs (wait_until_completed)`, `crates/metal2vulkan-runtime/src/command.rs (wait_until_scheduled)` (+2) | `-` | -| `OtherDevice` | An event, a buffer, a texture or a pipeline state of another device in an encode call (`CommandBuffer::encode_wait_for_event`,... | every device (a public call's own check of its arguments) | `ours`: an event's semaphore, a buffer's block, a texture's image, a pipeline and a block belong to the `VkDevice` that made them | 39: `crates/metal2vulkan-runtime/src/blit.rs (buffer_copy)`, `crates/metal2vulkan-runtime/src/blit.rs (copy_from_buffer_to_buffer)` (+32) | `-` | +| `OtherDevice` | An event, a buffer, a texture or a pipeline state of another device in an encode call (`CommandBuffer::encode_wait_for_event`,... | every device (a public call's own check of its arguments) | `ours`: an event's semaphore, a buffer's block, a texture's image, a pipeline and a block belong to the `VkDevice` that made them | 37: `crates/metal2vulkan-runtime/src/blit.rs (buffer_copy)`, `crates/metal2vulkan-runtime/src/blit.rs (copy_from_buffer_to_buffer)` (+30) | `-` | | `NoCommandBuffers` | A queue that may hold no command buffer (`Device::new_command_queue` with a count of 0) | every device (a public call's own check of its arguments) | `ours`: its first `commandBuffer` call would wait forever | 1: `crates/metal2vulkan-runtime/src/queue.rs (new_command_queue)` | `-` | | `EncoderOpen` | A second encoder, an encode call, or a commit or enqueue, while an encoder of the command buffer is open | every device (a public call's own check of its arguments) | `metal-documented`: a command buffer has one active encoder at a time, ended by `endEncoding` before another is made or the command buffer is committed | 1: `crates/metal2vulkan-runtime/src/command.rs (open)` | `-` | | `NoPipeline` | A dispatch or a draw with no pipeline state set | every device (a public call's own check of its arguments) | `metal-documented`: a compute dispatch needs a compute pipeline state set first, and a draw a render pipeline state | 4: `crates/metal2vulkan-runtime/src/encoder.rs (dispatch)`, `crates/metal2vulkan-runtime/src/render_encoder.rs (draw)` (+2) | `-` | @@ -304,7 +304,7 @@ Columns: | `AttachmentPlace` | A render pass attachment or resolve texture of a level or slice past its texture's | every device (a public call's own check of its arguments) | `ours`: no texel of the texture is there to render into | 4: `crates/metal2vulkan-runtime/src/texture.rs (attachment_view, 3 sites)`, `crates/metal2vulkan-runtime/src/texture.rs (resolve_attachment)` | `-` | | `AttachmentFormat` | A render pass color attachment of a depth or stencil pixel format, a depth attachment of a format without depth, or a stencil attachment of a... | every device (a public call's own check of its arguments) | `metal-documented`: a color attachment takes a color-renderable format, a depth attachment a format with depth and a stencil attachment a format with stencil; Metal's validation stops the descriptor | 3: `crates/metal2vulkan-runtime/src/pass.rs (check, 3 sites)` | `-` | | `NoAttachmentPass` | A render pass with no attachment whose `renderTargetWidth` or `renderTargetHeight` is 0, or whose `defaultRasterSampleCount` is 0, Metal's default | every device (a public call's own check of its arguments) | `metal-measured`: an Apple M3 Max, macOS 27.0.1, the API validation layer off, m3-max-62174, `probes/no_attachment_passes.m`: a side of 0 makes no encoder, nil, and a count of 0 ends the process at the encoder, SIGABRT, where 64 by 64 pixels at 1 sample makes one | 1: `crates/metal2vulkan-runtime/src/pass.rs (check)` | `-` | -| `VertexBufferOffset` | A draw whose vertex descriptor reads a vertex buffer at an offset at or past the buffer's length | every device (a public call's own check of its arguments) | `metal-documented`: a buffer's offset lies inside it; Metal's validation stops the bind | 1: `crates/metal2vulkan-runtime/src/render_encoder.rs (find)` | `-` | +| `VertexBufferOffset` | A draw whose vertex descriptor reads a vertex buffer at an offset at or past the buffer's length | every device (a public call's own check of its arguments) | `metal-documented`: a buffer's offset lies inside it; Metal's validation stops the bind | 1: `crates/metal2vulkan-runtime/src/render_encoder.rs (vertex_range)` | `-` | | `IndexBufferOffset` | An indexed draw whose index buffer offset is not a multiple of the index size, or whose indices leave the buffer | every device (a public call's own check of its arguments) | `metal-documented`: the offset is a multiple of the index size and the indices lie in the buffer; Metal's validation stops the draw | 1: `crates/metal2vulkan-runtime/src/render_encoder.rs (draw)` | `-` | | `TessellationFactorOffset` | A tessellation factor buffer whose factors, at its address plus the offset, start at an odd byte | every device (a public call's own check of its arguments) | `metal-documented`: `setTessellationFactorBuffer:offset:instanceStride:`'s offset is a multiple of 4; Metal's validation stops a patch draw with any other | 1: `crates/metal2vulkan-runtime/src/render_encoder.rs (set_tessellation_factor_buffer)` | `-` | | `ArgumentPlace` | An indirect dispatch's arguments, an indexed draw's indices, or a visibility result, at a byte of the allocation the buffer's block lies in (its... | every device (a public call's own check of its arguments) | `ours`: `vkCmdDispatchIndirect` reads its arguments at a multiple of 4 in the `VkBuffer`, `vkCmdBindIndexBuffer` takes indices at a multiple of their size in the memory, and `vkCmdCopyQueryPoolResults` writes 64-bit results at a multiple of 8, `VUID-vkCmdCopyQueryPoolResults-flags-00823`; a Metal buffer starts at an aligned address, so Metal's offset rules alone keep each aligned there | 4: `crates/metal2vulkan-runtime/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)`, `crates/metal2vulkan-runtime/src/render_encoder.rs (draw)` (+2) | `-` | @@ -535,13 +535,13 @@ Each refusal's sites, with the function that builds it. - `rt:Refusal::ManagedCopyExported`: `crates/metal2vulkan-runtime/src/buffer.rs (new_managed_buffer)` - `rt:Refusal::ZeroRangePastBlock`: `crates/metal2vulkan-runtime/src/buffer.rs (zero_block_range)` - `rt:Refusal::ZeroRangeShared`: `crates/metal2vulkan-runtime/src/buffer.rs (zero_block_range)` -- `rt:Refusal::NotExported`: `crates/metal2vulkan-runtime/src/blit.rs (release_to_external)`; `crates/metal2vulkan-runtime/src/export.rs (external_writes_done)` +- `rt:Refusal::NotExported`: `crates/metal2vulkan-runtime/src/export.rs (external_writes_done)`; `crates/metal2vulkan-runtime/src/export.rs (wait_until_ready)` - `rt:Refusal::SurfacePlanes`: `crates/metal2vulkan-runtime/src/d3d11.rs (import_d3d11_surface)`; `crates/metal2vulkan-runtime/src/surface.rs (new_exported_surface, 2 sites)` - `rt:Refusal::ModifiedRange`: `crates/metal2vulkan-runtime/src/buffer.rs (did_modify_range)` - `rt:Refusal::Committed`: `crates/metal2vulkan-runtime/src/command.rs (open)` - `rt:Refusal::InScheduledHandler`: `crates/metal2vulkan-runtime/src/command.rs (not_in_scheduled_handler)` - `rt:Refusal::WaitOnOwnThread`: `crates/metal2vulkan-runtime/src/command.rs (wait_until_completed)`; `crates/metal2vulkan-runtime/src/command.rs (wait_until_scheduled)`; `crates/metal2vulkan-runtime/src/event.rs (wait_until_signaled_value)`; `crates/metal2vulkan-runtime/src/queue.rs (command_buffer)` -- `rt:Refusal::OtherDevice`: `crates/metal2vulkan-runtime/src/blit.rs (buffer_copy)`; `crates/metal2vulkan-runtime/src/blit.rs (copy_from_buffer_to_buffer)`; `crates/metal2vulkan-runtime/src/blit.rs (copy_from_texture)`; `crates/metal2vulkan-runtime/src/blit.rs (fill_buffer)`; `crates/metal2vulkan-runtime/src/blit.rs (generate_mipmaps)`; `crates/metal2vulkan-runtime/src/blit.rs (optimize_indirect_command_buffer)`; `crates/metal2vulkan-runtime/src/blit.rs (release_surface_to_external)`; `crates/metal2vulkan-runtime/src/blit.rs (release_to_external)`; `crates/metal2vulkan-runtime/src/blit.rs (reset_commands_in_buffer)`; `crates/metal2vulkan-runtime/src/blit.rs (synchronize_resource)`; `crates/metal2vulkan-runtime/src/command.rs (check)`; `crates/metal2vulkan-runtime/src/command.rs (present_drawable)`; `crates/metal2vulkan-runtime/src/device.rs (release_block)`; `crates/metal2vulkan-runtime/src/encoder.rs (bind_sampler)`; `crates/metal2vulkan-runtime/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)`; `crates/metal2vulkan-runtime/src/encoder.rs (set_buffer)`; `crates/metal2vulkan-runtime/src/encoder.rs (set_compute_pipeline_state)`; `crates/metal2vulkan-runtime/src/encoder.rs (set_texture)`; `crates/metal2vulkan-runtime/src/encoder.rs (use_resource, 3 sites)`; `crates/metal2vulkan-runtime/src/fence.rs (check)`; `crates/metal2vulkan-runtime/src/pass.rs (check, 2 sites)`; `crates/metal2vulkan-runtime/src/pass.rs (resolve)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (draw)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (execute_commands_in_buffer)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (execute_commands_in_buffer_with_range)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (indirect)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (set_buffer)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (set_depth_stencil_state)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (set_render_pipeline_state)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (set_sampler_state)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (set_tessellation_factor_buffer)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (set_texture)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (use_resource, 3 sites)`; `crates/metal2vulkan-runtime/src/texture.rs (new_managed_texture)` +- `rt:Refusal::OtherDevice`: `crates/metal2vulkan-runtime/src/blit.rs (buffer_copy)`; `crates/metal2vulkan-runtime/src/blit.rs (copy_from_buffer_to_buffer)`; `crates/metal2vulkan-runtime/src/blit.rs (copy_from_texture)`; `crates/metal2vulkan-runtime/src/blit.rs (fill_buffer)`; `crates/metal2vulkan-runtime/src/blit.rs (generate_mipmaps)`; `crates/metal2vulkan-runtime/src/blit.rs (optimize_indirect_command_buffer)`; `crates/metal2vulkan-runtime/src/blit.rs (reset_commands_in_buffer)`; `crates/metal2vulkan-runtime/src/blit.rs (synchronize_resource)`; `crates/metal2vulkan-runtime/src/command.rs (check)`; `crates/metal2vulkan-runtime/src/command.rs (present_drawable)`; `crates/metal2vulkan-runtime/src/device.rs (release_block)`; `crates/metal2vulkan-runtime/src/encoder.rs (bind_sampler)`; `crates/metal2vulkan-runtime/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)`; `crates/metal2vulkan-runtime/src/encoder.rs (set_buffer)`; `crates/metal2vulkan-runtime/src/encoder.rs (set_compute_pipeline_state)`; `crates/metal2vulkan-runtime/src/encoder.rs (set_texture)`; `crates/metal2vulkan-runtime/src/encoder.rs (use_resource, 3 sites)`; `crates/metal2vulkan-runtime/src/fence.rs (check)`; `crates/metal2vulkan-runtime/src/pass.rs (check, 2 sites)`; `crates/metal2vulkan-runtime/src/pass.rs (resolve)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (draw)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (execute_commands_in_buffer)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (execute_commands_in_buffer_with_range)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (indirect)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (set_buffer)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (set_depth_stencil_state)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (set_render_pipeline_state)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (set_sampler_state)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (set_tessellation_factor_buffer)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (set_texture)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (use_resource, 3 sites)`; `crates/metal2vulkan-runtime/src/texture.rs (new_managed_texture)` - `rt:Refusal::NoCommandBuffers`: `crates/metal2vulkan-runtime/src/queue.rs (new_command_queue)` - `rt:Refusal::EncoderOpen`: `crates/metal2vulkan-runtime/src/command.rs (open)` - `rt:Refusal::NoPipeline`: `crates/metal2vulkan-runtime/src/encoder.rs (dispatch)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (draw)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (draw_reaches)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (execution_part)` @@ -601,7 +601,7 @@ Each refusal's sites, with the function that builds it. - `rt:Refusal::AttachmentPlace`: `crates/metal2vulkan-runtime/src/texture.rs (attachment_view, 3 sites)`; `crates/metal2vulkan-runtime/src/texture.rs (resolve_attachment)` - `rt:Refusal::AttachmentFormat`: `crates/metal2vulkan-runtime/src/pass.rs (check, 3 sites)` - `rt:Refusal::NoAttachmentPass`: `crates/metal2vulkan-runtime/src/pass.rs (check)` -- `rt:Refusal::VertexBufferOffset`: `crates/metal2vulkan-runtime/src/render_encoder.rs (find)` +- `rt:Refusal::VertexBufferOffset`: `crates/metal2vulkan-runtime/src/render_encoder.rs (vertex_range)` - `rt:Refusal::IndexBufferOffset`: `crates/metal2vulkan-runtime/src/render_encoder.rs (draw)` - `rt:Refusal::TessellationFactorOffset`: `crates/metal2vulkan-runtime/src/render_encoder.rs (set_tessellation_factor_buffer)` - `rt:Refusal::ArgumentPlace`: `crates/metal2vulkan-runtime/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (draw)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (indirect)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (set_visibility_result_mode)`