rt: a release waits for the command buffers committed before it, one commit-order mark for textures, samplers, idle allocations and imports
What: one mark (memory::Wait) for everything a command buffer may reach with no handle of it.
A release notes the last commit's place in the commit order. It goes once every command buffer
committed up to there is submitted (Work::settled) and that submission completed. With none in
flight (a count kept from commit to retire) it goes at once, as before.
- What waits:
- a texture's index (its set-1 elements), views and image, and its shadow view;
- a texture view's views;
- a sampler state's index and its device samplers;
- an idle allocation's free;
- an imported or exported block's free, and with it the import's release.
- How the objects and indices go: the block-maker thread holds them in one FIFO (Pool::release)
and hands each to the reaper once its wait is over; teardown frees what is left. With nothing
in flight, an index is vacated on the releasing thread, so its grant may be returned at once.
- What is unchanged: a displaced index; attachment views, pipelines and modules, which their
command buffers keep. The loose memory (texture allocations, surface plane imports, copies'
staging) takes no second wait: it comes from the reaper's frees, or from copies.
- New: Gauges::releases_waiting counts what waits. Every device test's teardown reads it zero, and
the harness compares it at runs 100 and 200.
- Consumer-visible: Gauges gains a field (non_exhaustive, so nothing breaks). release_indices
refuses IndicesInUse for an index whose texture or sampler state was released under work in
flight, until that work retires (docs/REFUSALS.md regenerated). A command buffer parked at an
event wait holds every such release after its commit until it retires (README, in the memory
and the set-1 paragraphs).
- Docs: new_texture's doc and the README take the new contract and Metal's own answers (the
consumer's game tool on two Macs, from main), and api_signatures.tsv is blessed for the field.
- Test: one ordinary test, argument_tier's held release. A command buffer at an event wait holds
a 17 MiB allocation's free and a released texture's index past twice the idle age; once it
retires, both go. The two hazard tests of the commit before run on a CPU device always, and
pass only with this.
Why: the consumer's game step loses the device on RTX 3090s (Xid 13, MMU faults). The game tool
remakes heap textures every frame and drops the old ones at once, while the frame in flight still
samples them through set 1 by resource ID, naming only the heap. Before this, rt nulled the
elements and destroyed the views and image at once, under that pass.
Product lines (comments left out): +171 -23 in crates/metal2vulkan-runtime/src.
Verified at this commit: cargo fmt; scripts/api-signatures --check after its bless (the one new
line is Gauges.releases_waiting); docs/REFUSALS.md regenerated (IndicesInUse's row). Before-run on
ms01's RTX 3090 at 2d0c57661d (job m3-max-62569): the address test (argument_tier) hung the GPU
(Xid 109 CTX SWITCH TIMEOUT, no loss rt saw, Xid 31 at teardown). The texture test showed no Xid,
and its lines were lost (the leg's buffered pipe). Its gate and its after-fix hazard run follow
this commit; main's landing names them.
This commit is contained in:
1 parent
33e402b518
commit
39b0efc6e7
14 files changed
+338
-45
No files matched your search
@@ -324,8 +324,14 @@ in its memory.
|
||||
An allocation that holds no block anyone holds is idle. Its idle time starts when its last block
|
||||
comes back, and only a take that lands in it again ends it. The idle age is 250 ms, on every
|
||||
device: the block-maker thread frees each allocation idle that long, one at a time, after
|
||||
`BlockMappings::unmap` of it, whatever the device's queues are doing, so a program that keeps
|
||||
committing gives back what it stopped using within 250 ms plus the frees ahead of it. The
|
||||
`BlockMappings::unmap` of it, once every command buffer committed before it went idle has
|
||||
retired. Memory a command buffer reaches by address alone (a heap's buffers through an argument
|
||||
buffer, with no handle of them) is so never freed while work committed before its release is
|
||||
unretired; a range of it taken again meanwhile still gives such a reader the new block's bytes.
|
||||
So a program that keeps committing gives back what it stopped using within 250 ms plus the
|
||||
frees ahead of it and the work in flight at its release. A command buffer that waits at an event
|
||||
(`CommandBuffer::encode_wait_for_event`) holds every such free released after its commit until
|
||||
it retires, as a free waits for the command buffers committed before it in commit order. The
|
||||
harness's own rows `idle_frees` and `idle_frees_under_commits` hold each free, measured alone,
|
||||
to begin within 25 ms of its idle age, with no commits and with one every 2 ms. It frees
|
||||
between the allocations it makes, never beside one. Each class keeps a reserve that the idle
|
||||
@@ -346,7 +352,9 @@ in its memory.
|
||||
free ranges between blocks; `shared_buffer_bytes` and `private_buffer_bytes` count live buffers'
|
||||
lengths by their block's class, `texture_block_bytes` the placed textures' image sizes and
|
||||
`texture_own_bytes` textures' allocations of their own, and `import_bytes` and
|
||||
`surface_import_bytes` the imports' and the surface plane imports' bytes. The texture blocks
|
||||
`surface_import_bytes` the imports' and the surface plane imports' bytes; `releases_waiting`
|
||||
counts the releases of textures and sampler states that wait for work in flight (Set 1 and
|
||||
index grants). The texture blocks
|
||||
and the allocations holding the consumer's Private blocks are counted apart, as nothing moves
|
||||
a live texture or block and a block or allocation goes back only once it holds nothing:
|
||||
`texture_block_held_bytes` counts the texture blocks whole (the one kept empty among them) and
|
||||
@@ -543,7 +551,8 @@ list a handle's extensions, or whose buffers do not import it, refuses that call
|
||||
An imported block is Shared, and is the whole of an allocation of its own, whose number
|
||||
(`BlockInfo::allocation`) no hook is told of. Each import is one `VkDeviceMemory` allocation and
|
||||
counts against the device's allocations; `Gauges::imports` counts those live. The block lives
|
||||
until its last handle and its last buffer, command buffer or upload are gone; then the block-maker
|
||||
until its last handle and its last buffer, command buffer or upload are gone, and every command
|
||||
buffer committed before then has retired (one may reach it by address alone); then the block-maker
|
||||
thread frees its memory, which ends the import, and runs `release`, Metal's deallocator, after it
|
||||
(at teardown, on the thread that tears down). Neither `BlockMappings` hook runs for an imported
|
||||
block.
|
||||
@@ -1114,8 +1123,17 @@ made, with no lock, and never rewritten for layouts.
|
||||
takes the ID: the new object writes its elements (a texture with no storage view writes its
|
||||
storage element null where it took the index from another, so nothing stale answers there),
|
||||
and the earlier object's going, at its release or once its command buffers retire, touches
|
||||
neither the index nor its elements. No work in flight may read a displaced or released object
|
||||
through the index: the program's duty, as it is Metal's, which the runtime does not check. A
|
||||
neither the index nor its elements. No work in flight may read a displaced object through the
|
||||
index: the program's duty, as it is Metal's, which the runtime does not check. A released one
|
||||
it may: a texture's index, elements, views and image, a texture view's views, and a sampler
|
||||
state's index and device samplers go once every command buffer committed before the release
|
||||
has retired, at once where none is in flight, so that work reads them as they were
|
||||
(`Gauges::releases_waiting` counts what waits). Metal leaves that read undefined: a program that
|
||||
released textures a frame in flight still sampled finished every run with no command buffer
|
||||
error on two Macs, with the answer it gave with the textures held on a Radeon Pro 5300M, and one
|
||||
a few channel levels off it, differing from run to run, on an Apple M3 Max. The runtime gives
|
||||
the first answer. As with memory, a command
|
||||
buffer that waits at an event holds every such release after its commit until it retires. A
|
||||
sampler state or constexpr sampler whose device samplers equal the displaced one's is safe under
|
||||
work in flight: equal create infos share the device's `VkSampler`s, the arrays keep the samplers last written at each index, and
|
||||
an element that holds its sampler already is not written, so the placement changes no
|
||||
@@ -1123,7 +1141,8 @@ made, with no lock, and never rewritten for layouts.
|
||||
written). A different sampler state stays the program's duty.
|
||||
Making one at an index not granted is `Refusal::IndicesNotGranted`. Where nothing took it, the
|
||||
index is free again once its owner's last handle is gone, and with it the last command buffer
|
||||
that used it; its elements read their default again from then.
|
||||
that used it, and every command buffer committed before that has retired; its elements read
|
||||
their default again from then.
|
||||
|
||||
## Textures
|
||||
|
||||
|
||||
@@ -1000,7 +1000,7 @@ impl Device {
|
||||
///
|
||||
/// Err: [`Refusal::IndicesNotGranted`] where one of its indices is not granted;
|
||||
/// [`Refusal::IndicesInUse`] where a texture or a sampler state lives at one, until its last
|
||||
/// handle is gone.
|
||||
/// handle is gone and the command buffers committed before that retired.
|
||||
pub fn release_indices(&self, grant: IndexGrant) -> Result<(), Error> {
|
||||
lock(&self.core().arrays.grants).release(grant)
|
||||
}
|
||||
|
||||
@@ -659,8 +659,11 @@ impl CommandBuffer {
|
||||
for (drawable, _) in &presents {
|
||||
drawable.presented();
|
||||
}
|
||||
let seq = work.seq();
|
||||
// What is given back from now waits for this command buffer (`crate::memory::Wait`).
|
||||
core.pool.committed(seq);
|
||||
let pending = Pending {
|
||||
seq: work.seq(),
|
||||
seq,
|
||||
next: 0,
|
||||
value: 0,
|
||||
gpu,
|
||||
@@ -1533,6 +1536,8 @@ pub(crate) fn retire(
|
||||
if let Some((start, end)) = gpu_times {
|
||||
inner.queue.ran(end.saturating_sub(start));
|
||||
}
|
||||
// What was released while it was in flight may go (`crate::memory::Wait`).
|
||||
core.pool.ended();
|
||||
let (stamps, stages) = {
|
||||
let mut state = lock(&inner.state);
|
||||
// One with nothing for the GPU, as Metal reports it: its start and end equal, at its
|
||||
|
||||
@@ -569,6 +569,7 @@ pub(crate) fn run(core: Arc<Core>) {
|
||||
// this round, which sees no completion, running while it is held.
|
||||
done.busy.store(true, Ordering::SeqCst);
|
||||
core.work.completed();
|
||||
core.pool.retired();
|
||||
// Handlers and listeners run with no lock held.
|
||||
// Each completed command buffer's timestamps are placed on the host clock by the
|
||||
// last calibration, read again first where the period has passed since it, and moved
|
||||
|
||||
@@ -437,6 +437,8 @@ pub(crate) enum Gauge {
|
||||
ImportBytes,
|
||||
/// [`Gauges::surface_import_bytes`].
|
||||
SurfaceImportBytes,
|
||||
/// [`Gauges::releases_waiting`].
|
||||
ReleasesWaiting,
|
||||
}
|
||||
|
||||
/// A site that allocates on the consumer's threads, inside its calls, counted on its own in
|
||||
@@ -716,6 +718,7 @@ struct Atomics {
|
||||
private_placed_bytes: AtomicU64,
|
||||
import_bytes: AtomicU64,
|
||||
surface_import_bytes: AtomicU64,
|
||||
releases_waiting: AtomicU64,
|
||||
/// Segment ends whose barrier reaches the host, for the tests.
|
||||
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
|
||||
host_reaches: AtomicU64,
|
||||
@@ -1393,6 +1396,7 @@ impl Counters {
|
||||
Gauge::PrivatePlacedBytes => &a.private_placed_bytes,
|
||||
Gauge::ImportBytes => &a.import_bytes,
|
||||
Gauge::SurfaceImportBytes => &a.surface_import_bytes,
|
||||
Gauge::ReleasesWaiting => &a.releases_waiting,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1697,6 +1701,7 @@ impl Counters {
|
||||
private_placed_bytes: a.private_placed_bytes.load(Relaxed),
|
||||
import_bytes: a.import_bytes.load(Relaxed),
|
||||
surface_import_bytes: a.surface_import_bytes.load(Relaxed),
|
||||
releases_waiting: a.releases_waiting.load(Relaxed),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2764,4 +2769,9 @@ pub struct Gauges {
|
||||
/// Bytes of the surface plane imports [`surface_imports`](Self::surface_imports) counts, as
|
||||
/// each was allocated.
|
||||
pub surface_import_bytes: u64,
|
||||
/// Releases of textures' indices, views and images, texture views' views, sampler states'
|
||||
/// indices and device samplers that wait for the command buffers committed before them to
|
||||
/// retire, which may reach them through set 1 with no handle of them: 0 once that work has
|
||||
/// retired, and with nothing in flight at the release.
|
||||
pub releases_waiting: u64,
|
||||
}
|
||||
@@ -430,8 +430,8 @@ pub enum Refusal {
|
||||
index: u32,
|
||||
},
|
||||
/// A release of a grant while a texture, a sampler state or a constexpr sampler holds one of
|
||||
/// its indices ([`Device::release_indices`](crate::Device::release_indices)). Metal has no
|
||||
/// counterpart.
|
||||
/// its indices ([`Device::release_indices`](crate::Device::release_indices)), a released one
|
||||
/// until the command buffers committed before its release retired. Metal has no counterpart.
|
||||
///
|
||||
/// Basis: ours (an object's index stays granted while the object holds it).
|
||||
IndicesInUse {
|
||||
|
||||
@@ -11,11 +11,13 @@ use crate::device::{lock, Core};
|
||||
use crate::error::{Error, Limit};
|
||||
use crate::floor;
|
||||
use crate::places::Ranges;
|
||||
use crate::reaper::{Free, Job};
|
||||
use crate::submit_calls::SubmitCalls;
|
||||
use ash::vk;
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{HashSet, VecDeque};
|
||||
use std::ptr::NonNull;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -49,8 +51,9 @@ const BASE_ALIGN: u64 = 2 << 20;
|
||||
|
||||
/// The idle age, in nanoseconds of [`host_time`](crate::host_time): 250 ms, one value for every
|
||||
/// device. An allocation is idle once it holds no live block: its idle time starts when its last
|
||||
/// live block comes back, and only a take that lands in it again ends it. Commits and submissions
|
||||
/// play no part, so a program that keeps committing gives back what it stopped using. The
|
||||
/// live block comes back, and only a take that lands in it again ends it. A program that keeps
|
||||
/// committing gives back what it stopped using: the free waits only for the work committed
|
||||
/// before the allocation went idle ([`Wait`]). The
|
||||
/// block-maker thread frees an allocation idle this long, after the consumer's unmap of it, one at
|
||||
/// a time and between the allocations it makes, so a free never runs beside its own
|
||||
/// `vkAllocateMemory`; a class's reserve ([`State::whole`]) is not freed. A driver may hold a
|
||||
@@ -70,6 +73,34 @@ const REMADE_WITHIN_NANOS: u64 = 1_000_000_000;
|
||||
/// [`Gauges::private_take_sparse_bytes`](crate::Gauges::private_take_sparse_bytes)).
|
||||
pub(crate) const SPARSE: u64 = 16;
|
||||
|
||||
/// What a release waits for before its memory, object or index goes: the command buffers
|
||||
/// committed before it, which may reach it with no handle of it, by address (a heap's buffers
|
||||
/// through an argument buffer) or through set 1 (a heap's textures and sampler states by their
|
||||
/// resource IDs). Such a reader may read another block's bytes by then, as on a Mac, but never
|
||||
/// memory or an object the device freed. Nothing is kept past the work in flight.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) enum Wait {
|
||||
/// Every command buffer committed up to this place in the commit order is to be submitted.
|
||||
Commits(u64),
|
||||
/// Then the submission of this progress value is to complete.
|
||||
Progress(u64),
|
||||
}
|
||||
|
||||
impl Wait {
|
||||
/// Whether the work it waits for completed, on the block-maker thread without the pool's
|
||||
/// lock: a wait for commits moves on to the progress value of the last submission once each
|
||||
/// of them is submitted (`Work::settled`).
|
||||
fn over(&mut self, core: &Core) -> bool {
|
||||
if let Wait::Commits(commits) = *self {
|
||||
match core.work.settled(commits) {
|
||||
Some(progress) => *self = Wait::Progress(progress),
|
||||
None => return false,
|
||||
}
|
||||
}
|
||||
matches!(*self, Wait::Progress(progress) if core.done.completed() >= progress)
|
||||
}
|
||||
}
|
||||
|
||||
/// The idle clock, the one clock for everything the runtime gives back: what became idle at
|
||||
/// `since` and stayed idle is due at `now` ([`host_time`](crate::host_time)) once
|
||||
/// [`IDLE_AGE_NANOS`] has passed (`None`); before then, the host time it becomes due.
|
||||
@@ -509,6 +540,8 @@ struct Allocation {
|
||||
/// When it became idle, in nanoseconds of [`host_time`](crate::host_time): when it was made,
|
||||
/// or when its last live block came back. The oldest idle allocation is freed first.
|
||||
idle_since: u64,
|
||||
/// What its free waits for, noted when it became idle.
|
||||
wait: Wait,
|
||||
/// A spilled allocation whose last block came back: no take lands in it, its bytes are not
|
||||
/// the class's free bytes, and the idle rule frees it next, so the next allocation tries
|
||||
/// device-local memory again.
|
||||
@@ -553,12 +586,22 @@ impl Allocation {
|
||||
///
|
||||
/// The idle rule runs on the block-maker thread as a block is taken or given back, and again when
|
||||
/// the oldest idle allocation reaches [`IDLE_AGE_NANOS`]: it frees each idle allocation of that
|
||||
/// age, one at a time, whatever the device's queues are doing.
|
||||
/// age, one at a time, once the work committed before it went idle completed ([`Wait`]); so wait
|
||||
/// the frees of imported and exported blocks, and the objects released under work in flight
|
||||
/// ([`Pool::release`]).
|
||||
pub(crate) struct Pool {
|
||||
state: Mutex<State>,
|
||||
/// Signalled whenever the state changes, for the block-maker thread and for takers waiting
|
||||
/// on it.
|
||||
changed: Condvar,
|
||||
/// The last commit's place in the device's commit order, which memory given back notes, and
|
||||
/// the command buffers committed and not yet retired.
|
||||
commits: AtomicU64,
|
||||
in_flight: AtomicU64,
|
||||
/// The completion thread's rounds of retirements, and whether the block-maker thread waits
|
||||
/// for one to free ([`retired`](Self::retired)).
|
||||
rounds: AtomicU64,
|
||||
awaiting: AtomicBool,
|
||||
mappings: Option<Arc<dyn BlockMappings>>,
|
||||
/// The device's counters: the idle bytes, the allocations made and the long reuses.
|
||||
counters: Counters,
|
||||
@@ -663,11 +706,14 @@ struct State {
|
||||
/// Per class, its allocations in the order they were made.
|
||||
allocations: [Vec<Allocation>; 2],
|
||||
/// Imported and exported blocks given back, with the imports' releases, for the block-maker
|
||||
/// thread to free.
|
||||
owned: VecDeque<(Memory, Option<Release>)>,
|
||||
/// thread to free, each with its [`Wait`].
|
||||
owned: VecDeque<((Memory, Option<Release>), Wait)>,
|
||||
/// Memory of its own other threads' objects held, given back for the block-maker thread to
|
||||
/// free.
|
||||
loose: VecDeque<Loose>,
|
||||
/// Objects and indices released while work was in flight, each with its [`Wait`], for the
|
||||
/// block-maker thread to hand to the reaper ([`Pool::release`]).
|
||||
held: VecDeque<(Free, Wait)>,
|
||||
/// Per class, the block-maker thread could not make the last allocation it tried. It tries
|
||||
/// again after the class's next take or give-back.
|
||||
failed: [bool; 2],
|
||||
@@ -794,6 +840,7 @@ impl Pool {
|
||||
allocations: [Vec::new(), Vec::new()],
|
||||
owned: VecDeque::new(),
|
||||
loose: VecDeque::new(),
|
||||
held: VecDeque::new(),
|
||||
failed: [false, false],
|
||||
freed_at: [0, 0],
|
||||
// The device's fixed-size internals: the block-maker thread's first work.
|
||||
@@ -811,6 +858,10 @@ impl Pool {
|
||||
waiting: 0,
|
||||
}),
|
||||
changed: Condvar::new(),
|
||||
commits: AtomicU64::new(0),
|
||||
in_flight: AtomicU64::new(0),
|
||||
rounds: AtomicU64::new(0),
|
||||
awaiting: AtomicBool::new(false),
|
||||
mappings,
|
||||
counters,
|
||||
granule: GRANULE.max(granularity.next_power_of_two()),
|
||||
@@ -824,6 +875,57 @@ impl Pool {
|
||||
lock(&self.state)
|
||||
}
|
||||
|
||||
/// A command buffer took place `seq` in the commit order.
|
||||
pub(crate) fn committed(&self, seq: u64) {
|
||||
self.in_flight.fetch_add(1, Ordering::SeqCst);
|
||||
self.commits.fetch_max(seq, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// A command buffer committed retired, completed or ended.
|
||||
pub(crate) fn ended(&self) {
|
||||
self.in_flight.fetch_sub(1, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// What memory given back now waits for: every command buffer committed so far, nothing where
|
||||
/// none is in flight.
|
||||
fn noted(&self) -> Wait {
|
||||
match self.in_flight.load(Ordering::SeqCst) {
|
||||
0 => Wait::Progress(0),
|
||||
_ => Wait::Commits(self.commits.load(Ordering::SeqCst)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The program let go of `object` (a texture's or a sampler state's index, views, image or
|
||||
/// sampler), which work committed before now may reach with no handle of it, through set 1:
|
||||
/// it goes once that work retired ([`Wait`]), on the reaper thread. Where none is in flight,
|
||||
/// it goes at once, an index on this thread, so its grant may be returned at once
|
||||
/// ([`Device::release_indices`](crate::Device::release_indices)). Releases keep their order.
|
||||
pub(crate) fn release(&self, core: &Core, object: Free) {
|
||||
let wait = self.noted();
|
||||
let now = matches!(wait, Wait::Progress(0));
|
||||
if now && matches!(object, Free::TextureIndex(..) | Free::SamplerIndex(..)) {
|
||||
return crate::reaper::free(core, object);
|
||||
}
|
||||
let mut state = self.lock();
|
||||
if now && state.held.is_empty() {
|
||||
drop(state);
|
||||
return core.reaper.give(Job::Free(object));
|
||||
}
|
||||
state.held.push_back((object, wait));
|
||||
self.counters.rise(Gauge::ReleasesWaiting);
|
||||
self.changed.notify_all();
|
||||
}
|
||||
|
||||
/// The completion thread ran a round of retirements: it wakes the block-maker thread where a
|
||||
/// free waits for work to complete.
|
||||
pub(crate) fn retired(&self) {
|
||||
self.rounds.fetch_add(1, Ordering::SeqCst);
|
||||
if self.awaiting.load(Ordering::SeqCst) {
|
||||
let _state = self.lock();
|
||||
self.changed.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
fn wait<'a>(&self, state: MutexGuard<'a, State>) -> MutexGuard<'a, State> {
|
||||
self.changed
|
||||
.wait(state)
|
||||
@@ -1133,6 +1235,7 @@ impl Pool {
|
||||
/// allocation at once.
|
||||
pub(crate) fn give_back(&self, memory: Memory) {
|
||||
let class = memory.class;
|
||||
let wait = self.noted();
|
||||
self.counters.fall_by(class.placed_gauge(), memory.len);
|
||||
let mut state = self.lock();
|
||||
state.failed[class.index()] = false;
|
||||
@@ -1144,6 +1247,7 @@ impl Pool {
|
||||
allocation.texture = false;
|
||||
// Its idle time starts now, however long ago the block was released.
|
||||
allocation.idle_since = crate::host_time();
|
||||
allocation.wait = wait;
|
||||
allocation.retiring = allocation.spilled;
|
||||
allocation.reused = false;
|
||||
}
|
||||
@@ -1157,7 +1261,8 @@ impl Pool {
|
||||
/// Takes back an imported or exported block, for the block-maker thread to free, and then to
|
||||
/// run an import's release.
|
||||
pub(crate) fn give_back_own(&self, memory: Memory, release: Option<Release>) {
|
||||
self.lock().owned.push_back((memory, release));
|
||||
let wait = self.noted();
|
||||
self.lock().owned.push_back(((memory, release), wait));
|
||||
self.changed.notify_all();
|
||||
}
|
||||
|
||||
@@ -1467,6 +1572,9 @@ pub(crate) fn run(core: Arc<Core>) {
|
||||
let pool = &core.pool;
|
||||
let mut state = pool.lock();
|
||||
loop {
|
||||
// A free whose wait is not over holds; a retirement round since this read wakes it.
|
||||
let round = pool.rounds.load(Ordering::SeqCst);
|
||||
let mut held = false;
|
||||
if state.stop {
|
||||
let ring = state.asked[Internal::RingBlock.index()];
|
||||
state.asked = [false; INTERNALS];
|
||||
@@ -1485,7 +1593,9 @@ pub(crate) fn run(core: Arc<Core>) {
|
||||
pool.changed.notify_all();
|
||||
continue;
|
||||
}
|
||||
if let Some((memory, release)) = state.owned.pop_front() {
|
||||
let own;
|
||||
(state, own) = ripe(&core, state, |state| &mut state.owned, &mut held);
|
||||
if let Some((memory, release)) = own {
|
||||
drop(state);
|
||||
free_own(&core, &memory, release);
|
||||
state = pool.lock();
|
||||
@@ -1498,6 +1608,15 @@ pub(crate) fn run(core: Arc<Core>) {
|
||||
state = pool.lock();
|
||||
continue;
|
||||
}
|
||||
let object;
|
||||
(state, object) = ripe(&core, state, |state| &mut state.held, &mut held);
|
||||
if let Some(object) = object {
|
||||
drop(state);
|
||||
core.counters.fall(Gauge::ReleasesWaiting);
|
||||
core.reaper.give(Job::Free(object));
|
||||
state = pool.lock();
|
||||
continue;
|
||||
}
|
||||
let wanted = (MemoryClass::ALL.into_iter())
|
||||
.find(|&class| !state.failed[class.index()] && !state.whole(class));
|
||||
if let Some(class) = wanted {
|
||||
@@ -1523,6 +1642,23 @@ pub(crate) fn run(core: Arc<Core>) {
|
||||
for class in MemoryClass::ALL {
|
||||
let due = match pool.rule(&state, class, now) {
|
||||
Rule::Free(memory) => {
|
||||
let Some(mut wait) = state.find(class, memory).map(|a| a.wait) else {
|
||||
continue;
|
||||
};
|
||||
pool.awaiting.store(true, Ordering::SeqCst);
|
||||
drop(state);
|
||||
let over = wait.over(&core);
|
||||
state = pool.lock();
|
||||
match state.find(class, memory) {
|
||||
// Still idle: no take landed in it while the lock was dropped.
|
||||
Some(allocation) if allocation.live == 0 && over => {}
|
||||
Some(allocation) => {
|
||||
allocation.wait = wait;
|
||||
held |= allocation.live == 0;
|
||||
continue;
|
||||
}
|
||||
None => continue,
|
||||
}
|
||||
gone = state.take_out(class, memory);
|
||||
pool.settle(&mut state, class);
|
||||
break;
|
||||
@@ -1541,6 +1677,10 @@ pub(crate) fn run(core: Arc<Core>) {
|
||||
state.freed_at[class.index()] = crate::host_time();
|
||||
continue;
|
||||
}
|
||||
if held && pool.rounds.load(Ordering::SeqCst) != round {
|
||||
continue;
|
||||
}
|
||||
pool.awaiting.store(held, Ordering::SeqCst);
|
||||
state = match wake {
|
||||
Some(timeout) => pool.wait_for(state, timeout),
|
||||
None => pool.wait(state),
|
||||
@@ -1548,6 +1688,29 @@ pub(crate) fn run(core: Arc<Core>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The oldest entry of a queue of memory given back, taken out where its [`Wait`] is over; where
|
||||
/// it is not, it stays first, and `held` is set. The pool's lock is dropped for the check.
|
||||
fn ripe<'a, T>(
|
||||
core: &'a Core,
|
||||
mut state: MutexGuard<'a, State>,
|
||||
queue: fn(&mut State) -> &mut VecDeque<(T, Wait)>,
|
||||
held: &mut bool,
|
||||
) -> (MutexGuard<'a, State>, Option<T>) {
|
||||
let Some((item, mut wait)) = queue(&mut state).pop_front() else {
|
||||
return (state, None);
|
||||
};
|
||||
core.pool.awaiting.store(true, Ordering::SeqCst);
|
||||
drop(state);
|
||||
let over = wait.over(core);
|
||||
let mut state = core.pool.lock();
|
||||
if over {
|
||||
return (state, Some(item));
|
||||
}
|
||||
queue(&mut state).push_front((item, wait));
|
||||
*held = true;
|
||||
(state, None)
|
||||
}
|
||||
|
||||
/// On the block-maker thread: makes `internal` with the function a call that needs it makes it
|
||||
/// with, into the part of the device that holds it. A make that fails leaves it unmade: the call
|
||||
/// that needs it makes it on its own thread, where the allocation may succeed then.
|
||||
@@ -1725,6 +1888,7 @@ fn make_allocation(
|
||||
placed: 0,
|
||||
texture: false,
|
||||
idle_since: crate::host_time(),
|
||||
wait: Wait::Progress(0),
|
||||
retiring: false,
|
||||
reused: false,
|
||||
ahead: false,
|
||||
@@ -2441,10 +2605,20 @@ fn free_allocation(core: &Core, allocation: Allocation) {
|
||||
pub(crate) fn free_all(core: &mut Core) {
|
||||
let mut allocations = Vec::new();
|
||||
let mut idle = [0; 2];
|
||||
// The GPU completed everything submitted: no wait holds. What was held goes first, as its
|
||||
// memory and places come back here.
|
||||
let held: Vec<Free> = {
|
||||
let state = (core.pool.state.get_mut()).unwrap_or_else(PoisonError::into_inner);
|
||||
state.held.drain(..).map(|(object, _)| object).collect()
|
||||
};
|
||||
for object in held {
|
||||
core.counters.fall(Gauge::ReleasesWaiting);
|
||||
crate::reaper::free(core, object);
|
||||
}
|
||||
let (owned, loose): (Vec<(Memory, Option<Release>)>, Vec<Loose>) = {
|
||||
let state = (core.pool.state.get_mut()).unwrap_or_else(PoisonError::into_inner);
|
||||
(
|
||||
state.owned.drain(..).collect(),
|
||||
state.owned.drain(..).map(|(own, _)| own).collect(),
|
||||
state.loose.drain(..).collect(),
|
||||
)
|
||||
};
|
||||
|
||||
@@ -6,8 +6,12 @@
|
||||
//! replacing it past its bound (`crate::cache`). No driver free runs on the completion thread,
|
||||
//! so no completion waits behind one. Device memory it does not free: a texture's allocation of
|
||||
//! its own, a surface plane's import and a copy's staging buffer go to the block-maker thread,
|
||||
//! whose form of every free a submission waits out at most one of (`crate::submit_calls`).
|
||||
//! whose form of every free a submission waits out at most one of (`crate::submit_calls`). A
|
||||
//! texture's or a sampler state's index, views, image or sampler released while work was in flight
|
||||
//! come from the block-maker thread once the command buffers committed before the release retired
|
||||
//! (`crate::memory::Pool::release`).
|
||||
|
||||
use crate::arrays::Owner;
|
||||
use crate::counters::Gauge;
|
||||
use crate::device::{lock, Core};
|
||||
use crate::memory::Loose;
|
||||
@@ -77,6 +81,11 @@ pub(crate) enum Free {
|
||||
AttachmentViews(Vec<vk::ImageView>),
|
||||
/// A device sampler no sampler state holds; the device samplers gauge falls with it.
|
||||
Sampler(vk::Sampler),
|
||||
/// A released texture's index and owner word, its second element too where it says so
|
||||
/// (`Arrays::vacate_texture`).
|
||||
TextureIndex((u32, Owner), bool),
|
||||
/// A released sampler state's index and owner word (`Arrays::vacate_samplers`).
|
||||
SamplerIndex(u32, Owner),
|
||||
}
|
||||
|
||||
impl Reaper {
|
||||
@@ -152,7 +161,7 @@ unsafe fn free_backing(core: &Core, backing: Backing) {
|
||||
}
|
||||
|
||||
/// Frees one object.
|
||||
fn free(core: &Core, object: Free) {
|
||||
pub(crate) fn free(core: &Core, object: Free) {
|
||||
let device = &core.device;
|
||||
match object {
|
||||
Free::Semaphore(semaphore) => {
|
||||
@@ -235,6 +244,15 @@ fn free(core: &Core, object: Free) {
|
||||
unsafe { device.destroy_sampler(sampler, None) };
|
||||
core.counters.fall(Gauge::DeviceSamplers);
|
||||
}
|
||||
// SAFETY: no pending work reads the elements: the work committed before the release
|
||||
// retired (`crate::memory::Wait`), and each command buffer that used the object held it.
|
||||
Free::TextureIndex(at, second) => unsafe {
|
||||
(core.arrays).vacate_texture(device, &core.counters, at, second)
|
||||
},
|
||||
// SAFETY: as above.
|
||||
Free::SamplerIndex(index, owner) => unsafe {
|
||||
(core.arrays).vacate_samplers(device, &core.counters, index, owner)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ use crate::arrays::{Owner, ResourceId};
|
||||
use crate::counters::Gauge;
|
||||
use crate::device::{lock, Core, Device};
|
||||
use crate::error::{Error, Gap, Limit};
|
||||
use crate::reaper::{Free, Job};
|
||||
use crate::reaper::Free;
|
||||
use ash::vk;
|
||||
use metal2vulkan::bind::SamplerDescriptor;
|
||||
use metal2vulkan::device::DeviceProfile;
|
||||
@@ -184,11 +184,7 @@ impl SamplerInner {
|
||||
impl Drop for SamplerInner {
|
||||
fn drop(&mut self) {
|
||||
let core = &self.core;
|
||||
// SAFETY: no work that reads its elements is pending: each command buffer that used the
|
||||
// state held it until it retired.
|
||||
unsafe {
|
||||
(core.arrays).vacate_samplers(&core.device, &core.counters, self.index, self.owner)
|
||||
};
|
||||
(core.pool).release(core, Free::SamplerIndex(self.index, self.owner));
|
||||
core.counters.fall(Gauge::Samplers);
|
||||
give_back(core, &self.uses);
|
||||
}
|
||||
@@ -335,7 +331,7 @@ fn give_back(core: &Core, uses: &[Option<SamplerDesc>]) {
|
||||
.collect()
|
||||
};
|
||||
for sampler in freed {
|
||||
core.reaper.give(Job::Free(Free::Sampler(sampler)));
|
||||
core.pool.release(core, Free::Sampler(sampler));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1164,6 +1164,19 @@ impl Work {
|
||||
pub(crate) fn progress(&self) -> u64 {
|
||||
self.lock().progress
|
||||
}
|
||||
|
||||
/// The progress value of the last submission once every command buffer committed up to place
|
||||
/// `commits` in the commit order is submitted, or ended before it was; None while one waits
|
||||
/// in its queue's FIFO or in a group not yet submitted (`crate::memory::Wait`).
|
||||
pub(crate) fn settled(&self, commits: u64) -> Option<u64> {
|
||||
let state = self.lock();
|
||||
let waits = |pending: &Pending| pending.seq <= commits;
|
||||
let queued = (state.fifos.iter()).flat_map(|fifo| &fifo.entries);
|
||||
let staged = (state.fifos.iter()).filter_map(|fifo| fifo.group.as_ref());
|
||||
let held = queued.filter_map(|entry| entry.pending.as_ref()).any(waits)
|
||||
|| (staged.flat_map(|group| &group.finished)).any(|(_, pending, _)| waits(pending));
|
||||
(!held).then_some(state.progress)
|
||||
}
|
||||
}
|
||||
|
||||
impl WorkState {
|
||||
|
||||
@@ -15,6 +15,9 @@
|
||||
//! CPU wrote into a constant buffer, and `ab_slot_address` stores a slot pointer converted to an
|
||||
//! integer, which is the slot's `gpuAddress` plus its offsets.
|
||||
//!
|
||||
//! A buffer read by address alone stays readable past its block's release until the read retires
|
||||
//! (a GPU hazard), and a release under work committed before it waits for that work.
|
||||
//!
|
||||
//! The program writes each texture member itself, as the texture's `gpuResourceID`, and each
|
||||
//! pointer member as the buffer's `gpu_address` plus the offset an encoder's `setBuffer:offset:`
|
||||
//! names, as tier 2's layout lets it. The floor holds every feature tier 2 rests on (buffer device addresses, and the
|
||||
@@ -536,6 +539,61 @@ mod on_device {
|
||||
});
|
||||
}
|
||||
|
||||
/// A release under work committed before it waits for that work (`crate::memory::Wait`): a
|
||||
/// command buffer that waits on an event, committed before the last handles of a 17 MiB
|
||||
/// Shared block (an allocation of its own) and of a texture at an index drop, holds both.
|
||||
/// Nothing reads either. Past twice the idle age the allocation is not freed, the index is in
|
||||
/// use and `releases_waiting` counts what waits; once the event is set and the command buffer
|
||||
/// retires, the allocation is freed, nothing waits and the grant may be returned.
|
||||
#[test]
|
||||
fn every_device_holds_a_release_until_the_work_committed_before_it_retires() {
|
||||
use crate::tests::command::on_device::{shared_event, within};
|
||||
use crate::{Error, Refusal};
|
||||
const LEN: u64 = 17 << 20;
|
||||
each_device("argument_tier_held_release", |name, _, device| {
|
||||
let counters = device.counters();
|
||||
let grant = (device.grant_indices(IndexClass::Texture, 1, 1))
|
||||
.unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
let mut d = TextureDescriptor::new(TextureType::Type2D, PixelFormat::RGBA8Unorm, 2, 2);
|
||||
d.usage = TextureUsage::SHADER_READ;
|
||||
let texture =
|
||||
(device.new_texture(&d, Some(1))).unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
let block = (device.take_block(MemoryClass::Shared, LEN)).expect("a block of its own");
|
||||
let event = shared_event(&device);
|
||||
let queue = device.new_command_queue(1).expect("a queue");
|
||||
let command_buffer = queue.command_buffer().expect("a command buffer");
|
||||
(command_buffer.encode_wait_for_event(event.as_event(), 1)).expect("a wait");
|
||||
command_buffer.commit().expect("a commit");
|
||||
let freed = counters.metrics().allocations_freed;
|
||||
drop((texture, block));
|
||||
std::thread::sleep(std::time::Duration::from_nanos(
|
||||
2 * crate::memory::IDLE_AGE_NANOS,
|
||||
));
|
||||
let (held, waiting) = (
|
||||
counters.metrics().allocations_freed,
|
||||
counters.gauges().releases_waiting,
|
||||
);
|
||||
let in_use = device.release_indices(grant);
|
||||
event.set_signaled_value(1);
|
||||
finished(name, &command_buffer);
|
||||
assert_eq!(held, freed, "{name}: an allocation freed under the work");
|
||||
assert!(waiting >= 1, "{name}: {waiting} releases waiting");
|
||||
assert!(
|
||||
matches!(
|
||||
in_use,
|
||||
Err(Error::Refused(Refusal::IndicesInUse { index: 1, .. }))
|
||||
),
|
||||
"{name}: the index under the work: {in_use:?}"
|
||||
);
|
||||
within("the releases once the work retired", || {
|
||||
counters.metrics().allocations_freed > freed
|
||||
&& counters.gauges().releases_waiting == 0
|
||||
});
|
||||
(device.release_indices(grant)).unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
println!("{name}: {waiting} releases held under the work, then gone");
|
||||
});
|
||||
}
|
||||
|
||||
/// A slot pointer converted to an integer: thread `i` stores the address of element `i` of
|
||||
/// buffer 0, bound 16 bytes past its buffer's start, and increments the element through the
|
||||
/// same pointer (`ab_slot_address`). The address is the buffer's `gpuAddress` plus 16 plus
|
||||
|
||||
@@ -357,7 +357,7 @@ struct Views {
|
||||
|
||||
impl Drop for Views {
|
||||
fn drop(&mut self) {
|
||||
(self.core.reaper).give(Job::Free(Free::Views([self.sampled, self.storage])));
|
||||
(self.core.pool).release(&self.core, Free::Views([self.sampled, self.storage]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -788,7 +788,7 @@ impl Drop for Image {
|
||||
backing: self.backing,
|
||||
},
|
||||
};
|
||||
self.core.reaper.give(Job::Free(free));
|
||||
self.core.pool.release(&self.core, free);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -887,17 +887,9 @@ impl Drop for TextureInner {
|
||||
core.reaper.give(Job::Released(image, self.image.bytes));
|
||||
}
|
||||
}
|
||||
if let Some((index, owner)) = self.index {
|
||||
// SAFETY: no work that reads its elements is pending: each command buffer that used
|
||||
// the texture held it until it retired.
|
||||
unsafe {
|
||||
(core.arrays).vacate_texture(
|
||||
&core.device,
|
||||
&core.counters,
|
||||
(index, owner),
|
||||
self.image.attachment_reads,
|
||||
)
|
||||
};
|
||||
if let Some(at) = self.index {
|
||||
let second = self.image.attachment_reads;
|
||||
core.pool.release(core, Free::TextureIndex(at, second));
|
||||
}
|
||||
// Its element is null, or another texture's: its view of the shadow goes before the
|
||||
// shadow, which its image holds.
|
||||
@@ -907,7 +899,7 @@ impl Drop for TextureInner {
|
||||
.take()
|
||||
});
|
||||
if let Some(view) = shadow {
|
||||
core.reaper.give(Job::Free(Free::ShadowView(view)));
|
||||
core.pool.release(core, Free::ShadowView(view));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -931,8 +923,14 @@ impl Device {
|
||||
/// buffer not yet retired still holds, is taken at once, as Metal's later texture at a
|
||||
/// resource ID takes the ID: the new texture owns the index and its elements from then, and
|
||||
/// the earlier one's going, at its release or once its command buffers retire, touches
|
||||
/// neither. No work in flight may read a displaced or released texture through the index
|
||||
/// (the program's duty, as it is Metal's; nothing checks it).
|
||||
/// neither. No work in flight may read a displaced texture through the index (the program's
|
||||
/// duty, as it is Metal's; nothing checks it). A released one it may: its index, elements,
|
||||
/// views and image go once every command buffer committed before the release retired
|
||||
/// ([`Gauges::releases_waiting`](crate::Gauges::releases_waiting)), so that work reads it as
|
||||
/// it was. Metal leaves that read undefined: a program that released textures a frame in
|
||||
/// flight still sampled finished every run with no command buffer error on two Macs, with the
|
||||
/// answer it gave with the textures held on a Radeon Pro 5300M, and one a few channel levels
|
||||
/// off it, differing from run to run, on an Apple M3 Max. The runtime gives the first answer.
|
||||
///
|
||||
/// A swizzle composes with the view's own component mapping. Shader-write usage writes the
|
||||
/// storage element where the device stores the format through a storage image without a
|
||||
|
||||
@@ -1506,6 +1506,7 @@ field metal2vulkan-runtime::Gauges.private_take_sparse_allocations pub private_t
|
||||
field metal2vulkan-runtime::Gauges.private_take_sparse_bytes pub private_take_sparse_bytes: u64
|
||||
field metal2vulkan-runtime::Gauges.private_unit_used_bytes pub private_unit_used_bytes: u64
|
||||
field metal2vulkan-runtime::Gauges.private_units pub private_units: u64
|
||||
field metal2vulkan-runtime::Gauges.releases_waiting pub releases_waiting: u64
|
||||
field metal2vulkan-runtime::Gauges.render_contents pub render_contents: u64
|
||||
field metal2vulkan-runtime::Gauges.samplers pub samplers: u64
|
||||
field metal2vulkan-runtime::Gauges.shadow_bytes pub shadow_bytes: u64
|
||||
|
||||
|
Can't render this file because it is too large.
|
+1
-1
@@ -289,7 +289,7 @@ Columns:
|
||||
| `BufferOffsetAlignment` | A dispatch whose kernel, or a draw whose vertex or fragment function, reaches a buffer bound where its address, the buffer's `gpuAddress` plus the... | every device (a public call's own check of its arguments) | `metal-documented`: Metal's API validation refuses the bind offset: "must be a multiple of 4 but was set to 2" for a `uint *` argument bound at offset 2, an Apple M3 Max, macOS 27.0.1, `probes/vector_access_placement.m` in the conformance crate | 1: `crates/metal2vulkan-runtime/src/encoder.rs (check_alignment)` | `-` |
|
||||
| `IndicesGranted` | A grant of an index already granted (`Device::grant_indices`) | every device (a public call's own check of its arguments) | `ours`: each index has one grant, so each resource ID names one object | 1: `crates/metal2vulkan-runtime/src/arrays.rs (grant)` | `-` |
|
||||
| `IndicesNotGranted` | A texture, a sampler state or a pipeline state's constexpr sampler at an index no live grant of its class holds (`Device::new_texture`,... | every device (a public call's own check of its arguments) | `ours`: an object takes an index the consumer was granted, and a grant is returned once | 2: `crates/metal2vulkan-runtime/src/arrays.rs (place)`, `crates/metal2vulkan-runtime/src/arrays.rs (release)` | `-` |
|
||||
| `IndicesInUse` | A release of a grant while a texture, a sampler state or a constexpr sampler holds one of its indices (`Device::release_indices`) | every device (a public call's own check of its arguments) | `ours`: an object's index stays granted while the object holds it | 1: `crates/metal2vulkan-runtime/src/arrays.rs (release)` | `-` |
|
||||
| `IndicesInUse` | A release of a grant while a texture, a sampler state or a constexpr sampler holds one of its indices (`Device::release_indices`), a released one... | every device (a public call's own check of its arguments) | `ours`: an object's index stays granted while the object holds it | 1: `crates/metal2vulkan-runtime/src/arrays.rs (release)` | `-` |
|
||||
| `TextureIndex` | A texture shaders reach made without an index, or one they do not reach made with one (`Device::new_texture`) | every device (a public call's own check of its arguments) | `ours`: an index is an element of set 1's texture arrays, which only shaders read | 4: `crates/metal2vulkan-runtime/src/texture.rs (new_drawable_texture)`, `crates/metal2vulkan-runtime/src/texture.rs (surface_texture)` (+2) | `-` |
|
||||
| `TextureZeroExtent` | A texture with a width, height or depth of 0 | every device (a public call's own check of its arguments) | `metal-measured`: an Apple M3 Max, macOS 27.0.1: plain Metal asserts "MTLTextureDescriptor has width of zero", and the same for a height of zero | 1: `crates/metal2vulkan-runtime/src/texture.rs (shape)` | `-` |
|
||||
| `TextureExtentForType` | A texture with a height other than 1 of a 1D type, or a depth other than 1 of a type that is not 3D | every device (a public call's own check of its arguments) | `metal-measured`: an Apple M3 Max, macOS 27.0.1: plain Metal asserts "the texture type MTLTextureType1D requires that height is 1", and the same for a 2D texture of depth 2 | 1: `crates/metal2vulkan-runtime/src/texture.rs (shape)` | `-` |
|
||||
|
||||
Reference in new issue
Block a user