diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 2d29c8410..8686f844e 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -926,6 +926,16 @@ Calls Metal does not have, for a consumer that emulates a Metal device: `copy_runs_to_host_ram` take each run at a byte of the buffer of its own, so a buffer that keeps a surface's layout (rows at a pitch, the padding between them untouched) is one call for every row. +- `BlitCommandEncoder::copy_texture_from_host_ram` and `copy_texture_to_host_ram`: one 2D region + of a texture's slice and level filled from, or copied out into, a surface laid out in a used + guest RAM: the surface's bytes in order as host runs (as `copy_from_host_ram` takes them), the + region's rows from a byte of them at a pitch (Metal's buffer layout for + `copy_from_buffer_to_texture`). Each row's texels in a run and a chunk are one region of a + `vkCmdCopyBufferToImage` or `vkCmdCopyImageToBuffer` straight on the chunk's import, with no + staging copy (first touch through the CPU as the buffer forms); only the texels' bytes are + read or written; ordered and seen as the buffer forms are, the texture as a blit uses it + ([HOWTO](../../docs/HOWTO.md#guest-ram-imported-whole)). For a single-sample texture of + uncompressed colour texels with an image of its own. - `HostBytes`: bytes at a pointer that may change while a call reads them (a guest's memory), which `Texture::replace_region_with_host_bytes` and `BufferContents::CopyHost` copy once through the pointer, where the slice forms would need the caller's own copy first. diff --git a/crates/metal2vulkan-runtime/src/blit_plan.rs b/crates/metal2vulkan-runtime/src/blit_plan.rs index 101901ce4..1f8340efe 100644 --- a/crates/metal2vulkan-runtime/src/blit_plan.rs +++ b/crates/metal2vulkan-runtime/src/blit_plan.rs @@ -65,7 +65,7 @@ impl BufferLayout { /// `buffer_length` bytes; the bytes it spans from its offset. A layout of more than one image /// reaches it within Metal's `bytesPerImage` rule ([`plan_buffer_copy`] places one off it first; /// a texture over a buffer, and a depth or stencil format, has one image). -fn check_layout( +pub(super) fn check_layout( layout: &BufferLayout, size: [u32; 3], unit: &CopyUnit, diff --git a/crates/metal2vulkan-runtime/src/blit_texture.rs b/crates/metal2vulkan-runtime/src/blit_texture.rs index cb8195f9e..4206ba68a 100644 --- a/crates/metal2vulkan-runtime/src/blit_texture.rs +++ b/crates/metal2vulkan-runtime/src/blit_texture.rs @@ -152,7 +152,7 @@ fn write() -> Access { } /// The levels and layers of the image a region of `region`'s level and slices covers. -fn subresources(region: &ImageRegion) -> (Range, Range) { +pub(super) fn subresources(region: &ImageRegion) -> (Range, Range) { ( region.level..region.level + 1, region.layer..region.layer + region.layers, @@ -163,7 +163,7 @@ fn subresources(region: &ImageRegion) -> (Range, Range) { /// of 0 that a texture of the copy lacks, depth on all but 3D textures and height on 1D textures /// and texture buffers, copies one texel there; `None` for a copy with another axis 0, which copies /// nothing. -fn copy_size(size: Size, types: &[TextureType]) -> Option { +pub(super) fn copy_size(size: Size, types: &[TextureType]) -> Option { use TextureType::{TextureBuffer, Type1D, Type1DArray, Type3D}; let any = |lacks: fn(TextureType) -> bool| types.iter().any(|&t| lacks(t)); let mut size = size; @@ -178,7 +178,7 @@ fn copy_size(size: Size, types: &[TextureType]) -> Option { /// `level` and `slice`, and `origin` and `size`, as a region of a texture; refused as Metal /// refuses a region past the texture when a value is past any texture. -fn region( +pub(super) fn region( call: &'static str, origin: Origin, size: Size, @@ -389,7 +389,7 @@ fn plan_copy( } /// The Vulkan region of `region`. -fn buffer_image_region(region: &BufferImageRegion) -> vk::BufferImageCopy { +pub(super) fn buffer_image_region(region: &BufferImageRegion) -> vk::BufferImageCopy { vk::BufferImageCopy { buffer_offset: region.buffer_offset, buffer_row_length: region.row_length, @@ -455,7 +455,11 @@ fn regions_meet(a: &ImageRegion, b: &ImageRegion) -> bool { impl BlitCommandEncoder { /// Refuse `texture` of another device; note it for its heap shadow (`BlitCommandEncoder::see`). - fn check_texture(&mut self, call: &'static str, texture: &Texture) -> Result<(), Error> { + pub(super) fn check_texture( + &mut self, + call: &'static str, + texture: &Texture, + ) -> Result<(), Error> { self.core().check_device(call, texture.generation())?; self.see(texture); Ok(()) @@ -466,7 +470,7 @@ impl BlitCommandEncoder { /// generation (`CommandBufferError::InvalidResource`, the encoder's whole run of blit /// encoders running nothing, an M3 Max under macOS 27.0.1), so the encoder fails it and the /// copy records nothing. - fn fails_on_memoryless(&mut self, textures: &[&Texture]) -> bool { + pub(super) fn fails_on_memoryless(&mut self, textures: &[&Texture]) -> bool { let memoryless = textures.iter().any(|texture| texture.is_memoryless()); if memoryless { self.core().fail_memoryless_use(); diff --git a/crates/metal2vulkan-runtime/src/error.rs b/crates/metal2vulkan-runtime/src/error.rs index c22afee88..ae7c3d278 100644 --- a/crates/metal2vulkan-runtime/src/error.rs +++ b/crates/metal2vulkan-runtime/src/error.rs @@ -627,15 +627,18 @@ pub enum Problem { DmaBuf, /// Guest RAM, or a run resolver's answer, that breaks its runtime extension's contract /// (`HostRam::new`, `Device::use_host_ram`, `HostMemory::with_runs`, - /// `BlitCommandEncoder::copy_from_host_ram`, `copy_to_host_ram`, `copy_runs_from_host_ram` - /// and `copy_runs_to_host_ram`; Metal has none). For the RAM: no range, or a range that is - /// empty, starts or ends off the host page, runs past the address space's end or overlaps - /// another (of the same RAM, or of another RAM the device uses). For an answer: runs that are - /// not whole host pages or do not cover exactly the pages asked for. For a copy: a RAM the - /// device does not use, a run that is empty, starts off a 4-byte word or lies outside the - /// RAM's ranges, of runs one after another bytes of the buffer that start off a 4-byte word - /// of its memory, or, of a copy by regions, a buffer over host pages the copy's bytes - /// overlap. + /// `BlitCommandEncoder::copy_from_host_ram`, `copy_to_host_ram`, `copy_runs_from_host_ram`, + /// `copy_runs_to_host_ram`, `copy_texture_from_host_ram` and `copy_texture_to_host_ram`; Metal + /// has none). For the RAM: no range, or a range that is empty, starts or ends off the host + /// page, runs past the address space's end or overlaps another (of the same RAM, or of another + /// RAM the device uses). For an answer: runs that are not whole host pages or do not cover + /// exactly the pages asked for. For a copy: a RAM the device does not use, a run that is + /// empty, starts off a 4-byte word or lies outside the RAM's ranges, of runs one after another + /// bytes of the buffer that start off a 4-byte word of its memory, or, of a copy by regions, a + /// buffer over host pages the copy's bytes overlap. For a copy with a texture: a row's piece + /// in a run and a chunk that does not start on a texel of host memory or hold whole texels, + /// and a texture that is not an image of its own of one sample and uncompressed colour texels + /// one to a texel, or a region of more than one image. /// /// Basis: ours (a runtime extension's own contract: Metal imports no guest RAM). HostRam, diff --git a/crates/metal2vulkan-runtime/src/host_ram.rs b/crates/metal2vulkan-runtime/src/host_ram.rs index 317dc6485..d52c50ae8 100644 --- a/crates/metal2vulkan-runtime/src/host_ram.rs +++ b/crates/metal2vulkan-runtime/src/host_ram.rs @@ -210,6 +210,7 @@ use std::time::{Duration, Instant}; pub(crate) mod copy; mod kept; +pub(crate) mod texture; /// No source of dma-bufs on this system: a RAM has none. #[cfg(not(unix))] diff --git a/crates/metal2vulkan-runtime/src/host_ram/copy.rs b/crates/metal2vulkan-runtime/src/host_ram/copy.rs index 9da55f406..2a1a79882 100644 --- a/crates/metal2vulkan-runtime/src/host_ram/copy.rs +++ b/crates/metal2vulkan-runtime/src/host_ram/copy.rs @@ -213,6 +213,7 @@ use crate::blit::{bytes_in, reads_by, writes_by, BlitCommandEncoder, TRANSFER}; use crate::buffer::{Buffer, CallerMemory, HostPages}; use crate::command_buffer::CommandBuffer; use crate::deferred::Deferred; +use crate::device::functions::Vk; use crate::device::lock; use crate::dirty_pages::PagesLog; use crate::encoder::{EncoderCore, RecordedSegment}; @@ -231,7 +232,7 @@ use std::collections::BTreeMap; use std::ops::Range; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, OnceLock, Weak}; -use std::time::Instant; +use std::time::{Duration, Instant}; /// The unit of a copy's runs: whole 4 KiB pages at 4 KiB-aligned host addresses (a guest's page; /// every host page and every chunk is whole such pages). @@ -241,7 +242,7 @@ pub(crate) const PAGE: u64 = PagesCopyModule::PAGE_BYTES as u64; /// So a copy of thousands of runs keeps the command buffer's writes apart (`dirty_pages.rs` /// keeps 4,096 writes of a command buffer and 64 ranges of a log apart, past which it takes every /// copy, or every page, as written). -const MOST_RANGES: usize = 16; +pub(super) const MOST_RANGES: usize = 16; /// The most ranges of a chunk not imported yet a copy imports alone while the device imports the /// chunk (`RamOnDevice::for_copy`): each import is a fixed cost on the encoding thread (a 2 MiB @@ -344,7 +345,7 @@ impl RamCopies { /// taken through the CPU while the device's thread imports it ([`CopyTake::ThroughCpu`]), only /// through the CPU ([`CopyTake::CpuOnly`]), or by waiting for its import ([`CopyTake::Waits`]). #[derive(Clone, Copy, Debug, Default)] -struct Takes { +pub(super) struct Takes { through_cpu: bool, cpu_only: bool, waits: bool, @@ -367,7 +368,7 @@ impl Takes { /// imports, whose chunks it would import or wait for on the encoding thread. A scatter's CPU /// copy waits for every batch submitted before it to complete, its own command buffer's /// before it among them. - fn staging(self, written: impl FnOnce() -> bool) -> Option { + pub(super) fn staging(self, written: impl FnOnce() -> bool) -> Option { self.staged().then(|| Staging { cpu_only: self.cpu_only, after_the_gpu: written(), @@ -599,7 +600,7 @@ enum Kept { impl RamOnDevice { /// The key of chunk `slot`'s bytes on `device`: made at the first copy over the chunk, and /// placed over its host bytes, its uses reported to the RAM's log where it has one. - fn chunk_key(&self, device: &Device, slot: usize) -> ResourceKey { + pub(super) fn chunk_key(&self, device: &Device, slot: usize) -> ResourceKey { let made = self.copies.keys[slot].get_or_init(|| { let shared = device.shared(); let span = &self.slots[slot].span; @@ -626,7 +627,7 @@ impl RamOnDevice { /// into a chunk the device refuses whatever it holds (`ChunkSlot::refused`) wrote by the CPU, /// in a host step before every later copy's (a staged scatter's drain): the GPU writes none of /// its pages. - fn written_over(&self, device: &Device, touched: &[(usize, Range)]) -> bool { + pub(super) fn written_over(&self, device: &Device, touched: &[(usize, Range)]) -> bool { let aliases = &device.shared().aliases; (touched.iter()).any(|(slot, bytes)| { let wrote = self.copies_wrote(*slot) && !self.slots[*slot].refused; @@ -645,13 +646,11 @@ impl RamOnDevice { /// Held by its segment until its command buffer completes. pub(crate) struct StagedGather { ram: Arc, - /// The buffer's `VkBuffer` and the byte of it the copy's first byte is at (`blit_at`, whose - /// command buffer keeps it live until it completes). - destination: (vk::Buffer, u64), + /// What the GPU's copy writes from the region: the buffer's bytes the pieces cover, or the + /// texture's texels ([`Target`]). + destination: Target, /// The copy's bytes: the region's length. length: u64, - /// The bytes of the copy the pieces cover ([`covered`]): the GPU's regions, each byte once. - covered: Vec>, /// Each piece's first host byte, its length and its byte of the region, in the runs' order: /// where two name one byte of the buffer, the later's bytes stay. pieces: Vec<(u64, u64, u64)>, @@ -688,6 +687,17 @@ impl Staging { fn through_imports(self) -> bool { !self.cpu_only && !self.after_the_gpu } + + /// How an encoding again stages a copy of `copy`'s direction its first encoding staged so + /// ([`HostRamCall::staged_again`]): a scatter so again, a gather where it does not copy it + /// through the imports ([`Staging::through_imports`]); `None` where it copies it through them. + pub(super) fn again(self, copy: PagesCopy) -> Option { + let again = match copy { + PagesCopy::Scatter => true, + PagesCopy::Gather => !self.through_imports(), + }; + again.then_some(self) + } } impl StagedGather { @@ -734,25 +744,12 @@ impl StagedGather { } let nanos = u64::try_from(started.elapsed().as_nanos()).unwrap_or(u64::MAX); (device.shared().counts).host_ram_staged_filled(nanos, self.gated.load(Ordering::Relaxed)); - let (destination, at) = self.destination; - let source = region.raw(); - let regions: Vec = (self.covered.iter()) - .map(|bytes| vk::BufferCopy { - src_offset: region.offset() + bytes.start, - dst_offset: at + bytes.start, - size: bytes.end - bytes.start, - }) - .collect(); let mut core = EncoderCore::segment(command_buffer, true)?; core.command(TRANSFER, &[], |functions, raw| { - for part in regions.chunks(MOST_REGIONS) { - // SAFETY: the segment's command buffer is recording, outside a render pass; the - // arena's region and the buffer are live until the command buffer completes (the - // arena, and `blit_at`); each region lies inside the arena's (as long as the - // copy's bytes) and inside the buffer's bytes (`bytes_in`), and no byte is written - // by two (`covered`). - unsafe { functions.cmd_copy_buffer(raw, source, destination, part) }; - } + // SAFETY: the segment's command buffer is recording, outside a render pass; the + // arena's region is live until the command buffer completes, and the target as + // [`Target::record`] says; the region is as long as the copy's bytes. + unsafe { self.destination.record(functions, raw, ®ion, true) }; }); core.end_segment() } @@ -768,13 +765,11 @@ impl StagedGather { pub(crate) struct StagedScatter { /// Kept until the CPU's copy: the pages stay mapped while the RAM lives (`HostRam::new`). _ram: Arc, - /// The buffer's `VkBuffer` and the byte of it the copy's first byte is at (`blit_at`, whose - /// command buffer keeps it live until it completes). - source: (vk::Buffer, u64), + /// What the GPU's copy reads into the region: the buffer's bytes the pieces cover, or the + /// texture's texels ([`Target`]). + source: Target, /// The copy's bytes: the region's length. length: u64, - /// The bytes of the copy the pieces cover ([`covered`]): the GPU's regions, each byte once. - covered: Vec>, /// Each piece's first host byte, its length and its byte of the region, in the runs' order: /// where two name one host byte, the later's bytes stay. pieces: Vec<(u64, u64, u64)>, @@ -791,25 +786,12 @@ impl StagedScatter { pub(crate) fn stage(&self, command_buffer: &CommandBuffer) -> Result { let device = command_buffer.device().clone(); let region = (command_buffer.state().uploads).unset(&device, self.length)?; - let (source, at) = self.source; - let target = region.raw(); - let regions: Vec = (self.covered.iter()) - .map(|bytes| vk::BufferCopy { - src_offset: at + bytes.start, - dst_offset: region.offset() + bytes.start, - size: bytes.end - bytes.start, - }) - .collect(); let mut core = EncoderCore::segment(command_buffer, true)?; core.command(TRANSFER, &[], |functions, raw| { - for part in regions.chunks(MOST_REGIONS) { - // SAFETY: the segment's command buffer is recording, outside a render pass; the - // buffer and the arena's region are live until the command buffer completes - // (`blit_at`, the arena); each region lies inside the buffer's bytes (`bytes_in`) - // and inside the arena's (as long as the copy's bytes), and no byte is written by - // two (`covered`). - unsafe { functions.cmd_copy_buffer(raw, source, target, part) }; - } + // SAFETY: the segment's command buffer is recording, outside a render pass; the + // arena's region is live until the command buffer completes, and the source as + // [`Target::record`] says; the region is as long as the copy's bytes. + unsafe { self.source.record(functions, raw, ®ion, false) }; }); if self.region.set(region).is_err() { return Err(internal("a staged scatter's staging taken twice")); @@ -838,9 +820,97 @@ impl StagedScatter { } } +/// The side of a staged copy that is not the RAM, as the GPU's copy between it and the region of +/// the arena takes it ([`StagedGather`], [`StagedScatter`]). +pub(crate) enum Target { + /// A buffer's `VkBuffer`, the byte of it the copy's first byte is at (`blit_at`, whose command + /// buffer keeps it live until it completes), and the bytes of the copy the pieces cover + /// ([`covered`]): the GPU's regions, each byte once. + Buffer { + raw: vk::Buffer, + at: u64, + covered: Vec>, + }, + /// A texture's image, in the `GENERAL` layout, held by the command buffer until it completes + /// (`host_ram/texture.rs`), and the regions of its texels, each `buffer_offset` a byte of the + /// copy's (the region's from its first), a multiple of the texel's bytes: no texel twice. + Image { + image: vk::Image, + regions: Vec, + }, +} + +impl Target { + /// Record the GPU's copy between `region` of the arena and the target: from the region into + /// it where `into`, else out of it into the region, at most [`MOST_REGIONS`] regions a + /// command. + /// + /// # Safety + /// + /// `raw` is recording, outside a render pass; the region is as long as the copy's bytes and + /// live until the command buffer completes, and so is the target: each buffer region lies + /// inside its bytes (`bytes_in`) and no byte is written by two (`covered`), each image region + /// inside its level (`check_region`), its `buffer_offset` from the region's first byte a + /// multiple of the texel's bytes (the arena's offsets are of 16 bytes at least: + /// `VUID-vkCmdCopyBufferToImage-dstImage-07975`, `VUID-vkCmdCopyImageToBuffer-srcImage-07975`). + unsafe fn record(&self, functions: &Vk, raw: vk::CommandBuffer, region: &Upload, into: bool) { + let staging = region.raw(); + match self { + Target::Buffer { + raw: buffer, + at, + covered, + } => { + let regions: Vec = (covered.iter()) + .map(|bytes| { + let (staged, placed) = (region.offset() + bytes.start, at + bytes.start); + let (src_offset, dst_offset) = match into { + true => (staged, placed), + false => (placed, staged), + }; + vk::BufferCopy { + src_offset, + dst_offset, + size: bytes.end - bytes.start, + } + }) + .collect(); + let (source, destination) = match into { + true => (staging, *buffer), + false => (*buffer, staging), + }; + for part in regions.chunks(MOST_REGIONS) { + // SAFETY: as the function's contract says. + unsafe { functions.cmd_copy_buffer(raw, source, destination, part) }; + } + } + Target::Image { image, regions } => { + let regions: Vec = (regions.iter()) + .map(|copy| vk::BufferImageCopy { + buffer_offset: region.offset() + copy.buffer_offset, + ..*copy + }) + .collect(); + let general = vk::ImageLayout::GENERAL; + for part in regions.chunks(MOST_REGIONS) { + // SAFETY: as the function's contract says. + unsafe { + match into { + true => functions + .cmd_copy_buffer_to_image(raw, staging, *image, general, part), + false => functions + .cmd_copy_image_to_buffer(raw, *image, general, staging, part), + } + }; + } + } + } + } +} + /// The host bytes `pieces` (cut where the chunks of `spans` end) lie in, joined as a copy's uses /// name them ([`chunk_ranges`]), each with its chunk. -fn touched_bytes(pieces: &[Piece], spans: &[Range]) -> Vec<(usize, Range)> { +pub(super) fn touched_bytes(pieces: &[Piece], spans: &[Range]) -> Vec<(usize, Range)> { (chunk_ranges(pieces, MOST_RANGES).into_iter()) .flat_map(|(slot, ranges)| { let start = spans[slot].start; @@ -1341,6 +1411,45 @@ pub(crate) fn run_lists( /// The indices of chunk `slot`'s imports in `by_chunk`, (chunk, index of the import) pairs by /// chunk (`CopyImports::of_chunk`, sorted by chunk alone), in their order there. +/// `pieces` (cut where the chunks of `spans` end) as they lie in `imports`, the imports +/// [`RamOnDevice::copy_imports`] gave a copy, of the chunks `of_chunk` names: each piece's `slot` +/// the index of the import that holds its bytes whole (the first of its chunk's, in the order they +/// were given), its `offset` theirs in that import (`RamChunk::offset_of`). +pub(super) fn in_imports( + imports: &[Arc], + of_chunk: &[(usize, usize)], + pieces: &[Piece], + spans: &[Range], +) -> Result, Error> { + // The imports of each chunk, by chunk, each chunk's in the order they were given. + let mut by_chunk = of_chunk.to_vec(); + by_chunk.sort_by_key(|&(slot, _)| slot); + let in_imports: Option> = (pieces.iter()) + .map(|piece| { + let start = spans[piece.slot].start + piece.offset; + let host = start..start + piece.length; + let mut found = imports_of(&by_chunk, piece.slot) + .filter_map(|index| Some((index, imports[index].offset_of(&host)?))); + let (index, offset) = found.next()?; + Some(Piece { + slot: index, + offset, + ..*piece + }) + }) + .collect(); + in_imports.ok_or_else(|| internal("a host RAM copy's piece outside the imports made for it")) +} + +/// Count on `device` the time a copy's encoding `waited` for chunks' imports, where it did +/// (`WorkCounts::host_ram_copy_import_waits`, `host_ram_copy_import_wait_nanos`). +pub(super) fn count_waited(device: &Device, waited: Duration) { + if !waited.is_zero() { + let nanos = u64::try_from(waited.as_nanos()).unwrap_or(u64::MAX); + device.shared().counts.host_ram_copy_waited(nanos); + } +} + fn imports_of(by_chunk: &[(usize, usize)], slot: usize) -> impl Iterator + '_ { let at = by_chunk.partition_point(|&(chunk, _)| chunk < slot); (by_chunk[at..].iter()) @@ -1451,6 +1560,12 @@ impl<'a> Given<'a> { } } +/// `device`'s use of the RAM `ram`, where it uses it (`Device::use_host_ram`). +pub(super) fn used_ram(device: &Device, ram: &HostRam) -> Option> { + (device.shared().host_ram.used().into_iter()) + .find(|used| std::ptr::eq(Arc::as_ptr(&used.ram), ram)) +} + /// Whether `given`'s runs merged ([`merged`]) are `kept`, in one pass with no vector made: each /// checked as `merged` checks it, joined as it joins them, and each joined run compared with the /// next of `kept` once the run after it starts apart. False where `merged` refuses one, or one @@ -1494,8 +1609,7 @@ impl HostRamCall { (ram, given): (&HostRam, Given<'_>), buffer: &Buffer, ) -> HostRamCall { - let ram = (device.shared().host_ram.used().into_iter()) - .find(|used| std::ptr::eq(Arc::as_ptr(&used.ram), ram)); + let ram = used_ram(device, ram); let consecutive = given.consecutive(); // The plan kept of the same copy: its runs, checked and copied by words, are the call's. let kept = (ram.as_ref()).and_then(|ram| ram.copies.kept_for(copy, buffer, given)); @@ -1539,12 +1653,7 @@ impl HostRamCall { /// (`Deferred::left_again_by_an_encoding_again`). `None` for every other copy, which an /// encoding again copies through the imports. fn staged_again(&self) -> Option { - let staging = *self.staged.get()?; - let again = match self.copy { - PagesCopy::Scatter => true, - PagesCopy::Gather => !staging.through_imports(), - }; - again.then_some(staging) + self.staged.get()?.again(self.copy) } /// The call's name, as its refusals give it. @@ -1818,13 +1927,24 @@ impl BlitCommandEncoder { // The first encoding's staging, which an encoding again finds set (its takes are // none: [`takes`](Self::takes)). let _ = call.staged.set(staging); - let bytes = (raw, at, span, total); + let target = Target::Buffer { + raw, + at, + covered: covered(&pieces), + }; + let length = span.end - span.start; + let read = Access::new(TRANSFER, vk::AccessFlags2::TRANSFER_READ); + let write = Access::new(TRANSFER, vk::AccessFlags2::TRANSFER_WRITE); return match call.copy { PagesCopy::Scatter => { - self.record_staged_scatter(call, ram, (&pieces, spans), bytes) + let read_by = reads_by(&call.buffer, span, read); + let side = (target, length, read_by); + self.record_staged_scatter(ram, (&pieces, spans), side, total) } PagesCopy::Gather => { - self.record_staged(call, ram, (&pieces, spans), bytes, staging) + let wrote = writes_by(&call.buffer, span, write); + let side = (target, length, wrote); + self.record_staged(ram, (&pieces, spans), side, total, staging) } }; } @@ -1851,30 +1971,8 @@ impl BlitCommandEncoder { "an import of host RAM past the device's storage range", )); } - if !waited.is_zero() { - let nanos = u64::try_from(waited.as_nanos()).unwrap_or(u64::MAX); - shared.counts.host_ram_copy_waited(nanos); - } - // The imports of each chunk, by chunk, each chunk's in the order they were given. - let mut by_chunk = of_chunk.clone(); - by_chunk.sort_by_key(|&(slot, _)| slot); - let in_imports: Option> = (pieces.iter()) - .map(|piece| { - let start = spans[piece.slot].start + piece.offset; - let host = start..start + piece.length; - let mut found = imports_of(&by_chunk, piece.slot) - .filter_map(|index| Some((index, imports[index].offset_of(&host)?))); - let (index, offset) = found.next()?; - Some(Piece { - slot: index, - offset, - ..*piece - }) - }) - .collect(); - let in_imports = in_imports.ok_or_else(|| { - crate::error::internal("a host RAM copy's piece outside the imports made for it") - })?; + count_waited(&device, waited); + let in_imports = in_imports(&imports, &of_chunk, &pieces, spans)?; // A copy whose runs write a destination byte twice is ordered by rounds of regions // alone: a scatter's that name a host byte twice, a gather's that name a byte of the // buffer twice (never runs one after another). @@ -1966,10 +2064,7 @@ impl BlitCommandEncoder { early.imports = Some(imports); return Ok(Kept::Not(early)); } - if !imports.waited.is_zero() { - let nanos = u64::try_from(imports.waited.as_nanos()).unwrap_or(u64::MAX); - device.shared().counts.host_ram_copy_waited(nanos); - } + count_waited(&device, imports.waited); let bytes = (blit.0, blit.1, plan.span.clone(), plan.total); let table = Table::Kept(plan.table_buffer(&device)?, plan.table.len() as u64); let planned = (table, &plan.dispatches[..], &plan.touched[..]); @@ -2131,7 +2226,7 @@ impl BlitCommandEncoder { /// takes them, each as [`RamOnDevice::copy_take`] says, for [`Takes::staging`]: none taken in /// an encoder encoded again (`replay.rs`, `command_buffer/reencode.rs`), which stages a copy /// only as its first encoding did ([`HostRamCall::staged_again`]). - fn takes( + pub(super) fn takes( &mut self, ram: &RamOnDevice, importer: &super::Importer, @@ -2153,26 +2248,27 @@ impl BlitCommandEncoder { takes } - /// Record `call`, a gather staged through the CPU as `staging` says ([`Takes::staging`]), - /// into the buffer's bytes `span`, from byte `at` of its `raw` (the module docs' "First - /// touch"): its work left to its batch's host step ([`StagedGather`]), at its place in the - /// encoder, its uses noted there: the chunks' bytes it reads, by their keys, and the buffer's - /// writes. One [`Staging::after_the_gpu`] starts a part of its own there, whose host step waits - /// for the work before it to complete, and its uses are noted again at that part's start, - /// where its copy lies. Each chunk is taken as an object over it takes it, and asked of the - /// device's thread where it is not imported ([`RamOnDevice::take_for_copies`]). A buffer detached - /// since records nothing, as a command over it does. - fn record_staged( + /// Record a gather staged through the CPU as `staging` says ([`Takes::staging`]) into + /// `destination` (the module docs' "First touch"): `length` bytes of the copy, each piece at + /// its byte of them, which the GPU's copy writes into the buffer's bytes or the texture's texels + /// `destination` names, whose use is `wrote`. Its work is left to its batch's host step + /// ([`StagedGather`]), at its place in the encoder, its uses noted there: the chunks' bytes it + /// reads, by their keys, and `wrote`. One [`Staging::after_the_gpu`] starts a part of its own + /// there, whose host step waits for the work before it to complete, and its uses are noted + /// again at that part's start, where its copy lies. Each chunk is taken as an object over it + /// takes it, and asked of the device's thread where it is not imported + /// ([`RamOnDevice::take_for_copies`]). A buffer detached since records nothing, as a command + /// over it does. + pub(super) fn record_staged( &mut self, - call: &HostRamCall, ram: &Arc, (pieces, spans): (&[Piece], &[Range]), - (raw, at, span, total): (vk::Buffer, u64, Range, u64), + (destination, length, wrote): (Target, u64, Use), + total: u64, staging: Staging, ) -> Result<(), Error> { let device = self.core().device().clone(); let read = Access::new(TRANSFER, vk::AccessFlags2::TRANSFER_READ); - let write = Access::new(TRANSFER, vk::AccessFlags2::TRANSFER_WRITE); let touched = chunk_ranges(pieces, MOST_RANGES); let mut uses = Vec::new(); for (slot, ranges) in &touched { @@ -2181,7 +2277,7 @@ impl BlitCommandEncoder { uses.push(Use::reads(key, true, UseRange::Bytes(range.clone()), read)); } } - uses.push(writes_by(&call.buffer, span.clone(), write)); + uses.push(wrote); if !self.core().note_left_uses(TRANSFER, &uses) { return Ok(()); } @@ -2196,9 +2292,8 @@ impl BlitCommandEncoder { .collect(); let staged = StagedGather { ram: Arc::clone(ram), - destination: (raw, at), - length: span.end - span.start, - covered: covered(pieces), + destination, + length, pieces: in_pages, touched: touched_bytes(pieces, spans), // A gather in a part of its own steps after the work before it completed. @@ -2217,25 +2312,25 @@ impl BlitCommandEncoder { Ok(()) } - /// Record `call`, a scatter staged through the CPU ([`Takes::staging`]), from the - /// buffer's bytes `span`, at byte `at` of its `raw` (the module docs' "First touch"): its - /// work left to two host steps ([`StagedScatter`]), the GPU's copy into the staging at its - /// place in the encoder, its read of the buffer noted there, and the CPU's copy into the - /// pages at the start of a part of its own after it, its writes of the chunks' bytes noted - /// there, by their keys. Each chunk is taken as an object over it takes it, and asked of the - /// device's thread where it is not imported ([`RamOnDevice::take_for_copies`]). A buffer - /// detached since records nothing, as a command over it does. - fn record_staged_scatter( + /// Record a scatter staged through the CPU ([`Takes::staging`]) out of `source` (the + /// module docs' "First touch"): `length` bytes of the copy, each piece at its byte of them, + /// which the GPU's copy reads from the buffer's bytes or the texture's texels `source` names, + /// whose use is `read_by`. Its work is left to two host steps ([`StagedScatter`]), the GPU's + /// copy into the staging at its place in the encoder, `read_by` noted there, and the CPU's + /// copy into the pages at the start of a part of its own after it, its writes of the chunks' + /// bytes noted there, by their keys. Each chunk is taken as an object over it takes it, and + /// asked of the device's thread where it is not imported ([`RamOnDevice::take_for_copies`]). + /// A buffer detached since records nothing, as a command over it does. + pub(super) fn record_staged_scatter( &mut self, - call: &HostRamCall, ram: &Arc, (pieces, spans): (&[Piece], &[Range]), - (raw, at, span, total): (vk::Buffer, u64, Range, u64), + (source, length, read_by): (Target, u64, Use), + total: u64, ) -> Result<(), Error> { let device = self.core().device().clone(); - let read = Access::new(TRANSFER, vk::AccessFlags2::TRANSFER_READ); let write = Access::new(TRANSFER, vk::AccessFlags2::TRANSFER_WRITE); - let reads = [reads_by(&call.buffer, span.clone(), read)]; + let reads = [read_by]; if !self.core().note_left_uses(TRANSFER, &reads) { return Ok(()); } @@ -2250,9 +2345,8 @@ impl BlitCommandEncoder { .collect(); let staged = Arc::new(StagedScatter { _ram: Arc::clone(ram), - source: (raw, at), - length: span.end - span.start, - covered: covered(pieces), + source, + length, pieces: in_pages, region: OnceLock::new(), }); diff --git a/crates/metal2vulkan-runtime/src/host_ram/texture.rs b/crates/metal2vulkan-runtime/src/host_ram/texture.rs new file mode 100644 index 000000000..96af1f609 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/host_ram/texture.rs @@ -0,0 +1,522 @@ +//! Copies between a guest RAM and a texture, by the GPU, from the device's imports of the RAM's +//! chunks (a runtime extension: Metal has none): [`BlitCommandEncoder::copy_texture_from_host_ram`] +//! fills one 2D region of a slice and level of a texture from a surface laid out in the RAM, and +//! [`BlitCommandEncoder::copy_texture_to_host_ram`] copies the region back out into it. A VMM +//! whose guest's surface is a scatter of guest pages, cached in an optimal texture, copies it with +//! no view of the pages and no staging buffer of its own. +//! +//! - **The surface** is its bytes in order, given as host runs laid one after another from its +//! first byte (`runs`: a surface's pages, each run starting on a 4-byte word, as +//! `copy_from_host_ram` takes them), and the region's place in them as a buffer's in Metal's +//! `copyFromBuffer:sourceOffset:sourceBytesPerRow:...`: row `y` of the region from surface byte +//! `offset + y × bytes_per_row`, its texels one after another. Metal's checks of that layout +//! are a buffer's (`blit_plan.rs`'s `check_layout`, the surface's bytes its length: +//! `Problem::Copy`), and of the region the texture's (`copy_plan.rs`'s `check_region`). +//! - **One region per row piece, straight on the imports.** Each row's texel bytes are cut where +//! a run ends and where a chunk ends (`copy.rs`'s `pieces`), and each piece is one region of a +//! `vkCmdCopyBufferToImage` (or `vkCmdCopyImageToBuffer`) on the import that holds it (the +//! chunk's, a range's alone, a list's: `RamOnDevice::copy_imports`, taken as the buffer forms +//! take them), its `bufferOffset` the piece's byte in that import and its `bufferRowLength` and +//! `bufferImageHeight` 0 (a row's texels, tight: `VUID-VkBufferImageCopy-bufferRowLength-09101`), +//! the regions of one import one command, at most `MOST_REGIONS` each. No staging copy and no +//! other byte of the pages read or written: the bytes between the rows and around the surface +//! stay as they were. A piece must start on a texel of its row and of host memory and hold +//! whole texels, so that its `bufferOffset` is a multiple of the texel's bytes +//! (`VUID-vkCmdCopyBufferToImage-dstImage-07975`, `VUID-vkCmdCopyImageToBuffer-srcImage-07975`; +//! the imports start on host pages); its texels lie inside the level (`check_region`: +//! `VUID-vkCmdCopyBufferToImage-imageSubresource-07971` and `-07972`, the same for +//! `vkCmdCopyImageToBuffer`), and no location is both a region's source and another's +//! destination (the image and the imports are apart: `VUID-vkCmdCopyBufferToImage-pRegions-00173`, +//! `VUID-vkCmdCopyImageToBuffer-pRegions-00184`). A piece that is not so (a run that splits a +//! texel, a surface whose texels lie off their size in host memory) is refused +//! (`Problem::HostRam`): the caller copies through a view of the pages. A copy out of the +//! texture whose pieces name a host byte twice takes a round of commands for each +//! (`copy.rs`'s `rounds`), the later piece's bytes kept. Counted: +//! `WorkCounts::host_ram_copies`, `host_ram_copy_bytes`, `host_ram_copy_regions`. +//! - **Ordered and seen as the buffer forms are** (`copy.rs`'s module docs): the chunks' bytes the +//! pieces touch by the chunks' keys (a read into the texture, a write out of it, reported to the +//! RAM's log of dirty pages where it has one), and the texture's region as a blit's copy with a +//! buffer uses it, the texture held by the command buffer until it completes. First touch and a +//! chunk that takes no import while it runs are staged through the CPU as the buffer forms +//! stage them (`StagedGather`, `StagedScatter`), the GPU's copy between the arena's region and +//! the texture one `vkCmdCopyBufferToImage` or `vkCmdCopyImageToBuffer` of the region's rows at +//! the surface's pitch; an encoding again stages them again as the buffer forms do. +//! - **The texture's contract**: an image of its own (not a texture over a buffer, a texture +//! buffer or a texture whose blits take a shadow's copies), one sample, a colour format of +//! uncompressed texels the image holds one to a texel (no block-compressed, depth, stencil, +//! two-plane or carried format), and a region of one image (a depth of 1). Any other is refused +//! (`Problem::HostRam`). A texture Metal keeps losslessly compressed is written as Metal's blit +//! writes it where the runtime rewrites such copies (`extended_canonical.rs`), else the bytes +//! are kept and announced (`compressed_blit.rs`), as a copy with a buffer is. + +use super::copy::{ + chunk_ranges, count_waited, in_imports, pieces, rounds, touched_bytes, touched_ranges, + used_ram, Piece, Run, Staging, Target, MOST_RANGES, MOST_REGIONS, WORD, +}; +use super::{CopyImports, HostRam, RamOnDevice}; +use crate::blit::{BlitCommandEncoder, TRANSFER}; +use crate::blit_plan::{check_layout, BufferImageRegion, BufferLayout}; +use crate::blit_texture::{buffer_image_region, copy_size, subresources, unit}; +use crate::compressed_blit::{self, degrade_compressed_blit}; +use crate::copy_plan::{check_region, shape, BlitOption, ImageRegion}; +use crate::error::{invalid, Error, Problem}; +use crate::fresh_unwritten::FreshUnwritten; +use crate::pvrtc::{image_buffer_region, image_region}; +use crate::replay::BlitCall; +use crate::sparse::emulated::Written; +use crate::texture::Texture; +use crate::tracker::{Access, Use, UseRange}; +use crate::two_planes; +use crate::values::{Origin, Size}; +use ash::vk; +use metal2vulkan::bind::PagesCopy; +use metal2vulkan::vk::ImageAspectFlags; +use std::collections::BTreeMap; +use std::ops::Range; +use std::sync::{Arc, OnceLock}; + +/// A copy between a guest RAM's surface and a texture's region as its call gave it +/// ([`BlitCall::HostRamTextureCopy`]), which an encoding again runs again (`replay.rs`). +pub(crate) struct HostRamTextureCall { + /// `Gather` into the texture, `Scatter` out of it. + copy: PagesCopy, + /// The device's use of the RAM; `None` where it uses none such. + ram: Option>, + /// The surface's bytes in order, as host runs laid one after another. + runs: Box<[Range]>, + /// The region's first byte of the surface and the surface's bytes per row. + layout: (u64, u64), + texture: Texture, + /// The region: its slice, level, origin and size. + region: (u64, u64, Origin, Size), + /// How its first encoding staged it through the CPU, where it did: an encoding again stages + /// it so again where [`Staging::again`] says. + staged: OnceLock, +} + +impl HostRamTextureCall { + /// The call's name, as its refusals give it. + fn name(&self) -> &'static str { + match self.copy { + PagesCopy::Gather => "copy_texture_from_host_ram", + PagesCopy::Scatter => "copy_texture_to_host_ram", + } + } + + /// The bytes it holds of its own, besides its size: its runs. + pub(crate) fn extra(&self) -> usize { + std::mem::size_of_val(&*self.runs) + } +} + +/// The runs of `runs`, a surface's bytes in order as host runs laid one after another, that the +/// surface's bytes `spans` lie in, cut to them, each at its byte of the surface: in one pass, +/// `spans` ascending and apart (a region's rows), their bytes inside the runs' total. +fn laid_over(runs: &[Range], spans: impl IntoIterator>) -> Vec { + let mut out = Vec::new(); + let (mut next, mut at) = (0usize, 0u64); + for span in spans { + while let Some(run) = runs.get(next) { + let end = at + (run.end - run.start); + let (from, to) = (span.start.max(at), span.end.min(end)); + if from < to { + out.push((from, run.start + (from - at)..run.start + (to - at))); + } + if end > span.end { + // The run goes on past the span, into the next one's bytes. + break; + } + (next, at) = (next + 1, end); + } + } + out +} + +impl BlitCommandEncoder { + /// Copy one 2D region of `destination` from a surface laid out in the guest RAM `ram`, by the + /// GPU, from the device's imports of the RAM's chunks: a runtime extension, Metal has none (a + /// program copies from a no-copy buffer over the pages, `copy_from_buffer_to_texture`). The + /// surface is `runs`, its bytes in order as host runs inside the RAM's ranges laid one after + /// another from its first byte, each starting on a 4-byte word (as + /// [`copy_from_host_ram`](Self::copy_from_host_ram) takes them); `source_size` texels of it, + /// row `y` from surface byte `source_offset + y × source_bytes_per_row`, land in + /// `destination_level` and `destination_slice` at `destination_origin`, as + /// `copy_from_buffer_to_texture` would land them from a buffer of the surface's bytes. Each + /// row's texels in each run and chunk are one region of a `vkCmdCopyBufferToImage` straight + /// from the import that holds them (the module docs of `host_ram/texture.rs`): no staging + /// copy, and no byte of the pages but the region's texels read. Ordered and seen as + /// [`copy_from_host_ram`](Self::copy_from_host_ram) is (the CPU's writes before the commit + /// seen, hazard tracking over the host bytes), and the texture written as by any blit; first + /// touch through the CPU as that call says. + /// + /// A size of 0 copies nothing. + /// + /// Refused: a device that imports no host memory (`Unsupported`, naming + /// `VK_EXT_external_memory_host`); a RAM the device does not use + /// ([`Device::use_host_ram`](crate::Device::use_host_ram)), a run that is empty, starts off a + /// 4-byte word or lies outside the RAM's ranges, a row's piece in a run or chunk that does not + /// start on a texel of host memory or hold whole texels, and a texture that is not one + /// image of its own of one sample and uncompressed colour texels one to a texel, or a + /// region of more than one image (a texture over a buffer, a texture buffer, a multisampled, + /// block-compressed, depth, stencil, two-plane or carried format: `Invalid`, + /// `Problem::HostRam`); a region past the level, a `source_offset` or `source_bytes_per_row` + /// off the texel, rows that overlap, or rows past the surface's bytes (`Invalid`, + /// `Problem::Copy`, as `copy_from_buffer_to_texture` refuses them); a texture of another + /// device (`Invalid`); and a chunk the device cannot import (the import's error). A caller + /// falls back to its own copy. + pub fn copy_texture_from_host_ram( + &mut self, + ram: &HostRam, + runs: &[Range], + source_offset: u64, + source_bytes_per_row: u64, + source_size: Size, + destination: &Texture, + destination_slice: u64, + destination_level: u64, + destination_origin: Origin, + ) -> Result<(), Error> { + let device = self.core().device().clone(); + let call = HostRamTextureCall { + copy: PagesCopy::Gather, + ram: used_ram(&device, ram), + runs: runs.into(), + layout: (source_offset, source_bytes_per_row), + texture: destination.clone(), + region: ( + destination_slice, + destination_level, + destination_origin, + source_size, + ), + staged: OnceLock::new(), + }; + self.host_ram_texture_copy(&Arc::new(call)) + } + + /// Copy one 2D region of `source` out into a surface laid out in the guest RAM `ram`, by the + /// GPU, into the device's imports of the RAM's chunks: the copy + /// [`copy_texture_from_host_ram`](Self::copy_texture_from_host_ram) makes the other way, a + /// runtime extension (Metal has none). `source_size` texels of `source_level` and + /// `source_slice` from `source_origin` land in the surface `runs` (its bytes in order, as + /// that call takes them), row `y` from surface byte `destination_offset + y × + /// destination_bytes_per_row`, each row's texels in each run and chunk one region of a + /// `vkCmdCopyImageToBuffer` straight into the import that holds them. Only the region's texels + /// are written: the bytes between the rows and the rest of the pages keep what they held. + /// Ordered and seen as [`copy_to_host_ram`](Self::copy_to_host_ram) is: its bytes are in the + /// pages once the command buffer completed, and where the RAM came with a log of its pages' + /// writes (`HostRam::with_dirty_pages`) they are reported to it as the GPU's writes in place. + /// Runs that name a host byte twice leave it as the later row's texels wrote it. + /// + /// Refused as [`copy_texture_from_host_ram`](Self::copy_texture_from_host_ram), `source` in + /// place of the destination. + pub fn copy_texture_to_host_ram( + &mut self, + source: &Texture, + source_slice: u64, + source_level: u64, + source_origin: Origin, + source_size: Size, + ram: &HostRam, + runs: &[Range], + destination_offset: u64, + destination_bytes_per_row: u64, + ) -> Result<(), Error> { + let device = self.core().device().clone(); + let call = HostRamTextureCall { + copy: PagesCopy::Scatter, + ram: used_ram(&device, ram), + runs: runs.into(), + layout: (destination_offset, destination_bytes_per_row), + texture: source.clone(), + region: (source_slice, source_level, source_origin, source_size), + staged: OnceLock::new(), + }; + self.host_ram_texture_copy(&Arc::new(call)) + } + + /// Run `call`, logged first where the encoder logs (`replay.rs`). + pub(crate) fn host_ram_texture_copy( + &mut self, + call: &Arc, + ) -> Result<(), Error> { + self.logged( + |_| BlitCall::HostRamTextureCopy(Arc::clone(call)), + |this| this.record_host_ram_texture_copy(call), + ) + } + + /// Check `call` and record it (the module docs). + fn record_host_ram_texture_copy(&mut self, call: &HostRamTextureCall) -> Result<(), Error> { + let name = call.name(); + let into = call.copy == PagesCopy::Gather; + let texture = &call.texture; + self.check_texture(name, texture)?; + let device = self.core().device().clone(); + let shared = device.shared(); + let importer = match &shared.host_import { + Ok(importer) => importer, + Err(unsupported) => return Err(Error::Unsupported(unsupported.clone())), + }; + let refused = || invalid(name, Problem::HostRam); + let ram = (call.ram.as_ref()) + .filter(|ram| shared.host_ram.uses(ram)) + .ok_or_else(refused)?; + texture.check_plane_copied()?; + if self.fails_on_memoryless(&[texture]) { + return Ok(()); + } + texture.check_rotated_reach()?; + let (slice, level, origin, size) = call.region; + let Some(size) = copy_size(size, &[texture.texture_type()]) else { + return Ok(()); + }; + // The texture's contract (the module docs): one image of its own, one sample, a region of + // one image of uncompressed colour texels one to a texel. + let own_image = !texture.over_buffer() && texture.shadow().is_none(); + let planes = two_planes::holds_planes(texture.pixel_format()); + if !own_image || planes || texture.record().samples > 1 || size.depth != 1 { + return Err(refused()); + } + let unit = unit(name, texture, BlitOption::None)?; + if unit.extent != [1, 1] || unit.aspect != ImageAspectFlags::COLOR { + return Err(refused()); + } + let region = crate::blit_texture::region(name, origin, size, level, slice)?; + let image = check_region(texture.record(), ®ion, &unit) + .map_err(|problem| invalid(name, Problem::Copy(problem)))?; + let plan = texture.image_plan()?; + if image_region(plan, image) != image { + return Err(refused()); + } + // The surface's bytes, and Metal's checks of the region's layout over them. + let mut surface: u64 = 0; + for run in call.runs.iter() { + if run.start >= run.end || !run.start.is_multiple_of(WORD) { + return Err(refused()); + } + surface = (surface.checked_add(run.end - run.start)).ok_or_else(refused)?; + } + let (offset, bytes_per_row) = call.layout; + let layout = BufferLayout { + offset, + bytes_per_row, + bytes_per_image: 0, + }; + let spanned = check_layout(&layout, region.size, &unit, surface) + .map_err(|problem| invalid(name, Problem::Copy(problem)))?; + let rows = shape(region.size, &unit); + // Each row's texel bytes, in the runs, cut where a chunk ends: within the surface's bytes + // (`check_layout`), so no row's byte passes `u64`. + let row_bytes = (0..rows.rows).map(|y| { + let start = offset + y * bytes_per_row; + start..start + rows.row_bytes + }); + let laid = laid_over(&call.runs, row_bytes); + let chunks = ram.chunks(); + let spans = &chunks.spans; + let (pieces, total) = pieces(&laid, &chunks).ok_or_else(refused)?; + let texel = u64::from(unit.bytes); + let whole = |piece: &Piece| { + let host = spans[piece.slot].start + piece.offset; + piece.at.is_multiple_of(texel) + && piece.length.is_multiple_of(texel) + && host.is_multiple_of(texel) + }; + if !pieces.iter().all(whole) { + return Err(refused()); + } + // The chunks' bytes the pieces touch, and how the copy takes their chunks: as the buffer + // forms take them (`copy.rs`). + let (ranges, host_twice) = touched_ranges(&pieces, spans); + if !into { + for &slot in ranges.keys() { + ram.copy_wrote(slot); + } + } + let again = (self.core().encodes_again()) + .then(|| { + call.staged + .get() + .and_then(|staging| staging.again(call.copy)) + }) + .flatten(); + let takes = self.takes(ram, importer, &ranges); + let written = || into && ram.written_over(&device, &touched_bytes(&pieces, spans)); + let (levels, layers) = subresources(&image); + let access = match into { + true => Access::new(TRANSFER, vk::AccessFlags2::TRANSFER_WRITE), + false => Access::new(TRANSFER, vk::AccessFlags2::TRANSFER_READ), + }; + let image_use = texture.image_use(levels, layers, access, into)?; + // The host bytes' use: the other side of the copy's. + let host_access = match into { + true => Access::new(TRANSFER, vk::AccessFlags2::TRANSFER_READ), + false => Access::new(TRANSFER, vk::AccessFlags2::TRANSFER_WRITE), + }; + let raw_image = texture.raw_image()?; + if let Some(staging) = again.or_else(|| takes.staging(written)) { + // The first encoding's staging, which an encoding again finds set. + let _ = call.staged.set(staging); + // The region's rows at the surface's pitch in the arena's region, from its first. + let texels_per_row = match rows.rows { + 1 => Some(0), + _ => u32::try_from(bytes_per_row / texel).ok(), + }; + let row_length = texels_per_row.ok_or_else(refused)?; + let staged = BufferImageRegion { + buffer_offset: 0, + row_length, + image_height: 0, + image, + }; + let target = Target::Image { + image: raw_image, + regions: vec![buffer_image_region(&image_buffer_region(plan, staged))], + }; + let from_first: Vec = (pieces.iter()) + .map(|piece| Piece { + at: piece.at - offset, + ..*piece + }) + .collect(); + let side = (target, spanned, image_use); + match into { + true => self.record_staged(ram, (&from_first, spans), side, total, staging)?, + false => self.record_staged_scatter(ram, (&from_first, spans), side, total)?, + } + return self.texture_written(name, texture, into, image); + } + let CopyImports { + imports, + of_chunk, + waited, + } = ram.copy_imports(&device, importer, &ranges)?; + count_waited(&device, waited); + let in_imports = in_imports(&imports, &of_chunk, &pieces, spans)?; + // A copy out of the texture whose pieces name a host byte twice goes by rounds, no byte + // written by two regions of one command, the later piece's kept. + let by_round = match (into, host_twice) { + (false, true) => { + let host: Vec> = (pieces.iter()) + .map(|piece| { + let start = spans[piece.slot].start + piece.offset; + start..start + piece.length + }) + .collect(); + rounds(&host) + } + _ => vec![(0..pieces.len()).collect()], + }; + // A copy out of the texture reads its region alone (`fresh_unwritten.rs`). + let fresh_reads = match into { + true => Vec::new(), + false => { + let read = [(image.aspect.into(), Written::of(&image))]; + FreshUnwritten::reads(&device, texture, &read)? + } + }; + let mut regions_recorded = 0u64; + for round in &by_round { + // The round's regions, by import, in order: each piece a row's texels from its byte. + let mut by_import: BTreeMap> = BTreeMap::new(); + for &index in round { + let piece = &in_imports[index]; + if !piece.offset.is_multiple_of(texel) { + return Err(refused()); + } + let from_first = piece.at - offset; + let y = match rows.rows { + 1 => 0, + _ => from_first / bytes_per_row, + }; + let x = (from_first - y * bytes_per_row) / texel; + // Inside the region (`check_region`), whose extent is a `u32`'s. + let texels = ImageRegion { + origin: [ + image.origin[0] + x as u32, + image.origin[1] + y as u32, + image.origin[2], + ], + size: [(piece.length / texel) as u32, 1, 1], + ..image + }; + let region = BufferImageRegion { + buffer_offset: piece.offset, + row_length: 0, + image_height: 0, + image: texels, + }; + let region = buffer_image_region(&image_buffer_region(plan, region)); + by_import.entry(piece.slot).or_default().push(region); + } + // The round's uses: the chunks' bytes it reads or writes, by their keys, and the + // texture's region. + let round_pieces: Vec = round.iter().map(|&index| pieces[index]).collect(); + let mut uses = Vec::new(); + for (slot, ranges) in chunk_ranges(&round_pieces, MOST_RANGES) { + let key = ram.chunk_key(&device, slot); + for range in ranges { + let range = UseRange::Bytes(range); + uses.push(match into { + true => Use::reads(key, true, range, host_access), + false => Use::writes(key, true, range, host_access), + }); + } + } + uses.push(image_use.clone()); + regions_recorded += round.len() as u64; + let imports = &imports; + self.command_reading(&uses, (&fresh_reads, &[]), |functions, raw| { + let general = vk::ImageLayout::GENERAL; + for (slot, regions) in &by_import { + let chunk = imports[*slot].raw; + for part in regions.chunks(MOST_REGIONS) { + // SAFETY: the encoder's command buffer is recording, outside a render + // pass; the imports and the texture are live until it completes (held + // below); each region's bytes lie inside its import (`pieces`, the imports + // made over them) from a multiple of the texel's bytes, its texels inside + // the level (`check_region`), the image is in the `GENERAL` layout, and + // no byte is written by two regions of one command (`rounds`). + unsafe { + match into { + true => functions + .cmd_copy_buffer_to_image(raw, chunk, raw_image, general, part), + false => functions + .cmd_copy_image_to_buffer(raw, raw_image, general, chunk, part), + } + }; + } + } + })?; + } + shared.counts.host_ram_copied(total, 0); + shared.counts.host_ram_copy_regions(regions_recorded); + self.core().retain(imports); + self.texture_written(name, texture, into, image) + } + + /// After a copy `call` recorded between the guest RAM and `region` of `texture`: the texture + /// held until the command buffer completes; into it (`into`), its region written + /// (`BlitCommandEncoder::scrub`), Metal's encoding of the texels where it keeps the texture + /// losslessly compressed and the runtime rewrites them, else the note that the bytes are kept, + /// and its decoded twin's texels; out of it, that note. + fn texture_written( + &mut self, + call: &'static str, + texture: &Texture, + into: bool, + region: ImageRegion, + ) -> Result<(), Error> { + self.core().retain_shared(texture.held()); + if !into { + return degrade_compressed_blit(call, texture); + } + self.scrub(texture, vec![(region.aspect.into(), Written::of(®ion))])?; + let written = [region]; + if !(compressed_blit::canonical(texture) && self.canonical_texels(texture, &written)?) { + degrade_compressed_blit(call, texture)?; + } + self.decode_twin(texture, &written) + } +} diff --git a/crates/metal2vulkan-runtime/src/replay.rs b/crates/metal2vulkan-runtime/src/replay.rs index d7319d214..1a9ce5e95 100644 --- a/crates/metal2vulkan-runtime/src/replay.rs +++ b/crates/metal2vulkan-runtime/src/replay.rs @@ -67,6 +67,7 @@ use super::fence::Fence; use super::function_table::VisibleFunctionTable; use super::heap::Heap; use super::host_ram::copy::HostRamCall; +use super::host_ram::texture::HostRamTextureCall; use super::indirect_command_buffer::IndirectCommandBuffer; use super::pipeline::{ComputePipelineState, RenderPipelineState}; use super::render::{RenderLog, RenderRoom}; @@ -805,6 +806,8 @@ pub(super) enum BlitCall { InvalidateCompressedTextureSlice(Texture, u64, u64), /// `copy_from_host_ram` or `copy_to_host_ram` (`host_ram/copy.rs`). HostRamCopy(Arc), + /// `copy_texture_from_host_ram` or `copy_texture_to_host_ram` (`host_ram/texture.rs`). + HostRamTextureCopy(Arc), } impl BlitCall { @@ -843,6 +846,7 @@ impl BlitCall { BlitCall::InvalidateCompressedTexture(_) => "invalidate_compressed_texture", BlitCall::InvalidateCompressedTextureSlice(..) => "invalidate_compressed_texture_slice", BlitCall::HostRamCopy(_) => "copy_from_host_ram", + BlitCall::HostRamTextureCopy(_) => "copy_texture_from_host_ram", }; Err(name) } @@ -858,6 +862,7 @@ impl BlitCall { BlitCall::CopyTextureSlices(call) => std::mem::size_of_val(&**call), BlitCall::CopyIndirectCommandBuffer(call) => std::mem::size_of_val(&**call), BlitCall::HostRamCopy(call) => std::mem::size_of_val(&**call) + call.extra(), + BlitCall::HostRamTextureCopy(call) => std::mem::size_of_val(&**call) + call.extra(), _ => 0, } } @@ -1208,5 +1213,6 @@ fn blit( encoder.invalidate_compressed_texture_slice(texture, *slice, *level) } B::HostRamCopy(call) => encoder.host_ram_copy(call), + B::HostRamTextureCopy(call) => encoder.host_ram_texture_copy(call), } } diff --git a/crates/metal2vulkan-runtime/src/tests/host_ram_copy_device.rs b/crates/metal2vulkan-runtime/src/tests/host_ram_copy_device.rs index a5192b9e0..b06146d29 100644 --- a/crates/metal2vulkan-runtime/src/tests/host_ram_copy_device.rs +++ b/crates/metal2vulkan-runtime/src/tests/host_ram_copy_device.rs @@ -103,13 +103,13 @@ use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; -const WAIT: Duration = Duration::from_secs(60); -const MIB: u64 = 1 << 20; -const PAGE: u64 = 4096; +pub(super) const WAIT: Duration = Duration::from_secs(60); +pub(super) const MIB: u64 = 1 << 20; +pub(super) const PAGE: u64 = 4096; /// The RAM's bytes: one whole chunk and a short second. -const RAM_BYTES: u64 = 64 * MIB + MIB; +pub(super) const RAM_BYTES: u64 = 64 * MIB + MIB; /// The first page of the second chunk. -const SECOND: u64 = 64 * MIB / PAGE; +pub(super) const SECOND: u64 = 64 * MIB / PAGE; /// Anonymous memory standing in for a guest's RAM, unmapped by the keep-alive it is given to. struct Mapping { @@ -127,7 +127,7 @@ impl Drop for Mapping { } /// A RAM of `RAM_BYTES`, its writes logged to `log` where given, and its first byte. -fn new_ram(log: Option>) -> (Arc, u64) { +pub(super) fn new_ram(log: Option>) -> (Arc, u64) { ram_of(RAM_BYTES, log) } @@ -148,7 +148,7 @@ fn ram_of(length: u64, log: Option>) -> (Arc, u64) { /// A device of the cfg's kind whose uses of a RAM start no thread importing its chunks ahead /// (`Device::hold_host_ram_imports`): each chunk is imported by the first copy or object over /// it. `None` where it imports no host memory. -fn device() -> Option { +pub(super) fn device() -> Option { let device = ahead_device()?; device.hold_host_ram_imports(); Some(device) @@ -182,13 +182,13 @@ fn ahead_device() -> Option { /// The byte `seed`'s pattern holds at host address `address`: the top byte of a product, which /// every bit of the address moves, so no two pages hold the same bytes. -fn pattern(address: u64, seed: u64) -> u8 { +pub(super) fn pattern(address: u64, seed: u64) -> u8 { let mixed = (address ^ seed.wrapping_mul(0x9e37_79b9)).wrapping_mul(0x9e37_79b9_7f4a_7c15); (mixed >> 56) as u8 } /// Write `seed`'s pattern over `range` of host addresses, while no command buffer runs. -fn write_pattern(range: Range, seed: u64) { +pub(super) fn write_pattern(range: Range, seed: u64) { for address in range { // SAFETY: bytes of the test's RAM, which no command buffer uses now. unsafe { *(address as *mut u8) = pattern(address, seed) }; @@ -196,7 +196,7 @@ fn write_pattern(range: Range, seed: u64) { } /// The bytes of `range` of host addresses, while no command buffer writes them. -fn bytes(range: Range) -> Vec { +pub(super) fn bytes(range: Range) -> Vec { let length = (range.end - range.start) as usize; // SAFETY: as above. unsafe { std::slice::from_raw_parts(range.start as *const u8, length) }.to_vec() @@ -216,7 +216,7 @@ fn shared(device: &Device, length: u64, fill: impl Fn(u64) -> u8) -> Buffer { } /// A `Shared` buffer's bytes, while no command writes them. -fn contents(buffer: &Buffer) -> Vec { +pub(super) fn contents(buffer: &Buffer) -> Vec { let contents = buffer.contents().unwrap(); // SAFETY: as above. unsafe { std::slice::from_raw_parts(contents.as_ptr(), buffer.length() as usize) }.to_vec() @@ -234,7 +234,7 @@ fn run(device: &Device, encode: impl FnOnce(&CommandBuffer), before: impl FnOnce } /// One command buffer of one blit encoder `encode` fills, committed and waited for. -fn blit(device: &Device, encode: impl FnOnce(&mut crate::BlitCommandEncoder)) { +pub(super) fn blit(device: &Device, encode: impl FnOnce(&mut crate::BlitCommandEncoder)) { run( device, |command_buffer| { @@ -1088,7 +1088,7 @@ fn copies_are_ordered_against_a_no_copy_buffer_over_the_same_pages() { /// The test's log of a RAM's writes: every write it is told of, stamped, with its writer (0 the /// consumer's). #[derive(Default)] -struct Log { +pub(super) struct Log { next: AtomicU64, writes: Mutex, u64)>>, } @@ -1100,7 +1100,7 @@ impl Log { } /// Whether a write by `writer` covering `range` was told. - fn heard(&self, range: &Range, writer: u64) -> bool { + pub(super) fn heard(&self, range: &Range, writer: u64) -> bool { let writes = self.writes.lock().unwrap(); (writes.iter()).any(|w| w.2 == writer && w.1.start <= range.start && range.end <= w.1.end) } @@ -1589,7 +1589,7 @@ fn a_copy_takes_its_chunks_as_an_object_does_and_the_window_ahead_moves_past_the /// Single pages 3 MiB apart in chunks 2 and 3 of a RAM from `start`: 20 ranges in each, more than /// a copy imports alone (`copy::MOST_ALONE`), none joined (`copy::JOIN_GAP`). -fn scattered_pages(start: u64) -> Vec> { +pub(super) fn scattered_pages(start: u64) -> Vec> { let mut runs = Vec::new(); for chunk in [2, 3] { for at in 0..20 { @@ -1603,7 +1603,7 @@ fn scattered_pages(start: u64) -> Vec> { /// A device whose thread imports ahead, using a RAM of four chunks whose first the thread /// imported, and settled: the device, the RAM's use, the RAM and its first byte, and the counts /// before the use. `None` where it imports no host memory. -fn ahead_ram() -> Option<(Device, crate::HostRamUse, Arc, u64, WorkCounts)> { +pub(super) fn ahead_ram() -> Option<(Device, crate::HostRamUse, Arc, u64, WorkCounts)> { let device = ahead_device()?; let (ram, start) = ram_of(4 * 64 * MIB, None); let before = device.work_counts(); diff --git a/crates/metal2vulkan-runtime/src/tests/host_ram_texture_device.rs b/crates/metal2vulkan-runtime/src/tests/host_ram_texture_device.rs new file mode 100644 index 000000000..ddcfab713 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/host_ram_texture_device.rs @@ -0,0 +1,553 @@ +//! Copies between a guest RAM's surface and a texture on a device (`host_ram/texture.rs`): +//! `BlitCommandEncoder::copy_texture_from_host_ram` and `copy_texture_to_host_ram`. +//! +//! - **Both ways, texel for texel, straight from the imports.** A 300 by 200 `BGRA8Unorm` +//! `Private` texture fills from a surface of 63 pages scattered over the RAM's two chunks +//! (two of them side by side across the first chunk's end, one run), its rows 1,280 bytes apart +//! from byte 48: every texel its row's bytes, one region for each row's bytes in a run and a +//! chunk (a row across the chunk's end two) and no dispatch or staging. Copied back out into +//! the pages, rewritten since, only the texels' bytes change: the bytes between the rows and +//! every other byte of the RAM stay, and the writes are told to the RAM's log. +//! - **Ordered as a blit is**, in one command buffer: a fill of part of the texture after a render +//! pass cleared it leaves the clear around the region and the surface's texels in it, as a +//! blit's read after it reads; a copy out after a render pass cleared the texture writes the +//! clear's texels, as a gather from the RAM after it reads. +//! - **First touch through the CPU**, on a device whose thread imports ahead: a fill from, and a +//! copy out into, pages of chunks not imported yet are staged (one copy of the region's rows +//! between the arena and the texture), and move the same texels. +//! - **Refused**: a RAM the device does not use, a run off a word, a run that splits a texel, a +//! region past the level, a pitch off the texel, rows past the surface, and textures off the +//! copies' contract (multisampled, depth, block-compressed). +//! +//! Device tests: compiled only under the GPU safety cfgs (`m2v_gpu`, `m2v_cpu_icd`), on the kind +//! of device the cfg selects. A device that imports no host memory says so and passes. + +use super::host_ram_copy_device::{ + ahead_ram, blit, bytes, contents, device, new_ram, pattern, scattered_pages, write_pattern, + Log, PAGE, RAM_BYTES, SECOND, WAIT, +}; +use crate::{ + BlitOption, Buffer, ClearColor, CommandBuffer, CommandBufferStatus, CopyProblem, Device, Error, + LoadAction, Origin, Problem, RenderPassDescriptor, ResourceOptions, Size, StoreAction, Texture, + TextureDescriptor, +}; +use metal2vulkan::metal::{PixelFormat, TextureType, TextureUsage}; +use std::ops::Range; +use std::sync::Arc; + +const WIDTH: u64 = 300; +const HEIGHT: u64 = 200; +const TEXEL: u64 = 4; +/// The surface's first texel's byte and its bytes per row: past a row's 1,200. +const OFFSET: u64 = 48; +const PITCH: u64 = 1280; +/// The surface's pages: its bytes, `OFFSET + HEIGHT × PITCH`, rounded up. +const SURFACE_PAGES: u64 = (OFFSET + HEIGHT * PITCH).div_ceil(PAGE); + +/// The RAM's page surface page `i` lies in: apart from each other in the first chunk, then two +/// side by side across its end, then apart in the second. +fn surface_page(i: u64) -> u64 { + match i { + 0..30 => 100 + 2 * i, + 30 => SECOND - 1, + 31 => SECOND, + _ => SECOND + 10 + 3 * (i - 32), + } +} + +/// The host address of byte `at` of the surface. +fn host(start: u64, at: u64) -> u64 { + start + surface_page(at / PAGE) * PAGE + at % PAGE +} + +/// The surface's bytes in order as runs of the RAM, pages side by side one run. +fn surface_runs(start: u64) -> Vec> { + let mut runs: Vec> = Vec::new(); + for i in 0..SURFACE_PAGES { + let at = start + surface_page(i) * PAGE; + match runs.last_mut() { + Some(last) if last.end == at => last.end = at + PAGE, + _ => runs.push(at..at + PAGE), + } + } + runs +} + +/// The regions of a copy of `rows` rows of `width` texels from surface byte `offset` at `PITCH`: +/// one a row and one more for each page's end inside it (each is a run's or the chunk's end). +fn row_pieces(offset: u64, (width, rows): (u64, u64)) -> u64 { + (0..rows) + .map(|y| { + let first = offset + y * PITCH; + let last = first + width * TEXEL - 1; + 1 + last / PAGE - first / PAGE + }) + .sum() +} + +/// A `Private` `BGRA8Unorm` texture of `WIDTH` by `HEIGHT`, a render target. +fn bgra_texture(device: &Device) -> Texture { + let mut descriptor = + TextureDescriptor::texture_2d(PixelFormat::BGRA8Unorm, WIDTH, HEIGHT, false); + descriptor.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + descriptor.resource_options = ResourceOptions::private(); + device.new_texture(&descriptor).unwrap() +} + +/// A `Shared` buffer of `length` bytes. +fn shared(device: &Device, length: u64) -> Buffer { + device + .new_buffer(length, ResourceOptions::shared()) + .unwrap() +} + +/// Encode in `command_buffer` a blit of the whole of `texture` into `out`, rows one after +/// another. +fn read_into(command_buffer: &CommandBuffer, texture: &Texture, out: &Buffer) { + let mut encoder = command_buffer.blit_command_encoder().unwrap(); + encoder + .copy_from_texture_to_buffer( + texture, + 0, + 0, + Origin::new(0, 0, 0), + Size::new(WIDTH, HEIGHT, 1), + out, + 0, + WIDTH * TEXEL, + WIDTH * TEXEL * HEIGHT, + BlitOption::None, + ) + .unwrap(); + encoder.end_encoding().unwrap(); +} + +/// Encode in `command_buffer` a render pass that clears `texture` to `color` and stores it. +fn clear(command_buffer: &CommandBuffer, texture: &Texture, color: [f64; 4]) { + let mut pass = RenderPassDescriptor::new(); + let attachment = &mut pass.color_attachments[0]; + attachment.texture = Some(texture.clone()); + attachment.load_action = LoadAction::Clear; + let [r, g, b, a] = color; + attachment.clear_color = ClearColor::new(r, g, b, a); + attachment.store_action = StoreAction::Store; + let encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encoder.end_encoding().unwrap(); +} + +/// Commit `command_buffer` and wait for it. +fn complete(command_buffer: &CommandBuffer) { + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); +} + +/// The texture's texels as a blit reads them, rows one after another. +fn read_back(device: &Device, texture: &Texture) -> Vec { + let out = shared(device, WIDTH * TEXEL * HEIGHT); + let queue = device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + read_into(&command_buffer, texture, &out); + complete(&command_buffer); + contents(&out) +} + +/// The surface's texels of a region of `width` by `rows` from surface byte `offset`, as the +/// CPU reads them, rows one after another. +fn surface_texels(start: u64, offset: u64, (width, rows): (u64, u64)) -> Vec { + let mut out = Vec::new(); + for y in 0..rows { + for b in 0..width * TEXEL { + let address = host(start, offset + y * PITCH + b); + out.extend(bytes(address..address + 1)); + } + } + out +} + +/// The counts a closure's work moved: regions, dispatches, staged gathers and scatters. +fn counted(device: &Device, work: impl FnOnce()) -> [u64; 4] { + let before = device.work_counts(); + work(); + let after = device.work_counts(); + [ + after.host_ram_copy_regions - before.host_ram_copy_regions, + after.host_ram_copy_dispatches - before.host_ram_copy_dispatches, + after.host_ram_copies_staged - before.host_ram_copies_staged, + after.host_ram_scatters_staged - before.host_ram_scatters_staged, + ] +} + +#[test] +fn a_texture_fills_from_a_surface_s_rows_and_copies_back_into_their_texel_bytes_alone() { + let Some(device) = device() else { + return; + }; + let log = Arc::new(Log::default()); + let (ram, start) = new_ram(Some(Arc::clone(&log))); + let _used = device.use_host_ram(&ram).unwrap(); + let runs = surface_runs(start); + let end = start + SECOND * PAGE; + assert!( + (runs.iter()).any(|run| run.start < end && end < run.end), + "a run across the first chunk's end" + ); + let crossing = (0..HEIGHT).any(|y| { + let row = OFFSET + y * PITCH..OFFSET + y * PITCH + WIDTH * TEXEL; + row.contains(&(31 * PAGE)) + }); + assert!(crossing, "a row across the chunk's end"); + for run in &runs { + write_pattern(run.clone(), 21); + } + let texture = bgra_texture(&device); + let whole = Size::new(WIDTH, HEIGHT, 1); + let origin = Origin::new(0, 0, 0); + let fill = counted(&device, || { + blit(&device, |encoder| { + (encoder.copy_texture_from_host_ram( + &ram, &runs, OFFSET, PITCH, whole, &texture, 0, 0, origin, + )) + .unwrap(); + }); + }); + assert!( + read_back(&device, &texture) == surface_texels(start, OFFSET, (WIDTH, HEIGHT)), + "every texel from its row's bytes" + ); + let pieces = row_pieces(OFFSET, (WIDTH, HEIGHT)); + eprintln!( + "HOST-RAM-TEXTURE {}: fill regions {}, dispatches {}, staged {}", + device.name(), + fill[0], + fill[1], + fill[2] + ); + assert_eq!( + fill, + [pieces, 0, 0, 0], + "a region a row's piece straight from its import, no dispatch, no staging" + ); + // Out again into the pages, rewritten since: the texels' bytes alone take the texture's. + for run in &runs { + write_pattern(run.clone(), 22); + } + let mut want = bytes(start..start + RAM_BYTES); + for y in 0..HEIGHT { + for b in 0..WIDTH * TEXEL { + let address = host(start, OFFSET + y * PITCH + b); + want[(address - start) as usize] = pattern(address, 21); + } + } + let out = counted(&device, || { + blit(&device, |encoder| { + (encoder.copy_texture_to_host_ram( + &texture, 0, 0, origin, whole, &ram, &runs, OFFSET, PITCH, + )) + .unwrap(); + }); + }); + let now = bytes(start..start + RAM_BYTES); + assert!( + now == want, + "the texels' bytes alone, and no other byte of the RAM" + ); + assert_eq!(out, [pieces, 0, 0, 0], "a region a row's piece, out"); + // Each row's texels told to the RAM's log as the GPU's writes in place. + for y in [0, 99, HEIGHT - 1] { + let first = host(start, OFFSET + y * PITCH); + assert!( + log.heard(&(first..first + 64), 0), + "row {y}'s writes told to the RAM's log" + ); + } +} + +#[test] +fn texture_copies_are_ordered_against_a_render_pass_before_and_a_read_after() { + let Some(device) = device() else { + return; + }; + let (ram, start) = new_ram(None); + let _used = device.use_host_ram(&ram).unwrap(); + let runs = surface_runs(start); + for run in &runs { + write_pattern(run.clone(), 23); + } + let texture = bgra_texture(&device); + let queue = device.new_command_queue().unwrap(); + // A fill of part of the texture after a clear of all of it, read back after it. + let (x, y, width, rows) = (20, 30, 260, 150); + let offset = OFFSET + 8 * TEXEL; + let out = shared(&device, WIDTH * TEXEL * HEIGHT); + let command_buffer = queue.command_buffer().unwrap(); + clear(&command_buffer, &texture, [0.0, 1.0, 0.0, 1.0]); + let mut encoder = command_buffer.blit_command_encoder().unwrap(); + let size = Size::new(width, rows, 1); + let at = Origin::new(x, y, 0); + (encoder.copy_texture_from_host_ram(&ram, &runs, offset, PITCH, size, &texture, 0, 0, at)) + .unwrap(); + encoder.end_encoding().unwrap(); + read_into(&command_buffer, &texture, &out); + complete(&command_buffer); + let got = contents(&out); + let texels = surface_texels(start, offset, (width, rows)); + for row in 0..HEIGHT { + for column in 0..WIDTH { + let at = ((row * WIDTH + column) * TEXEL) as usize; + let inside = (x..x + width).contains(&column) && (y..y + rows).contains(&row); + let want: &[u8] = match inside { + true => { + let from = (((row - y) * width + column - x) * TEXEL) as usize; + &texels[from..from + TEXEL as usize] + } + // BGRA: the clear's green, opaque. + false => &[0, 255, 0, 255], + }; + assert_eq!( + &got[at..at + TEXEL as usize], + want, + "texel ({column}, {row})" + ); + } + } + // A copy out after a clear, gathered from the RAM after it: the clear's texels. + let gathered = shared(&device, SURFACE_PAGES * PAGE); + let command_buffer = queue.command_buffer().unwrap(); + clear(&command_buffer, &texture, [1.0, 0.0, 0.0, 1.0]); + let mut encoder = command_buffer.blit_command_encoder().unwrap(); + let whole = Size::new(WIDTH, HEIGHT, 1); + let origin = Origin::new(0, 0, 0); + (encoder.copy_texture_to_host_ram(&texture, 0, 0, origin, whole, &ram, &runs, OFFSET, PITCH)) + .unwrap(); + encoder.end_encoding().unwrap(); + let mut encoder = command_buffer.blit_command_encoder().unwrap(); + encoder + .copy_from_host_ram(&ram, &runs, &gathered, 0) + .unwrap(); + encoder.end_encoding().unwrap(); + complete(&command_buffer); + let got = contents(&gathered); + for row in 0..HEIGHT { + let first = (OFFSET + row * PITCH) as usize; + for texel in got[first..first + (WIDTH * TEXEL) as usize].chunks(TEXEL as usize) { + assert_eq!( + texel, + [0, 0, 255, 255], + "row {row}: the clear's red, opaque" + ); + } + } +} + +#[test] +fn first_texture_copies_over_chunks_the_thread_imports_are_staged_through_the_cpu() { + // The surface over pages of chunks not imported yet: 40 pages, so a region of 100 rows. + let rows = 100; + let size = Size::new(WIDTH, rows, 1); + let origin = Origin::new(0, 0, 0); + let laid = |start: u64, at: u64| { + let runs = scattered_pages(start); + let page = &runs[(at / PAGE) as usize]; + page.start + at % PAGE + }; + let texels = |start: u64| { + let mut out = Vec::new(); + for y in 0..rows { + for b in 0..WIDTH * TEXEL { + let address = laid(start, OFFSET + y * PITCH + b); + out.extend(bytes(address..address + 1)); + } + } + out + }; + // A fill, staged. + let Some((device, used, ram, start, _)) = ahead_ram() else { + return; + }; + let runs = scattered_pages(start); + for run in &runs { + write_pattern(run.clone(), 31); + } + let texture = bgra_texture(&device); + let fill = counted(&device, || { + blit(&device, |encoder| { + (encoder.copy_texture_from_host_ram( + &ram, &runs, OFFSET, PITCH, size, &texture, 0, 0, origin, + )) + .unwrap(); + }); + }); + assert_eq!(fill, [0, 0, 1, 0], "the fill staged through the CPU"); + let got = read_back(&device, &texture); + assert!( + got[..(WIDTH * TEXEL * rows) as usize] == texels(start)[..], + "the staged fill's texels" + ); + drop((used, ram)); + // A copy out, staged, on a device of its own. + let Some((device, used, ram, start, _)) = ahead_ram() else { + return; + }; + let runs = scattered_pages(start); + for run in &runs { + write_pattern(run.clone(), 32); + } + let texture = bgra_texture(&device); + let source = shared(&device, WIDTH * TEXEL * rows); + let filled: Vec = (0..WIDTH * TEXEL * rows) + .map(|at| pattern(at, 33)) + .collect(); + let contents_at = source.contents().unwrap(); + // SAFETY: the buffer's bytes, which no command uses yet. + unsafe { + std::ptr::copy_nonoverlapping(filled.as_ptr(), contents_at.as_ptr(), filled.len()); + } + blit(&device, |encoder| { + encoder + .copy_from_buffer_to_texture( + &source, + 0, + WIDTH * TEXEL, + WIDTH * TEXEL * rows, + size, + &texture, + 0, + 0, + origin, + BlitOption::None, + ) + .unwrap(); + }); + // The surface's pages as they are, then with the texels' bytes the texture's. + let mut want: Vec> = runs.iter().map(|run| bytes(run.clone())).collect(); + for y in 0..rows { + for b in 0..WIDTH * TEXEL { + let at = OFFSET + y * PITCH + b; + want[(at / PAGE) as usize][(at % PAGE) as usize] = + filled[(y * WIDTH * TEXEL + b) as usize]; + } + } + let out = counted(&device, || { + blit(&device, |encoder| { + (encoder.copy_texture_to_host_ram( + &texture, 0, 0, origin, size, &ram, &runs, OFFSET, PITCH, + )) + .unwrap(); + }); + }); + assert_eq!(out, [0, 0, 0, 1], "the copy out staged through the CPU"); + for (page, run) in runs.iter().enumerate() { + assert!( + bytes(run.clone()) == want[page], + "the staged copy out's texels alone, in the surface's page {page}" + ); + } + drop((used, ram)); +} + +/// Whether `result` is the refusal `Invalid` of `problem`. +fn refused(result: Result<(), Error>, problem: &Problem) -> bool { + matches!(result, Err(Error::Invalid(invalid)) if invalid.problem == *problem) +} + +#[test] +fn texture_copies_off_their_contract_are_refused() { + let Some(device) = device() else { + return; + }; + let (ram, start) = new_ram(None); + let runs = surface_runs(start); + let texture = bgra_texture(&device); + let queue = device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.blit_command_encoder().unwrap(); + let whole = Size::new(WIDTH, HEIGHT, 1); + let origin = Origin::new(0, 0, 0); + let host_ram = Problem::HostRam; + // A RAM the device does not use yet. + let result = encoder + .copy_texture_from_host_ram(&ram, &runs, OFFSET, PITCH, whole, &texture, 0, 0, origin); + assert!(refused(result, &host_ram)); + let used = device.use_host_ram(&ram).unwrap(); + // A run off a word, and one that splits a texel (a run of 4,098 bytes, the next row's texel + // across its end). + let mut off = runs.clone(); + off[1].start += 2; + let mut split = runs.clone(); + split[0].end += 2; + for runs in [&off, &split] { + let into = encoder + .copy_texture_from_host_ram(&ram, runs, OFFSET, PITCH, whole, &texture, 0, 0, origin); + assert!(refused(into, &host_ram), "{:x?}", &runs[..2]); + let out = encoder + .copy_texture_to_host_ram(&texture, 0, 0, origin, whole, &ram, runs, OFFSET, PITCH); + assert!(refused(out, &host_ram), "{:x?}", &runs[..2]); + } + // A region past the level, a pitch or an offset off the texel, rows past the surface. + let copy = |problem: CopyProblem| Problem::Copy(problem); + let past = Size::new(WIDTH, HEIGHT, 1); + let shifted = Origin::new(1, 0, 0); + for (layout, size, at, problem) in [ + ((OFFSET, PITCH), past, shifted, copy(CopyProblem::Region)), + ( + (OFFSET, PITCH + 2), + whole, + origin, + copy(CopyProblem::BytesPerRow), + ), + ( + (OFFSET + 2, PITCH), + whole, + origin, + copy(CopyProblem::Offset), + ), + ( + (OFFSET + PAGE * 8, PITCH), + whole, + origin, + copy(CopyProblem::BufferRange), + ), + ] { + let (offset, pitch) = layout; + let into = encoder + .copy_texture_from_host_ram(&ram, &runs, offset, pitch, size, &texture, 0, 0, at); + assert!(refused(into, &problem), "{layout:?} {size:?} {at:?}"); + let out = + encoder.copy_texture_to_host_ram(&texture, 0, 0, at, size, &ram, &runs, offset, pitch); + assert!(refused(out, &problem), "{layout:?} {size:?} {at:?}"); + } + // Textures off the copies' contract: multisampled, depth, block-compressed. + let mut multisampled = + TextureDescriptor::texture_2d(PixelFormat::BGRA8Unorm, WIDTH, HEIGHT, false); + multisampled.texture_type = TextureType::Type2DMultisample; + multisampled.sample_count = 4; + multisampled.usage = TextureUsage::RENDER_TARGET; + multisampled.resource_options = ResourceOptions::private(); + let mut depth = TextureDescriptor::texture_2d(PixelFormat::Depth32Float, WIDTH, HEIGHT, false); + depth.usage = TextureUsage::RENDER_TARGET; + depth.resource_options = ResourceOptions::private(); + let mut compressed = TextureDescriptor::texture_2d(PixelFormat::BC1RGBA, WIDTH, HEIGHT, false); + compressed.resource_options = ResourceOptions::private(); + for descriptor in [multisampled, depth, compressed] { + let other = match device.new_texture(&descriptor) { + Ok(other) => other, + Err(error) => { + eprintln!( + "HOST-RAM-TEXTURE: no {:?} here: {error}", + descriptor.pixel_format + ); + continue; + } + }; + let into = encoder + .copy_texture_from_host_ram(&ram, &runs, OFFSET, PITCH, whole, &other, 0, 0, origin); + assert!(refused(into, &host_ram), "{:?}", descriptor.pixel_format); + let out = encoder + .copy_texture_to_host_ram(&other, 0, 0, origin, whole, &ram, &runs, OFFSET, PITCH); + assert!(refused(out, &host_ram), "{:?}", descriptor.pixel_format); + } + encoder.end_encoding().unwrap(); + complete(&command_buffer); + drop((used, ram)); +} diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 2a17da5ba..1c77ba00c 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -407,6 +407,8 @@ mod host_ram_managed; mod host_ram_spread_bench; #[cfg(all(m2v_gpu, target_os = "linux"))] mod host_ram_surface_fill_bench; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod host_ram_texture_device; #[cfg(all(any(m2v_gpu, m2v_cpu_icd), target_os = "linux"))] mod host_ram_whole; #[cfg(any(m2v_gpu, m2v_cpu_icd))] diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index bc83c3df0..19665a937 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 525; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 2483; +pub const RUNTIME_VERSION: u32 = 2484; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 584e6bf37..7dc09c949 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -8628,7 +8628,9 @@ method metal2vulkan-runtime::BlitCommandEncoder::copy_indirect_command_buffer pu method metal2vulkan-runtime::BlitCommandEncoder::copy_runs_from_host_ram pub fn copy_runs_from_host_ram(&mut self, ram: &HostRam, runs: &[(u64, Range)], destination: &Buffer) -> Result<(), Error> method metal2vulkan-runtime::BlitCommandEncoder::copy_runs_to_host_ram pub fn copy_runs_to_host_ram(&mut self, source: &Buffer, ram: &HostRam, runs: &[(u64, Range)]) -> Result<(), Error> method metal2vulkan-runtime::BlitCommandEncoder::copy_texture pub fn copy_texture(&mut self, source_texture: &Texture, destination_texture: &Texture) -> Result<(), Error> +method metal2vulkan-runtime::BlitCommandEncoder::copy_texture_from_host_ram pub fn copy_texture_from_host_ram(&mut self, ram: &HostRam, runs: &[Range], source_offset: u64, source_bytes_per_row: u64, source_size: Size, destination: &Texture, destination_slice: u64, destination_level: u64, destination_origin: Origin) -> Result<(), Error> method metal2vulkan-runtime::BlitCommandEncoder::copy_texture_slices pub fn copy_texture_slices(&mut self, source_texture: &Texture, source_slice: u64, source_level: u64, destination_texture: &Texture, destination_slice: u64, destination_level: u64, slice_count: u64, level_count: u64) -> Result<(), Error> +method metal2vulkan-runtime::BlitCommandEncoder::copy_texture_to_host_ram pub fn copy_texture_to_host_ram(&mut self, source: &Texture, source_slice: u64, source_level: u64, source_origin: Origin, source_size: Size, ram: &HostRam, runs: &[Range], destination_offset: u64, destination_bytes_per_row: u64) -> Result<(), Error> method metal2vulkan-runtime::BlitCommandEncoder::copy_to_host_ram pub fn copy_to_host_ram(&mut self, source: &Buffer, source_offset: u64, ram: &HostRam, runs: &[Range]) -> Result<(), Error> method metal2vulkan-runtime::BlitCommandEncoder::end_encoding pub fn end_encoding(self) -> Result<(), Error> method metal2vulkan-runtime::BlitCommandEncoder::fill_buffer pub fn fill_buffer(&mut self, buffer: &Buffer, range: Range, value: u8) -> Result<(), Error> diff --git a/docs/HOWTO.md b/docs/HOWTO.md index 1796df9bd..d987efe8b 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -1143,6 +1143,24 @@ submission, can give the device the guest's RAM once instead: bytes from the lowest run's first to the highest's last. Refused as above, and a run whose bytes pass the buffer's length (`Invalid`, `Problem::RangeOutOfBounds`, the first such run's); a run at a byte of the buffer off a word is copied by regions, not refused. +- `BlitCommandEncoder::copy_texture_from_host_ram(ram, runs, offset, bytes_per_row, size, + texture, slice, level, origin)` and `copy_texture_to_host_ram(texture, slice, level, origin, + size, ram, runs, offset, bytes_per_row)` copy one 2D region of a texture between it and a + surface laid out in the RAM, for a device cache that is a texture (an optimal one): `runs` are + the surface's bytes in order, host runs laid one after another as above (its pages), and row + `y` of the region lies from surface byte `offset + y × bytes_per_row`, Metal's buffer layout + for `copy_from_buffer_to_texture`, checked as Metal checks it over the surface's bytes + (`Invalid`, `Problem::Copy`). Each row's texels in a run and a chunk are one region of a + `vkCmdCopyBufferToImage` or `vkCmdCopyImageToBuffer` straight on the import that holds them + (`bufferRowLength` 0), with no staging buffer; over a chunk not imported yet, or one that takes + no import while it runs, the copy goes through the command buffer's own memory as the buffer + forms' does. Only the texels' bytes move: the bytes between the rows and around the surface + stay. Ordered and seen as the buffer forms are, the texture's region used as a blit's copy with + a buffer uses it; a copy out is reported to the RAM's log. Refused as above, and a row's piece + that does not start on a texel of host memory or hold whole texels (a run that splits a texel), + and a texture that is not one image of its own of one sample and uncompressed colour texels one + to a texel (a texture over a buffer, a multisampled, depth, stencil, block-compressed, two-plane + or carried format) or a region of more than one image (`Invalid`, `Problem::HostRam`). ## 7. Memory another API writes diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index 650294de9..6f431b157 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -342,7 +342,7 @@ Columns: | `ScheduledSignalAfterCompletion` | A scheduled signal encoded once the command buffer completed, or failed (status `Error`) (`CommandBuffer::encode_signal_event_scheduled`) | every device (a public call's own check of its arguments) | `metal-measured`: an M3 Max, macOS 27.0.1: a segmentation fault in 10 of 15 runs, as the consumer measured | 1: `crates/metal2vulkan-runtime/src/command_buffer/mod.rs (encode_signal_event_scheduled)` | `-` | | `ForeignObject` | An object made by another device | every device (a public call's own check of its arguments) | `unknown`: Metal's answer for an object another device made is unmeasured | 1: `crates/metal2vulkan-runtime/src/device/line.rs (foreign)` | `-` | | `DmaBuf` | Dma-bufs a `DmaBufSource` returned (a runtime extension | every device (a public call's own check of its arguments) | `ours`: a runtime extension's own contract: Metal imports no dma-buf | 3: `crates/metal2vulkan-runtime/src/dma_buf.rs (import_from_source)`, `crates/metal2vulkan-runtime/src/dma_buf.rs (ram_runs_as_dma_buf)` (+1) | `-` | -| `HostRam` | Guest RAM, or a run resolver's answer, that breaks its runtime extension's contract (`HostRam::new`, `Device::use_host_ram`,... | every device (a public call's own check of its arguments) | `ours`: a runtime extension's own contract: Metal imports no guest RAM | 5: `crates/metal2vulkan-runtime/src/host_ram.rs (new)`, `crates/metal2vulkan-runtime/src/host_ram.rs (ram_use_on)` (+3) | `-` | +| `HostRam` | Guest RAM, or a run resolver's answer, that breaks its runtime extension's contract (`HostRam::new`, `Device::use_host_ram`,... | every device (a public call's own check of its arguments) | `ours`: a runtime extension's own contract: Metal imports no guest RAM | 6: `crates/metal2vulkan-runtime/src/host_ram.rs (new)`, `crates/metal2vulkan-runtime/src/host_ram.rs (ram_use_on)` (+4) | `-` | | `HostPagesBacking` | A placement asked of host pages not imported yet (`Device::host_pages_texture_placement`, a runtime extension) for a backing other than... | every device (a public call's own check of its arguments) | `ours`: a runtime extension's own contract: Metal has no such query | 1: `crates/metal2vulkan-runtime/src/buffer_texture.rs (host_pages_texture_placement_now)` | `-` | | `WrappedImage` | An image the caller made that cannot be wrapped as a texture of the descriptor (`new_texture_with_vk_image`) | every device (a public call's own check of its arguments) | `ours`: a runtime extension: Metal wraps no Vulkan image | 2: `crates/metal2vulkan-runtime/src/texture/wrapped.rs (new_texture_with_vk_image)`, `crates/metal2vulkan-runtime/src/texture/wrapped.rs (new_texture_with_vk_image_plane)` | `-` | | `NotShareable` | A handle of a texture that is not shareable, for which Metal answers nil, an [`Error::Nil`] | every device (a public call's own check of its arguments) | `unknown`: Metal's nil for a texture that is not shareable is unmeasured | 1: `crates/metal2vulkan-runtime/src/texture/shared.rs (new_shared_texture_handle)` | `-` | @@ -371,7 +371,7 @@ Columns: | `MaxCommandBufferCount` | A command queue's `maxCommandBufferCount` of zero | every device (a public call's own check of its arguments) | `metal-measured`: an Apple M3 Max: Metal's command queue creation asserts "invalid descriptor.maxCommandBufferCount value 0", with and without API validation | 2: `crates/metal2vulkan-runtime/src/queue.rs (new_command_queue_unshared_now)`, `crates/metal2vulkan-runtime/src/queue.rs (new_command_queue_with_max_command_buffer_count_now)` | `-` | | `Texture` | A texture descriptor Metal stops (`Invalid`), or plain Metal answers nil for (`Nil`) | every device (a public call's own check of its arguments) | `delegated`: TextureProblem, section 9 | 7: `crates/metal2vulkan-runtime/src/buffer_texture.rs (shape_over)`, `crates/metal2vulkan-runtime/src/texture.rs (image_error)` (+3) | `-` | | `TextureView` | A texture view Metal stops, or a use of a texture its usage does not allow | every device (a public call's own check of its arguments) | `delegated`: ViewProblem, section 9 | 6: `crates/metal2vulkan-runtime/src/texture.rs (checked_view, 2 sites)`, `crates/metal2vulkan-runtime/src/texture.rs (subview, 2 sites)` (+1) | `-` | -| `Copy` | A texture copy Metal stops | every device (a public call's own check of its arguments) | `delegated`: CopyProblem, section 9 | 25: `crates/metal2vulkan-runtime/src/blit_texture.rs (buffer_into_texture)`, `crates/metal2vulkan-runtime/src/blit_texture.rs (check_slice_level)` (+17) | `-` | +| `Copy` | A texture copy Metal stops | every device (a public call's own check of its arguments) | `delegated`: CopyProblem, section 9 | 27: `crates/metal2vulkan-runtime/src/blit_texture.rs (buffer_into_texture)`, `crates/metal2vulkan-runtime/src/blit_texture.rs (check_slice_level)` (+18) | `-` | | `Mipmap` | A `generate_mipmaps` Metal stops | every device (a public call's own check of its arguments) | `delegated`: MipmapProblem, section 9 | 1: `crates/metal2vulkan-runtime/src/blit_texture.rs (mipmaps)` | `-` | | `BufferTexture` | A texture over a buffer plain Metal itself refuses | every device (a public call's own check of its arguments) | `delegated`: BufferTextureProblem, section 9 | 3: `crates/metal2vulkan-runtime/src/buffer_texture.rs (refusal_error, 2 sites)`, `crates/metal2vulkan-runtime/src/capabilities.rs (linear_alignment_rule)` | `-` | | `RenderPass` | A render pass descriptor, or a render encoder's late store action, Metal stops | every device (a public call's own check of its arguments) | `delegated`: RenderPassProblem, section 9 | 15: `crates/metal2vulkan-runtime/src/rate_mapped_pass.rs (check_descriptor)`, `crates/metal2vulkan-runtime/src/rate_mapped_pass.rs (of)` (+8) | `-` | @@ -844,7 +844,7 @@ Each refusal's sites, with the function that builds it. - `invalid::ScheduledSignalAfterCompletion`: `crates/metal2vulkan-runtime/src/command_buffer/mod.rs (encode_signal_event_scheduled)` - `invalid::ForeignObject`: `crates/metal2vulkan-runtime/src/device/line.rs (foreign)` - `invalid::DmaBuf`: `crates/metal2vulkan-runtime/src/dma_buf.rs (import_from_source)`; `crates/metal2vulkan-runtime/src/dma_buf.rs (ram_runs_as_dma_buf)`; `crates/metal2vulkan-runtime/src/dma_buf.rs (ram_span_as_dma_buf)` -- `invalid::HostRam`: `crates/metal2vulkan-runtime/src/host_ram.rs (new)`; `crates/metal2vulkan-runtime/src/host_ram.rs (ram_use_on)`; `crates/metal2vulkan-runtime/src/host_ram.rs (route_runs)`; `crates/metal2vulkan-runtime/src/host_ram/copy.rs (record_host_ram_copy)`; `crates/metal2vulkan-runtime/src/host_ram/copy.rs (record_regions)` +- `invalid::HostRam`: `crates/metal2vulkan-runtime/src/host_ram.rs (new)`; `crates/metal2vulkan-runtime/src/host_ram.rs (ram_use_on)`; `crates/metal2vulkan-runtime/src/host_ram.rs (route_runs)`; `crates/metal2vulkan-runtime/src/host_ram/copy.rs (record_host_ram_copy)`; `crates/metal2vulkan-runtime/src/host_ram/copy.rs (record_regions)`; `crates/metal2vulkan-runtime/src/host_ram/texture.rs (record_host_ram_texture_copy)` - `invalid::HostPagesBacking`: `crates/metal2vulkan-runtime/src/buffer_texture.rs (host_pages_texture_placement_now)` - `invalid::WrappedImage`: `crates/metal2vulkan-runtime/src/texture/wrapped.rs (new_texture_with_vk_image)`; `crates/metal2vulkan-runtime/src/texture/wrapped.rs (new_texture_with_vk_image_plane)` - `invalid::NotShareable`: `crates/metal2vulkan-runtime/src/texture/shared.rs (new_shared_texture_handle)` @@ -873,7 +873,7 @@ Each refusal's sites, with the function that builds it. - `invalid::MaxCommandBufferCount`: `crates/metal2vulkan-runtime/src/queue.rs (new_command_queue_unshared_now)`; `crates/metal2vulkan-runtime/src/queue.rs (new_command_queue_with_max_command_buffer_count_now)` - `invalid::Texture`: `crates/metal2vulkan-runtime/src/buffer_texture.rs (shape_over)`; `crates/metal2vulkan-runtime/src/texture.rs (image_error)`; `crates/metal2vulkan-runtime/src/texture.rs (texture_as)`; `crates/metal2vulkan-runtime/src/texture/heap.rs (planned_heap_texture, 2 sites)`; `crates/metal2vulkan-runtime/src/texture_descriptor.rs (error, 2 sites)` - `invalid::TextureView`: `crates/metal2vulkan-runtime/src/texture.rs (checked_view, 2 sites)`; `crates/metal2vulkan-runtime/src/texture.rs (subview, 2 sites)`; `crates/metal2vulkan-runtime/src/texture.rs (view_error, 2 sites)` -- `invalid::Copy`: `crates/metal2vulkan-runtime/src/blit_texture.rs (buffer_into_texture)`; `crates/metal2vulkan-runtime/src/blit_texture.rs (check_slice_level)`; `crates/metal2vulkan-runtime/src/blit_texture.rs (copy_error)`; `crates/metal2vulkan-runtime/src/blit_texture.rs (copy_from_texture_to_buffer)`; `crates/metal2vulkan-runtime/src/blit_texture.rs (copy_texture_slices)`; `crates/metal2vulkan-runtime/src/blit_texture.rs (multisampled_region)`; `crates/metal2vulkan-runtime/src/blit_texture.rs (plan_copy, 2 sites)`; `crates/metal2vulkan-runtime/src/blit_texture.rs (plane_copy)`; `crates/metal2vulkan-runtime/src/blit_texture.rs (region)`; `crates/metal2vulkan-runtime/src/blit_texture.rs (texel_copies)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs (bytes)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs (past_runs)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs (write_past)`; `crates/metal2vulkan-runtime/src/sample_interleave.rs (plan, 2 sites)`; `crates/metal2vulkan-runtime/src/texture.rs (copy_error)`; `crates/metal2vulkan-runtime/src/texture.rs (get_bytes)`; `crates/metal2vulkan-runtime/src/texture.rs (host_copy, 5 sites)`; `crates/metal2vulkan-runtime/src/texture.rs (replace)`; `crates/metal2vulkan-runtime/src/texture/heap.rs (contents)` +- `invalid::Copy`: `crates/metal2vulkan-runtime/src/blit_texture.rs (buffer_into_texture)`; `crates/metal2vulkan-runtime/src/blit_texture.rs (check_slice_level)`; `crates/metal2vulkan-runtime/src/blit_texture.rs (copy_error)`; `crates/metal2vulkan-runtime/src/blit_texture.rs (copy_from_texture_to_buffer)`; `crates/metal2vulkan-runtime/src/blit_texture.rs (copy_texture_slices)`; `crates/metal2vulkan-runtime/src/blit_texture.rs (multisampled_region)`; `crates/metal2vulkan-runtime/src/blit_texture.rs (plan_copy, 2 sites)`; `crates/metal2vulkan-runtime/src/blit_texture.rs (plane_copy)`; `crates/metal2vulkan-runtime/src/blit_texture.rs (region)`; `crates/metal2vulkan-runtime/src/blit_texture.rs (texel_copies)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs (bytes)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs (past_runs)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs (write_past)`; `crates/metal2vulkan-runtime/src/host_ram/texture.rs (record_host_ram_texture_copy, 2 sites)`; `crates/metal2vulkan-runtime/src/sample_interleave.rs (plan, 2 sites)`; `crates/metal2vulkan-runtime/src/texture.rs (copy_error)`; `crates/metal2vulkan-runtime/src/texture.rs (get_bytes)`; `crates/metal2vulkan-runtime/src/texture.rs (host_copy, 5 sites)`; `crates/metal2vulkan-runtime/src/texture.rs (replace)`; `crates/metal2vulkan-runtime/src/texture/heap.rs (contents)` - `invalid::Mipmap`: `crates/metal2vulkan-runtime/src/blit_texture.rs (mipmaps)` - `invalid::BufferTexture`: `crates/metal2vulkan-runtime/src/buffer_texture.rs (refusal_error, 2 sites)`; `crates/metal2vulkan-runtime/src/capabilities.rs (linear_alignment_rule)` - `invalid::RenderPass`: `crates/metal2vulkan-runtime/src/rate_mapped_pass.rs (check_descriptor)`; `crates/metal2vulkan-runtime/src/rate_mapped_pass.rs (of)`; `crates/metal2vulkan-runtime/src/render.rs (store_problem)`; `crates/metal2vulkan-runtime/src/render/late_resolve.rs (problem)`; `crates/metal2vulkan-runtime/src/render_pass.rs (2 sites)`; `crates/metal2vulkan-runtime/src/render_pass.rs (check_target)`; `crates/metal2vulkan-runtime/src/render_pass.rs (depth_stencil, 2 sites)`; `crates/metal2vulkan-runtime/src/render_pass.rs (layout, 4 sites)`; `crates/metal2vulkan-runtime/src/resolve.rs (problem)`; `crates/metal2vulkan-runtime/src/sample_positions.rs (problem)`