rt: a Managed buffer's copy-in is a GPU copy from the consumer's block, and the capture ring goes
Metal's contract for a Managed buffer (MTLBuffer.h, didModifyRange:): a CPU write makes the range
undefined for the GPU until a didModifyRange: and a commit of the command buffer that reads it,
and it does not reach a command buffer committed before. The capture ring met that by copying
the bytes on the committing thread into 64 MiB of Shared staging, and the commit then waited for
the GPU whenever the ring was full. One recording on an RTX 3090 waited 258 times for 6.7 s
(m3-max-53409). The ring also kept a Managed buffer over an imported dma-buf, a block the runtime
does not map, refused (Refusal::ManagedBlockNotShared). On the XTX that refusal bound nil 2,804
times, and 28.8 million draws were then refused.
The planner ruled one form. The commit records the copy-in into a command buffer of its own:
vkCmdCopyBuffer of each named range from the consumer's block into the device copy, ahead of the
command buffer's commands in its submission, after the copies back owed to textures over the
ranges and before the copies into them. Vulkan's host write ordering guarantee makes the
consumer's writes made before the submission visible to the copies. The copy reads the bytes as
it runs, so a write after the commit may reach it, which Metal leaves undefined. The copy-in
holds each consumer's block and device copy until the command buffer retires.
What goes with the ring:
- capture.rs keeps the named ranges and the copy-in, and loses the ring, Chunk, Overflowed and
the staging blocks of its own;
- submit.rs loses the commits' turn (capture now records under the work lock), the streams of
ring-fulls, the waits and the ring's spans;
- the counters lose capture_waits, capture_streams, capture_overflows, capture_overflow_bytes,
capture_copy_nanos, capture_wait_nanos, Gauges::capture_bytes and the capture ring's site, and
managed_bytes_captured counts the bytes the copies take;
- the player's report and the API table lose the same fields.
A Managed buffer's bytes may be in any Shared block, mapped or not: contents is None over an
import. A Private block is refused as Refusal::ManagedBlockPrivate, since a Managed buffer has a
CPU-side copy ("the data pointer of this buffer's shared copy", MTLBuffer.h) and a Private block
has no pages the consumer can write. docs/REFUSALS.md is regenerated. The rt README's memory
contract says when the copy runs, and its known gap of the ring's waits goes.
Tests:
- the snapshot tests now hold the header's contract: write, didModifyRange:, commit, and that
command buffer reads the bytes, here also behind an event wait with the consumer's handles
gone before it runs. Nothing is asserted of a write under a pending command buffer;
- the ring's tests go;
- a range of three 16 MiB units arrives whole at one commit, with no staging and no allocation;
- a Managed buffer over an imported, unmapped dma-buf (Shared, contents None) reads what the
consumer wrote through its own mapping, on a two-copy card and on a unified one;
- a Managed buffer over a Private block is refused;
- the first named range allocates nothing at any site;
- the commit's lock-wait test marks the start of its count with a test-only flag, where it read
the turn.
Verified: see the check job named in the landing.
This commit is contained in:
1 parent
c011924158
commit
d65374348e
15 files changed
+379
-1235
No files matched your search
@@ -203,12 +203,12 @@ in its memory.
|
||||
pipeline's creation waited out the whole 3.4 ms of a 16 MiB Shared allocation made beside it.
|
||||
`Metrics::consumer_allocation_nanos` and `consumer_allocation_max_nanos` count the time of
|
||||
allocations made on the consumer's threads, and `maker_allocation_nanos` those of the
|
||||
block-maker thread. Eight of the consumer's sites are
|
||||
block-maker thread. Seven of the consumer's sites are
|
||||
counted apart, each as a `SiteAllocations` (calls, bytes and the longest call):
|
||||
`texture_allocations` (a texture's allocation of its own), `texture_block_allocations`,
|
||||
`ring_block_allocations`, `staging_region_allocations`, `staging_buffer_allocations` (a copy
|
||||
larger than the staging region), `capture_ring_allocations`, `zero_source_allocations` and
|
||||
`take_allocations` (a take that no free range fits).
|
||||
larger than the staging region), `zero_source_allocations` and `take_allocations` (a take that
|
||||
no free range fits).
|
||||
- The runtime's fixed-size internals are made by the block-maker thread, never on a caller's
|
||||
thread and never inside `Device::new`: its first work once `Device::new` starts it is the zero
|
||||
source (64 KiB), the parameter ring's first block (2 MiB) and the staging region (16 MiB). The
|
||||
@@ -341,8 +341,11 @@ in its memory.
|
||||
a block, whether Metal's `newBufferWithLength:`, a heap's or a no-copy buffer stands behind it.
|
||||
- `Device::new_managed_buffer(bytes, copy, length, copied)` makes a Managed buffer whose bytes are
|
||||
`length` bytes at `bytes`, a block the consumer holds and an offset in it: the consumer's bytes,
|
||||
which `contents` answers, in a block the host maps (`Refusal::ManagedBlockNotShared` for a
|
||||
Private one). Vulkan's device type picks its form, as `Device::has_unified_memory` answers it.
|
||||
which `contents` answers where the runtime maps the block (one taken from the pool), and `None`
|
||||
where it does not (an imported block, whose pages the consumer reaches through its own mapping).
|
||||
The block is a Shared one (`Refusal::ManagedBlockPrivate` for a Private one, whose pages the
|
||||
consumer cannot write). Vulkan's device type picks its form, as `Device::has_unified_memory`
|
||||
answers it.
|
||||
On an integrated or CPU device the buffer is its bytes, as a Shared buffer is, its `gpu_address`
|
||||
theirs, `did_modify_range` does nothing, and `copy` is `None` (`Refusal::ManagedCopyOnUnified`
|
||||
otherwise). Elsewhere shaders reach a device copy at `gpu_address`, always: `length` bytes at
|
||||
@@ -352,31 +355,17 @@ in its memory.
|
||||
it. The copy's rest past its first `copied` bytes is zeroed in the upload, and those bytes are
|
||||
named as `did_modify_range` names a range.
|
||||
`Buffer::did_modify_range(start, length)` names a range changed (`Refusal::ModifiedRange` past
|
||||
the buffer), merged with the buffer's others where they overlap or touch, and submits nothing.
|
||||
The next commit of a command buffer with commands, on any queue, takes the bytes of every range
|
||||
named since: on the committing thread, before `commit` returns, it copies each once into a
|
||||
64 MiB staging ring of the Shared type (made at the device's first `did_modify_range`, on its
|
||||
thread, so no commit waits for the allocation; never zeroed, as each span is written before it
|
||||
is copied), and the copies from the ring into the device copies go
|
||||
ahead of that command buffer's commands, after every earlier command on the device, which the
|
||||
barrier ending each earlier command buffer orders; the copies record one barrier, after them. So
|
||||
the bytes are taken at the commit; Metal takes them shortly after, before the command buffer is
|
||||
scheduled. A write or a `did_modify_range` made while a command buffer runs does not reach it.
|
||||
Commits take turns while they copy, so command buffers keep the order of their captures. A
|
||||
commit that finds the ring full waits for its oldest copy's submission to complete. Where that
|
||||
copy is not yet submitted, the held groups go at once; once every command buffer committed
|
||||
before is submitted, the commit's own ring-full goes in a copy submission of its own, which the
|
||||
commit waits for before it reuses the ring, so the ring is all the staging a commit holds,
|
||||
whatever it names, and the wait runs at the GPU's copy speed. Where a command buffer committed
|
||||
before waits on the host instead (an event wait the host has not met, or a command buffer
|
||||
enqueued ahead of it and not committed), nothing can go before the host acts: the rest of the
|
||||
commit's bytes go into Shared staging blocks of its own from the pool (at most 256 MiB each),
|
||||
which its command buffer gives back as it retires, the pool's idle rule then deciding when their
|
||||
memory is freed. Every byte is still the commit's. `Metrics::managed_bytes_captured`,
|
||||
`capture_waits`, `capture_streams`, `capture_overflows` and `capture_overflow_bytes` count them,
|
||||
`capture_copy_nanos` and `capture_wait_nanos` time the commits' host copies and waits, and
|
||||
`Gauges::capture_bytes` counts the ring and the staging blocks alive. A command buffer
|
||||
keeps each device copy it uses, and so the copy's block, until it retires.
|
||||
the buffer), merged with the buffer's others where they overlap or touch, and submits and
|
||||
allocates nothing. The next commit of a command buffer with commands, on any queue, takes every
|
||||
range named since, once each: GPU copies from the consumer's block into the device copy,
|
||||
recorded at the commit into a command buffer of their own that goes ahead of that command
|
||||
buffer's commands in its submission, after every earlier command on the device, which the
|
||||
barrier ending each earlier command buffer orders; the copies record one barrier, after them.
|
||||
The copy runs when that submission reaches the GPU, so a command buffer reads the bytes the
|
||||
consumer wrote before its commit, as Metal's `didModifyRange:` asks, and a write made after the
|
||||
commit may reach it, where Metal leaves the range undefined for the GPU.
|
||||
`Metrics::managed_bytes_captured` counts the bytes the copies take. A command buffer keeps each
|
||||
device copy it uses, and the consumer's blocks its copies read, until it retires.
|
||||
|
||||
The consumer's ranges follow Metal's retention: it reuses a range only once the work that named
|
||||
the buffer there before has completed. A command buffer keeps each buffer it uses, and so its
|
||||
@@ -797,14 +786,6 @@ planes lie in memories of their own, and `Surface::handle()` is `None`.
|
||||
647 µs held it for 579 µs; the other submits took a median of 2 to 3 µs. A submit waits at most
|
||||
the rest of one allocation, and the pool makes one per 16 MiB the consumer takes, about what the
|
||||
take would spend allocating on its own thread.
|
||||
- A commit that fills the capture ring waits for each ring-full's copy into the device copies,
|
||||
which crosses the card's link to the host. On an RTX 3090 in a Thunderbolt 3 enclosure whose
|
||||
link runs at 20 Gb/s (rt at ac1896537f), a ring-full of 63.3 MiB took 33.4 ms on the GPU (1.99
|
||||
GB/s) of the 33.6 ms the commit waited; the runtime's own part (its submission, the queue ahead
|
||||
of the copy and the commit's wake) was about 0.2 ms. In one consumer's replay stream on that
|
||||
card, 258 ring-fulls took 7.3 s of a 98 s play. Over the internal link of an RTX 5080 Laptop GPU
|
||||
the same kind of copy, 64 MiB from Shared memory into a device copy, took 3.9 to 4.5 ms on the GPU
|
||||
(15 to 17 GB/s, rt at 5ad1438f7b), about an eighth of the time.
|
||||
- NVIDIA's Linux driver allocates host-visible memory at about 0.14 ms per MiB on an RTX 3090 and
|
||||
0.2 ms per MiB on an RTX 2080, in every form we tried (plain, with a device address, dedicated,
|
||||
cached or not), against about 0.03 ms per MiB for device-local memory on the 3090. A take longer
|
||||
|
||||
@@ -248,10 +248,12 @@ impl Device {
|
||||
|
||||
/// `newBufferWithLength:options:`, `newBufferWithBytes:length:options:` and
|
||||
/// `newBufferWithBytesNoCopy:length:options:deallocator:` with
|
||||
/// `MTLResourceStorageModeManaged`: `length` bytes at `bytes` (a block the consumer holds and
|
||||
/// the offset in it) are the consumer's bytes, which [`Buffer::contents`] answers. The block is
|
||||
/// one the host maps: a Shared block. Which form the buffer takes is the device's memory-type
|
||||
/// query's answer:
|
||||
/// `MTLResourceStorageModeManaged`: `length` bytes at `bytes` (a Shared block the consumer
|
||||
/// holds and the offset in it) are the consumer's bytes, which [`Buffer::contents`] answers
|
||||
/// where the runtime maps the block (a block it took from the pool), and `None` where it does
|
||||
/// not (an imported block, whose pages the consumer reaches through its own mapping, as for
|
||||
/// [`Device::new_buffer`]). Which form the buffer takes is the device's memory-type query's
|
||||
/// answer:
|
||||
///
|
||||
/// - where Vulkan's device type is integrated or CPU ([`Device::has_unified_memory`]), the
|
||||
/// buffer is its bytes, as a Shared buffer is, its [`Buffer::gpu_address`] the bytes' block's
|
||||
@@ -262,8 +264,8 @@ impl Device {
|
||||
/// the offset. The rest past its first `copied` bytes is zeroed, ahead of every command
|
||||
/// buffer committed after this call, and those first bytes (all of them where `copied` is
|
||||
/// the length or more) are named as [`Buffer::did_modify_range`] names a range: the next
|
||||
/// commit takes them from the consumer's bytes. The consumer's own bytes are as it wrote
|
||||
/// them.
|
||||
/// commit copies them from the consumer's bytes on the GPU. The consumer's own bytes are as
|
||||
/// it wrote them. The consumer's block lives until every copy from it has run.
|
||||
///
|
||||
/// Metal keeps such a copy on a Mac with a discrete GPU, and places it itself. Here the
|
||||
/// consumer places both, as it places every buffer ([`Device::new_buffer`]): any byte offset,
|
||||
@@ -277,8 +279,8 @@ impl Device {
|
||||
/// buffer lives.
|
||||
///
|
||||
/// Err: [`Refusal::InScheduledHandler`] in a scheduled handler, on every device; as
|
||||
/// [`Device::new_buffer`], for either range; [`Refusal::ManagedBlockNotShared`] for
|
||||
/// bytes in a block the host does not map; [`Refusal::ManagedCopyMissing`] for no `copy` where
|
||||
/// [`Device::new_buffer`], for either range; [`Refusal::ManagedBlockPrivate`] for bytes in a
|
||||
/// Private block; [`Refusal::ManagedCopyMissing`] for no `copy` where
|
||||
/// the device keeps one, [`Refusal::ManagedCopyOnUnified`] for a `copy` where it keeps none
|
||||
/// and [`Refusal::ManagedCopyNotPrivate`] for a `copy` in a Shared block; for a device copy,
|
||||
/// [`Error::Quiesced`], and [`Error::Vulkan`] where the upload's command buffer cannot be made,
|
||||
@@ -304,11 +306,11 @@ impl Device {
|
||||
}
|
||||
let (block, offset) = bytes;
|
||||
let block = self.placed(block, offset, length)?;
|
||||
let Some(mapping) = block.memory.mapping else {
|
||||
return Err(Error::Refused(Refusal::ManagedBlockNotShared {
|
||||
if block.memory.class == MemoryClass::Private {
|
||||
return Err(Error::Refused(Refusal::ManagedBlockPrivate {
|
||||
block: block.memory.id,
|
||||
}));
|
||||
};
|
||||
}
|
||||
let core = self.core();
|
||||
let copy = match (core.unified_memory(), copy) {
|
||||
(true, None) => None,
|
||||
@@ -324,8 +326,10 @@ impl Device {
|
||||
Some((copy_block, copy_offset))
|
||||
}
|
||||
};
|
||||
// SAFETY: `offset` is inside the block.
|
||||
let contents = Some(Mapping::new(unsafe { mapping.at(offset) }));
|
||||
let contents = block.memory.mapping.map(|mapping| {
|
||||
// SAFETY: `offset` is inside the block.
|
||||
Mapping::new(unsafe { mapping.at(offset) })
|
||||
});
|
||||
let Some((copy_block, copy_offset)) = copy else {
|
||||
return Ok(self.buffer(block, offset, length, contents, None, None));
|
||||
};
|
||||
@@ -476,24 +480,17 @@ impl Buffer {
|
||||
|
||||
/// `didModifyRange:`: the consumer changed `length` bytes from `start` of the buffer's bytes.
|
||||
/// Of a Managed buffer with a device copy, the range is named, and the next commit of a command
|
||||
/// buffer with commands, on any queue, copies the consumer's bytes of every range named since
|
||||
/// into staging memory before it returns, once each, merged where they overlap or touch. The
|
||||
/// copies into the device copy, and into the images of its textures over the range in images
|
||||
/// of their own, go ahead of that command buffer's commands. So the command buffers committed
|
||||
/// after this call read the bytes as they were at that commit; Metal takes them shortly after
|
||||
/// the commit, before the command buffer is scheduled. A write or a didModifyRange made while
|
||||
/// a command buffer runs does not reach it. A commit naming more than the staging ring holds
|
||||
/// sends its ring-fulls ahead and waits for them, or, behind a command buffer held on the
|
||||
/// host, takes staging of its own for the rest (the crate's README, Memory blocks and
|
||||
/// buffers). Of any other buffer it does nothing, as the GPU reads the consumer's bytes. The
|
||||
/// device's first range named makes the staging ring, on the calling thread, so no commit
|
||||
/// waits for it.
|
||||
/// buffer with commands, on any queue, takes every range named since, once each, merged where
|
||||
/// they overlap or touch: GPU copies from the consumer's block into the device copy, and into
|
||||
/// the images of its textures over the range in images of their own, go ahead of that command
|
||||
/// buffer's commands in its submission. So a command buffer committed after this call reads
|
||||
/// the bytes the consumer wrote before its commit, as Metal owes. The copy reads the
|
||||
/// consumer's bytes as it runs, so a write made after the commit may reach it, where Metal
|
||||
/// leaves the range undefined for the GPU. Of any other buffer it does nothing, as the GPU
|
||||
/// reads the consumer's bytes. It allocates nothing.
|
||||
///
|
||||
/// Err: [`Refusal::ModifiedRange`] for a range that leaves the buffer; for a copy,
|
||||
/// [`Error::Quiesced`], and at the device's first range named,
|
||||
/// [`Limit::MemoryAllocations`](crate::Limit::MemoryAllocations) where the staging ring's
|
||||
/// memory would take the device past its count and [`Error::Vulkan`] where the ring cannot be
|
||||
/// made.
|
||||
/// [`Error::Quiesced`].
|
||||
pub fn did_modify_range(&self, start: u64, length: u64) -> Result<(), Error> {
|
||||
BufferObject::did_modify_range(self, start, length)
|
||||
}
|
||||
@@ -556,22 +553,16 @@ pub(crate) trait BufferObject {
|
||||
length,
|
||||
buffer_length: inner.length,
|
||||
}))?;
|
||||
let Some(copy) = &inner.copy else {
|
||||
return Ok(());
|
||||
};
|
||||
// A Managed buffer's block is mapped (Refusal::ManagedBlockNotShared otherwise).
|
||||
let Some(contents) = inner.contents.filter(|_| length > 0) else {
|
||||
let Some(copy) = inner.copy.as_ref().filter(|_| length > 0) else {
|
||||
return Ok(());
|
||||
};
|
||||
let named = Named {
|
||||
copy,
|
||||
cpu: &inner.block,
|
||||
contents,
|
||||
offset: inner.offset,
|
||||
overs: &inner.overs,
|
||||
};
|
||||
let core = &inner.core;
|
||||
core.work.modify(core, named, start, end)
|
||||
inner.core.work.modify(named, start, end)
|
||||
}
|
||||
|
||||
/// [`Buffer::length`].
|
||||
|
||||
@@ -1,58 +1,42 @@
|
||||
//! A Managed buffer's changed ranges, captured at the commit: where a Managed buffer has a device
|
||||
//! A Managed buffer's changed ranges, copied in at the commit: where a Managed buffer has a device
|
||||
//! copy (a device whose Vulkan device type is neither integrated nor CPU), `didModifyRange:` only
|
||||
//! names a range ([`Changes::add`]), and the next commit on any queue of a command buffer with
|
||||
//! commands copies the consumer's bytes of every range named since the last such commit, once
|
||||
//! each, on the committing thread, before the call returns
|
||||
//! ([`Work::capture`](crate::submit::Work::capture)). Commits take their turns one at a time, so
|
||||
//! the command buffers keep the order of their captures. The copies into the device copies, and
|
||||
//! then into the images of the textures over the ranges in images of their own
|
||||
//! (`crate::over::ManagedOvers`), are recorded into command buffers of their own, [`CopyIn`]s,
|
||||
//! which go ahead of the command buffer's own commands in queue order. A copy-in records no barrier
|
||||
//! before its copies: the one that ends every earlier segment, upload, fill and copy-in on the queue
|
||||
//! puts every earlier command first, as it does for a segment (`record::end`). So a command buffer
|
||||
//! reads the bytes as they were
|
||||
//! at its commit, and a write after the commit reaches none committed before it. Metal takes them
|
||||
//! shortly after the commit, before the command buffer is scheduled, and a write or a
|
||||
//! `didModifyRange:` made while the command buffer runs does not reach it.
|
||||
//! commands takes every range named since the last such commit, once each
|
||||
//! ([`Work::capture`](crate::submit::Work::capture)). Its copy-in ([`copy_in`]) is a command
|
||||
//! buffer of its own, [`CopyIn`], that goes ahead of the command buffer's own commands in queue
|
||||
//! order: GPU copies of each range from the consumer's block into the device copy, after the
|
||||
//! copies back owed to the textures over the ranges in images of their own and before the copies
|
||||
//! in those textures take (`crate::over::ManagedOvers`). It holds each consumer's block and device
|
||||
//! copy until what takes it retires. A copy-in records no barrier before its copies: the one that
|
||||
//! ends every earlier segment, upload, fill and copy-in on the queue puts every earlier command
|
||||
//! first, as it does for a segment (`record::end`), and the submission that carries it makes the
|
||||
//! host's writes before it visible to the copies (Vulkan's host write ordering guarantee).
|
||||
//!
|
||||
//! The bytes go into the capture ring: one host-visible allocation of [`CAPTURE_LEN`] bytes of the
|
||||
//! Shared type, made at the first capture and kept for the device's life. A span is free again
|
||||
//! once the submission that carries its copy has completed. A capture that finds no room waits for
|
||||
//! the oldest span's submission. Where the oldest span is of a copy not yet submitted, the queues'
|
||||
//! held groups go at once, and once everything committed before is submitted, the capture's own
|
||||
//! ring-full goes as a copy-in submission of its own, which the commit waits for before it reuses
|
||||
//! the ring: the ring is all the staging memory a capture holds, whatever it names. Where a command
|
||||
//! buffer committed before is held on the host (an event wait the host has not met, or a command
|
||||
//! buffer enqueued ahead of it and not committed), nothing more can go before the host acts, so the
|
||||
//! rest of the capture takes a staging block of its own from the pool ([`overflow`]), which the
|
||||
//! command buffer gives back as it retires.
|
||||
//! So a command buffer committed after a range is named reads the bytes the consumer wrote there
|
||||
//! before the commit, which is what Metal owes (`MTLBuffer.h`, `didModifyRange:`): a write makes
|
||||
//! the range undefined for the GPU until a `didModifyRange:` and a commit of the command buffer
|
||||
//! that reads it, and does not reach a command buffer committed before. The copy reads the
|
||||
//! consumer's bytes as it runs, so a write after the commit may reach it, where Metal leaves the
|
||||
//! range undefined.
|
||||
|
||||
use crate::buffer::DeviceCopy;
|
||||
use crate::counters::{Counters, Gauge, Metric, Site};
|
||||
use crate::counters::Metric;
|
||||
use crate::device::Core;
|
||||
use crate::error::Error;
|
||||
use crate::memory::{Block, Mapping, MemoryClass};
|
||||
use crate::memory::Block;
|
||||
use crate::over::{self, Back, ManagedOvers};
|
||||
use crate::record::{self, Reach, Recorder};
|
||||
use crate::staging::{At, Region};
|
||||
use crate::texture::{Image, OverCopy};
|
||||
use ash::vk;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The capture ring's bytes.
|
||||
pub(crate) const CAPTURE_LEN: u64 = 64 << 20;
|
||||
|
||||
/// The longest staging block of its own a capture takes ([`overflow`]); a longer rest takes more.
|
||||
const OVERFLOW_BLOCK: u64 = 256 << 20;
|
||||
|
||||
/// A Managed buffer's ranges named since the last capture.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Modified {
|
||||
pub(crate) copy: Arc<DeviceCopy>,
|
||||
/// The block of the consumer's bytes, held, and the buffer's first byte in its mapping.
|
||||
/// The block of the consumer's bytes, held.
|
||||
pub(crate) cpu: Arc<Block>,
|
||||
pub(crate) contents: Mapping,
|
||||
/// The buffer's offset in `cpu`.
|
||||
pub(crate) offset: u64,
|
||||
/// Its textures over the device copy in images of their own.
|
||||
@@ -61,26 +45,21 @@ pub(crate) struct Modified {
|
||||
pub(crate) ranges: Vec<(u64, u64)>,
|
||||
}
|
||||
|
||||
/// A Managed buffer whose range is named: its device copy, its consumer's bytes (the block, the
|
||||
/// buffer's first byte in its mapping, and its offset in the block) and its textures over the
|
||||
/// device copy in images of their own.
|
||||
/// A Managed buffer whose range is named: its device copy, its consumer's bytes (the block and
|
||||
/// the buffer's offset in it) and its textures over the device copy in images of their own.
|
||||
pub(crate) struct Named<'a> {
|
||||
pub(crate) copy: &'a Arc<DeviceCopy>,
|
||||
pub(crate) cpu: &'a Arc<Block>,
|
||||
pub(crate) contents: Mapping,
|
||||
pub(crate) offset: u64,
|
||||
pub(crate) overs: &'a Arc<ManagedOvers>,
|
||||
}
|
||||
|
||||
/// The device's ranges named and not yet captured, in the order of each buffer's first, and the
|
||||
/// capture ring.
|
||||
/// The device's ranges named and not yet captured, in the order of each buffer's first.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Changes {
|
||||
modified: Vec<Modified>,
|
||||
/// Each buffer's place in `modified`, by its device copy's address.
|
||||
at: HashMap<usize, usize>,
|
||||
/// The ring, from the first capture on.
|
||||
pub(crate) region: Option<Region>,
|
||||
/// What a commit captured before it failed: the next commit's command buffer takes it first.
|
||||
pub(crate) carried: Vec<CopyIn>,
|
||||
}
|
||||
@@ -96,7 +75,6 @@ impl Changes {
|
||||
self.modified.push(Modified {
|
||||
copy: Arc::clone(buffer.copy),
|
||||
cpu: Arc::clone(buffer.cpu),
|
||||
contents: buffer.contents,
|
||||
offset: buffer.offset,
|
||||
overs: Arc::clone(buffer.overs),
|
||||
ranges: vec![(start, end)],
|
||||
@@ -116,14 +94,9 @@ impl Changes {
|
||||
!self.modified.is_empty()
|
||||
}
|
||||
|
||||
/// A capture that read `spans` of the ring for `modified` will not run: its spans are given up
|
||||
/// and its ranges named again, for the next commit to capture.
|
||||
pub(crate) fn give_up(&mut self, spans: &[u64], modified: &[Modified]) {
|
||||
if let Some(region) = &mut self.region {
|
||||
for &number in spans {
|
||||
region.ring.set(number, At::Done);
|
||||
}
|
||||
}
|
||||
/// A capture of `modified` that will not run: its ranges are named again, for the next commit
|
||||
/// to capture.
|
||||
pub(crate) fn give_up(&mut self, modified: &[Modified]) {
|
||||
for modified in modified {
|
||||
for &(start, end) in &modified.ranges {
|
||||
self.add(modified.named(), start, end);
|
||||
@@ -144,39 +117,26 @@ impl Modified {
|
||||
Named {
|
||||
copy: &self.copy,
|
||||
cpu: &self.cpu,
|
||||
contents: self.contents,
|
||||
offset: self.offset,
|
||||
overs: &self.overs,
|
||||
}
|
||||
}
|
||||
|
||||
/// Its bytes named, in all.
|
||||
pub(crate) fn bytes(&self) -> u64 {
|
||||
self.ranges.iter().map(|&(start, end)| end - start).sum()
|
||||
}
|
||||
}
|
||||
|
||||
/// What one capture's command buffer copies: into the device copies and the images over them,
|
||||
/// recorded into `command` of its own recorder, the spans of the ring they read, the staging
|
||||
/// blocks of its own (an [`overflow`]) they read, and the images they copy. What takes it keeps it,
|
||||
/// with each device copy and consumer's block, until it retires: the committing command buffer, or
|
||||
/// the upload of a ring-full's submission of its own.
|
||||
/// What one capture's command buffer copies: from the consumers' blocks into the device copies
|
||||
/// and the images over them, recorded into `command` of its own recorder, and the images it
|
||||
/// copies. What takes it keeps it, with each consumer's block and device copy, until it retires:
|
||||
/// the committing command buffer.
|
||||
pub(crate) struct CopyIn {
|
||||
pub(crate) recorder: Recorder,
|
||||
pub(crate) command: vk::CommandBuffer,
|
||||
pub(crate) spans: Vec<u64>,
|
||||
pub(crate) modified: Vec<Modified>,
|
||||
pub(crate) images: Vec<Arc<Image>>,
|
||||
pub(crate) staging: Vec<Overflowed>,
|
||||
}
|
||||
|
||||
/// A staging block of an [`overflow`], counted in `Gauges::capture_bytes` while it lives; it goes
|
||||
/// back to the pool as it drops.
|
||||
pub(crate) struct Overflowed {
|
||||
block: Block,
|
||||
counters: Counters,
|
||||
}
|
||||
|
||||
impl Drop for Overflowed {
|
||||
fn drop(&mut self) {
|
||||
self.counters
|
||||
.fall_by(Gauge::CaptureBytes, self.block.memory.len);
|
||||
}
|
||||
}
|
||||
|
||||
impl CopyIn {
|
||||
@@ -187,150 +147,84 @@ impl CopyIn {
|
||||
recorder,
|
||||
modified,
|
||||
images,
|
||||
staging,
|
||||
..
|
||||
} = self;
|
||||
core.recorders.give_back(core, recorder);
|
||||
drop((modified, images, staging));
|
||||
drop((modified, images));
|
||||
}
|
||||
}
|
||||
|
||||
/// A copy-in being recorded: its copies are recorded together at its end, one command for each
|
||||
/// run of copies from one source into one device copy.
|
||||
pub(crate) struct Chunk {
|
||||
recorder: Recorder,
|
||||
command: vk::CommandBuffer,
|
||||
pub(crate) spans: Vec<u64>,
|
||||
/// Each copy's source buffer, the index of its buffer among the capture's, and its region.
|
||||
copies: Vec<(vk::Buffer, usize, vk::BufferCopy)>,
|
||||
images: Vec<Arc<Image>>,
|
||||
staging: Vec<Overflowed>,
|
||||
}
|
||||
|
||||
impl Chunk {
|
||||
/// A copy-in's command buffer, recording, after the copies back `backs` (the first of a
|
||||
/// capture's). It begins with no barrier of its own: the one ending each earlier command
|
||||
/// buffer on the queue puts every earlier command first (`record::end`).
|
||||
///
|
||||
/// Err: [`Error::Vulkan`] where a command pool or buffer cannot be made.
|
||||
pub(crate) fn begin(core: &Core, backs: Vec<Back>) -> Result<Chunk, Error> {
|
||||
let device = &core.device;
|
||||
let mut recorder = core.recorders.take(device)?;
|
||||
let command = match recorder.next(device) {
|
||||
Ok(command) => command,
|
||||
Err(error) => {
|
||||
core.recorders.give_back(core, recorder);
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
let copies: Vec<OverCopy> = backs.iter().map(|(_, copy, _)| *copy).collect();
|
||||
// SAFETY: the command buffer is recording, and only this thread has it; each image is in
|
||||
// its home layout between commands, and the copy-in holds it.
|
||||
if !copies.is_empty() {
|
||||
unsafe { over::record_side(device, command, &copies, false, &core.counters) };
|
||||
/// The copy-in of `named`, the ranges a capture takes: a command buffer of its own, recorded and
|
||||
/// ended, with the copies back owed to the textures over the ranges in images of their own
|
||||
/// first, then one `vkCmdCopyBuffer` for each buffer from the consumer's block into its device
|
||||
/// copy, then the copies in those textures take, or a barrier that makes the copies visible to
|
||||
/// every later command. It begins with no barrier of its own: the one ending each earlier command
|
||||
/// buffer on the queue puts every earlier command first (`record::end`).
|
||||
///
|
||||
/// Err: [`Error::Vulkan`] where a command pool or buffer cannot be made or ended.
|
||||
pub(crate) fn copy_in(core: &Core, named: &[Modified]) -> Result<CopyIn, Error> {
|
||||
let device = &core.device;
|
||||
let mut recorder = core.recorders.take(device)?;
|
||||
let command = match recorder.next(device) {
|
||||
Ok(command) => command,
|
||||
Err(error) => {
|
||||
core.recorders.give_back(core, recorder);
|
||||
return Err(error);
|
||||
}
|
||||
Ok(Chunk {
|
||||
recorder,
|
||||
command,
|
||||
spans: Vec::new(),
|
||||
copies: Vec::new(),
|
||||
images: backs.into_iter().map(|(_, _, image)| image).collect(),
|
||||
staging: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
/// A copy of `region` from `source` into the device copy of the capture's buffer `index`.
|
||||
pub(crate) fn copy(&mut self, source: vk::Buffer, index: usize, region: vk::BufferCopy) {
|
||||
self.copies.push((source, index, region));
|
||||
}
|
||||
|
||||
/// Whether it copies from the ring.
|
||||
pub(crate) fn rings(&self) -> bool {
|
||||
!self.spans.is_empty()
|
||||
}
|
||||
|
||||
/// Records its copies into the device copies of `named`, the capture's buffers, then the copies
|
||||
/// in `into` (the last of a capture's), or a barrier that makes the copies visible to every
|
||||
/// later command, and ends its command buffer, for [`Chunk::ended`].
|
||||
///
|
||||
/// Err: [`Error::Vulkan`] where the command buffer cannot be ended; the chunk is then given
|
||||
/// up.
|
||||
pub(crate) fn end(
|
||||
&self,
|
||||
core: &Core,
|
||||
named: &[Modified],
|
||||
into: &[(OverCopy, Arc<Image>)],
|
||||
) -> Result<(), Error> {
|
||||
let device = &core.device;
|
||||
let (command, copies) = (self.command, &self.copies);
|
||||
let into_copies: Vec<OverCopy> = into.iter().map(|(copy, _)| *copy).collect();
|
||||
let mut at = 0;
|
||||
// SAFETY: the command buffer is recording, and only this thread has it; the ring's, the
|
||||
// staging blocks' and the device copies' buffers have transfer usage, each region lies in
|
||||
// them, what takes the copy-in keeps each block and device copy until it retires, and the
|
||||
// ring lives as long as the device; each image is in its home layout between commands.
|
||||
unsafe {
|
||||
while at < copies.len() {
|
||||
let (source, index, _) = copies[at];
|
||||
let run = copies[at..]
|
||||
.iter()
|
||||
.take_while(|&&(from, to, _)| from == source && to == index)
|
||||
.count();
|
||||
let regions: Vec<vk::BufferCopy> = copies[at..at + run]
|
||||
.iter()
|
||||
.map(|&(_, _, region)| region)
|
||||
.collect();
|
||||
let (into, _) = named[index].copy.range(0);
|
||||
device.cmd_copy_buffer(command, source, into, ®ions);
|
||||
at += run;
|
||||
}
|
||||
match into_copies.is_empty() {
|
||||
true => {
|
||||
record::barrier(device, command, Reach::Commands);
|
||||
core.counters.count(Metric::Barriers);
|
||||
}
|
||||
false => over::record_side(device, command, &into_copies, true, &core.counters),
|
||||
}
|
||||
};
|
||||
let backs = backs(named);
|
||||
let into = copies_in(named);
|
||||
let back_copies: Vec<OverCopy> = backs.iter().map(|(_, copy, _)| *copy).collect();
|
||||
let into_copies: Vec<OverCopy> = into.iter().map(|(copy, _)| *copy).collect();
|
||||
// SAFETY: the command buffer is recording, and only this thread has it; the consumers'
|
||||
// blocks' and the device copies' buffers have transfer usage, each region lies in them, and
|
||||
// what takes the copy-in keeps each block and device copy until it retires; each image is in
|
||||
// its home layout between commands, and the copy-in holds it.
|
||||
unsafe {
|
||||
if !back_copies.is_empty() {
|
||||
over::record_side(device, command, &back_copies, false, &core.counters);
|
||||
}
|
||||
// SAFETY: the command buffer is recording, and only this thread has it.
|
||||
unsafe { device.end_command_buffer(command) }.map_err(|result| Error::Vulkan {
|
||||
for modified in named {
|
||||
let (from, base) = modified.cpu.memory.range(modified.offset);
|
||||
let (to, _) = modified.copy.range(0);
|
||||
let regions: Vec<vk::BufferCopy> = (modified.ranges.iter())
|
||||
.map(|&(start, end)| vk::BufferCopy {
|
||||
src_offset: base + start,
|
||||
dst_offset: modified.copy.range(start).1,
|
||||
size: end - start,
|
||||
})
|
||||
.collect();
|
||||
device.cmd_copy_buffer(command, from, to, ®ions);
|
||||
}
|
||||
match into_copies.is_empty() {
|
||||
true => {
|
||||
record::barrier(device, command, Reach::Commands);
|
||||
core.counters.count(Metric::Barriers);
|
||||
}
|
||||
false => over::record_side(device, command, &into_copies, true, &core.counters),
|
||||
}
|
||||
}
|
||||
// SAFETY: the command buffer is recording, and only this thread has it.
|
||||
if let Err(result) = unsafe { device.end_command_buffer(command) } {
|
||||
core.recorders.give_back(core, recorder);
|
||||
return Err(Error::Vulkan {
|
||||
call: "vkEndCommandBuffer",
|
||||
result,
|
||||
})
|
||||
}
|
||||
|
||||
/// The chunk, ended with `named` and `into` ([`Chunk::end`]): a copy-in holding `named` and
|
||||
/// the images of `into`.
|
||||
pub(crate) fn ended(self, named: Vec<Modified>, into: Vec<(OverCopy, Arc<Image>)>) -> CopyIn {
|
||||
let Chunk {
|
||||
recorder,
|
||||
command,
|
||||
spans,
|
||||
copies: _,
|
||||
mut images,
|
||||
staging,
|
||||
} = self;
|
||||
images.extend(into.into_iter().map(|(_, image)| image));
|
||||
CopyIn {
|
||||
recorder,
|
||||
command,
|
||||
spans,
|
||||
modified: named,
|
||||
images,
|
||||
staging,
|
||||
}
|
||||
}
|
||||
|
||||
/// Gives up its recorder, for a capture that cannot finish: its spans come back.
|
||||
pub(crate) fn give_up(self, core: &Core) -> Vec<u64> {
|
||||
core.recorders.give_back(core, self.recorder);
|
||||
self.spans
|
||||
});
|
||||
}
|
||||
let mut images: Vec<Arc<Image>> = backs.into_iter().map(|(_, _, image)| image).collect();
|
||||
images.extend(into.into_iter().map(|(_, image)| image));
|
||||
Ok(CopyIn {
|
||||
recorder,
|
||||
command,
|
||||
modified: named.to_vec(),
|
||||
images,
|
||||
})
|
||||
}
|
||||
|
||||
/// The copies back owed to the textures over `named`'s ranges in images of their own, taken: they
|
||||
/// go ahead of a capture's copies, so the consumer's bytes land over them.
|
||||
pub(crate) fn backs(named: &[Modified]) -> Vec<Back> {
|
||||
fn backs(named: &[Modified]) -> Vec<Back> {
|
||||
let mut backs = Vec::new();
|
||||
for modified in named.iter().filter(|modified| modified.overs.any()) {
|
||||
modified.overs.backs_before(&modified.ranges, &mut backs);
|
||||
@@ -340,7 +234,7 @@ pub(crate) fn backs(named: &[Modified]) -> Vec<Back> {
|
||||
|
||||
/// The copies in the textures over `named`'s ranges in images of their own take, after a
|
||||
/// capture's copies.
|
||||
pub(crate) fn copies_in(named: &[Modified]) -> Vec<(OverCopy, Arc<Image>)> {
|
||||
fn copies_in(named: &[Modified]) -> Vec<(OverCopy, Arc<Image>)> {
|
||||
let mut into = Vec::new();
|
||||
for modified in named.iter().filter(|modified| modified.overs.any()) {
|
||||
modified.overs.copies_in_after(&modified.ranges, &mut into);
|
||||
@@ -348,81 +242,6 @@ pub(crate) fn copies_in(named: &[Modified]) -> Vec<(OverCopy, Arc<Image>)> {
|
||||
into
|
||||
}
|
||||
|
||||
/// The rest of a capture where work committed before it is held on the host: `pieces`, each a
|
||||
/// buffer's index among `named` and a range `start..end` of it, copied on the host into staging
|
||||
/// blocks of the Shared type of the capture's own, of at most [`OVERFLOW_BLOCK`] bytes each, taken
|
||||
/// from the pool, and their copies into the device copies added to `chunk`, which holds the blocks
|
||||
/// until what takes it retires, when they go back to the pool. Counted in
|
||||
/// `Metrics::capture_overflows` and `capture_overflow_bytes`. Returns the bytes copied.
|
||||
///
|
||||
/// Err: what taking a block returns.
|
||||
pub(crate) fn overflow(
|
||||
core: &Arc<Core>,
|
||||
named: &[Modified],
|
||||
pieces: &[(usize, u64, u64)],
|
||||
chunk: &mut Chunk,
|
||||
) -> Result<u64, Error> {
|
||||
let total: u64 = pieces.iter().map(|&(_, start, end)| end - start).sum();
|
||||
let mut left = total;
|
||||
// The block being filled: its allocation's buffer and its offset there, its mapping and
|
||||
// length, and how much of it is filled.
|
||||
let mut block: Option<(vk::Buffer, u64, Mapping, u64, u64)> = None;
|
||||
for &(index, start, end) in pieces {
|
||||
let modified = &named[index];
|
||||
let mut at = start;
|
||||
while at < end {
|
||||
let (buffer, base, mapping, block_len, filled) = match block.take() {
|
||||
Some(open) if open.4 < open.3 => open,
|
||||
_ => {
|
||||
let memory = core.take_memory(
|
||||
MemoryClass::Shared,
|
||||
left.min(OVERFLOW_BLOCK),
|
||||
Site::Take,
|
||||
)?;
|
||||
let Some(mapping) = memory.mapping else {
|
||||
unreachable!("a Shared block is mapped");
|
||||
};
|
||||
let ((buffer, base), block_len) = (memory.range(0), memory.len);
|
||||
core.counters.rise_by(Gauge::CaptureBytes, block_len);
|
||||
chunk.staging.push(Overflowed {
|
||||
block: Block::new(memory, Arc::clone(core)),
|
||||
counters: core.counters.clone(),
|
||||
});
|
||||
(buffer, base, mapping, block_len, 0)
|
||||
}
|
||||
};
|
||||
let len = (end - at).min(block_len - filled);
|
||||
let began = crate::host_time();
|
||||
// SAFETY: the block is the capture's alone, mapped, and holds `filled..filled + len`;
|
||||
// the consumer's buffer holds `at..at + len`; the two do not overlap.
|
||||
unsafe {
|
||||
modified
|
||||
.contents
|
||||
.at(at)
|
||||
.as_ptr()
|
||||
.copy_to_nonoverlapping(mapping.at(filled).as_ptr(), len as usize)
|
||||
};
|
||||
core.counters
|
||||
.capture_copied(crate::host_time().saturating_sub(began));
|
||||
chunk.copy(
|
||||
buffer,
|
||||
index,
|
||||
vk::BufferCopy {
|
||||
src_offset: base + filled,
|
||||
dst_offset: modified.copy.range(at).1,
|
||||
size: len,
|
||||
},
|
||||
);
|
||||
at += len;
|
||||
left -= len;
|
||||
block = Some((buffer, base, mapping, block_len, filled + len));
|
||||
}
|
||||
}
|
||||
core.counters.count(Metric::CaptureOverflows);
|
||||
core.counters.overflowed(total);
|
||||
Ok(total)
|
||||
}
|
||||
|
||||
/// Adds `start..end` to `ranges` (by start, no two overlapping or touching), joining the ranges it
|
||||
/// overlaps or touches.
|
||||
pub(crate) fn merge(ranges: &mut Vec<(u64, u64)>, start: u64, end: u64) {
|
||||
|
||||
@@ -578,7 +578,8 @@ impl CommandBuffer {
|
||||
// the reaper, never in this call.
|
||||
let core = self.building(|building| Ok(Arc::clone(building.device.core())))?;
|
||||
let began = crate::host_time();
|
||||
let turn = core.work.turn();
|
||||
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
|
||||
(core.work.counting).store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
let work = core.work.lock();
|
||||
core.counters
|
||||
.commit_lock_wait(crate::host_time().saturating_sub(began));
|
||||
@@ -648,7 +649,6 @@ impl CommandBuffer {
|
||||
drop(work);
|
||||
core.work.wake();
|
||||
}
|
||||
drop(turn);
|
||||
drop(core);
|
||||
drop(last);
|
||||
Ok(())
|
||||
|
||||
@@ -61,12 +61,6 @@ pub(crate) enum Metric {
|
||||
AllocationsFreed,
|
||||
/// [`Metrics::submissions_during_frees`].
|
||||
SubmissionsDuringFrees,
|
||||
/// [`Metrics::capture_waits`].
|
||||
CaptureWaits,
|
||||
/// [`Metrics::capture_streams`].
|
||||
CaptureStreams,
|
||||
/// [`Metrics::capture_overflows`].
|
||||
CaptureOverflows,
|
||||
/// [`Metrics::untimed_command_buffers`].
|
||||
UntimedCommandBuffers,
|
||||
/// [`Metrics::sampler_element_writes`].
|
||||
@@ -112,9 +106,6 @@ const METRIC_ORDER: [Metric; METRICS] = [
|
||||
Metric::Synchronizations,
|
||||
Metric::AllocationsFreed,
|
||||
Metric::SubmissionsDuringFrees,
|
||||
Metric::CaptureWaits,
|
||||
Metric::CaptureStreams,
|
||||
Metric::CaptureOverflows,
|
||||
Metric::UntimedCommandBuffers,
|
||||
Metric::SamplerElementWrites,
|
||||
Metric::StampsNotAvailable,
|
||||
@@ -200,8 +191,6 @@ pub(crate) enum Gauge {
|
||||
SharedIdleBytes,
|
||||
/// [`Gauges::private_idle_bytes`].
|
||||
PrivateIdleBytes,
|
||||
/// [`Gauges::capture_bytes`].
|
||||
CaptureBytes,
|
||||
/// [`Gauges::staging_bytes`].
|
||||
StagingBytes,
|
||||
/// [`Gauges::stage_entries`].
|
||||
@@ -242,8 +231,6 @@ pub(crate) enum Site {
|
||||
StagingRegion,
|
||||
/// [`Metrics::staging_buffer_allocations`].
|
||||
StagingBuffer,
|
||||
/// [`Metrics::capture_ring_allocations`].
|
||||
CaptureRing,
|
||||
/// [`Metrics::zero_source_allocations`].
|
||||
ZeroSource,
|
||||
/// [`Metrics::take_allocations`].
|
||||
@@ -333,9 +320,6 @@ struct Atomics {
|
||||
idle_frees_by_age: [AtomicU64; FREE_AGES_MS.len() + 1],
|
||||
idle_reuses_by_age: [AtomicU64; REUSE_AGES_MS.len() + 1],
|
||||
managed_bytes_captured: AtomicU64,
|
||||
capture_waits: AtomicU64,
|
||||
capture_streams: AtomicU64,
|
||||
capture_overflows: AtomicU64,
|
||||
untimed_command_buffers: AtomicU64,
|
||||
sampler_element_writes: AtomicU64,
|
||||
stamps_not_available: AtomicU64,
|
||||
@@ -349,9 +333,6 @@ struct Atomics {
|
||||
surface_wait_max_nanos: AtomicU64,
|
||||
surface_wait_submissions: AtomicU64,
|
||||
sparse_binds: AtomicU64,
|
||||
capture_overflow_bytes: AtomicU64,
|
||||
capture_copy_nanos: AtomicU64,
|
||||
capture_wait_nanos: AtomicU64,
|
||||
handles_out: AtomicU64,
|
||||
buffers: AtomicU64,
|
||||
textures: AtomicU64,
|
||||
@@ -386,7 +367,6 @@ struct Atomics {
|
||||
shared_long_reused_bytes: AtomicU64,
|
||||
/// As [`shared_long_reused_bytes`](Self::shared_long_reused_bytes), of Private allocations.
|
||||
private_long_reused_bytes: AtomicU64,
|
||||
capture_bytes: AtomicU64,
|
||||
staging_bytes: AtomicU64,
|
||||
stage_entries: AtomicU64,
|
||||
stage_entry_bytes: AtomicU64,
|
||||
@@ -458,9 +438,6 @@ impl Counters {
|
||||
Metric::Synchronizations => &a.synchronizations,
|
||||
Metric::AllocationsFreed => &a.allocations_freed,
|
||||
Metric::SubmissionsDuringFrees => &a.submissions_during_frees,
|
||||
Metric::CaptureWaits => &a.capture_waits,
|
||||
Metric::CaptureStreams => &a.capture_streams,
|
||||
Metric::CaptureOverflows => &a.capture_overflows,
|
||||
Metric::UntimedCommandBuffers => &a.untimed_command_buffers,
|
||||
Metric::SamplerElementWrites => &a.sampler_element_writes,
|
||||
Metric::StampsNotAvailable => &a.stamps_not_available,
|
||||
@@ -706,31 +683,14 @@ impl Counters {
|
||||
a.zeroed_texture_bytes.fetch_add(bytes, Relaxed);
|
||||
}
|
||||
|
||||
/// `bytes` more of Managed buffers' bytes a commit copied ([`Metrics::managed_bytes_captured`]).
|
||||
/// `bytes` more of Managed buffers' bytes a commit's copy-in copies
|
||||
/// ([`Metrics::managed_bytes_captured`]).
|
||||
pub(crate) fn captured(&self, bytes: u64) {
|
||||
self.atomics
|
||||
.managed_bytes_captured
|
||||
.fetch_add(bytes, Relaxed);
|
||||
}
|
||||
|
||||
/// `bytes` more of them copied into staging blocks of an overflow's own
|
||||
/// ([`Metrics::capture_overflow_bytes`]).
|
||||
pub(crate) fn overflowed(&self, bytes: u64) {
|
||||
self.atomics
|
||||
.capture_overflow_bytes
|
||||
.fetch_add(bytes, Relaxed);
|
||||
}
|
||||
|
||||
/// `nanos` more a capture spent copying bytes on the host ([`Metrics::capture_copy_nanos`]).
|
||||
pub(crate) fn capture_copied(&self, nanos: u64) {
|
||||
self.atomics.capture_copy_nanos.fetch_add(nanos, Relaxed);
|
||||
}
|
||||
|
||||
/// `nanos` more a capture spent waiting ([`Metrics::capture_wait_nanos`]).
|
||||
pub(crate) fn capture_waited(&self, nanos: u64) {
|
||||
self.atomics.capture_wait_nanos.fetch_add(nanos, Relaxed);
|
||||
}
|
||||
|
||||
/// `bytes` more written to the cache directory ([`Metrics::cache_bytes_written`]).
|
||||
pub(crate) fn cache_written(&self, bytes: u64) {
|
||||
self.atomics.cache_bytes_written.fetch_add(bytes, Relaxed);
|
||||
@@ -831,7 +791,6 @@ impl Counters {
|
||||
Gauge::PrivateAllocationBytes => &a.private_allocation_bytes,
|
||||
Gauge::SharedIdleBytes => &a.shared_idle_bytes,
|
||||
Gauge::PrivateIdleBytes => &a.private_idle_bytes,
|
||||
Gauge::CaptureBytes => &a.capture_bytes,
|
||||
Gauge::StagingBytes => &a.staging_bytes,
|
||||
Gauge::StageEntries => &a.stage_entries,
|
||||
Gauge::StageEntryBytes => &a.stage_entry_bytes,
|
||||
@@ -890,7 +849,6 @@ impl Counters {
|
||||
ring_block_allocations: site(Site::RingBlock),
|
||||
staging_region_allocations: site(Site::StagingRegion),
|
||||
staging_buffer_allocations: site(Site::StagingBuffer),
|
||||
capture_ring_allocations: site(Site::CaptureRing),
|
||||
zero_source_allocations: site(Site::ZeroSource),
|
||||
take_allocations: site(Site::Take),
|
||||
maker_waits: a.maker_waits.load(Relaxed),
|
||||
@@ -928,9 +886,6 @@ impl Counters {
|
||||
idle_frees_by_age: std::array::from_fn(|at| a.idle_frees_by_age[at].load(Relaxed)),
|
||||
idle_reuses_by_age: std::array::from_fn(|at| a.idle_reuses_by_age[at].load(Relaxed)),
|
||||
managed_bytes_captured: a.managed_bytes_captured.load(Relaxed),
|
||||
capture_waits: a.capture_waits.load(Relaxed),
|
||||
capture_streams: a.capture_streams.load(Relaxed),
|
||||
capture_overflows: a.capture_overflows.load(Relaxed),
|
||||
untimed_command_buffers: a.untimed_command_buffers.load(Relaxed),
|
||||
sampler_element_writes: a.sampler_element_writes.load(Relaxed),
|
||||
stamps_not_available: a.stamps_not_available.load(Relaxed),
|
||||
@@ -944,9 +899,6 @@ impl Counters {
|
||||
surface_wait_max_nanos: a.surface_wait_max_nanos.load(Relaxed),
|
||||
surface_wait_submissions: a.surface_wait_submissions.load(Relaxed),
|
||||
sparse_binds: a.sparse_binds.load(Relaxed),
|
||||
capture_overflow_bytes: a.capture_overflow_bytes.load(Relaxed),
|
||||
capture_copy_nanos: a.capture_copy_nanos.load(Relaxed),
|
||||
capture_wait_nanos: a.capture_wait_nanos.load(Relaxed),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -998,7 +950,6 @@ impl Counters {
|
||||
private_reserve_bytes: a.private_reserve_bytes.load(Relaxed),
|
||||
shared_long_reused_bytes: a.shared_long_reused_bytes.load(Relaxed),
|
||||
private_long_reused_bytes: a.private_long_reused_bytes.load(Relaxed),
|
||||
capture_bytes: a.capture_bytes.load(Relaxed),
|
||||
staging_bytes: a.staging_bytes.load(Relaxed),
|
||||
stage_entries: a.stage_entries.load(Relaxed),
|
||||
stage_entry_bytes: a.stage_entry_bytes.load(Relaxed),
|
||||
@@ -1117,8 +1068,8 @@ pub struct Metrics {
|
||||
/// frame allocated.
|
||||
pub block_bytes_made: u64,
|
||||
/// `vkAllocateMemory` calls made on the consumer's threads, inside its calls: takes that no
|
||||
/// free range fits, textures' allocations of their own, copies' staging buffers of their own
|
||||
/// and the capture ring; and the runtime's fixed-size internals (the zero source, the
|
||||
/// free range fits, textures' allocations of their own and copies' staging buffers of their
|
||||
/// own; and the runtime's fixed-size internals (the zero source, the
|
||||
/// parameter ring's blocks and the staging region) only where the block-maker thread's make
|
||||
/// of one failed. A driver may hold the device's other calls for an allocation's whole length.
|
||||
pub consumer_allocations: u64,
|
||||
@@ -1153,18 +1104,12 @@ pub struct Metrics {
|
||||
/// Those of staging buffers of their own, one for each `replace_region` or `get_bytes` copy
|
||||
/// larger than the 16 MiB staging region.
|
||||
pub staging_buffer_allocations: SiteAllocations,
|
||||
/// Those of the capture ring, the staging memory commits copy Managed buffers' modified bytes
|
||||
/// into ([`managed_bytes_captured`](Self::managed_bytes_captured)), made at the device's first
|
||||
/// [`Buffer::did_modify_range`](crate::Buffer::did_modify_range) of a Managed buffer with a
|
||||
/// device copy.
|
||||
pub capture_ring_allocations: SiteAllocations,
|
||||
/// Those of the zero source, the buffer of zeros that Private fills and new block-compressed
|
||||
/// textures copy from, which the block-maker thread makes as its first work: made by the
|
||||
/// first such fill or texture only where that make failed.
|
||||
pub zero_source_allocations: SiteAllocations,
|
||||
/// Those of takes from the pool that no free range fit: the consumer's
|
||||
/// ([`Device::take_block`](crate::Device::take_block)), and a capture's staging blocks of its
|
||||
/// own ([`capture_overflows`](Self::capture_overflows)). Texture blocks' are
|
||||
/// ([`Device::take_block`](crate::Device::take_block)). Texture blocks' are
|
||||
/// [`texture_block_allocations`](Self::texture_block_allocations).
|
||||
pub take_allocations: SiteAllocations,
|
||||
/// Calls that waited for the block-maker thread's make of one of the runtime's fixed-size
|
||||
@@ -1301,29 +1246,11 @@ pub struct Metrics {
|
||||
/// 50 to 100 ms, 100 to 250 ms, 250 to 500 ms, 500 ms to 1 s, 1 to 2 s, and 2 s or more. Only
|
||||
/// a class's reserve, which the idle rule does not free, is taken again past 250 ms.
|
||||
pub idle_reuses_by_age: [u64; 7],
|
||||
/// Bytes commits copied on the host from Managed buffers' bytes into staging memory: each range
|
||||
/// `didModifyRange:` named since the last capture, once, on a device whose Managed buffers have
|
||||
/// device copies ([`Buffer::did_modify_range`](crate::Buffer::did_modify_range)).
|
||||
/// Bytes the commits' copy-ins copy on the GPU from Managed buffers' bytes into their device
|
||||
/// copies: each range `didModifyRange:` named since the last capture, once, on a device whose
|
||||
/// Managed buffers have device copies
|
||||
/// ([`Buffer::did_modify_range`](crate::Buffer::did_modify_range)).
|
||||
pub managed_bytes_captured: u64,
|
||||
/// Waits of commits for a submission to complete for room in the capture ring: an earlier
|
||||
/// command buffer's copy, or the commit's own ring-full sent ahead.
|
||||
pub capture_waits: u64,
|
||||
/// Ring-fulls of a commit's own bytes sent as copy submissions of their own, which the commit
|
||||
/// waited for before it used the ring again.
|
||||
pub capture_streams: u64,
|
||||
/// Commits whose capture took staging blocks of its own, as a command buffer committed before
|
||||
/// was held on the host.
|
||||
pub capture_overflows: u64,
|
||||
/// The bytes those commits copied into such blocks.
|
||||
pub capture_overflow_bytes: u64,
|
||||
/// Host time commits spent copying Managed buffers' bytes into the capture ring and into
|
||||
/// staging blocks of their own, in nanoseconds.
|
||||
pub capture_copy_nanos: u64,
|
||||
/// Host time commits spent waiting in their captures, in nanoseconds: for a submission to
|
||||
/// complete for room in the ring (an earlier command buffer's copy, or the commit's own
|
||||
/// ring-full sent ahead, from its flush to its completion), and for command buffers committed
|
||||
/// before to be submitted.
|
||||
pub capture_wait_nanos: u64,
|
||||
/// Command buffers that ran untimed, their GPU start and end times 0
|
||||
/// ([`CommandBuffer::gpu_start_time`](crate::CommandBuffer::gpu_start_time)): at their first
|
||||
/// record, every pair of the device's timestamp pools was taken and the device made no new
|
||||
@@ -1540,9 +1467,6 @@ pub struct Gauges {
|
||||
pub shared_long_reused_bytes: u64,
|
||||
/// As [`shared_long_reused_bytes`](Self::shared_long_reused_bytes), of Private allocations.
|
||||
pub private_long_reused_bytes: u64,
|
||||
/// Bytes of staging for Managed buffers' captures: the capture ring, once a commit made it, and
|
||||
/// the staging blocks of overflows that command buffers not yet retired hold.
|
||||
pub capture_bytes: u64,
|
||||
/// Bytes of staging for copies between textures and the CPU (`replace_region`, `get_bytes`):
|
||||
/// the staging region, once made, and the staging buffers of their own that copies
|
||||
/// larger than the region hold until the upload that copies through them is gone.
|
||||
|
||||
@@ -290,7 +290,7 @@ pub(crate) struct Core {
|
||||
/// thread placed, in the order it placed them ([`Ticks::span`](crate::times::Ticks::span)).
|
||||
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
|
||||
pub(crate) tick_spans: Mutex<Vec<u64>>,
|
||||
/// For the device tests: where set, the making of a staging or capture ring meets the test at
|
||||
/// For the device tests: where set, the making of the staging region meets the test at
|
||||
/// the barrier twice before it allocates, once parked and once released.
|
||||
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
|
||||
pub(crate) park_region: Mutex<Option<Arc<std::sync::Barrier>>>,
|
||||
@@ -1528,12 +1528,6 @@ impl Drop for Core {
|
||||
// The store's removal thread, the one thread no stop ends, is waited for here, so every
|
||||
// gauge, `Gauges::threads` among them, reads zero once the core is gone.
|
||||
self.caches.join_removal();
|
||||
if let Some(region) = self.work.take_capture_region() {
|
||||
self.counters
|
||||
.fall_by(Gauge::CaptureBytes, crate::capture::CAPTURE_LEN);
|
||||
// SAFETY: every command buffer whose copy-in read it retired, and no commit runs.
|
||||
unsafe { region.free(self) };
|
||||
}
|
||||
if let Some(region) = self.work.take_region() {
|
||||
self.counters
|
||||
.fall_by(Gauge::StagingBytes, crate::staging::REGION_LEN);
|
||||
|
||||
@@ -115,12 +115,15 @@ pub enum Refusal {
|
||||
/// The heap's bytes.
|
||||
heap_len: u64,
|
||||
},
|
||||
/// A Managed buffer whose bytes are in a block the host does not map, a Private block
|
||||
/// ([`Device::new_managed_buffer`](crate::Device::new_managed_buffer)).
|
||||
/// A Managed buffer whose bytes are in a Private block
|
||||
/// ([`Device::new_managed_buffer`](crate::Device::new_managed_buffer)): a Managed buffer's
|
||||
/// bytes are the consumer's, which it writes, and a Private block has no pages the consumer
|
||||
/// can write.
|
||||
///
|
||||
/// Basis: ours (a Managed buffer's bytes are the consumer's, which the host reaches through
|
||||
/// the block's mapping; a Private block has none).
|
||||
ManagedBlockNotShared {
|
||||
/// Basis: metal-documented (a Managed buffer has a CPU-side copy: `MTLBuffer.h` gives its
|
||||
/// `contents` as "the data pointer of this buffer's shared copy", and `didModifyRange:` names
|
||||
/// the ranges "the CPU has modified").
|
||||
ManagedBlockPrivate {
|
||||
/// The block named.
|
||||
block: BlockId,
|
||||
},
|
||||
@@ -1654,7 +1657,7 @@ impl fmt::Display for Refusal {
|
||||
f,
|
||||
"a heap buffer of {length} bytes at offset {offset} leaves its heap of {heap_len} bytes"
|
||||
),
|
||||
Refusal::ManagedBlockNotShared { block } => write!(
|
||||
Refusal::ManagedBlockPrivate { block } => write!(
|
||||
f,
|
||||
"a Managed buffer's bytes are in block {}, which is Private",
|
||||
block.get()
|
||||
|
||||
@@ -175,8 +175,7 @@ impl Ring {
|
||||
}
|
||||
|
||||
/// A ring of host-visible bytes: its buffer, the allocation of its own that the buffer spans, its
|
||||
/// mapping, and its ring. The device's staging region is one, of [`REGION_LEN`] bytes; the
|
||||
/// capture ring of Managed buffers' changed ranges is another (`crate::capture`).
|
||||
/// mapping, and its ring: the device's staging region, of [`REGION_LEN`] bytes.
|
||||
pub(crate) struct Region {
|
||||
pub(crate) buffer: vk::Buffer,
|
||||
memory: vk::DeviceMemory,
|
||||
|
||||
@@ -32,12 +32,13 @@
|
||||
//! device's staging region ([`crate::staging`]), which the work lock guards with the upload; the
|
||||
//! upload goes without a wait once its copies' spans take half the region.
|
||||
//!
|
||||
//! A command buffer's commit captures the Managed buffers' ranges named since the last capture
|
||||
//! ([`crate::capture`]): its copy-ins go ahead of its first segment's commands, after that
|
||||
//! segment's waits, in the same submission.
|
||||
//! A command buffer's commit takes the Managed buffers' ranges named since the last capture
|
||||
//! ([`crate::capture`]): its copy-in, GPU copies from the consumers' blocks into the device
|
||||
//! copies, goes ahead of its first segment's commands, after that segment's waits, in the same
|
||||
//! submission.
|
||||
|
||||
use crate::buffer::{BufferInner, BufferObject, DeviceCopy};
|
||||
use crate::capture::{self, Changes, Chunk, CopyIn, Modified, Named, CAPTURE_LEN};
|
||||
use crate::capture::{self, Changes, CopyIn, Modified, Named};
|
||||
use crate::command::{self, CbInner, CommandBufferError, Gpu, Handler, Pending, Segment};
|
||||
use crate::complete;
|
||||
use crate::counters::{Gauge, Metric, Site};
|
||||
@@ -131,11 +132,6 @@ pub(crate) const HOMES_PRUNE: usize = 64;
|
||||
pub(crate) struct Work {
|
||||
state: Mutex<WorkState>,
|
||||
changed: Condvar,
|
||||
/// The commits' turn ([`Work::turn`]).
|
||||
turn: Mutex<()>,
|
||||
/// The submit thread ended a pass, or the device closed or was lost: a capture waiting for
|
||||
/// the command buffers committed before it to go looks again ([`Work::capture`]).
|
||||
passed: Condvar,
|
||||
/// A span of the staging region another call held was released, or the device closed or was
|
||||
/// lost: a staging call asleep for it looks again ([`Work::stage`]). Signalled only while one
|
||||
/// sleeps ([`WorkState::span_sleepers`]).
|
||||
@@ -146,6 +142,9 @@ pub(crate) struct Work {
|
||||
/// began: they count against [`UPLOAD_BYTES`]. A texture's release adds without the work lock,
|
||||
/// which its drop may run under.
|
||||
released: AtomicU64,
|
||||
/// For the device tests: a commit began its count of the wait for the work lock.
|
||||
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
|
||||
pub(crate) counting: AtomicBool,
|
||||
}
|
||||
|
||||
pub(crate) struct WorkState {
|
||||
@@ -166,7 +165,7 @@ pub(crate) struct WorkState {
|
||||
prune_at: usize,
|
||||
/// The staging region, from the first copy on.
|
||||
region: Option<Region>,
|
||||
/// The Managed buffers' ranges named since the last commit, and the capture ring.
|
||||
/// The Managed buffers' ranges named since the last commit.
|
||||
changes: Changes,
|
||||
/// Something changed that may let a held segment or group go.
|
||||
dirty: bool,
|
||||
@@ -222,18 +221,6 @@ pub(crate) struct Upload {
|
||||
/// The staging region's spans its copies use, and their bytes.
|
||||
spans: Vec<u64>,
|
||||
span_bytes: u64,
|
||||
/// Ring-fulls of commits' captures sent ahead ([`WorkState::stream`]): each goes after its
|
||||
/// command buffer in the submission, in order, and is kept until the upload retires.
|
||||
copy_ins: Vec<CopyIn>,
|
||||
}
|
||||
|
||||
/// What a capture that finds the ring held by copies not yet submitted can do, once the held
|
||||
/// groups went ([`Work::capture`]).
|
||||
enum Ahead {
|
||||
/// Every command buffer committed is submitted: the capture's own ring-full can go next.
|
||||
Sent,
|
||||
/// A command buffer committed waits on the host: nothing goes before the host acts.
|
||||
Held,
|
||||
}
|
||||
|
||||
/// What an upload keeps until it retires.
|
||||
@@ -276,7 +263,6 @@ impl Upload {
|
||||
staging: 0,
|
||||
spans: Vec::new(),
|
||||
span_bytes: 0,
|
||||
copy_ins: Vec::new(),
|
||||
}),
|
||||
Err(error) => {
|
||||
core.recorders.give_back(core, recorder);
|
||||
@@ -375,8 +361,6 @@ struct Batch {
|
||||
/// The textures over a Managed buffer's device copy its segments wrote, one for each segment
|
||||
/// that wrote one, whose copies back its submission settles.
|
||||
wrote: Vec<Arc<TextureInner>>,
|
||||
/// The capture ring's spans its command buffers' copy-ins read, free once it completes.
|
||||
spans: Vec<u64>,
|
||||
}
|
||||
|
||||
/// One segment's part of a submit info: its event waits, its commands and its signals.
|
||||
@@ -459,11 +443,11 @@ impl Work {
|
||||
span_sleepers: 0,
|
||||
}),
|
||||
changed: Condvar::new(),
|
||||
turn: Mutex::new(()),
|
||||
passed: Condvar::new(),
|
||||
spans: Condvar::new(),
|
||||
keeping: AtomicBool::new(false),
|
||||
released: AtomicU64::new(0),
|
||||
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
|
||||
counting: AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -576,82 +560,31 @@ impl Work {
|
||||
|
||||
/// `didModifyRange:` of a Managed buffer with a device copy: the consumer's bytes
|
||||
/// `start..end` of `buffer` changed. The range is only named, merged with the buffer's others
|
||||
/// where they overlap or touch; the next commit of a command buffer with commands captures it
|
||||
/// ([`capture`](Self::capture)). The device's first named range makes the capture ring, on
|
||||
/// the naming thread without the work lock, so no commit waits for its allocation.
|
||||
/// where they overlap or touch; the next commit of a command buffer with commands copies it
|
||||
/// in ([`capture`](Self::capture)). It allocates nothing.
|
||||
///
|
||||
/// Err: [`Error::Quiesced`]; what making the capture ring returns.
|
||||
pub(crate) fn modify(
|
||||
&self,
|
||||
core: &Core,
|
||||
buffer: Named<'_>,
|
||||
start: u64,
|
||||
end: u64,
|
||||
) -> Result<(), Error> {
|
||||
/// Err: [`Error::Quiesced`].
|
||||
pub(crate) fn modify(&self, buffer: Named<'_>, start: u64, end: u64) -> Result<(), Error> {
|
||||
let mut state = self.lock();
|
||||
if state.closed {
|
||||
return Err(Error::Quiesced);
|
||||
}
|
||||
if state.changes.region.is_none() {
|
||||
drop(state);
|
||||
let made = Region::new(core, CAPTURE_LEN, Site::CaptureRing)?;
|
||||
state = self.lock();
|
||||
if state.changes.region.is_none() && !state.closed {
|
||||
state.changes.region = Some(made);
|
||||
core.counters.rise_by(Gauge::CaptureBytes, CAPTURE_LEN);
|
||||
} else {
|
||||
// SAFETY: another call made the ring first, or the device closed; nothing used
|
||||
// this one.
|
||||
unsafe { made.free(core) };
|
||||
}
|
||||
if state.closed {
|
||||
return Err(Error::Quiesced);
|
||||
}
|
||||
}
|
||||
state.changes.add(buffer, start, end);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A commit's turn: commits take it one at a time, before the work lock, and keep it until
|
||||
/// they have handed their command buffer over, so command buffers keep the order of their
|
||||
/// captures, which copy without the work lock ([`capture`](Self::capture)).
|
||||
pub(crate) fn turn(&self) -> MutexGuard<'_, ()> {
|
||||
lock(&self.turn)
|
||||
}
|
||||
|
||||
/// Whether a commit holds its turn: it began its count of the wait for the work lock
|
||||
/// ([`turn`](Self::turn) is taken after it).
|
||||
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
|
||||
pub(crate) fn turn_taken(&self) -> bool {
|
||||
matches!(
|
||||
self.turn.try_lock(),
|
||||
Err(std::sync::TryLockError::WouldBlock)
|
||||
)
|
||||
}
|
||||
|
||||
/// At a commit of a command buffer with commands, in the commit's turn
|
||||
/// ([`turn`](Self::turn)), on the committing thread, under the work lock `state` (released
|
||||
/// while it copies and while it waits): captures every Managed buffer's range named since the
|
||||
/// last capture (`crate::capture`). Each range's consumer's bytes are copied into spans of
|
||||
/// the capture ring, which the first named range made ([`modify`](Self::modify)), and the
|
||||
/// copies from them into the device
|
||||
/// copies are recorded into copy-ins, command buffers of their own: the first after the copies
|
||||
/// back owed to textures over the ranges in images of their own, the last before the copies
|
||||
/// in those textures take.
|
||||
/// At a commit of a command buffer with commands, on the committing thread, under the work
|
||||
/// lock `state`, which it keeps: takes every Managed buffer's range named since the last
|
||||
/// capture (`crate::capture`) into one copy-in, GPU copies from the consumers' blocks into the
|
||||
/// device copies, recorded into a command buffer of its own ([`capture::copy_in`]). Returns
|
||||
/// the copy-ins the committing command buffer takes: a commit that failed after its capture
|
||||
/// left its own first.
|
||||
///
|
||||
/// Where the ring has no room, it waits for the oldest span's submission. Where the oldest
|
||||
/// span is of a copy not yet submitted, the held groups go at once; once every command buffer
|
||||
/// committed before is submitted, the capture's own ring-full goes in a submission of its own
|
||||
/// ([`stream`](WorkState::stream)), which the commit waits for. Where one is held on the host
|
||||
/// instead, the rest takes staging blocks of its own (`crate::capture::overflow`). Returns the
|
||||
/// copy-ins the committing command buffer takes: a commit that failed after its capture left
|
||||
/// its own first.
|
||||
///
|
||||
/// Err: [`Error::Quiesced`]; what making a recorder or a staging block can return;
|
||||
/// [`Error::Vulkan`] with `VK_ERROR_DEVICE_LOST` where the device is lost while it waits.
|
||||
/// Err: [`Error::Quiesced`]; what making the copy-in's command buffer returns. The ranges are
|
||||
/// then named again for the next commit.
|
||||
pub(crate) fn capture<'a>(
|
||||
&'a self,
|
||||
core: &Arc<Core>,
|
||||
core: &Core,
|
||||
mut state: MutexGuard<'a, WorkState>,
|
||||
) -> Result<(MutexGuard<'a, WorkState>, Vec<CopyIn>), Error> {
|
||||
if !state.changes.named() {
|
||||
@@ -659,248 +592,35 @@ impl Work {
|
||||
return Ok((state, carried));
|
||||
}
|
||||
let named = state.changes.take();
|
||||
let mut chunk = match Chunk::begin(core, capture::backs(&named)) {
|
||||
Ok(chunk) => chunk,
|
||||
Err(error) => return Err(self.unwind(state, Vec::new(), &named, error)),
|
||||
};
|
||||
// Every range, by its buffer's index in `named`.
|
||||
let pieces: Vec<(usize, u64, u64)> = (named.iter().enumerate())
|
||||
.flat_map(|(index, modified)| {
|
||||
(modified.ranges.iter()).map(move |&(start, end)| (index, start, end))
|
||||
})
|
||||
.collect();
|
||||
let mut captured = 0;
|
||||
let mut piece = 0;
|
||||
let mut at = pieces.first().map_or(0, |&(_, start, _)| start);
|
||||
// The progress value known complete: what the completion thread has seen, or what this
|
||||
// capture waited for. A wait frees the spans of the submission it waited for at once,
|
||||
// before the completion thread has retired it, so the capture waits once for each.
|
||||
let mut completed = 0;
|
||||
while let Some(&(index, _, end)) = pieces.get(piece) {
|
||||
if at == end {
|
||||
piece += 1;
|
||||
at = pieces.get(piece).map_or(0, |&(_, start, _)| start);
|
||||
continue;
|
||||
}
|
||||
let modified = &named[index];
|
||||
let len = (end - at).min(CAPTURE_LEN);
|
||||
let Some(region) = state.changes.region.as_mut() else {
|
||||
unreachable!("the first named range made the ring, freed only at the device's end");
|
||||
};
|
||||
region.ring.reclaim(completed.max(core.done.completed()));
|
||||
if let Some((number, offset)) = region.ring.take(len, false) {
|
||||
let (host, ring) = (region.host(offset), region.buffer);
|
||||
drop(state);
|
||||
let began = crate::host_time();
|
||||
// SAFETY: the span is this capture's alone until it is set recorded, and the
|
||||
// consumer's buffer is mapped and holds `at..at + len`; the two do not overlap.
|
||||
unsafe {
|
||||
(modified.contents.at(at).as_ptr())
|
||||
.copy_to_nonoverlapping(host.get().as_ptr(), len as usize)
|
||||
};
|
||||
core.counters
|
||||
.capture_copied(crate::host_time().saturating_sub(began));
|
||||
state = self.lock();
|
||||
if let Some(region) = &mut state.changes.region {
|
||||
region.ring.set(number, At::Recorded);
|
||||
}
|
||||
chunk.spans.push(number);
|
||||
let copy = vk::BufferCopy {
|
||||
src_offset: offset,
|
||||
dst_offset: modified.copy.range(at).1,
|
||||
size: len,
|
||||
};
|
||||
chunk.copy(ring, index, copy);
|
||||
captured += len;
|
||||
at += len;
|
||||
continue;
|
||||
}
|
||||
let oldest = region.ring.oldest();
|
||||
let ahead = match oldest {
|
||||
Some(Oldest::Submitted(value)) => {
|
||||
drop(state);
|
||||
core.counters.count(Metric::CaptureWaits);
|
||||
let began = crate::host_time();
|
||||
let waited = core.done.wait(core, value);
|
||||
core.counters
|
||||
.capture_waited(crate::host_time().saturating_sub(began));
|
||||
state = self.lock();
|
||||
match waited.and(if state.closed {
|
||||
Err(Error::Quiesced)
|
||||
} else {
|
||||
Ok(())
|
||||
}) {
|
||||
Ok(()) => {
|
||||
completed = completed.max(value);
|
||||
continue;
|
||||
}
|
||||
Err(error) => {
|
||||
let spans = chunk.give_up(core);
|
||||
return Err(self.unwind(state, spans, &named, error));
|
||||
}
|
||||
}
|
||||
}
|
||||
// Of a copy not yet submitted: this capture's own, or a held command buffer's.
|
||||
_ => {
|
||||
let began = crate::host_time();
|
||||
let ahead;
|
||||
(state, ahead) = self.send_ahead(state);
|
||||
core.counters
|
||||
.capture_waited(crate::host_time().saturating_sub(began));
|
||||
ahead
|
||||
}
|
||||
};
|
||||
let streams = match ahead {
|
||||
Ok(Ahead::Sent) => {
|
||||
let oldest = (state.changes.region.as_ref()).and_then(|r| r.ring.oldest());
|
||||
if matches!(oldest, Some(Oldest::Submitted(_))) {
|
||||
continue;
|
||||
}
|
||||
// What holds the ring now is this capture's own, unless a failed commit's
|
||||
// capture carried for this one's command buffer does.
|
||||
chunk.rings()
|
||||
}
|
||||
Ok(Ahead::Held) => false,
|
||||
Err(error) => {
|
||||
let spans = chunk.give_up(core);
|
||||
return Err(self.unwind(state, spans, &named, error));
|
||||
}
|
||||
};
|
||||
if streams {
|
||||
// This capture's ring-full goes in a submission of its own, after every command
|
||||
// buffer committed before, and the commit waits for it.
|
||||
let next = match Chunk::begin(core, Vec::new()) {
|
||||
Ok(next) => next,
|
||||
Err(error) => {
|
||||
let spans = chunk.give_up(core);
|
||||
return Err(self.unwind(state, spans, &named, error));
|
||||
}
|
||||
};
|
||||
let upload = chunk
|
||||
.end(core, &named, &[])
|
||||
.and_then(|()| (state.upload.take()).map_or_else(|| Upload::begin(core), Ok));
|
||||
let upload = match upload {
|
||||
Ok(upload) => upload,
|
||||
Err(error) => {
|
||||
let spans = chunk.give_up(core);
|
||||
let spans = spans.into_iter().chain(next.give_up(core)).collect();
|
||||
return Err(self.unwind(state, spans, &named, error));
|
||||
}
|
||||
};
|
||||
let began = crate::host_time();
|
||||
let value = state.stream(upload, chunk.ended(named.clone(), Vec::new()));
|
||||
chunk = next;
|
||||
drop(state);
|
||||
self.wake();
|
||||
core.counters.count(Metric::CaptureStreams);
|
||||
core.counters.count(Metric::CaptureWaits);
|
||||
let waited = core.done.wait(core, value);
|
||||
core.counters
|
||||
.capture_waited(crate::host_time().saturating_sub(began));
|
||||
state = self.lock();
|
||||
if let Err(error) = waited.and(if state.closed {
|
||||
Err(Error::Quiesced)
|
||||
} else {
|
||||
Ok(())
|
||||
}) {
|
||||
let spans = chunk.give_up(core);
|
||||
return Err(self.unwind(state, spans, &named, error));
|
||||
}
|
||||
completed = completed.max(value);
|
||||
continue;
|
||||
}
|
||||
// A command buffer committed before is held on the host: the rest takes staging of
|
||||
// its own.
|
||||
let rest: Vec<(usize, u64, u64)> = std::iter::once((index, at, end))
|
||||
.chain(pieces[piece + 1..].iter().copied())
|
||||
.collect();
|
||||
drop(state);
|
||||
let overflowed = capture::overflow(core, &named, &rest, &mut chunk);
|
||||
state = self.lock();
|
||||
match overflowed {
|
||||
Ok(bytes) => captured += bytes,
|
||||
Err(error) => {
|
||||
let spans = chunk.give_up(core);
|
||||
return Err(self.unwind(state, spans, &named, error));
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
if state.closed {
|
||||
let spans = chunk.give_up(core);
|
||||
return Err(self.unwind(state, spans, &named, Error::Quiesced));
|
||||
return Err(self.unwind(state, &named, Error::Quiesced));
|
||||
}
|
||||
let into = capture::copies_in(&named);
|
||||
if let Err(error) = chunk.end(core, &named, &into) {
|
||||
let spans = chunk.give_up(core);
|
||||
return Err(self.unwind(state, spans, &named, error));
|
||||
}
|
||||
let last = chunk.ended(named.clone(), into);
|
||||
core.counters.captured(captured);
|
||||
let last = match capture::copy_in(core, &named) {
|
||||
Ok(last) => last,
|
||||
Err(error) => return Err(self.unwind(state, &named, error)),
|
||||
};
|
||||
core.counters
|
||||
.captured(named.iter().map(Modified::bytes).sum());
|
||||
// Taken last, so a capture that failed before left them carried.
|
||||
let mut copy_ins = std::mem::take(&mut state.changes.carried);
|
||||
copy_ins.push(last);
|
||||
Ok((state, copy_ins))
|
||||
}
|
||||
|
||||
/// A capture that cannot finish: `spans`, the ring's spans its copy-ins not submitted read,
|
||||
/// are given up, its ranges `named` named again for the next commit (none once the device is
|
||||
/// closed: its submit thread forgot the ranges at its end), and `error` is the commit's.
|
||||
/// A capture that cannot finish: its ranges `named` are named again for the next commit (none
|
||||
/// once the device is closed: its submit thread forgot the ranges at its end), and `error` is
|
||||
/// the commit's.
|
||||
fn unwind(
|
||||
&self,
|
||||
mut state: MutexGuard<'_, WorkState>,
|
||||
spans: Vec<u64>,
|
||||
named: &[Modified],
|
||||
error: Error,
|
||||
) -> Error {
|
||||
let again = if state.closed { &[] } else { named };
|
||||
state.changes.give_up(&spans, again);
|
||||
state.changes.give_up(again);
|
||||
error
|
||||
}
|
||||
|
||||
/// For a capture that finds the ring held by copies not yet submitted, in its turn: has every
|
||||
/// queue's held group go at once, and waits, without the lock, while the submit thread can
|
||||
/// still submit a command buffer committed before. [`Ahead::Sent`] once every committed
|
||||
/// command buffer is submitted; [`Ahead::Held`] where one waits on the host (an event wait the
|
||||
/// host has not met, or a command buffer enqueued ahead of it and not committed).
|
||||
///
|
||||
/// Err: [`Error::Quiesced`]; [`Error::Vulkan`] with `VK_ERROR_DEVICE_LOST` at a loss.
|
||||
fn send_ahead<'a>(
|
||||
&'a self,
|
||||
mut state: MutexGuard<'a, WorkState>,
|
||||
) -> (MutexGuard<'a, WorkState>, Result<Ahead, Error>) {
|
||||
state.send_all();
|
||||
self.wake();
|
||||
loop {
|
||||
if state.closed {
|
||||
return (state, Err(Error::Quiesced));
|
||||
}
|
||||
if state.lost {
|
||||
let error = Error::Vulkan {
|
||||
call: "vkQueueSubmit2",
|
||||
result: vk::Result::ERROR_DEVICE_LOST,
|
||||
};
|
||||
return (state, Err(error));
|
||||
}
|
||||
match state.unsent() {
|
||||
Some(ahead) => return (state, Ok(ahead)),
|
||||
None => {
|
||||
state = (self.passed.wait(state)).unwrap_or_else(PoisonError::into_inner);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// At teardown: the capture ring, for the core to free.
|
||||
pub(crate) fn take_capture_region(&mut self) -> Option<Region> {
|
||||
self.state
|
||||
.get_mut()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.changes
|
||||
.region
|
||||
.take()
|
||||
}
|
||||
|
||||
/// [`upload`](Self::upload) up to the span's give-up on a failure.
|
||||
fn record_upload<const N: usize>(
|
||||
&self,
|
||||
@@ -1215,8 +935,7 @@ impl Work {
|
||||
let entries: Vec<Entry> = fifo.entries.drain(..).collect();
|
||||
let mut ended = Vec::new();
|
||||
for entry in entries {
|
||||
// Copy-ins not yet staged never run: their spans are given up, and their
|
||||
// ranges named again.
|
||||
// Copy-ins not yet staged never run: their ranges are named again.
|
||||
let unstaged = (entry.pending.iter())
|
||||
.flat_map(|pending| &pending.gpu.segments[pending.next..])
|
||||
.flat_map(|segment| &segment.copy_ins);
|
||||
@@ -1226,7 +945,7 @@ impl Work {
|
||||
} else {
|
||||
©_in.modified[..]
|
||||
};
|
||||
state.changes.give_up(©_in.spans, again);
|
||||
state.changes.give_up(again);
|
||||
}
|
||||
fifo.end(entry, CommandBufferError::NotRun, &mut ended);
|
||||
}
|
||||
@@ -1251,7 +970,6 @@ impl Work {
|
||||
state.stop = true;
|
||||
state.dirty = true;
|
||||
self.wake();
|
||||
self.passed.notify_all();
|
||||
self.release_spans(&state);
|
||||
}
|
||||
|
||||
@@ -1261,7 +979,6 @@ impl Work {
|
||||
state.lost = true;
|
||||
state.dirty = true;
|
||||
self.wake();
|
||||
self.passed.notify_all();
|
||||
self.release_spans(&state);
|
||||
}
|
||||
|
||||
@@ -1292,41 +1009,6 @@ impl WorkState {
|
||||
self.changes.carried.extend(copy_ins);
|
||||
}
|
||||
|
||||
/// A capture's ring-full, `full`, goes in the next submission with `upload`, the pending
|
||||
/// upload taken or a new one, after its commands and the copy-ins carried from a failed
|
||||
/// commit, and the upload is submitted at once: the progress value at which it completes. The
|
||||
/// caller wakes the thread.
|
||||
fn stream(&mut self, upload: Upload, full: CopyIn) -> u64 {
|
||||
let upload = self.upload.insert(upload);
|
||||
upload
|
||||
.copy_ins
|
||||
.extend(std::mem::take(&mut self.changes.carried));
|
||||
upload.copy_ins.push(full);
|
||||
upload.entries += 1;
|
||||
self.flush()
|
||||
}
|
||||
|
||||
/// What a capture behind copies not yet submitted can do: `None` while a held group or a
|
||||
/// ready command buffer can still go.
|
||||
fn unsent(&self) -> Option<Ahead> {
|
||||
if self.fifos.iter().any(|fifo| fifo.group.is_some()) || self.next_ready().is_some() {
|
||||
return None;
|
||||
}
|
||||
let committed = (self.fifos.iter())
|
||||
.any(|fifo| fifo.entries.iter().any(|entry| entry.pending.is_some()));
|
||||
Some(if committed { Ahead::Held } else { Ahead::Sent })
|
||||
}
|
||||
|
||||
/// Every command buffer committed so far goes at once: each queue's held group, and each
|
||||
/// later one as it is staged. The caller wakes the thread.
|
||||
fn send_all(&mut self) {
|
||||
let through = self.next_place;
|
||||
for fifo in &mut self.fifos {
|
||||
fifo.send_through = fifo.send_through.max(through);
|
||||
}
|
||||
self.dirty = true;
|
||||
}
|
||||
|
||||
/// Has the upload submitted at once, alone where no group goes: the progress value at which
|
||||
/// everything recorded into uploads so far has completed. The caller wakes the thread.
|
||||
fn flush(&mut self) -> u64 {
|
||||
@@ -1352,11 +1034,6 @@ impl WorkState {
|
||||
region.ring.set(number, At::Submitted(value));
|
||||
}
|
||||
}
|
||||
if let Some(region) = &mut self.changes.region {
|
||||
for &number in upload.copy_ins.iter().flat_map(|copy_in| ©_in.spans) {
|
||||
region.ring.set(number, At::Submitted(value));
|
||||
}
|
||||
}
|
||||
self.prune_at = HOMES_PRUNE;
|
||||
let mut homes = Vec::new();
|
||||
for image in self.homes.drain(..).filter_map(|home| home.upgrade()) {
|
||||
@@ -1383,11 +1060,6 @@ impl WorkState {
|
||||
region.ring.set(number, At::Done);
|
||||
}
|
||||
}
|
||||
if let Some(region) = &mut self.changes.region {
|
||||
for &number in upload.copy_ins.iter().flat_map(|copy_in| ©_in.spans) {
|
||||
region.ring.set(number, At::Done);
|
||||
}
|
||||
}
|
||||
Some(upload)
|
||||
}
|
||||
|
||||
@@ -1523,7 +1195,7 @@ impl WorkState {
|
||||
.flat_map(|pending| &pending.gpu.segments)
|
||||
.flat_map(|segment| &segment.copy_ins);
|
||||
for copy_in in copy_ins {
|
||||
self.changes.give_up(©_in.spans, ©_in.modified);
|
||||
self.changes.give_up(©_in.modified);
|
||||
}
|
||||
fifo.end(entry, error, ended);
|
||||
}
|
||||
@@ -1614,7 +1286,6 @@ impl WorkState {
|
||||
backs: Vec::new(),
|
||||
written: Vec::new(),
|
||||
wrote: Vec::new(),
|
||||
spans: Vec::new(),
|
||||
});
|
||||
if leads {
|
||||
group.run = group.run.saturating_add(run.unwrap_or(u64::MAX));
|
||||
@@ -1667,7 +1338,6 @@ impl WorkState {
|
||||
),
|
||||
signals: Vec::new(),
|
||||
});
|
||||
group.spans.extend(©_in.spans);
|
||||
}
|
||||
let staged = Staged {
|
||||
waits: waits.unwrap_or_default(),
|
||||
@@ -1750,11 +1420,6 @@ impl WorkState {
|
||||
pending.gpu.fences.submitted(value);
|
||||
}
|
||||
}
|
||||
if let Some(region) = &mut self.changes.region {
|
||||
for &number in &batch.spans {
|
||||
region.ring.set(number, At::Submitted(value));
|
||||
}
|
||||
}
|
||||
self.flush = false;
|
||||
Some((value, self.take_upload(core, released, value), batch))
|
||||
}
|
||||
@@ -1963,7 +1628,6 @@ pub(crate) fn run(core: Arc<Core>) {
|
||||
} else {
|
||||
state = pass(&core, state);
|
||||
}
|
||||
work.passed.notify_all();
|
||||
if state.stop {
|
||||
let ended: Vec<Ended> = (state.fifos.drain(..))
|
||||
.flat_map(|fifo| end(fifo.entries, |_| CommandBufferError::NotRun))
|
||||
@@ -2068,7 +1732,6 @@ impl Batch {
|
||||
backs: Vec::new(),
|
||||
written: Vec::new(),
|
||||
wrote: Vec::new(),
|
||||
spans: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2135,18 +1798,16 @@ fn submit(core: &Core, value: u64, upload: Option<Upload>, batch: Batch) {
|
||||
});
|
||||
let mut ahead = 0;
|
||||
if let Some(upload) = &upload {
|
||||
let commands = std::iter::once(upload.command)
|
||||
.chain(upload.copy_ins.iter().map(|copy_in| copy_in.command));
|
||||
for (at, command) in commands.enumerate() {
|
||||
segments.insert(
|
||||
at,
|
||||
Staged {
|
||||
command: Some(vk::CommandBufferSubmitInfo::default().command_buffer(command)),
|
||||
..Staged::default()
|
||||
},
|
||||
);
|
||||
ahead += 1;
|
||||
}
|
||||
segments.insert(
|
||||
0,
|
||||
Staged {
|
||||
command: Some(
|
||||
vk::CommandBufferSubmitInfo::default().command_buffer(upload.command),
|
||||
),
|
||||
..Staged::default()
|
||||
},
|
||||
);
|
||||
ahead += 1;
|
||||
}
|
||||
// One part, or, where the group goes member by member, one for each command buffer that leads
|
||||
// in it, the upload with the first.
|
||||
@@ -2264,8 +1925,5 @@ impl Upload {
|
||||
/// or where it never went.
|
||||
pub(crate) fn retire(self, core: &Core) {
|
||||
core.recorders.give_back(core, self.recorder);
|
||||
for copy_in in self.copy_ins {
|
||||
copy_in.retire(core);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1583,8 +1583,8 @@ pub(crate) mod on_device {
|
||||
}
|
||||
|
||||
/// A commit's wait for the submission lock is counted: one made while another thread holds
|
||||
/// the lock counts at least the time from its turn (taken after its count began) to the
|
||||
/// lock's release, here 20 ms or more. No clock of the test's bounds it from above.
|
||||
/// the lock counts at least the time from the start of its count to the lock's release, here
|
||||
/// 20 ms or more. No clock of the test's bounds it from above.
|
||||
#[test]
|
||||
fn every_device_counts_a_commits_wait_for_the_submission_lock() {
|
||||
each_device("command_lock_wait", |name, _, device| {
|
||||
@@ -1598,7 +1598,9 @@ pub(crate) mod on_device {
|
||||
let command_buffer = command_buffer.clone();
|
||||
thread::spawn(move || command_buffer.commit().expect("a commit"))
|
||||
};
|
||||
within("the commit's turn", || device.core().work.turn_taken());
|
||||
within("the commit's count", || {
|
||||
(device.core().work.counting).load(std::sync::atomic::Ordering::SeqCst)
|
||||
});
|
||||
let waiting = host_time();
|
||||
thread::sleep(Duration::from_millis(20));
|
||||
let released = host_time();
|
||||
@@ -1608,7 +1610,7 @@ pub(crate) mod on_device {
|
||||
let metrics = device.counters().metrics();
|
||||
assert!(
|
||||
metrics.commit_lock_wait_max_nanos >= released - waiting,
|
||||
"{name}: {} counted, the lock held {} past the commit's turn",
|
||||
"{name}: {} counted, the lock held {} past the start of the commit's count",
|
||||
metrics.commit_lock_wait_max_nanos,
|
||||
released - waiting
|
||||
);
|
||||
|
||||
@@ -3,19 +3,20 @@
|
||||
//! where the device is neither integrated nor a CPU, the copy holds the consumer's first bytes and
|
||||
//! zeros after them, a changed range reaches it at the next commit and a range not marked changed
|
||||
//! does not, a change submits nothing, and the copy-in at a commit adds one barrier; without one,
|
||||
//! shaders read the consumer's bytes as they are. A command buffer reads the bytes of its commit, not those written and named after it
|
||||
//! while it waits, where there is a device copy; a write after the range is named and before the
|
||||
//! commit is seen. Three rings' worth named with nothing held streams through the ring alone;
|
||||
//! more than a ring behind a command buffer held on the host takes staging of its own, which it
|
||||
//! gives back as it retires, and reads the bytes of its commit. Metal's two-copy rule holds where
|
||||
//! `Device::has_unified_memory` is false: a kernel's write stays in the device copy, and a range
|
||||
//! named with no host write puts the consumer's bytes back over it. A range past the buffer and a
|
||||
//! Managed buffer over a Private block are refused, and every gauge reads zero after teardown. The
|
||||
//! consumer places the device copy: at an odd offset of its Private block it holds the bytes there
|
||||
//! and nowhere else, the consumer's slack after it and the bytes before it as the consumer left
|
||||
//! them; a missing copy, a copy on a unified device, one in a Shared block and one past its block
|
||||
//! are refused. The device's first named range makes the capture ring on the naming thread: a
|
||||
//! commit on another thread, with that making parked, completes.
|
||||
//! shaders read the consumer's bytes as they are. In both forms a command buffer reads the bytes
|
||||
//! the consumer wrote and named before its commit (Metal's `didModifyRange:` contract), though the
|
||||
//! consumer's buffer and block handles go before it runs; nothing writes under a pending command
|
||||
//! buffer, where Metal leaves the range undefined for the GPU. A range of three 16 MiB units named
|
||||
//! arrives whole at one commit, which takes no staging and allocates nothing. A Managed buffer over
|
||||
//! an imported dma-buf, a block the runtime does not map, has no `contents`, and a kernel reads the
|
||||
//! bytes the consumer wrote through its own mapping and named, in either form. Metal's two-copy
|
||||
//! rule holds where `Device::has_unified_memory` is false: a kernel's write stays in the device
|
||||
//! copy, and a range named with no host write puts the consumer's bytes back over it. A range past
|
||||
//! the buffer and a Managed buffer over a Private block are refused, and every gauge reads zero
|
||||
//! after teardown. The consumer places the device copy: at an odd offset of its Private block it
|
||||
//! holds the bytes there and nowhere else, the consumer's slack after it and the bytes before it
|
||||
//! as the consumer left them; a missing copy, a copy on a unified device, one in a Shared block
|
||||
//! and one past its block are refused.
|
||||
//!
|
||||
//! Managed textures, on every device: the image takes the named bytes of a region at its upload
|
||||
//! and nothing outside it, `get_bytes` reads the named bytes, `replace_region` writes them and
|
||||
@@ -57,8 +58,6 @@ fn changed_ranges_merge_where_they_overlap_or_touch() {
|
||||
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
|
||||
pub(crate) mod on_device {
|
||||
use crate::buffer::BufferObject;
|
||||
use crate::capture::CAPTURE_LEN;
|
||||
use crate::device::lock;
|
||||
use crate::tests::command::on_device::{each_device, finished, within, Arena};
|
||||
use crate::tests::compute::on_device::{add, step, WORDS};
|
||||
use crate::{
|
||||
@@ -67,9 +66,6 @@ pub(crate) mod on_device {
|
||||
TextureDescriptor, TextureType, TextureUsage,
|
||||
};
|
||||
use ash::vk;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Barrier};
|
||||
use std::thread;
|
||||
use std::time::Instant;
|
||||
|
||||
const LEN: u64 = 64 << 10;
|
||||
@@ -217,7 +213,7 @@ pub(crate) mod on_device {
|
||||
let private = (device.take_block(MemoryClass::Private, 1))
|
||||
.unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
match device.new_managed_buffer((private.id, 0), None, 256, 0) {
|
||||
Err(Error::Refused(Refusal::ManagedBlockNotShared { block })) => {
|
||||
Err(Error::Refused(Refusal::ManagedBlockPrivate { block })) => {
|
||||
assert_eq!(block, private.id, "{name}")
|
||||
}
|
||||
Err(error) => panic!("{name}: a Managed buffer over a Private block: {error}"),
|
||||
@@ -229,9 +225,7 @@ pub(crate) mod on_device {
|
||||
);
|
||||
drop((managed, into));
|
||||
for block in [cpu, private] {
|
||||
device
|
||||
.release_block(block)
|
||||
.unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
(device.release_block(block)).unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -513,11 +507,13 @@ pub(crate) mod on_device {
|
||||
});
|
||||
}
|
||||
|
||||
/// A kernel reads a Managed buffer's bytes as they were at its commit where it has a device
|
||||
/// copy: written and named, committed behind an event wait, then written and named again
|
||||
/// before the event lets it run, it reads the first bytes (the old live read at submission
|
||||
/// read the second). Without a device copy it reads the bytes as they are when it runs. And a
|
||||
/// write after a range is named and before the commit is what the kernel reads, on both.
|
||||
/// A command buffer reads the bytes the consumer wrote and named before its commit, in either
|
||||
/// form (Metal's `didModifyRange:` contract): written and named, a kernel committed after reads
|
||||
/// them; written and named again, a kernel committed behind an event wait reads the second
|
||||
/// bytes once the event lets it run, though the consumer's buffer and block handles went
|
||||
/// before that, as what the commit took holds the consumer's block until its copy ran. Nothing
|
||||
/// here writes under a pending command buffer, where Metal leaves the range undefined for the
|
||||
/// GPU.
|
||||
#[test]
|
||||
fn every_device_takes_a_managed_buffer_s_bytes_at_the_commit() {
|
||||
each_device("managed at commit", |name, _, device| {
|
||||
@@ -531,48 +527,45 @@ pub(crate) mod on_device {
|
||||
.unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
let state = add(&device);
|
||||
let queue = device.new_command_queue(4).expect("a queue");
|
||||
let buffers = [&managed, &zero, &out];
|
||||
let (a, b) = (vec![0xA1; 256], vec![0xB2; 256]);
|
||||
let before = counters.metrics();
|
||||
|
||||
write(&managed, 0, &a);
|
||||
(managed.did_modify_range(0, 256)).unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
let event = device.new_shared_event().expect("an event");
|
||||
let held = queue.command_buffer().expect("a command buffer");
|
||||
(held.encode_wait_for_event(event.as_event(), 1)).expect("a wait");
|
||||
kernel(&held, &state, buffers);
|
||||
held.commit().expect("a commit");
|
||||
write(&managed, 0, &b);
|
||||
(managed.did_modify_range(0, 256)).unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
event.set_signaled_value(1);
|
||||
finished("the held kernel", &held);
|
||||
assert_eq!(held.error(), None, "{name}");
|
||||
let want = if copied { &a } else { &b };
|
||||
assert!(
|
||||
read(&out, 256) == *want,
|
||||
"{name}: the bytes at the commit (device copy: {copied})"
|
||||
);
|
||||
|
||||
write(&managed, 0, &a);
|
||||
(managed.did_modify_range(0, 256)).unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
write(&managed, 0, &b);
|
||||
let command_buffer = queue.command_buffer().expect("a command buffer");
|
||||
kernel(&command_buffer, &state, buffers);
|
||||
kernel(&command_buffer, &state, [&managed, &zero, &out]);
|
||||
command_buffer.commit().expect("a commit");
|
||||
finished("the kernel", &command_buffer);
|
||||
assert_eq!(command_buffer.error(), None, "{name}");
|
||||
assert!(
|
||||
read(&out, 256) == b,
|
||||
"{name}: the bytes written before the commit (device copy: {copied})"
|
||||
read(&out, 256) == a,
|
||||
"{name}: the bytes named before the commit (device copy: {copied})"
|
||||
);
|
||||
|
||||
// The first commit took the first range; the second, the range named twice, once.
|
||||
write(&managed, 0, &b);
|
||||
(managed.did_modify_range(0, 256)).unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
let event = device.new_shared_event().expect("an event");
|
||||
let held = queue.command_buffer().expect("a command buffer");
|
||||
(held.encode_wait_for_event(event.as_event(), 1)).expect("a wait");
|
||||
kernel(&held, &state, [&managed, &zero, &out]);
|
||||
held.commit().expect("a commit");
|
||||
drop(managed);
|
||||
(device.release_block(cpu)).unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
event.set_signaled_value(1);
|
||||
finished("the held kernel", &held);
|
||||
assert_eq!(held.error(), None, "{name}");
|
||||
assert!(
|
||||
read(&out, 256) == b,
|
||||
"{name}: the bytes named before the held commit, the consumer's handles gone \
|
||||
(device copy: {copied})"
|
||||
);
|
||||
|
||||
// Each commit took its range once.
|
||||
let metrics = counters.metrics();
|
||||
let captured = metrics.managed_bytes_captured - before.managed_bytes_captured;
|
||||
assert_eq!(captured, if copied { 512 } else { 0 }, "{name}: captured");
|
||||
println!("managed at commit: {name}: device copy {copied}; metrics {metrics:?}");
|
||||
drop((managed, zero, out, arena));
|
||||
(device.release_block(cpu)).unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
drop((command_buffer, held, event, queue, zero, out, arena));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -622,331 +615,133 @@ pub(crate) mod on_device {
|
||||
(managed, into, [cpu, side])
|
||||
}
|
||||
|
||||
/// The device's first named range makes the capture ring on the naming thread, never inside a
|
||||
/// commit, so a commit on another thread does not wait for the ring's allocation: with the
|
||||
/// making parked, another thread's commit of a command buffer with commands completes. Then
|
||||
/// the named range reaches the device copy at the naming thread's commit.
|
||||
/// A range of three 16 MiB units named arrives whole at one commit, copied on the GPU from the
|
||||
/// consumer's block: the commit takes no staging and allocates nothing. It prints the commit's
|
||||
/// time on the host.
|
||||
#[test]
|
||||
fn every_device_makes_the_capture_ring_outside_every_commit() {
|
||||
each_device("capture ring off the commit", |name, _, device| {
|
||||
fn every_device_copies_a_long_named_range_with_no_staging() {
|
||||
each_device("managed long range", |name, _, device| {
|
||||
if device.core().unified_memory() {
|
||||
println!("capture ring off the commit: {name}: no device copy");
|
||||
return;
|
||||
}
|
||||
let bytes: Vec<u8> = (0..LEN).map(|i| (i % 251) as u8).collect();
|
||||
let cpu = (device.take_block(MemoryClass::Shared, LEN))
|
||||
.unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
let side = (device.take_block(MemoryClass::Shared, LEN))
|
||||
.unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
let into = (device.new_buffer(side.id, 0, LEN, None))
|
||||
.unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
let managed = (new_managed(&device, cpu.id, 0, LEN, 0))
|
||||
.unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
write(&managed, 0, &bytes);
|
||||
let park = Arc::new(Barrier::new(2));
|
||||
*lock(&device.core().park_region) = Some(Arc::clone(&park));
|
||||
// The naming thread: its range named, then a commit that captures it.
|
||||
let namer = {
|
||||
let (device, managed, into) = (device.clone(), managed.clone(), into.clone());
|
||||
thread::spawn(move || {
|
||||
managed.did_modify_range(0, LEN).expect("the range named");
|
||||
let queue = device.new_command_queue(1).expect("a queue");
|
||||
let command_buffer = queue.command_buffer().expect("a command buffer");
|
||||
copy_out(&command_buffer, &managed, &into, 0, LEN);
|
||||
command_buffer.commit().expect("a commit");
|
||||
command_buffer
|
||||
})
|
||||
};
|
||||
// It is parked where the ring is made.
|
||||
park.wait();
|
||||
*lock(&device.core().park_region) = None;
|
||||
let other = {
|
||||
let device = device.clone();
|
||||
let done = Arc::new(AtomicBool::new(false));
|
||||
let committed = Arc::clone(&done);
|
||||
let thread = thread::spawn(move || {
|
||||
let mut arena = Arena::new(&device);
|
||||
let (from, to) = (arena.buffer(), arena.buffer());
|
||||
let queue = device.new_command_queue(1).expect("a queue");
|
||||
let command_buffer = queue.command_buffer().expect("a command buffer");
|
||||
copy_out(&command_buffer, &from, &to, 0, 256);
|
||||
command_buffer.commit().expect("a commit");
|
||||
finished("the other commit", &command_buffer);
|
||||
committed.store(true, Ordering::SeqCst);
|
||||
});
|
||||
within("another thread's commit while the ring is made", || {
|
||||
done.load(Ordering::SeqCst)
|
||||
});
|
||||
thread
|
||||
};
|
||||
park.wait();
|
||||
other.join().expect("the other commit");
|
||||
let command_buffer = namer.join().expect("the naming thread");
|
||||
finished("the capture", &command_buffer);
|
||||
assert_eq!(command_buffer.error(), None, "{name}");
|
||||
assert_eq!(read(&into, LEN as usize), bytes, "{name}: the named bytes");
|
||||
});
|
||||
}
|
||||
|
||||
/// A commit naming three times the capture ring with nothing held streams: each ring-full goes
|
||||
/// in a submission of its own, which the commit waits for, with no staging of its own; the
|
||||
/// ring is all the staging that lives, and the bytes arrive whole, twice. It prints the time
|
||||
/// in the commit split into host copies, waits and the rest, and a ring-full's copy alone
|
||||
/// timed on the GPU. Two commits of three quarters of the ring each, the first scheduled
|
||||
/// before the second's commit, arrive whole too, the second waiting for the first's copy.
|
||||
#[test]
|
||||
fn every_device_streams_a_capture_past_the_ring() {
|
||||
each_device("managed past the ring", |name, _, device| {
|
||||
if device.core().unified_memory() {
|
||||
println!("managed past the ring: {name}: no device copy");
|
||||
println!("managed long range: {name}: no device copy");
|
||||
return;
|
||||
}
|
||||
let counters = device.counters();
|
||||
let len = 3 * CAPTURE_LEN;
|
||||
let mut bytes: Vec<u8> = (0..len).map(|i| (i % 253) as u8).collect();
|
||||
let (managed, into, blocks) = named_whole(&device, name, len, &bytes);
|
||||
let queue = device.new_command_queue(4).expect("a queue");
|
||||
// Twice: the first commit's copies are the first to touch the ring and the device
|
||||
// copy, the second's are not.
|
||||
for pass in ["first", "again"] {
|
||||
if pass == "again" {
|
||||
(managed.did_modify_range(0, len))
|
||||
.unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
}
|
||||
let before = counters.metrics();
|
||||
let command_buffer = queue.command_buffer().expect("a command buffer");
|
||||
copy_out(&command_buffer, &managed, &into, 0, len);
|
||||
let began = Instant::now();
|
||||
command_buffer.commit().expect("a commit");
|
||||
let took = began.elapsed();
|
||||
let staged = counters.gauges().capture_bytes;
|
||||
finished("the copy", &command_buffer);
|
||||
assert_eq!(command_buffer.error(), None, "{name}");
|
||||
assert!(
|
||||
read(&into, len as usize) == bytes,
|
||||
"{name}: the bytes past the ring"
|
||||
);
|
||||
let metrics = counters.metrics();
|
||||
let delta = |of: fn(&crate::Metrics) -> u64| of(&metrics) - of(&before);
|
||||
let streams = delta(|m| m.capture_streams);
|
||||
println!(
|
||||
"managed past the ring: {name}: {pass}: commit of {} MiB took {:.2} ms \
|
||||
({:.2} GB/s): host copies {:.2} ms, waits {:.2} ms ({:.2} ms a stream), \
|
||||
the rest {:.2} ms; streams {streams}, waits {}, staging {} MiB",
|
||||
len >> 20,
|
||||
took.as_secs_f64() * 1e3,
|
||||
len as f64 / took.as_secs_f64() / 1e9,
|
||||
delta(|m| m.capture_copy_nanos) as f64 / 1e6,
|
||||
delta(|m| m.capture_wait_nanos) as f64 / 1e6,
|
||||
delta(|m| m.capture_wait_nanos) as f64 / 1e6 / streams.max(1) as f64,
|
||||
(took.as_nanos() as f64
|
||||
- (delta(|m| m.capture_copy_nanos) + delta(|m| m.capture_wait_nanos))
|
||||
as f64)
|
||||
/ 1e6,
|
||||
delta(|m| m.capture_waits),
|
||||
staged >> 20
|
||||
);
|
||||
assert_eq!(
|
||||
delta(|m| m.managed_bytes_captured),
|
||||
len,
|
||||
"{name}: every byte once"
|
||||
);
|
||||
assert!(streams >= 2, "{name}: streamed");
|
||||
assert_eq!(delta(|m| m.capture_overflows), 0, "{name}: nothing held");
|
||||
assert_eq!(staged, CAPTURE_LEN, "{name}: the ring alone");
|
||||
}
|
||||
|
||||
// Two commits of three quarters each.
|
||||
let part = CAPTURE_LEN / 4 * 3;
|
||||
let before = counters.metrics();
|
||||
let mut commits = Vec::new();
|
||||
for (index, fill) in [0x3C_u8, 0xC3].into_iter().enumerate() {
|
||||
let at = index as u64 * part;
|
||||
bytes[at as usize..(at + part) as usize].fill(fill);
|
||||
write(&managed, at, &bytes[at as usize..(at + part) as usize]);
|
||||
(managed.did_modify_range(at, part))
|
||||
.unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
let command_buffer = queue.command_buffer().expect("a command buffer");
|
||||
copy_out(&command_buffer, &managed, &into, at, part);
|
||||
// The time in the commit: the capture's copy into the ring, and for the second a
|
||||
// wait for the first's copy where it was still running.
|
||||
let began = Instant::now();
|
||||
command_buffer.commit().expect("a commit");
|
||||
let took = began.elapsed();
|
||||
println!(
|
||||
"managed past the ring: {name}: commit {index} of {} MiB took {:.2} ms \
|
||||
({:.2} GB/s), waits {}",
|
||||
part >> 20,
|
||||
took.as_secs_f64() * 1e3,
|
||||
part as f64 / took.as_secs_f64() / 1e9,
|
||||
counters.metrics().capture_waits
|
||||
);
|
||||
command_buffer
|
||||
.wait_until_scheduled()
|
||||
.expect("a wait outside a scheduled handler");
|
||||
commits.push(command_buffer);
|
||||
}
|
||||
for command_buffer in &commits {
|
||||
finished("a part", command_buffer);
|
||||
assert_eq!(command_buffer.error(), None, "{name}");
|
||||
}
|
||||
assert!(
|
||||
read(&into, (2 * part) as usize) == bytes[..(2 * part) as usize],
|
||||
"{name}: the two parts"
|
||||
);
|
||||
let metrics = counters.metrics();
|
||||
let captured = metrics.managed_bytes_captured - before.managed_bytes_captured;
|
||||
assert_eq!(captured, 2 * part, "{name}: every byte once");
|
||||
assert_eq!(
|
||||
metrics.capture_overflows, before.capture_overflows,
|
||||
"{name}"
|
||||
);
|
||||
println!("managed past the ring: {name}: metrics {metrics:?}");
|
||||
|
||||
// The link a stream's copy crosses: a ring-full's bytes copied from a Shared buffer
|
||||
// into the device copy, alone in a command buffer, timed on the GPU, twice.
|
||||
for pass in ["first", "again"] {
|
||||
let command_buffer = queue.command_buffer().expect("a command buffer");
|
||||
copy_out(&command_buffer, &into, &managed, 0, CAPTURE_LEN);
|
||||
let began = Instant::now();
|
||||
command_buffer.commit().expect("a commit");
|
||||
finished("the link's copy", &command_buffer);
|
||||
let host = began.elapsed();
|
||||
assert_eq!(command_buffer.error(), None, "{name}");
|
||||
let gpu = command_buffer.gpu_end_time() - command_buffer.gpu_start_time();
|
||||
println!(
|
||||
"managed past the ring: {name}: link {pass}: {} MiB from a Shared buffer \
|
||||
into the device copy took {:.2} ms on the GPU ({:.2} GB/s), {:.2} ms from \
|
||||
the commit to its completion seen",
|
||||
CAPTURE_LEN >> 20,
|
||||
gpu as f64 / 1e6,
|
||||
CAPTURE_LEN as f64 / gpu as f64,
|
||||
host.as_secs_f64() * 1e3
|
||||
);
|
||||
}
|
||||
drop((managed, into, commits, queue));
|
||||
for block in blocks {
|
||||
(device.release_block(block)).unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// A commit naming three times the capture ring waits once for each ring-full it sends, though
|
||||
/// the completion thread sees no completion meanwhile (as on a loaded host): the wait frees the
|
||||
/// spans of the submission it waited for, so the capture never waits again for one that has
|
||||
/// completed. The bytes arrive whole.
|
||||
#[test]
|
||||
fn every_device_waits_once_for_each_ring_full_while_completions_lag() {
|
||||
each_device("one wait a ring-full", |name, _, device| {
|
||||
if device.core().unified_memory() {
|
||||
println!("one wait a ring-full: {name}: no device copy");
|
||||
return;
|
||||
}
|
||||
let counters = device.counters();
|
||||
let len = 3 * CAPTURE_LEN;
|
||||
device.core().pool.await_internals();
|
||||
let len = 3 * MemoryClass::Shared.block_len();
|
||||
let bytes: Vec<u8> = (0..len).map(|i| (i % 251) as u8).collect();
|
||||
let (managed, into, blocks) = named_whole(&device, name, len, &bytes);
|
||||
let queue = device.new_command_queue(4).expect("a queue");
|
||||
let queue = device.new_command_queue(1).expect("a queue");
|
||||
let command_buffer = queue.command_buffer().expect("a command buffer");
|
||||
copy_out(&command_buffer, &managed, &into, 0, len);
|
||||
// Another thread holds the completion thread for a while; the commit runs inside it.
|
||||
let core = Arc::clone(device.core());
|
||||
let (held, holding) = std::sync::mpsc::channel();
|
||||
let holder = thread::spawn(move || {
|
||||
let hold = core.hold_completions.write().expect("the hold");
|
||||
held.send(()).expect("the test");
|
||||
thread::sleep(std::time::Duration::from_millis(300));
|
||||
drop(hold);
|
||||
});
|
||||
holding.recv().expect("the hold taken");
|
||||
let before = counters.metrics();
|
||||
let before = (counters.metrics(), counters.gauges().staging_bytes);
|
||||
let began = Instant::now();
|
||||
command_buffer.commit().expect("a commit");
|
||||
let metrics = counters.metrics();
|
||||
holder.join().expect("the holder");
|
||||
let commit = began.elapsed();
|
||||
let after = (counters.metrics(), counters.gauges().staging_bytes);
|
||||
finished("the copy", &command_buffer);
|
||||
assert_eq!(command_buffer.error(), None, "{name}");
|
||||
let delta = |of: fn(&crate::Metrics) -> u64| of(&metrics) - of(&before);
|
||||
let (streams, waits) = (delta(|m| m.capture_streams), delta(|m| m.capture_waits));
|
||||
println!("one wait a ring-full: {name}: streams {streams}, waits {waits}");
|
||||
assert!(streams >= 2, "{name}: streamed");
|
||||
assert_eq!(waits, streams, "{name}: one wait a ring-full");
|
||||
assert!(read(&into, len as usize) == bytes, "{name}: the bytes");
|
||||
drop((managed, into, command_buffer, queue));
|
||||
assert!(
|
||||
read(&into, len as usize) == bytes,
|
||||
"{name}: the named bytes"
|
||||
);
|
||||
assert_eq!(
|
||||
after.0.managed_bytes_captured - before.0.managed_bytes_captured,
|
||||
len,
|
||||
"{name}: captured"
|
||||
);
|
||||
assert_eq!(
|
||||
(after.0.consumer_allocations, after.1),
|
||||
(before.0.consumer_allocations, before.1),
|
||||
"{name}: the commit takes no staging and allocates nothing"
|
||||
);
|
||||
println!(
|
||||
"managed long range: {name}: {} MiB named, the commit {:.3} ms on the host",
|
||||
len >> 20,
|
||||
commit.as_secs_f64() * 1e3
|
||||
);
|
||||
drop((command_buffer, queue, managed, into));
|
||||
for block in blocks {
|
||||
(device.release_block(block)).unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// A commit naming more than the ring behind a command buffer that waits on an event the host
|
||||
/// has not signalled, committed before the bytes were named, cannot send its ring-full ahead:
|
||||
/// the rest takes staging of its own, the
|
||||
/// command buffer reads the bytes of its commit, not those written and named after it, and the
|
||||
/// staging goes back once it retires.
|
||||
/// A Managed buffer over an imported dma-buf, a block the runtime does not map: the buffer
|
||||
/// has no `contents`, and the consumer writes the pages through its own mapping (here the
|
||||
/// memfd behind the dma-buf). Written and named, a kernel committed after reads the bytes,
|
||||
/// with a device copy or without; written and named again, the next one reads the new bytes.
|
||||
/// A device that imports no such dma-buf is passed over, as the import tests check its
|
||||
/// refusal.
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn every_device_takes_staging_of_its_own_behind_a_held_command_buffer() {
|
||||
each_device("managed behind a hold", |name, _, device| {
|
||||
if device.core().unified_memory() {
|
||||
println!("managed behind a hold: {name}: no device copy");
|
||||
fn every_device_makes_a_managed_buffer_over_an_imported_dma_buf() {
|
||||
use crate::tests::import::on_device::{memfd, udmabuf};
|
||||
use crate::{ImportHandle, Limit};
|
||||
use std::os::unix::fs::FileExt;
|
||||
each_device("managed over a dma-buf", |name, _, device| {
|
||||
const LEN: u64 = 64 << 10;
|
||||
let copied = !device.core().unified_memory();
|
||||
let memfd = memfd(LEN);
|
||||
let Some(fd) = udmabuf(&memfd, 0, LEN) else {
|
||||
println!("managed over a dma-buf: {name}: no /dev/udmabuf here; not run");
|
||||
return;
|
||||
}
|
||||
let counters = device.counters();
|
||||
let len = CAPTURE_LEN / 2 * 3;
|
||||
let first = vec![0xA1; len as usize];
|
||||
let queue = device.new_command_queue(4).expect("a queue");
|
||||
let event = device.new_shared_event().expect("an event");
|
||||
let held = queue.command_buffer().expect("a command buffer");
|
||||
(held.encode_wait_for_event(event.as_event(), 1)).expect("a wait");
|
||||
// Committed before the buffer's bytes are named, so its own capture takes none.
|
||||
held.commit().expect("a commit");
|
||||
let (managed, into, blocks) = named_whole(&device, name, len, &first);
|
||||
let before = counters.metrics();
|
||||
let command_buffer = queue.command_buffer().expect("a command buffer");
|
||||
copy_out(&command_buffer, &managed, &into, 0, len);
|
||||
command_buffer.commit().expect("a commit");
|
||||
let staged = counters.gauges().capture_bytes;
|
||||
write(&managed, 0, &vec![0xB2; len as usize]);
|
||||
(managed.did_modify_range(0, len)).unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
event.set_signaled_value(1);
|
||||
for command_buffer in [&held, &command_buffer] {
|
||||
finished("behind the hold", command_buffer);
|
||||
assert_eq!(command_buffer.error(), None, "{name}");
|
||||
}
|
||||
assert!(
|
||||
read(&into, len as usize) == first,
|
||||
"{name}: the bytes at the commit"
|
||||
);
|
||||
let metrics = counters.metrics();
|
||||
let delta = |of: fn(&crate::Metrics) -> u64| of(&metrics) - of(&before);
|
||||
println!(
|
||||
"managed behind a hold: {name}: overflows {}, {} MiB of its own; staging {} MiB",
|
||||
delta(|m| m.capture_overflows),
|
||||
delta(|m| m.capture_overflow_bytes) >> 20,
|
||||
staged >> 20
|
||||
);
|
||||
assert_eq!(delta(|m| m.capture_overflows), 1, "{name}: one overflow");
|
||||
};
|
||||
let block = match device.import_dma_buf(fd, LEN, None) {
|
||||
Ok((block, _)) => block,
|
||||
Err(
|
||||
error @ Error::Limit(
|
||||
Limit::NoImport {
|
||||
handle: ImportHandle::DmaBuf,
|
||||
}
|
||||
| Limit::ImportType {
|
||||
handle: ImportHandle::DmaBuf,
|
||||
..
|
||||
},
|
||||
),
|
||||
) => {
|
||||
println!(
|
||||
"managed over a dma-buf: {name}: not imported here ({error}); not run"
|
||||
);
|
||||
return;
|
||||
}
|
||||
Err(error) => panic!("{name}: the import: {error}"),
|
||||
};
|
||||
assert_eq!(
|
||||
delta(|m| m.capture_overflow_bytes),
|
||||
len - CAPTURE_LEN,
|
||||
"{name}: what the ring did not take"
|
||||
(block.class, block.contents),
|
||||
(MemoryClass::Shared, None),
|
||||
"{name}: an imported dma-buf's block, Shared and not mapped by the runtime"
|
||||
);
|
||||
assert_eq!(
|
||||
delta(|m| m.managed_bytes_captured),
|
||||
len,
|
||||
"{name}: every byte once"
|
||||
);
|
||||
assert!(
|
||||
staged > CAPTURE_LEN,
|
||||
"{name}: the ring and staging of its own"
|
||||
);
|
||||
drop((held, command_buffer));
|
||||
within("the staging given back", || {
|
||||
counters.gauges().capture_bytes == CAPTURE_LEN
|
||||
let mut arena = Arena::new(&device);
|
||||
let (zero, out) = (arena.buffer(), arena.buffer());
|
||||
let managed = (new_managed(&device, block.id, 0, 256, 0)).unwrap_or_else(|error| {
|
||||
panic!("{name}: a Managed buffer over the import: {error}")
|
||||
});
|
||||
drop((managed, into, queue, event));
|
||||
for block in blocks {
|
||||
(device.release_block(block)).unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
assert!(
|
||||
managed.contents().is_none(),
|
||||
"{name}: no mapping of the runtime's"
|
||||
);
|
||||
let state = add(&device);
|
||||
let queue = device.new_command_queue(4).expect("a queue");
|
||||
let pages = std::fs::File::from(memfd);
|
||||
for word in [0xA1u8, 0xB2] {
|
||||
let bytes = vec![word; 256];
|
||||
(pages.write_all_at(&bytes, 0)).expect("the consumer's write");
|
||||
(managed.did_modify_range(0, 256))
|
||||
.unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
let command_buffer = queue.command_buffer().expect("a command buffer");
|
||||
kernel(&command_buffer, &state, [&managed, &zero, &out]);
|
||||
command_buffer.commit().expect("a commit");
|
||||
finished("the kernel", &command_buffer);
|
||||
assert_eq!(command_buffer.error(), None, "{name}");
|
||||
assert!(
|
||||
read(&out, 256) == bytes,
|
||||
"{name}: the bytes written through the consumer's mapping, {word:#x} \
|
||||
(device copy: {copied})"
|
||||
);
|
||||
}
|
||||
println!("managed over a dma-buf: {name}: read twice (device copy: {copied})");
|
||||
drop((managed, queue, zero, out, arena));
|
||||
(device.release_block(block)).unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@
|
||||
|
||||
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
|
||||
mod on_device {
|
||||
use crate::capture::CAPTURE_LEN;
|
||||
use crate::fill::ZEROS;
|
||||
use crate::memory::MakerTest;
|
||||
use crate::ring::{Writes, CHUNK};
|
||||
@@ -19,14 +18,13 @@ mod on_device {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
|
||||
/// Each site's counter in `metrics`, by name.
|
||||
fn sites(metrics: &Metrics) -> [(&'static str, SiteAllocations); 8] {
|
||||
fn sites(metrics: &Metrics) -> [(&'static str, SiteAllocations); 7] {
|
||||
[
|
||||
("texture", metrics.texture_allocations),
|
||||
("texture block", metrics.texture_block_allocations),
|
||||
("ring block", metrics.ring_block_allocations),
|
||||
("staging region", metrics.staging_region_allocations),
|
||||
("staging buffer", metrics.staging_buffer_allocations),
|
||||
("capture ring", metrics.capture_ring_allocations),
|
||||
("zero source", metrics.zero_source_allocations),
|
||||
("take", metrics.take_allocations),
|
||||
]
|
||||
@@ -265,8 +263,8 @@ mod on_device {
|
||||
);
|
||||
});
|
||||
|
||||
// A device that keeps a device copy of a Managed buffer makes the capture ring at the
|
||||
// first range named; one that keeps none names nothing.
|
||||
// A Managed buffer's first named range allocates nothing, with a device copy or without:
|
||||
// the commit copies it from the consumer's block.
|
||||
let two = !device.has_unified_memory();
|
||||
let copy = two.then(|| {
|
||||
(device.take_block(MemoryClass::Private, 4096 + 4096))
|
||||
@@ -277,15 +275,11 @@ mod on_device {
|
||||
let at = copy.as_ref().map(|copy| (copy.id, 4096));
|
||||
let managed = (device.new_managed_buffer((bytes_block.id, 0), at, 4096, 0))
|
||||
.unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
let expected: &[(&str, u64)] = match two {
|
||||
true => &[("capture ring", CAPTURE_LEN)],
|
||||
false => &[],
|
||||
};
|
||||
step(
|
||||
name,
|
||||
device,
|
||||
"a Managed buffer's first named range",
|
||||
expected,
|
||||
&[],
|
||||
|| {
|
||||
(managed.did_modify_range(0, 4096))
|
||||
.unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
|
||||
@@ -746,7 +746,6 @@ fn named(gauges: rt::Gauges) -> Vec<(&'static str, u64)> {
|
||||
"private_long_reused_bytes",
|
||||
gauges.private_long_reused_bytes,
|
||||
),
|
||||
("capture_bytes", gauges.capture_bytes),
|
||||
("staging_bytes", gauges.staging_bytes),
|
||||
("stage_entries", gauges.stage_entries),
|
||||
("stage_entry_bytes", gauges.stage_entry_bytes),
|
||||
@@ -2628,12 +2627,6 @@ impl Backend for NewRuntime {
|
||||
("staging_sleeps", metrics.staging_sleeps),
|
||||
("synchronizations", metrics.synchronizations),
|
||||
("managed_bytes_captured", metrics.managed_bytes_captured),
|
||||
("capture_waits", metrics.capture_waits),
|
||||
("capture_streams", metrics.capture_streams),
|
||||
("capture_overflows", metrics.capture_overflows),
|
||||
("capture_overflow_bytes", metrics.capture_overflow_bytes),
|
||||
("capture_copy_nanos", metrics.capture_copy_nanos),
|
||||
("capture_wait_nanos", metrics.capture_wait_nanos),
|
||||
("stamps_not_available", metrics.stamps_not_available),
|
||||
("waits_behind_counter", metrics.waits_behind_counter),
|
||||
("external_acquires", metrics.external_acquires),
|
||||
@@ -2703,7 +2696,6 @@ impl Backend for NewRuntime {
|
||||
"private_long_reused_bytes",
|
||||
gauges.private_long_reused_bytes,
|
||||
),
|
||||
("capture_bytes", gauges.capture_bytes),
|
||||
("staging_bytes", gauges.staging_bytes),
|
||||
("stage_entries", gauges.stage_entries),
|
||||
("stage_entry_bytes", gauges.stage_entry_bytes),
|
||||
|
||||
@@ -2321,7 +2321,6 @@ field metal2vulkan-rt::FunctionDescriptor.specialized pub specialized: bool
|
||||
field metal2vulkan-rt::Gauges.attachment_views pub attachment_views: u64
|
||||
field metal2vulkan-rt::Gauges.blocks pub blocks: u64
|
||||
field metal2vulkan-rt::Gauges.buffers pub buffers: u64
|
||||
field metal2vulkan-rt::Gauges.capture_bytes pub capture_bytes: u64
|
||||
field metal2vulkan-rt::Gauges.command_buffers pub command_buffers: u64
|
||||
field metal2vulkan-rt::Gauges.descriptor_slots pub descriptor_slots: u64
|
||||
field metal2vulkan-rt::Gauges.device_samplers pub device_samplers: u64
|
||||
@@ -2382,13 +2381,6 @@ field metal2vulkan-rt::Metrics.bytes_copied pub bytes_copied: u64
|
||||
field metal2vulkan-rt::Metrics.bytes_zeroed pub bytes_zeroed: u64
|
||||
field metal2vulkan-rt::Metrics.cache_bytes_written pub cache_bytes_written: u64
|
||||
field metal2vulkan-rt::Metrics.cache_writes_dropped pub cache_writes_dropped: u64
|
||||
field metal2vulkan-rt::Metrics.capture_copy_nanos pub capture_copy_nanos: u64
|
||||
field metal2vulkan-rt::Metrics.capture_overflow_bytes pub capture_overflow_bytes: u64
|
||||
field metal2vulkan-rt::Metrics.capture_overflows pub capture_overflows: u64
|
||||
field metal2vulkan-rt::Metrics.capture_ring_allocations pub capture_ring_allocations: SiteAllocations
|
||||
field metal2vulkan-rt::Metrics.capture_streams pub capture_streams: u64
|
||||
field metal2vulkan-rt::Metrics.capture_wait_nanos pub capture_wait_nanos: u64
|
||||
field metal2vulkan-rt::Metrics.capture_waits pub capture_waits: u64
|
||||
field metal2vulkan-rt::Metrics.commit_lock_wait_max_nanos pub commit_lock_wait_max_nanos: u64
|
||||
field metal2vulkan-rt::Metrics.commit_lock_wait_nanos pub commit_lock_wait_nanos: u64
|
||||
field metal2vulkan-rt::Metrics.consumer_allocation_max_nanos pub consumer_allocation_max_nanos: u64
|
||||
@@ -14040,7 +14032,7 @@ variant metal2vulkan-rt::Refusal::IndicesGranted IndicesGranted { class: IndexCl
|
||||
variant metal2vulkan-rt::Refusal::IndicesInUse IndicesInUse { class: IndexClass, index: u32 }
|
||||
variant metal2vulkan-rt::Refusal::IndicesNotGranted IndicesNotGranted { class: IndexClass, index: u32 }
|
||||
variant metal2vulkan-rt::Refusal::IndirectOffset IndirectOffset { offset: u64, length: u64 }
|
||||
variant metal2vulkan-rt::Refusal::ManagedBlockNotShared ManagedBlockNotShared { block: BlockId }
|
||||
variant metal2vulkan-rt::Refusal::ManagedBlockPrivate ManagedBlockPrivate { block: BlockId }
|
||||
variant metal2vulkan-rt::Refusal::ManagedCopyMissing ManagedCopyMissing
|
||||
variant metal2vulkan-rt::Refusal::ManagedCopyNotPrivate ManagedCopyNotPrivate { block: BlockId }
|
||||
variant metal2vulkan-rt::Refusal::ManagedCopyOnUnified ManagedCopyOnUnified
|
||||
|
||||
|
Can't render this file because it is too large.
|
+3
-3
@@ -55,7 +55,7 @@ Columns:
|
||||
| What a call did wrong | 22 | 3 | 5 | 0 | 18 | 8 | 17 | 0 |
|
||||
| What a call did wrong, in detail | 60 | 26 | 23 | 0 | 39 | 26 | 0 | 0 |
|
||||
| Devices below the new runtime's floor | 0 | 0 | 0 | 8 | 0 | 0 | 0 | 0 |
|
||||
| The new runtime's `Refusal` | 20 | 17 | 0 | 0 | 36 | 0 | 0 | 0 |
|
||||
| The new runtime's `Refusal` | 20 | 18 | 0 | 0 | 35 | 0 | 0 | 0 |
|
||||
| The new runtime's `Limit` | 0 | 0 | 0 | 13 | 4 | 0 | 0 | 0 |
|
||||
| The new runtime's `Gap` | 0 | 0 | 0 | 1 | 27 | 0 | 0 | 0 |
|
||||
|
||||
@@ -620,7 +620,7 @@ Columns:
|
||||
| `BufferTooLong` | A buffer longer than `MAX_BUFFER_LENGTH` (`Device::new_buffer`) | every device (a public call's own check of its arguments) | `ours`: this crate's cap: a buffer's every byte lies within 2^31 bytes of each bind address in it | 2: `crates/metal2vulkan-rt/src/buffer.rs (new_managed_buffer)`, `crates/metal2vulkan-rt/src/buffer.rs (placed_buffer)` | `-` |
|
||||
| `BufferPastBlock` | A buffer whose range leaves its block (`Device::new_buffer`) | every device (a public call's own check of its arguments) | `metal-measured`: an Apple M3 Max, macOS 27.0.1: a placement heap of 1 MiB answers nil for a 4096-byte buffer at offset 1,047,552 | 1: `crates/metal2vulkan-rt/src/buffer.rs (placed)` | `-` |
|
||||
| `HeapBufferPlace` | A heap buffer whose range leaves its heap (`Device::new_heap_buffer`) | every device (a public call's own check of its arguments) | `metal-measured`: an Apple M3 Max, macOS 27.0.1: a placement heap of 1 MiB answers nil for a 4096-byte buffer at offset 1,047,552 | 1: `crates/metal2vulkan-rt/src/buffer.rs (new_heap_buffer)` | `-` |
|
||||
| `ManagedBlockNotShared` | A Managed buffer whose bytes are in a block the host does not map, a Private block (`Device::new_managed_buffer`) | every device (a public call's own check of its arguments) | `ours`: a Managed buffer's bytes are the consumer's, which the host reaches through the block's mapping; a Private block has none | 1: `crates/metal2vulkan-rt/src/buffer.rs (new_managed_buffer)` | `-` |
|
||||
| `ManagedBlockPrivate` | A Managed buffer whose bytes are in a Private block (`Device::new_managed_buffer`) | every device (a public call's own check of its arguments) | `metal-documented`: a Managed buffer has a CPU-side copy: `MTLBuffer.h` gives its `contents` as "the data pointer of this buffer's shared copy", and `didModifyRange:` names the ranges "the CPU has modified" | 1: `crates/metal2vulkan-rt/src/buffer.rs (new_managed_buffer)` | `-` |
|
||||
| `ManagedCopyMissing` | A Managed buffer given no place for its device copy on a device that keeps one, where `Device::has_unified_memory` is false... | every device (a public call's own check of its arguments) | `ours`: Metal keeps a Managed buffer's second copy on a Mac with a discrete GPU; the consumer places it, as it places every buffer | 1: `crates/metal2vulkan-rt/src/buffer.rs (new_managed_buffer)` | `-` |
|
||||
| `ManagedCopyOnUnified` | A Managed buffer given a place for a device copy on a device that keeps none, where `Device::has_unified_memory` is true... | every device (a public call's own check of its arguments) | `ours`: on unified memory a Managed buffer is its bytes, as Metal keeps one copy of a Managed buffer on Apple silicon | 1: `crates/metal2vulkan-rt/src/buffer.rs (new_managed_buffer)` | `-` |
|
||||
| `ManagedCopyNotPrivate` | A Managed buffer whose device copy is placed in a block that is not Private (`Device::new_managed_buffer`) | every device (a public call's own check of its arguments) | `ours`: shaders reach the device copy in Private memory, device-local where it has room, as a discrete GPU's Metal keeps the copy in its own memory | 1: `crates/metal2vulkan-rt/src/buffer.rs (new_managed_buffer)` | `-` |
|
||||
@@ -1239,7 +1239,7 @@ Each refusal's sites, with the function that builds it.
|
||||
- `rt:Refusal::BufferTooLong`: `crates/metal2vulkan-rt/src/buffer.rs (new_managed_buffer)`; `crates/metal2vulkan-rt/src/buffer.rs (placed_buffer)`
|
||||
- `rt:Refusal::BufferPastBlock`: `crates/metal2vulkan-rt/src/buffer.rs (placed)`
|
||||
- `rt:Refusal::HeapBufferPlace`: `crates/metal2vulkan-rt/src/buffer.rs (new_heap_buffer)`
|
||||
- `rt:Refusal::ManagedBlockNotShared`: `crates/metal2vulkan-rt/src/buffer.rs (new_managed_buffer)`
|
||||
- `rt:Refusal::ManagedBlockPrivate`: `crates/metal2vulkan-rt/src/buffer.rs (new_managed_buffer)`
|
||||
- `rt:Refusal::ManagedCopyMissing`: `crates/metal2vulkan-rt/src/buffer.rs (new_managed_buffer)`
|
||||
- `rt:Refusal::ManagedCopyOnUnified`: `crates/metal2vulkan-rt/src/buffer.rs (new_managed_buffer)`
|
||||
- `rt:Refusal::ManagedCopyNotPrivate`: `crates/metal2vulkan-rt/src/buffer.rs (new_managed_buffer)`
|
||||
|
||||
Reference in new issue
Block a user