rt: a heap texture moves from undefined before its next write after an alias's write

Vulkan's memory aliasing asks that an image over bytes another resource wrote move from
VK_IMAGE_LAYOUT_UNDEFINED before it is used. rt moved a heap texture only once, at its making, so a
device that keeps a compression state beside an image's bytes read the alias's state: on the Iris
Xe (ANV, Mesa 26.2.6) a 512x512 RGBA16Float array written through a 2D view after eight aliased
arrays read 8152 of 262144 texels wrong (job m3-max-71690, the test c26698712c).

The form (crate::alias):
- Each heap texture and heap buffer is a Place, linked at placement with the placements of its heap
  whose bytes meet its, both ways and weakly; a release drops its links. A placement with no links
  pays one test at each use.
- A write of a placement makes its links stale. A stale texture's next write moves its whole image
  from undefined to home, in one barrier from every command's writes to every command's reads and
  writes. Reads move nothing; a buffer is never moved. A declared write counts as a write.
- Inside a command buffer, encode order is run order: Building's marks keep each touched
  placement's state (fresh, stale, untouched) and the segment its commands last read it in. A write
  of a stale one moves in place: before a dispatch, a pass's begin or a blit; inside a rendering,
  through the pass's interruption.
- A write of an untouched one adds a check at its segment's head; where the segment read one of its
  links before, the segment ends first. The submit thread resolves a segment's checks as it stages
  it, in the order the device's one queue runs segments (so a command buffer committed out of its
  encode order, or held by an enqueue, is decided where it runs), recording the moves owed into a
  command buffer of the cb's recorder staged just ahead of the segment's, in its submit info and so
  its vkQueueSubmit2; then it applies the segment's writes. A failed record loses the device as a
  failed submission does.
- A texture placed over another's bytes is stale from its making, and its making move waits for
  every earlier write (ALL_COMMANDS / MEMORY_WRITE in place of NONE).
- Metrics::heap_moves counts the moves, in place and leading.

No upload piece: a heap texture sits on a Private block and Metal gives a heap's textures the
heap's storage mode, so no Metal-valid replaceRegion reaches one (TextureBytesPrivate).

The README's gap line now says what remains: a read of a stale texture, writes rt cannot name, a
declared write taken whole, the making move's effect on a live alias's bytes, the move's whole
image, and a draw's check at the head of its pass's segment.

Tests: src/tests/alias.rs holds the state machine on every device of the cfg (commit order against
encode order, the segment ended before a check behind an alias's read, moves in place, a draw's
write through the pass, apart placements with no check or move); the red test is
heap_alias.rs's array test. Gate and device runs follow in the next commits.
This commit is contained in:
Anees Iqbal committed 2026-11-23 10:43:30 -08:00
1 parent a7a86b22b6
commit 20ddd2daad
16 files changed
+1094 -39

No files matched your search

+13 -4
View File
@@ -1807,10 +1807,19 @@ made, with no lock, and never rewritten for layouts.
- `Device::pixel_format_info` answers as an Apple M3 Max under macOS 27.0.1, which describes
none of the values from 630 to 645 (`BGRA10Unorm`, its packed, sRGB, PQ and HLG forms,
`R10UintX6`, `RG10UintX12` and the rest); an Apple M4 under that release describes them.
- A heap texture whose bytes another resource of its heap wrote is used again in the layout it
moved to once, at its making: rt records no move out of `VK_IMAGE_LAYOUT_UNDEFINED` before that
use, where Vulkan's memory aliasing asks that "each of those image subresources must have its
layout transitioned from `VK_IMAGE_LAYOUT_UNDEFINED` to a valid layout before it is used".
- A heap texture whose bytes another resource of its heap wrote moves out of
`VK_IMAGE_LAYOUT_UNDEFINED` before its next use that writes it (`Metrics::heap_moves`), as
Vulkan's memory aliasing asks: "each of those image subresources must have its layout
transitioned from `VK_IMAGE_LAYOUT_UNDEFINED` to a valid layout before it is used". What remains:
a read of such a texture before its next write takes no move; a write rt cannot name, through a
resource ID or an address outside the encoder's slots and `use_resource` declarations, leaves no
texture stale; a declared write (`use_resource` with a usage that writes) counts as a write of
the whole resource; a texture placed over another's bytes moves home from undefined at its
making, which on a device whose move writes memory may change a live alias's bytes; a move is
of the whole image, so where an alias's write met only part of it, the move takes the rest too;
and a draw's write of a texture that nothing earlier in its command buffer wrote, nor an alias
of it, is checked where the pass's part of the command buffer starts, so its move may go ahead
of a read of an alias there.
- A texture's memory is device-local; where the device has none left, the call fails
(`Error::Vulkan`).
- A texture over a buffer other than 2D of one level, sample and slice, or of a depth, stencil
+384
View File
@@ -0,0 +1,384 @@
//! Heap resources whose bytes meet, and the moves of heap textures' images from
//! `VK_IMAGE_LAYOUT_UNDEFINED` that Vulkan's memory aliasing asks for: an image over bytes another
//! resource wrote holds undefined contents, and moves from undefined before it is used again
//! (vkspec "Memory Aliasing"). A device that keeps a compression state beside an image's bytes
//! needs the move, as a write through an alias leaves that state the alias's.
//!
//! Each resource placed in a heap is a [`Place`], linked at placement with the others of its heap
//! whose bytes meet its, both ways and weakly; a release drops its links. A heap with no meeting
//! placements holds no links, and its resources' uses pay one test.
//!
//! A use that writes a placement makes its links stale. A stale texture's next use that writes it
//! moves its whole image from undefined to its home layout first, in a barrier that orders every
//! earlier command before it and every later one after it. Reads move nothing. A buffer is never
//! moved; its writes make its links stale.
//!
//! Inside a command buffer, encode order is the order its commands run in: [`Marks`] keeps what
//! the command buffer did to the placements it touched, and a write of one that a link was
//! written over since moves it in place. A write of one that nothing in the command buffer wrote,
//! nor any of its links, depends on the placement as the command buffer starts: a check at the
//! head of its segment ([`Aliased`]), which the submit thread resolves as it stages the segment,
//! in the order the device's one queue runs segments, a move it finds owed going in a command
//! buffer of its own ahead of the segment's, in its submit info ([`stage`]). A segment that read
//! one of the placement's links before the write ends first, so the move never goes ahead of that
//! read. Then the segment's writes apply, in their order.
use crate::command::DeviceLoss;
use crate::counters::Metric;
use crate::device::{lock, Core};
use crate::error::Error;
use crate::hazard::{Access, HeapId};
use crate::record::{memory_barrier, Reach, Recorder};
use ash::vk;
use std::collections::HashMap;
use std::hash::{BuildHasherDefault, DefaultHasher};
use std::sync::atomic::{AtomicBool, Ordering::Relaxed};
use std::sync::{Arc, Mutex, PoisonError, Weak};
/// A heap texture's image, which its move from undefined names.
#[derive(Clone, Copy)]
pub(crate) struct Moved {
pub(crate) image: vk::Image,
pub(crate) home: vk::ImageLayout,
pub(crate) aspects: vk::ImageAspectFlags,
}
impl Moved {
/// The move of the whole image from undefined to its home layout, after every earlier
/// command's writes and before every later command's reads and writes.
fn barrier(self) -> vk::ImageMemoryBarrier2<'static> {
vk::ImageMemoryBarrier2::default()
.src_stage_mask(vk::PipelineStageFlags2::ALL_COMMANDS)
.src_access_mask(vk::AccessFlags2::MEMORY_WRITE)
.dst_stage_mask(vk::PipelineStageFlags2::ALL_COMMANDS)
.dst_access_mask(vk::AccessFlags2::MEMORY_READ | vk::AccessFlags2::MEMORY_WRITE)
.old_layout(vk::ImageLayout::UNDEFINED)
.new_layout(self.home)
.src_queue_family_index(vk::QUEUE_FAMILY_IGNORED)
.dst_queue_family_index(vk::QUEUE_FAMILY_IGNORED)
.image(self.image)
.subresource_range(vk::ImageSubresourceRange {
aspect_mask: self.aspects,
base_mip_level: 0,
level_count: vk::REMAINING_MIP_LEVELS,
base_array_layer: 0,
layer_count: vk::REMAINING_ARRAY_LAYERS,
})
}
}
/// A link to a placement whose bytes meet another's: the placement, held weakly, and its
/// staleness, which a write of the other sets.
struct Link {
place: Weak<Place>,
stale: Arc<AtomicBool>,
}
/// A resource's bytes in its heap: a heap texture's or a heap buffer's.
pub(crate) struct Place {
heap: Arc<HeapId>,
/// Its first and past-last byte in the heap's block.
start: u64,
end: u64,
/// A texture's image; `None` for a buffer.
moved: Option<Moved>,
/// The placements of its heap whose bytes meet its, changed under its heap's lock.
links: Mutex<Vec<Link>>,
/// It has links: the one test a placement with none pays, read without the lock.
linked: AtomicBool,
/// As the submit thread has staged the segments: a link was written since its own last write,
/// or it was placed over another's bytes and is not yet written. A texture's alone is read.
stale: Arc<AtomicBool>,
}
impl Place {
/// A resource placed at bytes `[start, end)` of `heap`'s block, an image where `moved`,
/// linked with the placements of the heap whose bytes meet those. A texture with links is
/// stale from the start: its bytes may hold another's writes.
pub(crate) fn new(
heap: &Arc<HeapId>,
start: u64,
end: u64,
moved: Option<Moved>,
) -> Arc<Place> {
let place = Arc::new(Place {
heap: Arc::clone(heap),
start,
end,
moved,
links: Mutex::new(Vec::new()),
linked: AtomicBool::new(false),
stale: Arc::new(AtomicBool::new(false)),
});
let mut places = lock(heap.places());
places.retain(|other| other.strong_count() > 0);
// Held until the heap's lock is let go: the last handle of one dropped here would take it.
let met: Vec<Arc<Place>> = (places.iter())
.filter_map(Weak::upgrade)
.filter(|other| other.start < end && start < other.end)
.collect();
let mut links = Vec::with_capacity(met.len());
for other in &met {
let mut theirs = lock(&other.links);
theirs.push(Link {
place: Arc::downgrade(&place),
stale: Arc::clone(&place.stale),
});
other.linked.store(true, Relaxed);
links.push(Link {
place: Arc::downgrade(other),
stale: Arc::clone(&other.stale),
});
}
if !links.is_empty() {
place.stale.store(moved.is_some(), Relaxed);
place.linked.store(true, Relaxed);
*lock(&place.links) = links;
}
places.push(Arc::downgrade(&place));
drop(places);
drop(met);
place
}
/// Whether a placement of its heap meets its bytes.
pub(crate) fn linked(&self) -> bool {
self.linked.load(Relaxed)
}
/// Placed over another's bytes: its first move from the layout it is made in waits for every
/// earlier command's writes.
pub(crate) fn over(&self) -> bool {
self.stale.load(Relaxed)
}
fn key(&self) -> usize {
std::ptr::from_ref(self) as usize
}
}
impl Drop for Place {
fn drop(&mut self) {
let me: *const Place = self;
let met: Vec<Arc<Place>> = {
let mut places = lock(self.heap.places());
places.retain(|other| other.strong_count() > 0);
let links = self.links.get_mut().unwrap_or_else(PoisonError::into_inner);
links
.iter()
.filter_map(|link| link.place.upgrade())
.collect()
};
for other in &met {
let mut links = lock(&other.links);
links.retain(|link| !std::ptr::eq(link.place.as_ptr(), me));
other.linked.store(!links.is_empty(), Relaxed);
}
}
}
/// Of the uses `uses` of resources, the ones of placements with links, with their accesses: the
/// uses a command's marks and moves look at. Empty, and nothing allocated, where none has links.
pub(crate) fn uses<'a>(
uses: impl Iterator<Item = (Option<&'a Arc<Place>>, Access)>,
) -> Vec<(&'a Arc<Place>, Access)> {
uses.filter_map(|(place, access)| Some((place.filter(|p| p.linked())?, access)))
.collect()
}
/// What a placement's state is in a command buffer, as its commands so far leave it.
#[derive(Clone, Copy, PartialEq, Eq)]
enum State {
/// Neither it nor a link was written in the command buffer.
Untouched,
/// Written, and no link written since.
Fresh,
/// A link written since its last write in the command buffer, or with none.
Stale,
}
/// A placement's mark in a command buffer.
struct Mark {
/// Held so its address names no other placement while the mark lives.
_place: Weak<Place>,
state: State,
/// The segment, from 1, whose commands last read it; 0 where none did.
read: usize,
}
/// What a command buffer's commands did to the linked placements they touched, by placement's
/// address. Its hasher takes no seed, so a command buffer that touches none makes nothing.
#[derive(Default)]
pub(crate) struct Marks {
marks: HashMap<usize, Mark, BuildHasherDefault<DefaultHasher>>,
}
impl Marks {
fn mark(&mut self, key: usize, place: impl FnOnce() -> Weak<Place>) -> &mut Mark {
self.marks.entry(key).or_insert_with(|| Mark {
_place: place(),
state: State::Untouched,
read: 0,
})
}
fn state(&self, place: &Place) -> State {
self.marks
.get(&place.key())
.map_or(State::Untouched, |mark| mark.state)
}
/// For a command whose uses of linked placements are `uses`, in segment `segment` (from 0):
/// whether a check it adds must go at the head of a segment of its own, a link of the
/// placement checked having been read in this one.
pub(crate) fn splits(&self, uses: &[(&Arc<Place>, Access)], segment: usize) -> bool {
let read_here = |link: &Link| {
(self.marks.get(&(link.place.as_ptr() as usize)))
.is_some_and(|mark| mark.read == segment + 1)
};
(uses.iter())
.filter(|(place, access)| access.writes() && place.moved.is_some())
.filter(|(place, _)| self.state(place) == State::Untouched)
.any(|(place, _)| lock(&place.links).iter().any(read_here))
}
/// The command's uses `uses` in segment `segment` (from 0), whose part is `part`: the checks
/// it adds there and its writes, its marks, and the moves it records in place before it, a
/// texture's once.
pub(crate) fn used(
&mut self,
uses: &[(&Arc<Place>, Access)],
segment: usize,
part: &mut Aliased,
) -> Vec<vk::ImageMemoryBarrier2<'static>> {
let mut moves: Vec<vk::ImageMemoryBarrier2<'static>> = Vec::new();
for (place, _) in uses.iter().filter(|(_, access)| access.writes()) {
let Some(moved) = place.moved else {
continue;
};
match self.state(place) {
State::Fresh => {}
State::Stale => {
if !moves.iter().any(|m| m.image == moved.image) {
moves.push(moved.barrier());
}
}
State::Untouched => {
if !part.checks.iter().any(|p| Arc::ptr_eq(p, place)) {
part.checks.push(Arc::clone(place));
}
}
}
}
for (place, access) in uses {
if access.writes() && self.state(place) != State::Fresh {
self.mark(place.key(), || Arc::downgrade(place)).state = State::Fresh;
for link in lock(&place.links).iter() {
let key = link.place.as_ptr() as usize;
self.mark(key, || link.place.clone()).state = State::Stale;
}
part.writes.push(Arc::clone(place));
}
if access.reads() {
self.mark(place.key(), || Arc::downgrade(place)).read = segment + 1;
}
}
moves
}
}
/// A segment's part: the checks at its head and its writes of linked placements, in order.
#[derive(Default)]
pub(crate) struct Aliased {
checks: Vec<Arc<Place>>,
writes: Vec<Arc<Place>>,
}
impl Aliased {
pub(crate) fn is_empty(&self) -> bool {
self.checks.is_empty() && self.writes.is_empty()
}
/// For the device tests: its checks.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) fn checks(&self) -> usize {
self.checks.len()
}
}
/// As the submit thread stages a segment whose part is `part`: the moves its checks find owed,
/// recorded into a command buffer of `recorder` that goes ahead of the segment's, each counted
/// (`Metrics::heap_moves`); then its writes, applied in order. `None` where nothing is owed.
///
/// Err: the Vulkan call that failed, which loses the device.
pub(crate) fn stage(
core: &Core,
recorder: &mut Option<Recorder>,
part: &Aliased,
) -> Result<Option<vk::CommandBuffer>, DeviceLoss> {
let moves: Vec<vk::ImageMemoryBarrier2<'static>> = (part.checks.iter())
.filter(|place| place.stale.load(Relaxed))
.filter_map(|place| place.moved.map(Moved::barrier))
.collect();
for place in &part.writes {
place.stale.store(false, Relaxed);
for link in lock(&place.links).iter() {
link.stale.store(true, Relaxed);
}
}
if moves.is_empty() {
return Ok(None);
}
let device = &core.device;
let lost = |error: Error| match error {
Error::Vulkan { call, result } => DeviceLoss::of(call)(result),
error => unreachable!("a recorder fails only in a Vulkan call: {error}"),
};
let recorder = match recorder {
Some(recorder) => recorder,
None => recorder.insert(core.recorders.take(device).map_err(lost)?),
};
let command = recorder.next(device).map_err(lost)?;
let earlier = [memory_barrier(Reach::Commands)];
let dependency = vk::DependencyInfo::default()
.memory_barriers(&earlier)
.image_memory_barriers(&moves);
// SAFETY: the command buffer is recording, and only the submit thread has it; the command
// buffer it leads keeps each texture until it retires; a move from undefined names no layout
// the image must be in.
unsafe {
device.cmd_pipeline_barrier2(command, &dependency);
device.end_command_buffer(command)
}
.map_err(DeviceLoss::of("vkEndCommandBuffer"))?;
core.counters.count(Metric::Barriers);
for _ in &moves {
core.counters.count(Metric::HeapMoves);
}
Ok(Some(command))
}
/// Records `moves`, heap textures' moves from undefined ([`Marks::used`]), into `command`, the
/// current segment's, in one barrier that orders every earlier command before them and every
/// later one after, each counted (`Metrics::heap_moves`).
///
/// # Safety
///
/// `command` is recording outside a rendering, and keeps each texture until it retires.
pub(crate) unsafe fn record(
device: &ash::Device,
command: vk::CommandBuffer,
moves: &[vk::ImageMemoryBarrier2<'_>],
count: &mut impl FnMut(Metric),
) {
let earlier = [memory_barrier(Reach::Commands)];
let dependency = vk::DependencyInfo::default()
.memory_barriers(&earlier)
.image_memory_barriers(moves);
// SAFETY: the caller's contract; a move from undefined names no layout the image must be in.
unsafe { device.cmd_pipeline_barrier2(command, &dependency) };
count(Metric::Barriers);
for _ in moves {
count(Metric::HeapMoves);
}
}
+35
View File
@@ -220,6 +220,15 @@ impl BlitCommandEncoder {
building.keep_texture(source);
building.keep_texture(destination);
building.wrote_texture_managed(destination);
// A heap texture it writes that an alias's write left stale moves from undefined first
// (`crate::alias`).
building.places(
[
(source.object().place(), Access::Read),
(destination.object().place(), Access::Write),
]
.into_iter(),
)?;
let overs = [
(Reached::Texture(source.object()), Access::Read),
(Reached::Texture(destination.object()), Access::ReadWrite),
@@ -448,6 +457,14 @@ impl BlitCommandEncoder {
building.managed_reach(destination, &mut backs);
building.managed_backs(backs)?;
building.wrote_managed(destination);
// A write of a heap buffer leaves the textures over its bytes stale (`crate::alias`).
building.places(
[
(source.object().place(), Access::Read),
(destination.object().place(), Access::Write),
]
.into_iter(),
)?;
let overs = [
(Reached::Buffer(source.span()), Access::Read),
(Reached::Buffer(destination.span()), Access::Write),
@@ -547,6 +564,19 @@ impl BlitCommandEncoder {
true => building.wrote_texture_managed(texture),
false => building.wrote_managed(buffer),
}
// A heap texture it writes that an alias's write left stale moves from undefined first,
// and a write of a heap buffer leaves the textures over its bytes stale (`crate::alias`).
let (into, out) = match into_image {
true => (Access::Write, Access::Read),
false => (Access::Read, Access::Write),
};
building.places(
[
(texture.object().place(), into),
(buffer.object().place(), out),
]
.into_iter(),
)?;
let overs = match into_image {
true => [
(Reached::Texture(texture.object()), Access::ReadWrite),
@@ -673,6 +703,8 @@ impl BlitCommandEncoder {
building.managed_reach(buffer, &mut backs);
building.managed_backs(backs)?;
building.wrote_managed(buffer);
// A write of a heap buffer leaves the textures over its bytes stale (`crate::alias`).
building.places([(buffer.object().place(), Access::Write)].into_iter())?;
let overs = [(Reached::Buffer(buffer.span()), Access::Write)];
building.overs_before(overs, false)?;
let command = building.ordered_command()?;
@@ -824,6 +856,9 @@ impl BlitCommandEncoder {
}
building.keep_texture(texture);
building.wrote_texture_managed(texture);
// Its levels past the first are written: a heap texture an alias's write left stale
// moves from undefined first (`crate::alias`).
building.places([(texture.object().place(), Access::ReadWrite)].into_iter())?;
let overs = [(Reached::Texture(texture.object()), Access::ReadWrite)];
building.overs_before(overs, false)?;
let command = building.ordered_command()?;
+11
View File
@@ -1,6 +1,7 @@
//! Buffers: views of a range of a block, with no Vulkan object of their own; a Managed buffer's
//! device copy, where the device has one, is a range of a Private block the consumer placed it in.
use crate::alias::Place;
use crate::capture::Modified;
use crate::counters::{Gauge, Part};
use crate::device::{Core, Device};
@@ -64,6 +65,8 @@ pub(crate) struct BufferInner {
/// The heap the consumer placed it in ([`Device::new_heap_buffer`]), whose id its uses take in
/// the hazard sets.
heap: Option<Arc<HeapId>>,
/// Its bytes in its heap, which the placements whose bytes meet them link (`crate::alias`).
place: Option<Arc<Place>>,
/// The block the consumer placed it in: of a Managed buffer, the block of its bytes.
block: Arc<Block>,
offset: u64,
@@ -115,6 +118,11 @@ impl Drop for DeviceCopy {
}
impl BufferInner {
/// Its bytes' placement in its heap, where it was placed in one (`crate::alias`).
pub(crate) fn place(&self) -> Option<&Arc<Place>> {
self.place.as_ref()
}
/// A capture's take of `ranges` of the buffer ([`crate::capture::Changes::take`]), holding its
/// blocks from here; none where it has no device copy.
pub(crate) fn modified(self: &Arc<Self>, ranges: Vec<(u64, u64)>) -> Option<Modified> {
@@ -487,10 +495,13 @@ impl BufferInner {
core.counters.rise(Gauge::Buffers);
let gauge = block.memory.class.buffer_gauge();
core.counters.rise_by(gauge, length);
let place = (heap.as_ref())
.map(|heap| Place::new(heap, offset, offset.saturating_add(length), None));
Arc::new(BufferInner {
core: Arc::clone(core),
id: core.ids.take(),
heap,
place,
block,
offset,
length,
@@ -1,6 +1,7 @@
//! Command buffers: recorded at once into segments that event waits and signals split, and their
//! states from creation to retirement.
use crate::alias::{Aliased, Marks, Place};
use crate::buffer::{Buffer, BufferInner, BufferObject};
use crate::complete::Completion;
use crate::counters::{Metric, Stage, Tally};
@@ -232,6 +233,8 @@ pub(crate) struct Building {
/// The drawables it presents, each with the consumer's semaphore its end signals
/// ([`CommandBuffer::present_drawable`]).
presents: Vec<(Texture, vk::Semaphore)>,
/// What its commands did to the heap placements with links they touched (`crate::alias`).
marks: Marks,
}
/// The push constant bytes a command buffer holds, from offset 0, as its pushes left them.
@@ -340,6 +343,9 @@ pub(crate) struct Segment {
/// Windows): its submission acquires them from `VK_QUEUE_FAMILY_EXTERNAL` at its start and
/// releases them to it at its end (`crate::submit`).
pub(crate) planes: Vec<Arc<Image>>,
/// The checks at its head and its writes of heap placements with links (`crate::alias`):
/// staged, a command buffer of moves leads it where the checks find one owed.
pub(crate) aliased: Aliased,
}
pub(crate) struct Handlers {
@@ -426,6 +432,7 @@ impl CommandBuffer {
vertex: Vec::new(),
tally: Tally::default(),
presents: Vec::new(),
marks: Marks::default(),
}),
ended: None,
times: Times::default(),
@@ -889,6 +896,17 @@ impl CommandBuffer {
})
}
/// For the device tests: the checks of heap placements at the head of each of its segments
/// so far (`crate::alias`), in order.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) fn alias_checks_for_test(&self) -> Vec<usize> {
let state = self.state();
let building = (state.building.as_ref()).expect("a command buffer not yet committed");
(building.gpu.segments.iter())
.map(|segment| segment.aliased.checks())
.collect()
}
/// For the device tests: keeps `textures` and `states` until the command buffer retires, as
/// an encoder that binds them does.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
@@ -1111,6 +1129,61 @@ impl Building {
}
}
/// A command's uses of heap placements with links, `uses` (`crate::alias`), before it is
/// recorded: its marks, the checks it adds at its segment's head, a segment ended first where
/// a check would go ahead of a read of one of the placement's links in it, and the moves owed
/// in place, which the caller records before the command ([`record_moves`](Self::record_moves),
/// or inside a rendering between its end and its new beginning). Inside a rendering
/// (`rendering`) nothing ends: the check goes at the head of the segment the pass is in.
pub(crate) fn aliases(
&mut self,
uses: &[(&Arc<Place>, Access)],
rendering: bool,
) -> Result<Vec<vk::ImageMemoryBarrier2<'static>>, Error> {
if !rendering && !self.last().signals.is_empty() {
self.split()?;
}
let mut segment = self.gpu.segments.len() - 1;
if !rendering && self.last().command.is_some() && self.marks.splits(uses, segment) {
self.split()?;
segment += 1;
}
let part = &mut self.gpu.segments[segment].aliased;
Ok(self.marks.used(uses, segment, part))
}
/// [`aliases`](Self::aliases) and [`record_moves`](Self::record_moves) for a command outside a
/// rendering, of the resources it touches, `uses`: nothing where none is a heap placement
/// with links.
pub(crate) fn places<'a>(
&mut self,
uses: impl Iterator<Item = (Option<&'a Arc<Place>>, Access)>,
) -> Result<(), Error> {
let uses = crate::alias::uses(uses);
if uses.is_empty() {
return Ok(());
}
let moves = self.aliases(&uses, false)?;
self.record_moves(&moves)
}
/// Records `moves` ([`aliases`](Self::aliases)) before the next command, outside a rendering.
pub(crate) fn record_moves(
&mut self,
moves: &[vk::ImageMemoryBarrier2<'static>],
) -> Result<(), Error> {
if moves.is_empty() {
return Ok(());
}
let command = self.ordered_command()?;
let device = &self.device.core().device;
let tally = &mut self.tally;
// SAFETY: the command buffer records outside any rendering and keeps each texture it uses
// until it retires.
unsafe { crate::alias::record(device, command, moves, &mut |metric| tally.count(metric)) };
Ok(())
}
/// The fences the encoders wait on and update.
pub(crate) fn fences(&mut self) -> &mut Fences {
&mut self.gpu.fences
+14 -1
View File
@@ -313,10 +313,12 @@ pub(crate) enum Metric {
AccumulatedVisibilityRefused,
/// [`Metrics::overlapping_copies_refused`].
OverlappingCopiesRefused,
/// [`Metrics::heap_moves`].
HeapMoves,
}
/// The number of [`Metric`]s.
const METRICS: usize = Metric::OverlappingCopiesRefused as usize + 1;
const METRICS: usize = Metric::HeapMoves as usize + 1;
/// Every [`Metric`], in its order: each at its own index.
const METRIC_ORDER: [Metric; METRICS] = [
@@ -371,6 +373,7 @@ const METRIC_ORDER: [Metric; METRICS] = [
Metric::VisibilityInterruptsRefused,
Metric::AccumulatedVisibilityRefused,
Metric::OverlappingCopiesRefused,
Metric::HeapMoves,
];
// Each metric of the order is at its own index.
@@ -796,6 +799,7 @@ struct Atomics {
visibility_interrupts_refused: AtomicU64,
accumulated_visibility_refused: AtomicU64,
overlapping_copies_refused: AtomicU64,
heap_moves: AtomicU64,
/// Each [`Part`]'s calls, at its index: their count, bytes, total and longest nanoseconds,
/// and those over each of [`OVER_NANOS`].
parts: [[AtomicU64; 7]; PARTS],
@@ -964,6 +968,7 @@ impl Counters {
Metric::VisibilityInterruptsRefused => &a.visibility_interrupts_refused,
Metric::AccumulatedVisibilityRefused => &a.accumulated_visibility_refused,
Metric::OverlappingCopiesRefused => &a.overlapping_copies_refused,
Metric::HeapMoves => &a.heap_moves,
}
}
@@ -1903,6 +1908,7 @@ impl Counters {
visibility_interrupts_refused: a.visibility_interrupts_refused.load(Relaxed),
accumulated_visibility_refused: a.accumulated_visibility_refused.load(Relaxed),
overlapping_copies_refused: a.overlapping_copies_refused.load(Relaxed),
heap_moves: a.heap_moves.load(Relaxed),
takes: part(Part::Take),
take_lock_waits: part(Part::TakeLock),
take_makes: part(Part::TakeMake),
@@ -2881,6 +2887,13 @@ pub struct Metrics {
/// and a texture placed in a heap whose memory meets the other side's. Copies the guest
/// asked for that did not run.
pub overlapping_copies_refused: u64,
/// Heap textures' images moved from undefined to their home layout before a command that
/// writes them (a dispatch's slot or declared write, a pass's attachment, a draw's write, a
/// blit's destination), because a write over their bytes through another resource of their
/// heap left them stale since their last write (Vulkan's memory aliasing): in place, or in a
/// command buffer of its own that leads the command's part of its command buffer. No Metal
/// counterpart.
pub heap_moves: u64,
/// Takes from the pool on the consumer's threads, each whole: a block of
/// [`Device::take_block`](crate::Device::take_block) and a texture block, carved from a free
/// range or from an allocation the take made ([`take_makes`](Self::take_makes)); their bytes
+38 -5
View File
@@ -1,5 +1,6 @@
//! Compute command encoders: their binding state, their dispatches, and where barriers go.
use crate::alias::Place;
use crate::arena;
use crate::buffer::{Buffer, BufferInner, BufferObject};
use crate::command::{Building, CommandBuffer};
@@ -829,7 +830,7 @@ impl ComputeCommandEncoder {
usage: ResourceUsage,
) -> Result<(), Error> {
let building = self.building();
let (id, shared, unstored, texture, span) = match resource {
let (id, shared, unstored, texture, span, place) = match resource {
Resource::Buffer(buffer) => {
if !buffer.is_of(building.device.core()) {
return Err(Error::Refused(Refusal::OtherDevice));
@@ -841,6 +842,7 @@ impl ComputeCommandEncoder {
None,
None,
Some(buffer.span()),
buffer.object().place().cloned(),
)
}
Resource::Texture(texture) => {
@@ -858,6 +860,7 @@ impl ComputeCommandEncoder {
texture.storage_gap(true, false),
Some(lent),
None,
texture.object().place().cloned(),
)
}
Resource::IndirectCommandBuffer(commands) => {
@@ -884,7 +887,7 @@ impl ComputeCommandEncoder {
Some((_, declared, ..)) => *declared = merge(*declared, access),
None => {
self.copied += over::copied(texture.as_deref());
self.declared.push((id, access, texture, span));
self.declared.push((id, access, texture, span, place));
}
}
Ok(())
@@ -1219,6 +1222,9 @@ impl ComputeCommandEncoder {
},
};
let building = recording(&mut self.building);
// Heap textures it writes that an alias's write left stale move from undefined first
// (`crate::alias`).
building.places(accesses.places(interface))?;
// Textures over a buffer in an image of their own take their copies first
// (`crate::over`): looked for where one is bound or declared, the kernel reaches
// memory outside its resources, or such an image is ahead of its buffer, and among
@@ -1803,7 +1809,13 @@ pub(crate) fn merge(a: Access, b: Access) -> Access {
/// A `use_resource` declaration, by resource id: its own and its id in the hazard sets; its
/// access; the texture, where the resource is one; and the memory of the buffer, where it is one,
/// as the copies over buffers track it (`crate::over`).
pub(crate) type Declared = ([u32; 2], Access, Option<Lent<Texture>>, Option<Span>);
pub(crate) type Declared = (
[u32; 2],
Access,
Option<Lent<Texture>>,
Option<Span>,
Option<Arc<Place>>,
);
/// What a dispatch touches besides its pipeline's own facts.
pub(crate) struct Accesses<'a> {
@@ -1868,8 +1880,8 @@ impl Accesses<'_> {
Some((Reached::Texture(texture), access))
});
let declared = (self.declared.iter())
.filter(move |(_, access, texture, _)| (buffers || texture.is_some()) && kept(*access))
.filter_map(|(_, access, texture, span)| match (texture, span) {
.filter(move |(_, access, texture, ..)| (buffers || texture.is_some()) && kept(*access))
.filter_map(|(_, access, texture, span, _)| match (texture, span) {
(Some(texture), _) => Some((Reached::Texture(texture), *access)),
(None, span) => span.map(|span| (Reached::Buffer(span), *access)),
});
@@ -1878,6 +1890,27 @@ impl Accesses<'_> {
.map(|(_, span)| (Reached::Buffer(span), Access::Read));
slots.chain(textures).chain(declared).chain(indirect)
}
/// Each heap placement the dispatch of a kernel of `interface` touches through its slots and
/// declarations, with its access: `None` for a resource in no heap (`crate::alias`).
pub(crate) fn places<'b>(
&'b self,
interface: &'b Interface,
) -> impl Iterator<Item = (Option<&'b Arc<Place>>, Access)> + 'b {
let slots = (interface.buffers.iter()).filter_map(move |&(slot, access)| {
match self.slots.get(slot as usize) {
Some(Slot::Buffer { buffer, .. }) => Some((buffer.object().place(), access)),
_ => None,
}
});
let textures = (interface.textures.iter()).filter_map(move |&(slot, access)| {
let texture = self.textures.get(slot as usize)?.as_deref()?;
Some((texture.object().place(), access))
});
let declared =
(self.declared.iter()).map(|(_, access, .., place)| (place.as_ref(), *access));
slots.chain(textures).chain(declared)
}
}
impl Building {
+10
View File
@@ -5,6 +5,7 @@
//! increment. They carry across the encoders of a command buffer until a barrier, so a write after
//! an encoder that only read still finds the read.
use crate::alias::Place;
use crate::device::Core;
use crate::memory::BlockId;
use metal2vulkan::metal::BindingAccess;
@@ -170,6 +171,8 @@ impl Ids {
pub(crate) struct HeapId {
core: Arc<Core>,
id: u32,
/// Its resources' placements, held weakly, whose bytes meeting link them (`crate::alias`).
places: Mutex<Vec<Weak<Place>>>,
}
impl HeapId {
@@ -179,6 +182,7 @@ impl HeapId {
Arc::new(HeapId {
core: Arc::clone(core),
id: core.ids.take(),
places: Mutex::new(Vec::new()),
})
}
@@ -186,6 +190,11 @@ impl HeapId {
pub(crate) fn get(&self) -> u32 {
self.id
}
/// Its resources' placements.
pub(crate) fn places(&self) -> &Mutex<Vec<Weak<Place>>> {
&self.places
}
}
impl Drop for HeapId {
@@ -226,6 +235,7 @@ impl HeapIds {
let id = Arc::new(HeapId {
core: Arc::clone(core),
id: core.ids.take(),
places: Mutex::new(Vec::new()),
});
state.heaps.insert((block, offset), Arc::downgrade(&id));
id
+1
View File
@@ -8,6 +8,7 @@
#![warn(missing_docs)]
mod alias;
mod arena;
mod arrays;
mod blit;
@@ -81,6 +81,7 @@
//! are the device's ([`PrecisionNote::DeviceDepthBias`]); a state that tests or writes depth
//! carries [`PrecisionNote::DepthDenormals`].
use crate::alias;
use crate::buffer::{Buffer, BufferInner, BufferObject};
use crate::command::{Building, CommandBuffer};
use crate::counters::Metric;
@@ -515,10 +516,10 @@ fn slots<'a>(
false => &[],
};
let declared = (declared.iter())
.filter(move |(_, access, texture, _)| {
.filter(move |(_, access, texture, ..)| {
(buffers || texture.is_some()) && (!written || access.writes())
})
.filter_map(|(_, access, texture, span)| match (texture, span) {
.filter_map(|(_, access, texture, span, _)| match (texture, span) {
(Some(texture), _) => Some((Reached::Texture(texture), *access)),
(None, span) => span.map(|span| (Reached::Buffer(span), *access)),
});
@@ -843,6 +844,12 @@ fn begin(
let lent = unsafe { building.lend_buffer(buffer) };
(lent, descriptor.visibility_result_type)
});
// Heap textures it renders into that an alias's write left stale move from undefined first
// (`crate::alias`).
let places = (pass.targets().map(|t| &t.texture))
.chain(resolves().map(|r| &r.texture))
.map(|texture| (TextureObject::object(texture).place(), Access::Write));
building.places(places)?;
building.overs_before(overs(), false)?;
let opens = building.opens_command_buffer();
let command = building.ordered_command()?;
@@ -1930,14 +1937,22 @@ impl RenderCommandEncoder {
usage: ResourceUsage,
) -> Result<(), Error> {
let building = self.building();
let (id, host, unstored, texture, span) = match resource {
let (id, host, unstored, texture, span, place) = match resource {
Resource::Buffer(buffer) => {
if !buffer.is_of(building.device.core()) {
return Err(Error::Refused(Refusal::OtherDevice));
}
building.keep(buffer);
let id = [buffer.id(), buffer.tracked_id()];
(id, buffer.is_shared(), None, None, Some(buffer.span()))
let place = buffer.object().place().cloned();
(
id,
buffer.is_shared(),
None,
None,
Some(buffer.span()),
place,
)
}
Resource::Texture(texture) => {
if !texture.is_of(building.device.core()) {
@@ -1953,6 +1968,7 @@ impl RenderCommandEncoder {
texture.storage_gap(true, false),
Some(lent),
None,
texture.object().place().cloned(),
)
}
Resource::IndirectCommandBuffer(commands) => {
@@ -1975,7 +1991,7 @@ impl RenderCommandEncoder {
Some((_, each, ..)) => *each = merge(*each, access),
None => {
declared.copied += over::copied(texture.as_deref());
declared.each.push((id, access, texture, span));
declared.each.push((id, access, texture, span, place));
}
}
self.changed();
@@ -2493,6 +2509,7 @@ impl RenderCommandEncoder {
|| arguments.is_some_and(|buffer| buffer.managed_overs().is_some())
|| factors.is_some_and(|(buffer, _)| buffer.managed_overs().is_some())
|| overs;
self.draw_aliases()?;
match each {
true => self.draw_reaches(reads, [index_buffer, arguments], overs, commands)?,
false => {
@@ -3158,6 +3175,47 @@ impl RenderCommandEncoder {
Ok(())
}
/// A draw's uses of heap placements with links (`crate::alias`): its marks, and the moves of
/// the heap textures it writes that an alias's write left stale, recorded between the
/// rendering's end and its new beginning. Refused as another command that ends the rendering
/// is while a visibility result's query counts the draws.
fn draw_aliases(&mut self) -> Result<(), Error> {
let Some(state) = &self.pipeline else {
return Ok(());
};
let draws = &state.inner.compiled.draws;
let tables = &self.tables;
let bound = (draws.buffers.iter()).map(|&(table, slot, access)| {
(tables[table].buffer(slot).and_then(|b| b.place()), access)
});
let textures = (draws.textures.iter()).map(|&(table, slot, access)| {
(tables[table].texture(slot).and_then(|t| t.place()), access)
});
let declared =
(self.declared.each.iter()).map(|(_, access, .., place)| (place.as_ref(), *access));
let uses = alias::uses(bound.chain(textures).chain(declared));
if uses.is_empty() {
return Ok(());
}
let building = (self.building.as_mut())
.expect("an encoder holds its command buffer's recording until it ends");
let moves = building.aliases(&uses, true)?;
drop(uses);
if moves.is_empty() {
return Ok(());
}
if self.results.counting() {
return Err(self.interrupt_refused());
}
let command = self.command;
self.interrupt(|building, core| {
// SAFETY: the rendering ended, and the command buffer keeps each texture it uses
// until it retires.
unsafe { alias::record(&core.device, command, &moves, &mut |m| building.count(m)) };
Ok(())
})
}
/// Whether [`draw_reaches`](Self::draw_reaches) may end the rendering for the draw: where it
/// moves an image to the feedback layout, pays the barrier owed before an attachment read, or
/// reads what an attachment's shadow does not hold; and, not looking at whether a copy is
+24 -3
View File
@@ -58,6 +58,7 @@
//! copies, waits at that commit's number, and the first submission of a command buffer numbered
//! at or after it takes it, ahead of that command buffer's first segment and outside its waits.
use crate::alias;
use crate::buffer::{BufferInner, BufferObject, DeviceCopy};
use crate::capture::{self, Changes, CopyIn, Modified};
use crate::command::{self, CbInner, CommandBufferError, DeviceLoss, Handler, Pending, Segment};
@@ -540,6 +541,9 @@ struct Batch {
reached: Vec<Arc<BufferInner>>,
/// The images of the Direct3D 11 planes its segments use (`Segment::planes`).
planes: Vec<Arc<Image>>,
/// The first failed call recording a command buffer of moves that leads a segment of it
/// (`crate::alias::stage`), which loses the device.
lost: Option<DeviceLoss>,
}
/// One part of a submit info: a segment's or an upload's commands and its signals, and for a
@@ -1774,10 +1778,11 @@ impl WorkState {
fn step(
&mut self,
now: u64,
counters: &Counters,
core: &Core,
joined: &mut Vec<Joined>,
ended: &mut Vec<Ended>,
) -> Step {
let counters = &core.counters;
let Some((index, waits)) = self.next_ready() else {
return Step::Idle;
};
@@ -1882,6 +1887,7 @@ impl WorkState {
wrote: Vec::new(),
reached: Vec::new(),
planes: Vec::new(),
lost: None,
});
if leads {
group.run = group.run.saturating_add(run.unwrap_or(u64::MAX));
@@ -1913,6 +1919,19 @@ impl WorkState {
for image in &segment.planes {
image.keep_plane(&mut group.planes);
}
// The moves its checks find owed lead it, in its submit info (`crate::alias`).
if !segment.aliased.is_empty() {
match alias::stage(core, &mut pending.gpu.recorder, &segment.aliased) {
Ok(Some(lead)) => group.segments.push(Staged {
command: Some(vk::CommandBufferSubmitInfo::default().command_buffer(lead)),
..Staged::default()
}),
Ok(None) => {}
Err(loss) => {
group.lost.get_or_insert(loss);
}
}
}
let staged = stage(segment, &mut group.watch);
let at = (pending.seq, pending.next);
if let Some((.., since)) =
@@ -2331,7 +2350,7 @@ fn pass<'a>(core: &'a Core, mut state: MutexGuard<'a, WorkState>) -> MutexGuard<
let now = times::host_time();
let step = match then.take() {
Some(index) => Step::Goes(index),
None => state.step(now, &core.counters, &mut joined, &mut ended),
None => state.step(now, core, &mut joined, &mut ended),
};
let index = match step {
Step::Idle => match state.unheld() {
@@ -2430,6 +2449,7 @@ impl Batch {
wrote: Vec::new(),
reached: Vec::new(),
planes: Vec::new(),
lost: None,
}
}
}
@@ -2508,6 +2528,7 @@ fn submit(core: &Core, value: u64, uploads: Vec<Upload>, batch: Batch) {
held,
copy_ins,
mut planes,
lost,
..
} = batch;
let device = &core.device;
@@ -2515,7 +2536,7 @@ fn submit(core: &Core, value: u64, uploads: Vec<Upload>, batch: Batch) {
// for the copies into textures over a buffer in an image of their own.
let sides = !overs.is_empty() || !backs.is_empty();
// The first failed call, which loses the device.
let mut ok: Result<(), DeviceLoss> = Ok(());
let mut ok: Result<(), DeviceLoss> = lost.map_or(Ok(()), Err);
let mut empty = None;
let mut kept = Vec::with_capacity(uploads.len());
for upload in uploads {
@@ -0,0 +1,330 @@
//! The placements of a heap whose bytes meet (`crate::alias`), under a device cfg, on every device
//! of the cfg's kind, read through `Metrics::heap_moves` and through the checks each segment of a
//! command buffer holds before its commit. P and Q are textures at offset 0 of one heap, P placed
//! first, so Q is stale from its making; each is written through its view (`rows_write`).
//!
//! - Commit order against encode order: A writes P and B writes Q, encoded A then B and committed
//! B then A. Each holds one check; the submit thread resolves them in the order the queue runs
//! them, so Q's move goes first and leaves P stale for A's.
//! - A read of an alias, then a write of a texture nothing earlier in the command buffer wrote:
//! the segment ends between them, and the check sits at the head of the second.
//! - Writes of P, Q and P in one command buffer: the second and third move in place.
//! - A draw whose fragment writes P after a dispatch wrote Q: P moves through the pass's
//! interruption.
//! - A heap whose two textures' bytes do not meet: no links, no check and no move.
//!
//! `llvm-as` assembles the kernels' libraries; without it the tests are skipped, visibly.
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod on_device {
use crate::tests::command::on_device::{each_device, finished};
use crate::tests::draw::on_device::{library, pass, state};
use crate::tests::heap_alias::on_device::{
input, kernels, libraries, place, place_at, read, write, Buffers, Kernels, Placed,
};
use crate::texture::TextureObject;
use crate::{
Block, Buffer, ColorAttachmentDescriptor, CommandBuffer, CommandQueue, CullMode, Device,
FunctionDescriptor, HeapRange, IndexClass, MemoryClass, PixelFormat, PrimitiveType,
RenderPipelineDescriptor, StageSource, StorageMode, TextureDescriptor, TextureType,
TextureUsage,
};
use metal2vulkan_devtools::fixtures_dir;
/// The first texture index the tests grant.
const FIRST: u32 = 4600;
fn moves(device: &Device) -> u64 {
device.counters().metrics().heap_moves
}
/// A Private block and a heap over all of it.
fn heap(name: &str, device: &Device) -> (Block, HeapRange) {
let len = MemoryClass::Private.block_len();
let block = (device.take_block(MemoryClass::Private, len))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let heap = HeapRange {
block: block.id,
offset: 0,
len,
};
(block, heap)
}
/// P and Q, 64 by 64 `RGBA16Float` at offset 0 of `heap`, P placed first, and the inputs
/// `rows_write` writes into each.
struct Pair {
p: Placed,
q: Placed,
inputs: [Buffer; 2],
_buffers: Buffers,
}
fn pair(name: &str, device: &Device, heap: HeapRange) -> Pair {
let format = PixelFormat::RGBA16Float;
let p = place(name, device, heap, (0, format, 64, 64), FIRST);
let q = place(name, device, heap, (1, format, 64, 64), FIRST + 2);
let mut buffers = Buffers::new(name, device, 4);
let inputs = [&p, &q].map(|t| buffers.of(name, device, &input(t)));
Pair {
p,
q,
inputs,
_buffers: buffers,
}
}
/// Runs one command buffer of `queue` that writes `order`'s textures in turn.
fn settle(name: &str, queue: &CommandQueue, kernels: &Kernels, order: [(&Placed, &Buffer); 2]) {
let cb = queue.command_buffer().expect("a command buffer");
for (t, input) in order {
write(name, &cb, kernels, t, input);
}
run(name, &cb);
}
fn run(name: &str, cb: &CommandBuffer) {
cb.commit().expect("a commit");
finished(name, cb);
assert_eq!(cb.error(), None, "{name}");
}
/// Commit order against encode order: A writes P and B writes Q, encoded A then B, committed
/// B then A, after a command buffer that wrote Q then P (Q's move from its making, P's in
/// place). Q is stale and P is not as B runs; B's write of Q leaves P stale for A, so each
/// check finds a move owed, as the queue runs them.
#[test]
fn every_device_resolves_heap_checks_in_the_order_the_queue_runs_them() {
let Some(libraries) = libraries() else {
return;
};
each_device("alias_order", |name, _, device| {
let kernels = kernels(name, &device, &libraries);
let _grant = (device.grant_indices(IndexClass::Texture, FIRST, 4))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let (block, heap) = heap(name, &device);
let Pair { p, q, inputs, .. } = pair(name, &device, heap);
let queue = device.new_command_queue(4).expect("a queue");
let start = moves(&device);
settle(name, &queue, &kernels, [(&q, &inputs[1]), (&p, &inputs[0])]);
assert_eq!(
moves(&device) - start,
2,
"{name}: Q from its making, P in place"
);
let before = moves(&device);
let a = queue.command_buffer().expect("a command buffer");
write(name, &a, &kernels, &p, &inputs[0]);
let b = queue.command_buffer().expect("a command buffer");
write(name, &b, &kernels, &q, &inputs[1]);
assert_eq!(a.alias_checks_for_test(), [1], "{name}: A");
assert_eq!(b.alias_checks_for_test(), [1], "{name}: B");
assert_eq!(moves(&device), before, "{name}: nothing moves in place");
run(name, &b);
run(name, &a);
assert_eq!(moves(&device) - before, 2, "{name}: Q's move, then P's");
drop((p, q, inputs, queue));
(device.release_block(block)).unwrap_or_else(|error| panic!("{name}: {error}"));
println!("heap checks: {name}: resolved in the order the queue ran them");
});
}
/// A read of Q, then a write of P, which nothing earlier in the command buffer wrote nor an
/// alias of it: the segment ends between them, and P's check heads the second, where the
/// move it finds owed (P stale after a command buffer that wrote P then Q) runs after the
/// read. A command buffer with no such read holds the check in its one segment.
#[test]
fn every_device_ends_a_segment_before_a_heap_check_behind_an_alias_s_read() {
let Some(libraries) = libraries() else {
return;
};
each_device("alias_split", |name, _, device| {
let kernels = kernels(name, &device, &libraries);
let _grant = (device.grant_indices(IndexClass::Texture, FIRST, 4))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let (block, heap) = heap(name, &device);
let Pair { p, q, inputs, .. } = pair(name, &device, heap);
let mut buffers = Buffers::new(name, &device, 1);
let out = buffers.of(name, &device, &vec![0.0; input(&q).len()]);
let queue = device.new_command_queue(4).expect("a queue");
settle(name, &queue, &kernels, [(&p, &inputs[0]), (&q, &inputs[1])]);
let before = moves(&device);
let cb = queue.command_buffer().expect("a command buffer");
read(name, &cb, &kernels, &q, &out);
write(name, &cb, &kernels, &p, &inputs[0]);
assert_eq!(cb.alias_checks_for_test(), [0, 1], "{name}: split");
run(name, &cb);
assert_eq!(
moves(&device) - before,
1,
"{name}: P's move after Q's read"
);
let cb = queue.command_buffer().expect("a command buffer");
write(name, &cb, &kernels, &q, &inputs[1]);
assert_eq!(cb.alias_checks_for_test(), [1], "{name}: no read, no split");
run(name, &cb);
drop((p, q, inputs, out, buffers, queue));
(device.release_block(block)).unwrap_or_else(|error| panic!("{name}: {error}"));
println!("heap checks: {name}: a check behind an alias's read heads a segment");
});
}
/// Writes of P, Q and P in one command buffer, after one that wrote P then Q: P's first write
/// is a check, which finds P stale; Q's and P's second move in place, each after its alias's
/// write.
#[test]
fn every_device_moves_heap_textures_in_place_after_their_alias_s_write() {
let Some(libraries) = libraries() else {
return;
};
each_device("alias_in_place", |name, _, device| {
let kernels = kernels(name, &device, &libraries);
let _grant = (device.grant_indices(IndexClass::Texture, FIRST, 4))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let (block, heap) = heap(name, &device);
let Pair { p, q, inputs, .. } = pair(name, &device, heap);
let queue = device.new_command_queue(4).expect("a queue");
settle(name, &queue, &kernels, [(&p, &inputs[0]), (&q, &inputs[1])]);
let before = moves(&device);
let cb = queue.command_buffer().expect("a command buffer");
write(name, &cb, &kernels, &p, &inputs[0]);
write(name, &cb, &kernels, &q, &inputs[1]);
write(name, &cb, &kernels, &p, &inputs[0]);
assert_eq!(cb.alias_checks_for_test(), [1], "{name}: P's first write");
assert_eq!(moves(&device) - before, 2, "{name}: Q and P in place");
run(name, &cb);
assert_eq!(moves(&device) - before, 3, "{name}: and P's check");
drop((p, q, inputs, queue));
(device.release_block(block)).unwrap_or_else(|error| panic!("{name}: {error}"));
println!("heap checks: {name}: moves in place after an alias's write");
});
}
/// The draw's target and fragment texture's extent.
const WIDTH: u32 = 32;
const HEIGHT: u32 = 16;
/// A dispatch writes Q, then a draw whose fragment (`lw_late_write`) writes P, an
/// `RGBA32Float` texture at Q's offset: P moves in place, through the pass's interruption,
/// and the fragment runs.
#[test]
fn every_device_moves_a_draw_s_written_heap_texture_through_the_pass() {
let Some(libraries) = libraries() else {
return;
};
let Some(writes) = library(&fixtures_dir().join("examples/lost_writes.ll")) else {
return;
};
each_device("alias_draw", |name, _, device| {
let kernels = kernels(name, &device, &libraries);
let _grant = (device.grant_indices(IndexClass::Texture, FIRST, 4))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let (block, heap) = heap(name, &device);
let format = PixelFormat::RGBA16Float;
let q = place(name, &device, heap, (1, format, 64, 64), FIRST);
let p = place(
name,
&device,
heap,
(0, PixelFormat::RGBA32Float, WIDTH, HEIGHT),
FIRST + 2,
);
let mut buffers = Buffers::new(name, &device, 2);
let q_in = buffers.of(name, &device, &input(&q));
let runs = buffers.of(name, &device, &[0.0]);
let function = |name| {
StageSource::Function(FunctionDescriptor::new(
writes.function(name).expect("the function"),
))
};
let mut d = RenderPipelineDescriptor::new(function("lw_cover"));
d.fragment = Some(function("lw_late_write"));
d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm));
let drawn = state(name, &device, &d);
let mut target =
TextureDescriptor::new(TextureType::Type2D, PixelFormat::RGBA8Unorm, WIDTH, HEIGHT);
target.usage = TextureUsage::RENDER_TARGET;
target.storage_mode = StorageMode::Private;
let target = (device.new_texture_for_views(&target))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let queue = device.new_command_queue(4).expect("a queue");
let before = moves(&device);
let cb = queue.command_buffer().expect("a command buffer");
write(name, &cb, &kernels, &q, &q_in);
let mut encoder = (cb.render_command_encoder(&pass(&target, None)))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let done = |result: Result<(), crate::Error>| {
result.unwrap_or_else(|error| panic!("{name}: {error}"))
};
done(encoder.set_render_pipeline_state(&drawn));
encoder.set_cull_mode(CullMode::None);
done(encoder.set_fragment_texture(Some(&p.texture), 0));
done(encoder.set_fragment_buffer(Some(&runs), 0, 0));
done(encoder.draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0));
encoder.end_encoding();
assert_eq!(cb.alias_checks_for_test(), [1], "{name}: Q's write");
assert_eq!(
moves(&device) - before,
1,
"{name}: P in place, in the pass"
);
run(name, &cb);
let contents = runs.contents().expect("a Shared buffer");
// SAFETY: the buffer holds one word, which the finished draw wrote and whose writes
// reach the host.
let ran = unsafe { contents.as_ptr().cast::<u32>().read_unaligned() };
assert!(ran > 0, "{name}: the fragment ran");
drop((p, q, q_in, runs, buffers, target, cb, queue));
(device.release_block(block)).unwrap_or_else(|error| panic!("{name}: {error}"));
println!("heap checks: {name}: a draw's write moved through the pass ({ran} runs)");
});
}
/// Two textures of one heap whose bytes do not meet, written in turn: no links, no check, no
/// move and one segment, in one command buffer and across two.
#[test]
fn every_device_takes_no_check_or_move_on_a_heap_of_apart_placements() {
let Some(libraries) = libraries() else {
return;
};
each_device("alias_apart", |name, _, device| {
let kernels = kernels(name, &device, &libraries);
let _grant = (device.grant_indices(IndexClass::Texture, FIRST, 4))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let (block, heap) = heap(name, &device);
let format = PixelFormat::RGBA16Float;
let mut d = TextureDescriptor::new(TextureType::Type2D, format, 64, 64);
d.usage = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE;
d.storage_mode = StorageMode::Private;
let fit = (device.heap_texture_size_and_align(&d))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let apart = fit.size.next_multiple_of(fit.align);
let p = place(name, &device, heap, (0, format, 64, 64), FIRST);
let r = place_at(name, &device, (heap, apart), (1, format, 64, 64), FIRST + 2);
for t in [&p, &r] {
let place = (t.texture.object().place()).expect("a heap texture's placement");
assert!(!place.linked(), "{name}: no links");
}
let mut buffers = Buffers::new(name, &device, 2);
let inputs = [&p, &r].map(|t| buffers.of(name, &device, &input(t)));
let queue = device.new_command_queue(4).expect("a queue");
let before = moves(&device);
let cb = queue.command_buffer().expect("a command buffer");
for _ in 0..2 {
write(name, &cb, &kernels, &p, &inputs[0]);
write(name, &cb, &kernels, &r, &inputs[1]);
}
assert_eq!(
cb.alias_checks_for_test(),
[0],
"{name}: one segment, no check"
);
run(name, &cb);
settle(name, &queue, &kernels, [(&r, &inputs[1]), (&p, &inputs[0])]);
assert_eq!(moves(&device), before, "{name}: no move");
drop((p, r, inputs, buffers, queue));
(device.release_block(block)).unwrap_or_else(|error| panic!("{name}: {error}"));
println!("heap checks: {name}: apart placements take no check or move");
});
}
}
@@ -18,7 +18,7 @@
//! kernels' libraries; without it the tests are skipped, visibly.
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod on_device {
pub(crate) mod on_device {
use crate::tests::command::on_device::{each_device, finished};
use crate::tests::draw::on_device::{examples, library};
use crate::{
@@ -47,19 +47,23 @@ mod on_device {
/// The kernels: `rows_write` and `rows_read` of `examples/texel_rows`, and `invert_texels` of
/// the runtime's examples.
struct Kernels {
pub(crate) struct Kernels {
write: ComputePipelineState,
read: ComputePipelineState,
invert: ComputePipelineState,
}
/// The libraries, or None where `llvm-as` is missing.
fn libraries() -> Option<(Library, Library)> {
pub(crate) fn libraries() -> Option<(Library, Library)> {
let rows = library(&fixtures_dir().join("examples/texel_rows.ll"))?;
Some((rows, examples()?))
}
fn kernels(name: &str, device: &Device, (rows, examples): &(Library, Library)) -> Kernels {
pub(crate) fn kernels(
name: &str,
device: &Device,
(rows, examples): &(Library, Library),
) -> Kernels {
let state = |library: &Library, function: &str| {
let source = StageSource::Function(FunctionDescriptor::new(
library.function(function).expect("the function"),
@@ -117,14 +121,14 @@ mod on_device {
}
/// Shared buffers in a block of their own, each `at` bytes apart.
struct Buffers {
pub(crate) struct Buffers {
block: Block,
at: u64,
next: u64,
}
impl Buffers {
fn new(name: &str, device: &Device, count: u64) -> Buffers {
pub(crate) fn new(name: &str, device: &Device, count: u64) -> Buffers {
Buffers::apart(name, device, count, AT)
}
@@ -135,7 +139,7 @@ mod on_device {
}
/// The next buffer, holding `floats`.
fn of(&mut self, name: &str, device: &Device, floats: &[f32]) -> Buffer {
pub(crate) fn of(&mut self, name: &str, device: &Device, floats: &[f32]) -> Buffer {
let len = (floats.len() * 4) as u64;
assert!(len <= self.at, "{name}: a buffer past its place");
let buffer = (device.new_buffer(self.block.id, self.next, len, None))
@@ -160,21 +164,32 @@ mod on_device {
}
/// A heap texture: its number, format and extent, the texture and its view.
struct Placed {
pub(crate) struct Placed {
t: u32,
format: PixelFormat,
width: u32,
height: u32,
texture: Texture,
pub(crate) texture: Texture,
view: Texture,
}
/// Texture `t` of `format`, `width` by `height`, at offset 0 of `heap`, at index `index`, and
/// its view at `index + 1`.
fn place(
pub(crate) fn place(
name: &str,
device: &Device,
heap: HeapRange,
shape: (u32, PixelFormat, u32, u32),
index: u32,
) -> Placed {
place_at(name, device, (heap, 0), shape, index)
}
/// As [`place`], at `offset` in `heap`, a multiple of the texture's alignment there.
pub(crate) fn place_at(
name: &str,
device: &Device,
(heap, offset): (HeapRange, u64),
(t, format, width, height): (u32, PixelFormat, u32, u32),
index: u32,
) -> Placed {
@@ -183,8 +198,12 @@ mod on_device {
d.storage_mode = StorageMode::Private;
let fit = (device.heap_texture_size_and_align(&d))
.unwrap_or_else(|error| panic!("{name}: texture {t}: {error}"));
assert!(fit.size <= heap.len, "{name}: texture {t}: {fit:?}");
let texture = (device.new_heap_texture(&d, Some(index), heap, 0))
assert!(
offset + fit.size <= heap.len,
"{name}: texture {t}: {fit:?}"
);
assert_eq!(offset % fit.align, 0, "{name}: texture {t}: {fit:?}");
let texture = (device.new_heap_texture(&d, Some(index), heap, offset))
.unwrap_or_else(|error| panic!("{name}: texture {t}: {error}"));
let view =
(texture.new_texture_view(format, TextureType::Type2D, 0..1, 0..1, Some(index + 1)))
@@ -200,7 +219,7 @@ mod on_device {
}
/// The input `rows_write` writes into `p`: each texel's four values.
fn input(p: &Placed) -> Vec<f32> {
pub(crate) fn input(p: &Placed) -> Vec<f32> {
let mut floats = Vec::new();
for y in 0..p.height {
for x in 0..p.width {
@@ -212,7 +231,13 @@ mod on_device {
/// Encodes, in a serial compute encoder of its own, `rows_write` of `input` into `p` through
/// its view.
fn write(name: &str, cb: &CommandBuffer, kernels: &Kernels, p: &Placed, input: &Buffer) {
pub(crate) fn write(
name: &str,
cb: &CommandBuffer,
kernels: &Kernels,
p: &Placed,
input: &Buffer,
) {
let done = |result: Result<(), crate::Error>| {
result.unwrap_or_else(|error| panic!("{name}: texture {}: {error}", p.t))
};
@@ -227,7 +252,13 @@ mod on_device {
/// Encodes, in a serial compute encoder of its own, `rows_read` of `p` through itself into
/// `out`.
fn read(name: &str, cb: &CommandBuffer, kernels: &Kernels, p: &Placed, out: &Buffer) {
pub(crate) fn read(
name: &str,
cb: &CommandBuffer,
kernels: &Kernels,
p: &Placed,
out: &Buffer,
) {
let done = |result: Result<(), crate::Error>| {
result.unwrap_or_else(|error| panic!("{name}: texture {}: {error}", p.t))
};
@@ -1,4 +1,5 @@
mod ahead;
mod alias;
mod aliased_encoders;
mod alpha_test;
mod argument_sampling;
+50 -6
View File
@@ -38,6 +38,7 @@
//! it moves it from home to the present layout at its end
//! ([`CommandBuffer::present_drawable`](crate::CommandBuffer::present_drawable)).
use crate::alias::{Moved, Place};
use crate::arrays::{Owner, ResourceId};
use crate::buffer::{Buffer, BufferInner, BufferObject};
use crate::copy_out;
@@ -234,6 +235,9 @@ pub(crate) struct TextureInner {
/// The heap it was placed in ([`Device::new_heap_texture`]), whose id its uses take in the
/// compute encoders' hazard sets; a view's is its parent's.
heap: Option<Arc<HeapId>>,
/// Its image's bytes in its heap, where it was placed in one, which the placements whose
/// bytes meet them link (`crate::alias`); a view's is its parent's.
place: Option<Arc<Place>>,
/// The bytes the host reaches in a buffer: a Managed texture's, or a texture over a buffer's.
named: Option<Named>,
/// A view's parent and place in the image ([`Texture::new_texture_view`]); `None` for a
@@ -491,6 +495,10 @@ pub(crate) struct Image {
/// in place, whose move home keeps the bytes (over a dma-buf's import, the layout of the
/// bytes the host wrote, which the move's acquire names, `foreign`).
first: vk::ImageLayout,
/// A heap texture's image placed over bytes another resource of its heap reaches
/// (`crate::alias`): its move home waits for every earlier command's writes. False for every
/// other image.
over: bool,
/// In place over a dma-buf's import (`Device::import_dma_buf`, on Unix): the import's buffer
/// and the range of it the image's memory is, which its move home acquires from the foreign
/// queue family (`VK_QUEUE_FAMILY_FOREIGN_EXT`) in one barrier with the image, so that both
@@ -782,10 +790,18 @@ impl Image {
.dst_queue_family_index(vk::QUEUE_FAMILY_IGNORED)
.image(self.image)
.subresource_range(whole(self.aspects));
// Placed over another resource's bytes, after every earlier command's writes.
let (stages, written) = match self.over {
true => (
vk::PipelineStageFlags2::ALL_COMMANDS,
vk::AccessFlags2::MEMORY_WRITE,
),
false => (vk::PipelineStageFlags2::NONE, vk::AccessFlags2::NONE),
};
let Some(zero) = self.zero else {
let first = barrier
.src_stage_mask(vk::PipelineStageFlags2::NONE)
.src_access_mask(vk::AccessFlags2::NONE)
.src_stage_mask(stages)
.src_access_mask(written)
.dst_stage_mask(vk::PipelineStageFlags2::ALL_COMMANDS)
.dst_access_mask(every)
.old_layout(first)
@@ -927,6 +943,7 @@ impl Image {
cube: plan.cube,
linear_attachment: false,
first: vk::ImageLayout::UNDEFINED,
over: false,
homed: AtomicBool::new(false),
zero: None,
foreign: None,
@@ -1475,6 +1492,7 @@ impl Device {
cube: false,
linear_attachment: false,
first: vk::ImageLayout::UNDEFINED,
over: false,
// No move home until the consumer acquires it.
homed: AtomicBool::new(true),
foreign: None,
@@ -1517,6 +1535,7 @@ impl Device {
word: plan.word,
id: core.ids.take(),
heap: None,
place: None,
named: None,
view: None,
emulation: plan.emulation,
@@ -1547,10 +1566,14 @@ impl Device {
Reach::Views => None,
};
let core = self.core();
// A heap's texture takes the heap's id in the hazard sets.
let heap_id = match &source {
Source::Heap(_, heap, _) => Some(core.heap_ids.of(core, heap.block, heap.offset)),
_ => None,
// A heap's texture takes the heap's id in the hazard sets, and its image's first byte in
// the heap's block is its placement's.
let (heap_id, heap_at) = match &source {
Source::Heap(_, heap, offset) => (
Some(core.heap_ids.of(core, heap.block, heap.offset)),
Some(heap.offset.saturating_add(*offset)),
),
_ => (None, None),
};
// Over a buffer in place, the memory its image lies in (`check_over`).
let mut laid = None;
@@ -1708,6 +1731,16 @@ impl Device {
image: Mutex::new(None),
})
});
// A heap's texture's image is placed among its heap's resources, linked with those whose
// bytes meet its (`crate::alias`).
let place = (heap_id.as_ref().zip(heap_at)).map(|(heap, at)| {
let moved = Moved {
image,
home,
aspects: plan.aspects,
};
Place::new(heap, at, at.saturating_add(bytes), Some(moved))
});
let image = Arc::new(Image {
core: Arc::clone(core),
image,
@@ -1733,6 +1766,7 @@ impl Device {
cube: plan.cube,
linear_attachment: false,
first,
over: place.as_ref().is_some_and(|place| place.over()),
foreign,
homed: AtomicBool::new(false),
zero,
@@ -1774,6 +1808,7 @@ impl Device {
word: plan.word,
id: core.ids.take(),
heap: heap_id,
place,
named,
view: None,
emulation: plan.emulation,
@@ -3886,6 +3921,11 @@ impl TextureInner {
}
impl TextureInner {
/// Its image's placement in its heap, where it was placed in one (`crate::alias`).
pub(crate) fn place(&self) -> Option<&Arc<Place>> {
self.place.as_ref()
}
/// Its image: its own, or a view's parent's; `None` for a texture buffer.
fn image_of(&self) -> Option<&Arc<Image>> {
match &self.body {
@@ -4340,6 +4380,7 @@ impl Texture {
word: plan.word,
id: inner.id,
heap: inner.heap.clone(),
place: inner.place.clone(),
named,
view: Some(View {
parent,
@@ -5997,6 +6038,7 @@ impl Device {
word: form.word,
id: core.ids.take(),
heap: None,
place: None,
named: Some(named),
view: None,
emulation: FormatEmulation::Direct,
@@ -6217,6 +6259,7 @@ impl Device {
true => home,
false => vk::ImageLayout::UNDEFINED,
},
over: false,
// An image already general owes no move.
homed: AtomicBool::new(general),
foreign: None,
@@ -6262,6 +6305,7 @@ impl Device {
word: plan.word,
id: core.ids.take(),
heap: Some(unit),
place: None,
named: None,
view: None,
emulation: plan.emulation,
@@ -1462,6 +1462,7 @@ field metal2vulkan-runtime::Metrics.gpu_end_to_handler_tail pub gpu_end_to_handl
field metal2vulkan-runtime::Metrics.gpu_end_to_handler_tail_steps_nanos pub gpu_end_to_handler_tail_steps_nanos: [u64; HANDLER_STEPS]
field metal2vulkan-runtime::Metrics.gpu_run pub gpu_run: [u64; STAGE_BUCKETS]
field metal2vulkan-runtime::Metrics.gpu_run_nanos pub gpu_run_nanos: u64
field metal2vulkan-runtime::Metrics.heap_moves pub heap_moves: u64
field metal2vulkan-runtime::Metrics.held_for_room pub held_for_room: u64
field metal2vulkan-runtime::Metrics.held_release_bytes pub held_release_bytes: u64
field metal2vulkan-runtime::Metrics.held_release_starts pub held_release_starts: u64
Can't render this file because it is too large.