rt: a texture over an exported block is copied in once a change of its bytes

A texture over a buffer in an exported block (Private; no host write reaches it; the other
API's writes are announced by Block::external_writes_done) took the Shared rules: the upload
that leads every submission that used it copied its bytes in again. On a device whose dma-buf
surfaces take the copy form (the RX 550: no modifier extension, and no dma-buf image in LINEAR
tiling either) that was every plane of every picture in every submission that read it.

Now the submissions keep such textures (over::ExportedOvers, in the work state) with what each
owes: a copy in after its making, an acquire or a zero fill of the block (numbered by the next
commit, so a submission of command buffers committed before the event does not settle it), a
submitted command's write of its bytes, a write through an address, or another texture's copy
back over them. The leading copy is taken only where one is owed; a submission that only reads
the texture copies nothing. Inside a segment the Shared rules stand. No new form: the copy form
itself is unchanged, and Managed and Shared buffers keep their rules.

Test: tests/exported_overs.rs, on every device: a fill and the block's acquire, then four reads
= 1 copy (one plane's bytes); a fill, three reads = 1; a zero fill, two reads = 1; two reads with
no event = 0; each read's bytes are the last event's. Without the change the first four reads
copy 4.

README: the texture-over-buffer rules gain the exported block's; the copy form's known gap
states the RX 550's measured queries (no dma-buf image in LINEAR tiling either) and the bound,
and the RTX 3090 row names its jobs.
This commit is contained in:
Anees Iqbal committed 2026-11-21 23:23:48 -08:00
1 parent a347af5f65
commit bef2ec1df4
8 files changed
+308 -15

No files matched your search

+27 -8
View File
@@ -808,7 +808,8 @@ wait far longer than those submissions' GPU times waited behind work the runtime
why (`SurfaceCopy`): `NoModifier`, `Tiling`, `Dedicated`, `Pitch`, `Start` or `MemoryType`. The
surface is then an exported block (as above) laid by the same rule at the tightest pitch the
multiples allow, and each plane's texture is a texture over a buffer in it, an image of its own
that the submissions copy the bytes into and back (`Metrics::over_copies`). A start or pitch the
that the submissions copy the bytes into and back (`Metrics::over_copies`): in, once after each
acquire or other change of the bytes (Textures over a buffer, the exported block's rule). A start or pitch the
driver cannot take falls to the copy form with no error: the answer's `form` is the only sign.
`Metrics::surfaces_in_place` and `Metrics::surfaces_copied` count each form made.
@@ -898,14 +899,21 @@ the Direct3D 11 texture's payload until it is freed.
- A dma-buf surface on a device without `VK_EXT_image_drm_format_modifier`, or whose
`DRM_FORMAT_MOD_LINEAR` entry lacks a plane's format or one of its four usages
(`SurfaceCopy::NoModifier`, `SurfaceCopy::Tiling`): the device offers no in-place form for it.
On the Radeon RX 550 (Polaris 12) the driver lists no modifier extension, and its plain
`LINEAR` images refuse the dma-buf handle.
On the Radeon RX 550 (Polaris 12, RADV of Mesa 26.2.6) the driver lists no modifier extension,
and it offers no dma-buf image in `LINEAR` tiling either: its image format query refuses the
dma-buf handle with `LINEAR` tiling for every usage, though the `LINEAR` format features of
R8, RG8, R16 and RG16 hold sampling, the colour attachment, both copies and storage (jobs
m3-max-66247 and m3-max-66261). So neither in-place form exists there; the Radeon 780M and the
RX 7900 XTX answer that query alike. Each plane is copied in once a change of its bytes, an
acquire among them (the exported block's rule, Textures over a buffer).
- A dma-buf surface on NVIDIA (`SurfaceCopy::Tiling`): on the RTX 3090 and the RTX 5080 Laptop
GPU (NVIDIA 620.70.06) the `DRM_FORMAT_MOD_LINEAR` modifier's features carry
`VK_FORMAT_FEATURE_2_LINEAR_COLOR_ATTACHMENT_BIT_NV`, not the colour attachment feature, for
every plane format it is listed for, and that bit holds no modifier's image in place
(Exported surfaces); the other formats measured have no such modifier there. The opaque fd surface of the same planes is in place where its pitch multiple
divides the driver's pitch (above), its planes marked.
every plane format it is listed for (R8, RG8, R16 and RG16 among them on the RTX 3090, jobs
m3-max-66251 and m3-max-66264), and that bit holds no modifier's image in place
(Exported surfaces); the other formats measured have no such modifier there. The opaque fd surface of the same
planes is in place where its pitch multiple divides the driver's pitch (above), its planes
marked, and is the NVIDIA route a consumer takes.
- A layout the device cannot meet (`SurfaceCopy::Pitch`, `SurfaceCopy::Start`): a pitch or
start the consumer asks that the driver's linear images do not take. A pitch multiple of
4,096 takes `SurfaceCopy::Pitch` on every device measured: the Radeon 780M, the RTX 3090,
@@ -1014,8 +1022,9 @@ the Direct3D 11 texture's payload until it is freed.
- A texture over a buffer in an exported block is the counted copy of a texture over a buffer on
every device (`Metrics::over_copies`). The runtime makes no image in an exported block's memory,
which is dedicated to its buffer. A decoded picture in an exported block is then one copy a
plane into the plane's image, made before the first submission that uses the picture; a
picture the decoder writes over before any use is not copied. In the video decodes we replay
plane into the plane's image, made by the first submission that uses the picture after its
acquire; later submissions that only read it copy nothing, and a picture the decoder writes
over before any use is not copied. In the video decodes we replay
(two planes a picture: 3,110,400 bytes for an 8-bit 1920x1080 picture, 24,883,200 for a 16-bit
3840x2160 one), that is 2 copies and about 8.6 MB a picture used, and a picture's copies take
0.288 ms of GPU time on the Radeon 780M, 0.294 ms on the RX 550, 0.520 ms on the Iris Xe
@@ -1395,6 +1404,16 @@ made, with no lock, and never rewritten for layouts.
define which bytes it sees; the bytes at the group's execution are one of the allowed outcomes.
A guest that waits for a completion before writing has, by that fact, a command buffer not in
a held group.
- Over a buffer in an exported block (`Device::new_exported_block`), the Shared rules inside a
segment, and the leading copy only once after each event that changes the bytes: the
texture's making, the block's acquire (`Block::external_writes_done`, which
`Surface::external_writes_done` makes in the copy form) or a zero fill of its range
(`Device::zero_block_range`), each ahead of every command buffer committed after it, and a
submitted command's write of the texture's bytes (every such texture for a write through an
address) or another texture's copy back over them. The upload that leads the next submission
that uses the texture makes it; a submission that only reads the texture copies nothing. The
block is Private, so no host write reaches it, and the other API's writes are the consumer's
to announce by the acquire.
- Over a Managed buffer's device copy, only at Metal's own Managed events, each texture keeping
one flag of each kind: in, after a `did_modify_range` over its range, by the commit that
captures the range, after its copies into the device copy; and at its making, or where device
@@ -307,6 +307,10 @@ impl Block {
// family is enabled (`Device::new_exported_block`).
unsafe { device.cmd_pipeline_barrier2(command, &dependency) };
})?;
// The other API's writes change the bytes of the textures over the block
// (`crate::over::ExportedOvers`).
core.work
.exported_changed(block.memory.id, (0, block.memory.len));
core.counters.count(Metric::Barriers);
core.counters.count(Metric::ExternalAcquires);
Ok(())
@@ -423,6 +423,12 @@ impl Memory {
}
}
/// Whether it is a dedicated allocation the consumer shares with another API ([`export`],
/// [`export_surface`]), Private and never mapped.
pub(crate) fn exported(&self) -> bool {
matches!(self.own, Some(Own::Export { .. }))
}
pub(crate) fn info(&self) -> BlockInfo {
BlockInfo {
id: self.id,
+95 -2
View File
@@ -4,7 +4,8 @@
//! reach (a Managed buffer's device copy, where it has one) into it and back, one
//! `vkCmdCopyBufferToImage` or `vkCmdCopyImageToBuffer` region a texture, with no CPU copy. Over a
//! Managed buffer's device copy, only Metal's Managed events copy ([`ManagedOvers`]); over any
//! other buffer, the Shared rules:
//! other buffer, the Shared rules, but for a buffer in an exported block, whose leading copy waits
//! for an event that changes its bytes ([`ExportedOvers`]):
//!
//! - **In, once a submission.** The upload that leads a submission copies the bytes into the
//! image of every such texture a segment of the submission uses before any command of the
@@ -56,7 +57,7 @@ use ash::vk;
use std::collections::{HashMap, HashSet};
use std::hash::BuildHasherDefault;
use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
use std::sync::{Arc, Mutex};
use std::sync::{Arc, Mutex, Weak};
/// Bytes of memory a resource lies in: `start..end` of block `block`, from the block's first
/// byte. Buffers over the same bytes of a block lie in the same span, whatever their ids.
@@ -588,6 +589,98 @@ pub(crate) struct ManagedOvers {
count: AtomicUsize,
}
/// A texture over a buffer in an exported block in an image of its own, as the submissions keep it
/// ([`ExportedOvers`]).
struct Exported {
/// The texture, whose image is `image` while it lives.
texture: Weak<TextureInner>,
id: u32,
image: vk::Image,
memory: Span,
/// An event changed its bytes since its image last took them: the commit number from which
/// every command buffer runs behind that event (0 for a submitted write).
owed: Option<u64>,
}
/// The textures over a buffer in an exported block ([`crate::Device::new_exported_block`]) in an
/// image of their own. No host write reaches such a block, which is Private: only the device's
/// commands and the other API, whose writes [`crate::Block::external_writes_done`] announces,
/// change its bytes. So such a texture is copied in once after each event that changes its bytes,
/// by the upload that leads the next submission that leans on the leading copy for it, and a
/// submission that only reads it copies nothing. The events: the texture's making; an acquire or a
/// zero fill of the block, which go ahead of every command buffer committed after them; and a
/// submitted command's write of memory its texels lie in, a write through an address (every
/// texture), or another texture's copy back over those bytes. Within a segment the Shared rules
/// stand.
#[derive(Default)]
pub(crate) struct ExportedOvers {
entries: Vec<Exported>,
}
impl ExportedOvers {
/// Keeps `texture`, whose copy is `copy`, owing its first copy in.
pub(crate) fn add(&mut self, texture: &Arc<TextureInner>, copy: &OverCopy) {
self.entries
.retain(|entry| entry.texture.strong_count() > 0);
self.entries.push(Exported {
texture: Arc::downgrade(texture),
id: texture.id(),
image: copy.image,
memory: copy.memory,
owed: Some(0),
});
}
/// Work ahead of every command buffer numbered `number` or later changed the bytes `range`
/// of block `block`: each texture over them owes its copy in.
pub(crate) fn owe(&mut self, block: BlockId, range: (u64, u64), number: u64) {
let span = Span {
block,
start: range.0,
end: range.1,
};
for entry in &mut self.entries {
if entry.memory.meets(span) {
entry.owed = Some(entry.owed.map_or(number, |owed| owed.max(number)));
}
}
}
/// Whether the submission whose last command buffer is numbered `through` copies `copy` in:
/// where an event owes it, settled where every such event runs ahead of that command buffer.
/// A texture over another block's buffer takes its copy, as the Shared rules have it.
pub(crate) fn takes(&mut self, copy: &OverCopy, through: u64) -> bool {
let found = (self.entries.iter_mut())
.find(|entry| entry.image == copy.image && entry.texture.strong_count() > 0);
let Some(entry) = found else {
return true;
};
let Some(owed) = entry.owed else {
return false;
};
if owed <= through {
entry.owed = None;
}
true
}
/// A submission went whose segments wrote `leans`: each texture whose bytes they changed owes
/// its copy in to every later submission.
pub(crate) fn wrote(&mut self, leans: &Leans) {
self.entries
.retain(|entry| entry.texture.strong_count() > 0);
for entry in &mut self.entries {
let memory = entry.memory;
let changed = leans.unbound
|| leans.wrote.meets(memory)
|| (leans.backed.iter()).any(|&(span, by)| span.meets(memory) && by != entry.id);
if changed {
entry.owed = Some(entry.owed.unwrap_or(0));
}
}
}
}
/// Whether two ranges meet.
fn meets(a: (u64, u64), b: (u64, u64)) -> bool {
a.0 < b.1 && b.0 < a.1
+34 -5
View File
@@ -68,8 +68,8 @@ use crate::error::Error;
use crate::event::EventInner;
use crate::fault;
use crate::fill;
use crate::memory::{Block, Internal};
use crate::over::{self, Leans};
use crate::memory::{Block, BlockId, Internal};
use crate::over::{self, ExportedOvers, Leans};
use crate::queue::QueueInner;
use crate::record::{self, Reach, Recorder};
use crate::staging::{At, Oldest, Region, Stage, Staging, REGION_LEN};
@@ -250,6 +250,9 @@ pub(crate) struct WorkState {
span_sleepers: u32,
/// The command buffers scheduled while held for room so far ([`WorkState::hold`]).
holds: u64,
/// The textures over a buffer in an exported block in an image of their own, and what each
/// owes its copy in.
exported: ExportedOvers,
/// For the device tests: the progress value of the last submission when the first loss came
/// ([`Work::stall`]).
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
@@ -473,7 +476,8 @@ struct Batch {
/// (`crate::over`).
leans: Leans,
/// The copies into those textures' images its upload makes first: one for each texture a
/// segment leans on the leading copy for, and, taken as it goes ([`WorkState::close`]), each
/// segment leans on the leading copy for (over an exported block, one an event owes,
/// `crate::over::ExportedOvers`), and, taken as it goes ([`WorkState::close`]), each
/// texture over a Managed buffer's device copy a command buffer of it keeps that owes one
/// (`crate::over::ManagedOvers`).
overs: Vec<OverCopy>,
@@ -573,6 +577,7 @@ impl Work {
loss: None,
span_sleepers: 0,
holds: 0,
exported: ExportedOvers::default(),
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
lost_at: 0,
}),
@@ -587,6 +592,21 @@ impl Work {
}
}
/// Keeps `texture`, over a buffer in an exported block in an image of its own whose copy is
/// `copy` ([`ExportedOvers`]).
pub(crate) fn exported_over(&self, texture: &Arc<TextureInner>, copy: &OverCopy) {
self.lock().exported.add(texture, copy);
}
/// Work recorded into the upload changed `range` of `block`'s bytes, ahead of every command
/// buffer committed from now on: the textures over them owe their copies in
/// ([`ExportedOvers`]).
pub(crate) fn exported_changed(&self, block: BlockId, range: (u64, u64)) {
let mut state = self.lock();
let number = state.next_seq + 1;
state.exported.owe(block, range, number);
}
pub(crate) fn lock(&self) -> MutexGuard<'_, WorkState> {
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
let began = crate::times::host_time();
@@ -1152,7 +1172,11 @@ impl Work {
) -> Result<(), Error> {
let (buffer, base) = block.memory.range(0);
let held = Held::Block(Arc::clone(block));
self.fill(core, held, buffer, base + offset, base + end)
self.fill(core, held, buffer, base + offset, base + end)?;
if block.memory.exported() {
self.exported_changed(block.memory.id, (offset, end));
}
Ok(())
}
/// Records the zero fill of `start..end` of `buffer` into the upload, which keeps `held`, what
@@ -1926,6 +1950,12 @@ impl WorkState {
batch.overs.extend(taken);
}
}
// Over an exported block, a texture takes its copy in only where an event changed its
// bytes, and the batch's writes change those they meet (`crate::over::ExportedOvers`).
let through = batch.leads.last().copied().unwrap_or(0);
let exported = &mut self.exported;
(batch.overs).retain(|copy| !copy.exported || exported.takes(copy, through));
self.exported.wrote(&batch.leans);
// The copy-ins captured at or before the number of a command buffer that goes first in
// it, each ahead of the first such one, and the copies back owed to the textures over
// their ranges by writes submitted before, which its upload makes first
@@ -1961,7 +1991,6 @@ impl WorkState {
}
}
(self.carried).extend((batch.finished.iter()).map(|(_, pending, _)| (pending.seq, value)));
let through = batch.leads.last().copied().unwrap_or(0);
let uploads = self.take_uploads(core, released, value, through);
Some((value, uploads, batch))
}
@@ -0,0 +1,132 @@
//! A texture over a buffer in an exported block, under a device cfg, on every device of the cfg's
//! kind: copied in once after each event that changes its bytes (`crate::over::ExportedOvers`),
//! counted in `Metrics::over_copies` and `Metrics::over_copy_bytes`. After a fill of the buffer and
//! the block's acquire, four submissions that read the texture copy it in once; a fill between
//! makes one copy more, and a zero fill of the block's range one more; reads with no event between
//! copy nothing. Each read finds the bytes of the last event.
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod on_device {
use crate::tests::command::on_device::{each_device, finished};
use crate::{
Buffer, BufferLayout, CommandQueue, Device, ExportHandle, IndexClass, MemoryClass,
PixelFormat, StorageMode, Texture, TextureDescriptor, TexturePlace, TextureType,
TextureUsage,
};
const WIDTH: u32 = 64;
const HEIGHT: u32 = 8;
const ROW: u64 = WIDTH as u64 * 4;
const LEN: u64 = 1 << 16;
/// Runs `encode` in a command buffer of its own on `queue`, and waits for it.
fn run(name: &str, queue: &CommandQueue, encode: impl FnOnce(&mut crate::BlitCommandEncoder)) {
let command_buffer = queue.command_buffer().expect("a command buffer");
let mut encoder = command_buffer.blit_command_encoder().expect("an encoder");
encode(&mut encoder);
encoder.end_encoding();
command_buffer.commit().expect("a commit");
finished(name, &command_buffer);
assert_eq!(command_buffer.error(), None, "{name}");
}
/// `count` submissions that each copy the texture into `out`, every byte of which then is
/// `byte`: the copies in they made, and their bytes.
fn reads(
name: &str,
(device, queue): (&Device, &CommandQueue),
(texture, out): (&Texture, &Buffer),
count: usize,
byte: u8,
) -> (u64, u64) {
let before = device.counters().metrics();
let contents = out.contents().expect("Shared");
for read in 0..count {
// SAFETY: no pending command reaches the buffer's bytes.
unsafe { contents.as_ptr().write_bytes(0xee, out.length() as usize) };
let layout = BufferLayout {
offset: 0,
bytes_per_row: ROW,
bytes_per_image: 0,
};
run(name, queue, |encoder| {
(encoder.copy_from_texture_to_buffer(
texture,
TexturePlace::default(),
[WIDTH, HEIGHT, 1],
out,
layout,
))
.unwrap_or_else(|error| panic!("{name}: the read: {error}"));
});
// SAFETY: the read has completed; nothing else reaches the bytes.
let bytes =
unsafe { std::slice::from_raw_parts(contents.as_ptr(), out.length() as usize) };
let wrong = bytes.iter().position(|&b| b != byte);
assert_eq!(wrong, None, "{name}: read {read}: byte {byte:#x}");
}
let after = device.counters().metrics();
(
after.over_copies - before.over_copies,
after.over_copy_bytes - before.over_copy_bytes,
)
}
#[test]
fn an_exported_blocks_texture_is_copied_in_once_a_change() {
each_device("exported_overs", |name, _, device| {
let Some(handle) = (ExportHandle::ALL.into_iter())
.find(|&handle| device.new_exported_block(handle, LEN).is_ok())
else {
println!("exported_overs: {name}: exports no handle");
return;
};
let (block, _export) = (device.new_exported_block(handle, LEN))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let buffer = (device.new_buffer(block.id, 0, LEN, None)).expect("a buffer");
let pitch = (device.minimum_linear_texture_alignment(PixelFormat::RGBA8Unorm))
.unwrap_or_else(|error| panic!("{name}: {error}"))
.max(ROW);
let mut d =
TextureDescriptor::new(TextureType::Type2D, PixelFormat::RGBA8Unorm, WIDTH, HEIGHT);
d.usage = TextureUsage::SHADER_READ;
d.storage_mode = StorageMode::Private;
let first = IndexClass::Texture.range().start;
let _grant = (device.grant_indices(IndexClass::Texture, first, 1)).expect("a grant");
let texture = (buffer.new_texture(&d, Some(first), 0, pitch))
.unwrap_or_else(|error| panic!("{name}: a texture over the export: {error}"));
let out_block = (device.take_block(MemoryClass::Shared, ROW * u64::from(HEIGHT)))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let out = (device.new_buffer(out_block.id, 0, ROW * u64::from(HEIGHT), Some(0)))
.expect("a buffer");
let queue = device.new_command_queue(4).expect("a queue");
let plane = ROW * u64::from(HEIGHT);
let fill = |value: u8| {
run(name, &queue, |encoder| {
(encoder.fill_buffer(&buffer, 0..LEN, value))
.unwrap_or_else(|error| panic!("{name}: the fill: {error}"));
});
};
let at = (&device, &queue);
let over = (&texture, &out);
fill(0x5a);
(block.external_writes_done()).unwrap_or_else(|error| panic!("{name}: {error}"));
let acquired = reads(name, at, over, 4, 0x5a);
assert_eq!(acquired, (1, plane), "{name}: an acquire, four reads");
fill(0xb7);
let filled = reads(name, at, over, 3, 0xb7);
assert_eq!(filled, (1, plane), "{name}: a fill, three reads");
(device.zero_block_range(block.id, 0, LEN))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let zeroed = reads(name, at, over, 2, 0);
assert_eq!(zeroed, (1, plane), "{name}: a zero fill, two reads");
let unchanged = reads(name, at, over, 2, 0);
assert_eq!(unchanged, (0, 0), "{name}: two reads, no event");
println!(
"exported_overs: {name}: {handle:?}: copies in after an acquire, a fill, a zero \
fill and no event: {} {} {} {}",
acquired.0, filled.0, zeroed.0, unchanged.0
);
});
}
}
@@ -25,6 +25,7 @@ mod dispatch_tiles;
mod dma_bufs;
mod draw;
mod export;
mod exported_overs;
mod fault;
mod feature_enables;
mod fence;
@@ -1617,6 +1617,11 @@ impl Device {
let image = Arc::clone(texture.inner.imaged());
(buffer.over_entries()).add(texture.inner.id, image, copy, copy.range);
}
// Over an exported block, the submissions keep what changes its bytes
// (`crate::over::ExportedOvers`).
if let Some((_, copy)) = texture.copied_over().filter(|(_, copy)| copy.exported) {
core.work.exported_over(&texture.inner, &copy);
}
Ok(texture)
}
}
@@ -4897,6 +4902,7 @@ pub(crate) trait TextureObject {
bytes: u64::from(d.width) * u64::from(d.height) * u64::from(unit.bytes),
shared: named.buffer.is_shared(),
imported: device_copy.is_none() && block.memory.imported(),
exported: device_copy.is_none() && block.memory.exported(),
cause,
};
Some((&named.buffer, copy))
@@ -5372,6 +5378,9 @@ pub(crate) struct OverCopy {
pub(crate) shared: bool,
/// The bytes shaders reach are in an imported block (`Metrics::over_copies_imported`).
pub(crate) imported: bool,
/// The bytes shaders reach are in an exported block, whose copies in wait for an event that
/// changes them (`crate::over::ExportedOvers`).
pub(crate) exported: bool,
/// Why the texture is not in place: the pair of [`Metrics`](crate::Metrics) its copies count
/// in too.
pub(crate) cause: OverCause,