RUNTIME 2479: A reused command buffer state keeps its predication and fold-order room and its compute logs

A command buffer's state, reset at its release for the next command buffer
(spare_states.rs), started its command predication's lists (opened, alone,
each unit's opened_fresh) and each group's FoldOrder (its map and a Vec of
priors per resource) empty, so every 5-encoder command buffer allocated them
again over memory another thread freed. And every compute encoder took its log
from the device's SpareLogs mutex, which the queue's handler thread takes as
releases give logs back.

- Predication::reset clears its lists in place. opened_fresh moves from Unit to
  Predication: one unit is open at a time, and it is cleared as the unit ends.
- State.order_room holds the group order the way stash_room holds the stash:
  Fold::begun takes it, close_fold gives it back cleared (FoldOrder::clear keeps
  the map's room and moves each resource's emptied list into its boxes, which
  join reuses). The order's second-encoder build is a join into that room;
  FoldOrder::after is gone (tests build it with none + join).
- The release clears compute logs outside the state lock and keeps up to
  STATE_LOGS (32) in the state (State::keep_compute_logs). The rest go to the
  device spares in one give_all. A compute encoder's open takes its log under
  the state lock it already holds (State::kept_compute_log), and uses the device
  spares only when the state has none left.
- Bounds: Room counts the new lists (entries, for record_lists_grown) and the
  kept logs' bytes, so the existing caps hold. A state with more than 8 MiB is
  not kept, and kept states hold at most 16 MiB in total.
- Predication::enter no longer moves unit.carried out with mem::take. It
  drains it instead.

Same commands, barriers, predication and fold answers. New tests:
tests::spare_states::a_reused_command_buffer_of_five_compute_encoders_grows_no_list_and_takes_no_spare_log
(device) and tests::tracker::a_cleared_fold_order_answers_as_a_fresh_one_in_the_room_it_kept
(host).

With: Predication::enter rebuilds its unit around the bodies it hands on (take_if; no mem::take, no empty value left in a borrowed owner); the cleared fold-order test measures the room the clear kept.

Checks at the lane tip b107e56a6c (msi): clippy -p metal2vulkan-runtime --all-targets --all-features -D warnings under m2v_cpu_icd 0 (m3-max-37853); at ed6a832c98 the lavapipe spare_states, tracker, fold, rebind, compute, spares and encoder suites 250/251 (m3-max-37842; the one failure, the host test's baseline, is fixed in b107e56a6c). The suites and two negative controls at the tip, and the timing (encopen's estimate ~85 + ~48 ns a guest dispatch), follow on development.
This commit is contained in:
Anees Iqbal committed 2026-11-16 14:03:54 -08:00
1 parent 0f29d6a6e3
commit 5a0d21cdc5
12 files changed
+476 -123

No files matched your search

@@ -18,7 +18,7 @@ impl State {
/// The group the encoder opening now joins, asking `joining`, where its
/// command buffer's tail holds one it may join (`encoder_fold.rs`'s **Where**): taken, with
/// the tail, which the encoder records into, and, where it is the group's second encoder, the
/// group's order built from its first part's summary (`Fold::order`). `None` where it joins
/// group's order joined to its first part's summary (`Fold::order`). `None` where it joins
/// none, the group left in place: the encoder's open closes it once it opened
/// ([`close_fold`](Self::close_fold)). A refusal is counted by its reason ([`Refusal`]): the
/// group's, or, where the tail holds none, why the encoder before left none
@@ -55,14 +55,14 @@ impl State {
return None;
}
// Its second encoder orders after its first part, as that part's end left it.
let order = match fold.members.len() {
1 => Some(FoldOrder::after(&self.recorded.get(fold.leader)?.summary)),
let first = match fold.members.len() {
1 => Some(&self.recorded.get(fold.leader)?.summary),
_ => None,
};
self.tail = None;
let mut fold = self.fold.take()?;
if let Some(order) = order {
fold.order = order;
if let Some(first) = first {
fold.order.join(first);
}
// It records into the tail outside any render pass instance (`encoder_fold.rs`'s
// **Continued passes**).
@@ -107,19 +107,26 @@ impl State {
if !admits {
return None;
}
let order = match fold.members.len() {
1 => Some(FoldOrder::after(&self.recorded.get(fold.leader)?.summary)),
// Its second encoder orders after its first part, as that part's end left it: joined
// here, and cleared again where `writes` refuses it, so a group of one encoder holds
// its order empty.
let first = match fold.members.len() {
1 => Some(&self.recorded.get(fold.leader)?.summary),
_ => None,
};
if !writes(order.as_ref().unwrap_or(&fold.order)) {
let fold = self.fold.as_mut()?;
if let Some(first) = first {
fold.order.join(first);
}
if !writes(&fold.order) {
if first.is_some() {
fold.order.clear();
}
counts.command_buffer_split_at_aliases();
return None;
}
self.tail = None;
let mut fold = self.fold.take()?;
if let Some(order) = order {
fold.order = order;
}
fold.order.continued();
// The instance is the encoder's own from here: its pass holds it, and ends it or leaves
// it open again as it ends.
@@ -200,15 +207,17 @@ impl State {
record.in_tail = true;
}
let (leader, batches) = (self.recorded.len() - 1, self.batches.all().len());
// Its stash takes the room the command buffer's lists keep (`spare_states.rs`).
// Its stash and its order take the room the command buffer's lists keep
// (`spare_states.rs`).
let mut stashed = self.stash_room.take().unwrap_or_default();
stashed.extend(log);
let order = self.order_room.take().unwrap_or_else(FoldOrder::none);
let open = open.take();
self.fold = Some(Box::new(Fold::begun(
tail,
(leader, encoder),
(batches, joining),
(stashed, open),
(stashed, order, open),
)));
}
(Some(_), None) => {
@@ -248,7 +257,7 @@ impl State {
/// commit, whose failure may split the group ([`split_failure`](Self::split_failure)). A lone
/// encoder's comes back, for the caller to give back to the device's spares without this lock
/// (`replay.rs`). A group of more gives the room of its stash back, emptied, for the next
/// group's (`spare_states.rs`).
/// group's; and every group, the room of its order (`spare_states.rs`).
pub(crate) fn close_fold(&mut self, counts: &Counters) -> Vec<Replay> {
let Some(mut fold) = self.fold.take() else {
return Vec::new();
@@ -257,8 +266,11 @@ impl State {
let Fold {
members,
mut stashed,
mut order,
..
} = *fold;
order.clear();
self.order_room = Some(order);
if members.len() < 2 {
return stashed.into_iter().map(|stashed| stashed.log).collect();
}
@@ -83,6 +83,7 @@ use super::device::relay::{self, Relayed};
use super::device::{lock, DeviceShared};
use super::dirty_pages::DirtyCommit;
use super::encoder::{Recorded, Segment};
use super::encoder_fold::FoldOrder;
use super::error::{
internal, invalid, vulkan, CommandBufferError, DeadlockCause, EncoderCall, Error,
FailedPipeline, FailedState, MemoryKind, MeshRecordsOverflow, PipelineCreationCause, Problem,
@@ -111,7 +112,7 @@ use super::program_objects;
use super::queue::{QueueGen, Slot};
use super::rebind::{Holds, SubmittedHolds, Taken};
use super::render::{Carried, EndInFlight, NoneKept};
use super::replay::Replay;
use super::replay::{CallLog, ComputeCall, Replay};
use super::residency::Residency;
use super::resource::{ObjectId, ResourceKey};
use super::retained::Lately;
@@ -869,9 +870,20 @@ pub(super) struct State {
/// logs its members do not keep in (`encoder_fold::Fold`'s `stashed`), empty; `None` while a
/// group holds it.
stash_room: Option<Vec<crate::encoder_fold::Stashed>>,
/// The room its lists of records (`ended`, `recorded`, `held_logs` and `stash_room`) held as
/// the command buffer took the state (`spare_states.rs`): its release counts those that grew
/// past it (`WorkCounts::record_lists_grown`).
/// The order the next group of its encoders recorded into one `VkCommandBuffer` joins its
/// encoders' uses to (`encoder_fold::Fold`'s `order`), empty, the room of the groups before
/// kept (`FoldOrder::clear`); `None` while a group holds it.
order_room: Option<FoldOrder<ResourceKey>>,
/// Cleared logs of compute encoders (`replay.rs`), each with its room in bytes, that the
/// release of a command buffer that held this state kept for the compute encoders of the one
/// that takes it next, at most [`STATE_LOGS`](spare_states::STATE_LOGS): such an encoder
/// takes its log here, under the lock its open takes, and from the device's spares only where
/// none is left.
compute_logs: Vec<(CallLog<ComputeCall>, usize)>,
/// The room its lists of records (`ended`, `recorded`, `held_logs`, `stash_room`, its command
/// predication's lists and its groups' order) held as the command buffer took the state
/// (`spare_states.rs`): its release counts those that grew past it
/// (`WorkCounts::record_lists_grown`).
room: Room,
/// What its last ended compute encoder parked for its next one, until the commit gives it back
/// to the device (`compute/live.rs`'s `Parked`).
@@ -1276,6 +1288,8 @@ impl State {
unfolded: None,
held_logs: Vec::new(),
stash_room: Some(Vec::new()),
order_room: Some(FoldOrder::none()),
compute_logs: Vec::new(),
room: Room::default(),
parked_compute: None,
left_out_from: None,
@@ -1377,21 +1391,49 @@ impl State {
}
}
/// The room its lists of records hold, each list's in entries (`spare_states.rs`).
/// The room its lists of records hold, each list's in entries, and with its kept compute
/// logs' in bytes (`spare_states.rs`).
fn lists_room(&self) -> Room {
Room([
self.ended.capacity(),
self.recorded.capacity(),
self.stash_room.as_ref().map_or(0, Vec::capacity),
self.held_logs.capacity(),
])
let order = (self.order_room.as_ref()).map_or([0; 3], FoldOrder::room);
let logs = self.compute_logs.iter().map(|(_, room)| room).sum();
Room::new(
[
self.ended.capacity(),
self.recorded.capacity(),
self.stash_room.as_ref().map_or(0, Vec::capacity),
self.held_logs.capacity(),
],
self.predication.room(),
order,
logs,
)
}
/// A compute encoder's log, opening now: a cleared one this state kept
/// ([`compute_logs`](Self::compute_logs)), where it keeps one.
pub(super) fn kept_compute_log(&mut self) -> Option<CallLog<ComputeCall>> {
self.compute_logs.pop().map(|(log, _)| log)
}
/// Keep `logs`, cleared compute logs with their room in bytes, for the compute encoders of
/// the command buffer that takes this state next, as many as it has room for
/// ([`STATE_LOGS`](spare_states::STATE_LOGS)): those it does not keep come back.
pub(super) fn keep_compute_logs(
&mut self,
mut logs: Vec<(CallLog<ComputeCall>, usize)>,
) -> Vec<(CallLog<ComputeCall>, usize)> {
let room = spare_states::STATE_LOGS.saturating_sub(self.compute_logs.len());
let from = logs.len().saturating_sub(room);
self.compute_logs.extend(logs.drain(from..));
logs
}
/// The state reset in place, by its release, for a command buffer the device makes next
/// (`spare_states.rs`): every part as [`State::new`] makes it, what it held going here, but
/// its lists of records, emptied with their room kept (their entries going first, as they
/// went before the rest), and the revision its parts move. Its room is the room the next
/// command buffer starts on.
/// went before the rest), its command predication's lists and its groups' order, emptied in
/// place with their room kept, the compute logs its release kept, and the revision its parts
/// move. Its room is the room the next command buffer starts on.
fn reset(&mut self) {
let State {
status,
@@ -1424,6 +1466,8 @@ impl State {
unfolded,
held_logs: _,
stash_room: _,
order_room: _,
compute_logs: _,
room: _,
parked_compute,
left_out_from,
@@ -1516,7 +1560,7 @@ impl State {
check,
checks,
storage_form,
predication,
predication: _,
replaying_predication,
predicated,
trail_mark,
@@ -1527,6 +1571,7 @@ impl State {
self.recorded.clear();
self.held_logs.clear();
self.stash_room.get_or_insert_with(Vec::new).clear();
(self.order_room.get_or_insert_with(FoldOrder::none)).clear();
self.status = status;
self.error = error;
self.encoder_open = encoder_open;
@@ -1644,7 +1689,7 @@ impl State {
self.check = check;
self.checks = checks;
self.storage_form = storage_form;
self.predication = predication;
self.predication.reset();
self.replaying_predication = replaying_predication;
self.predicated = predicated;
self.trail_mark = trail_mark;
@@ -7349,19 +7394,24 @@ impl CommandBufferShared {
drop(resource);
}
// Its encoders' logs go here too, those they kept and those held for its commit
// (`fold.rs`), back to the device's spares (`replay.rs`): they hold what their calls
// named, which Metal holds until the command buffer completed
// (a binding replaced before any command among it), and no thread but this one may
// hold such a handle past the completion.
// (`fold.rs`), cleared without the state's lock (`replay.rs`): they hold what their
// calls named, which Metal holds until the command buffer completed (a binding
// replaced before any command among it), and no thread but this one may hold such a
// handle past the completion. Its state keeps the compute ones, as many as it keeps,
// for the compute encoders of the command buffer that takes it next
// (`spare_states.rs`); the rest go back to the device's spares.
let logs: Vec<Arc<Replay>> = (lock(&self.state).ended.iter_mut())
.filter_map(|record| record.replay.take())
.collect();
let spares = self.device.shared().scheduler.spare_logs();
for log in logs {
spares.give_last(log);
}
let held = lock(&self.state).unsplit_logs();
spares.give_held(held);
let spares = self.device.shared().scheduler.spare_logs();
let logs = logs.into_iter().filter_map(Arc::into_inner).chain(held);
let compute = spares.cleared_compute(logs);
let unkept = match compute.is_empty() {
true => compute,
false => lock(&self.state).keep_compute_logs(compute),
};
spares.give_compute(unkept);
let residency = lock(&self.state).residency.take();
drop(residency);
let residencies = lock(&self.state).let_go_of_uses();
@@ -3,11 +3,17 @@
//! ([`State::reset`]): what it held goes as it went before, at the release, and its lists of what
//! its encoders ended with (its ended encoders' records, their recordings, the logs of a group of
//! encoders recorded into one `VkCommandBuffer` its members did not keep, `encoder_fold.rs`'s
//! `Fold`, and those held for its commit, `fold.rs`) are emptied with their room kept. A command
//! buffer being made takes a kept state whole ([`SpareStates::take`]): its making neither
//! allocates nor fills one, and its encoders' ends push into room the lists already had rather
//! than grow them one reallocation at a time over fresh pages. A state goes on only to command
//! buffers of the device generation that made it, and the kept ones go with that generation.
//! `Fold`, and those held for its commit, `fold.rs`), its command predication's lists
//! (`predication.rs`) and its groups' order (`FoldOrder`, its map and its resources' lists) are
//! emptied with their room kept. A command buffer being made takes a kept state whole
//! ([`SpareStates::take`]): its making neither allocates nor fills one, and its encoders' ends push
//! into room the lists already had rather than grow them one reallocation at a time over fresh
//! pages. Its release also keeps up to [`STATE_LOGS`] of its compute encoders' logs, cleared, in
//! the state (`State::compute_logs`): the compute encoders of the command buffer that takes it
//! take those, under the lock their open takes, rather than the device's spares' (`replay.rs`),
//! whose lock the queues' handler threads take as they give logs back. A state goes on only to
//! command buffers of the device generation that made it, and the kept ones go with that
//! generation.
use std::sync::atomic::AtomicU64;
use std::sync::{Arc, Mutex};
@@ -15,7 +21,9 @@ use std::sync::{Arc, Mutex};
use super::State;
use crate::device::lock;
use crate::encoder::Recorded;
use crate::encoder_fold::Stashed;
use crate::encoder_fold::{FoldOrder, Stashed};
use crate::predication::Predication;
use crate::resource::ResourceKey;
use crate::used_resources::EncoderRecord;
/// The states a device keeps, at most: one per uncompleted command buffer of a queue of Metal's
@@ -31,24 +39,70 @@ const STATE_ROOM_BYTES: usize = 8 << 20;
/// The room the kept states' lists hold together, at most, in bytes.
const SPARE_ROOM_BYTES: usize = 2 * STATE_ROOM_BYTES;
/// The room of each of a state's lists of records, in entries: its ended encoders' records, their
/// recordings, its stash of a group's logs and the logs it holds for its commit.
/// The cleared compute logs a state keeps, at most (`State::compute_logs`): each holds at most
/// `SPARE_LOG_BYTES` (64 KiB, `replay.rs`), and their room counts toward the state's
/// ([`STATE_ROOM_BYTES`]).
pub(super) const STATE_LOGS: usize = 32;
/// The lists of records a state keeps the room of ([`Room`]).
const LISTS: usize = 12;
/// The room of each of a state's lists of records, in entries (its ended encoders' records, their
/// recordings, its stash of a group's logs, the logs it holds for its commit, its command
/// predication's five lists, and its groups' order's map, boxes and priors), and the room they
/// and the compute logs it keeps hold, in bytes.
#[derive(Clone, Copy, Default)]
pub(super) struct Room(pub(super) [usize; 4]);
pub(super) struct Room {
lists: [usize; LISTS],
bytes: usize,
}
impl Room {
/// The room of a state's lists: of its lists of records `records` (its ended encoders'
/// records, their recordings, its stash and the logs it holds for its commit), of its command
/// predication's lists `predication` (`Predication::room`), of its groups' order `order`
/// (`FoldOrder::room`), each in entries, and of the compute logs it keeps, `logs` bytes.
pub(super) fn new(
records: [usize; 4],
predication: [usize; 5],
order: [usize; 3],
logs: usize,
) -> Room {
let [ended, recorded, stashed, held_logs] = records;
let bytes = ended * std::mem::size_of::<EncoderRecord>()
+ recorded * std::mem::size_of::<Recorded>()
+ (stashed + held_logs) * std::mem::size_of::<Stashed>()
+ Predication::room_bytes(predication)
+ FoldOrder::<ResourceKey>::room_bytes(order)
+ logs;
let [runs, open_checks, opened, alone, opened_fresh] = predication;
let [map, boxes, priors] = order;
let lists = [
ended,
recorded,
stashed,
held_logs,
runs,
open_checks,
opened,
alone,
opened_fresh,
map,
boxes,
priors,
];
Room { lists, bytes }
}
/// How many of the lists hold more room in `now` than in this: those that grew since.
pub(super) fn grown(self, now: Room) -> u64 {
let grown = (self.0.iter().zip(now.0)).filter(|&(&was, now)| now > was);
let grown = (self.lists.iter().zip(now.lists)).filter(|&(&was, now)| now > was);
grown.count() as u64
}
/// The room, in bytes.
pub(super) fn bytes(self) -> usize {
let [ended, recorded, stashed, held_logs] = self.0;
ended * std::mem::size_of::<EncoderRecord>()
+ recorded * std::mem::size_of::<Recorded>()
+ (stashed + held_logs) * std::mem::size_of::<Stashed>()
self.bytes
}
}
+10 -5
View File
@@ -295,9 +295,10 @@ impl CommandBuffer {
let counts = &self.device().shared().counts;
// Under the core's one lock of the state: it joins its command buffer's unit of command
// predication, carrying on the loops open across its start, or starts the next; it starts
// with the residency the ended encoders left (`State::inheriting`); and it takes what the
// command buffer's last compute encoder parked (`compute/live.rs`).
let (opened, (carried, residency, predicated, parked)) = EncoderCore::open(
// with the residency the ended encoders left (`State::inheriting`); it takes what the
// command buffer's last compute encoder parked (`compute/live.rs`); and it takes a log its
// state kept (`spare_states.rs`), where it kept one.
let (opened, (carried, residency, predicated, parked, log)) = EncoderCore::open(
self,
call,
EncoderKind::Compute,
@@ -305,7 +306,9 @@ impl CommandBuffer {
|state| {
let carried = state.enter_predication(dispatch_type);
let residency = state.inheriting(false, counts);
(carried, residency, state.predicated, state.unpark_compute())
let parked = state.unpark_compute();
let log = state.kept_compute_log();
(carried, residency, state.predicated, parked, log)
},
)?;
// The core in the box the command buffer's last compute encoder parked, and its bind state
@@ -342,7 +345,9 @@ impl CommandBuffer {
indirect_stage_in: None,
residency,
captures: Captures::carried(carried, predicated),
log: Some(self.device().shared().scheduler.spare_logs().compute()),
log: Some(
log.unwrap_or_else(|| self.device().shared().scheduler.spare_logs().compute()),
),
dispatches: 0,
live,
heaps_noted: None,
+48 -15
View File
@@ -232,10 +232,11 @@
//! - **Logs.** A group's members' logs are held from the group's close for the commit, which
//! keeps them for every member where one member keeps its own for a rebind, and keeps those of
//! a group its failure splits; the rest stay held until the command buffer's release, which
//! gives them back to the device's spares under one lock on its queue's handler thread
//! (`SpareLogs::give_held`), as it gives back the logs its encoders kept. The spares keep as
//! many as it gave back within 1 MiB of room, so a next command buffer's encoders reuse them
//! rather than allocate. A log holds one
//! clears them on its queue's handler thread, as it clears the logs its encoders kept, and keeps
//! up to 32 in the command buffer's state for the compute encoders of the one that takes it
//! next (`command_buffer/spare_states.rs`), giving the rest back to the device's spares under
//! one lock (`SpareLogs::give_compute`). The spares keep as many as it gave back within 1 MiB
//! of room, so a next command buffer's encoders reuse them rather than allocate. A log holds one
//! `ComputeCall` per call (at most 64 bytes, `tests::encoder_fold`) besides the bytes and handles
//! its slices take in its arenas: a one-dispatch encoder's five calls (state, three buffers, the
//! dispatch) hold about 320 bytes, so 2,300 such encoders hold about 0.7 MiB until their command buffer completes.
@@ -286,6 +287,9 @@ impl Prior {
/// that updated a fence (**Fences** in the module docs).
pub(crate) struct FoldOrder<K> {
priors: KeyMap<K, Vec<Prior>>,
/// The lists of priors of its resources a [`clear`](Self::clear) emptied, their room kept for
/// the resources a next group's encoders use.
boxes: Vec<Vec<Prior>>,
/// The writes the group's fence updates cover, in the stages the updating encoders' commands
/// ran in that each update covers: every later command of the group orders after them, to
/// what it may reach of memory no use names. Empty where no member updated a fence.
@@ -299,16 +303,41 @@ impl<K: Copy + Eq + Hash> FoldOrder<K> {
pub(crate) fn none() -> FoldOrder<K> {
FoldOrder {
priors: KeyMap::default(),
boxes: Vec::new(),
fenced: Access::NONE,
fenced_visible: Access::NONE,
}
}
/// The order after the encoder whose summary is `summary`.
pub(crate) fn after(summary: &Summary<K>) -> FoldOrder<K> {
let mut order = FoldOrder::none();
order.join(summary);
order
/// Empty it, the order after nothing again, for a next group (`command_buffer/fold.rs`): its
/// map's room kept, and each resource's list of priors emptied into its boxes, their room
/// kept.
pub(crate) fn clear(&mut self) {
for (_, mut priors) in self.priors.drain() {
priors.clear();
self.boxes.push(priors);
}
self.fenced = Access::NONE;
self.fenced_visible = Access::NONE;
}
/// The room it holds, in entries: its map's, its boxes', and the priors' its lists of priors
/// hold together.
pub(crate) fn room(&self) -> [usize; 3] {
let lists = self.priors.values().chain(&self.boxes);
[
self.priors.capacity(),
self.boxes.capacity(),
lists.map(Vec::capacity).sum(),
]
}
/// [`room`](Self::room) in bytes.
pub(crate) fn room_bytes(room: [usize; 3]) -> usize {
let [map, boxes, priors] = room;
map * std::mem::size_of::<(K, Vec<Prior>)>()
+ boxes * std::mem::size_of::<Vec<Prior>>()
+ priors * std::mem::size_of::<Prior>()
}
/// Note the next encoder of the group ended, with `summary`: its uses come after everything
@@ -322,7 +351,9 @@ impl<K: Copy + Eq + Hash> FoldOrder<K> {
self.fenced_visible = Access::NONE;
}
for used in summary.uses() {
let priors = self.priors.entry(used.key).or_default();
let boxes = &mut self.boxes;
let priors =
(self.priors.entry(used.key)).or_insert_with(|| boxes.pop().unwrap_or_default());
if !used.write.is_empty() {
priors.retain(|prior| !used.range.contains(&prior.range));
}
@@ -695,8 +726,10 @@ pub(crate) struct Fold {
/// joins its first part's (`Fold::overwrites_join`).
pub(crate) blits_alone: bool,
/// What its encoders did, which the next one's commands order after: empty until a second
/// encoder joins, which builds it from its first part's summary (`State::join_fold`), so a
/// group no encoder joins costs no copy of what its first encoder used.
/// encoder joins, which joins its first part's summary to it (`State::join_fold`), so a
/// group no encoder joins costs no copy of what its first encoder used. It holds the room
/// the command buffer's group before left it (`FoldOrder::clear`), which its close gives
/// back.
pub(crate) order: FoldOrder<ResourceKey>,
/// Its members' logs not kept by themselves.
pub(crate) stashed: Vec<Stashed>,
@@ -719,12 +752,12 @@ impl Fold {
}
/// The group `joining`'s encoder begins, its first part `leader`, its first `VkCommandBuffer`
/// the tail; its order is built as a second encoder joins.
/// the tail; its order, `order` (empty), is joined as a second encoder joins.
pub(crate) fn begun(
tail: vk::CommandBuffer,
(leader, encoder): (usize, usize),
(batches, joining): (usize, Joining),
(stashed, open): (Vec<Stashed>, Option<OpenPass>),
(stashed, order, open): (Vec<Stashed>, FoldOrder<ResourceKey>, Option<OpenPass>),
) -> Fold {
Fold {
tail,
@@ -733,7 +766,7 @@ impl Fold {
batches,
dispatch_type: joining.dispatch_type(None),
blits_alone: joining == Joining::Blit,
order: FoldOrder::none(),
order,
stashed,
open,
}
+79 -16
View File
@@ -207,6 +207,12 @@ pub(super) struct Predication {
/// ([`alone`](Self::alone)): a rebind may encode one again
/// ([`replaying`](Self::replaying)).
alone: Vec<usize>,
/// The places among the command buffer's ended encoders of the current unit's compute
/// encoders that opened with no step of it laid ([`Unit::fresh`]), in order: its first
/// encoder's, and each later one's until one laid a step, so a prefix of its encoders
/// ([`alone`](Predication::alone)). Emptied as the unit ends, its room kept for the next
/// unit's.
opened_fresh: Vec<usize>,
}
/// What a compute encoder found as it opened: its place among the command buffer's ended
@@ -480,11 +486,6 @@ struct Unit {
looped: bool,
/// An unbalanced record left out what its encoders recorded before it.
left: bool,
/// The places among the command buffer's ended encoders of its compute encoders that opened
/// with no step of its laid ([`Unit::fresh`]), in order: its first encoder's, and each
/// later one's until one laid a step, so a prefix of its encoders
/// ([`alone`](Predication::alone)).
opened_fresh: Vec<usize>,
}
/// The range of a unit an unbalanced record drops (the module docs): from the anchor to the next
@@ -571,7 +572,6 @@ impl Unit {
carried: Vec::new(),
looped: false,
left: false,
opened_fresh: vec![place],
}
}
@@ -660,24 +660,85 @@ impl Predication {
dispatch_type,
records: self.records,
});
if let Some(unit) = &mut self.unit {
if !unit.closing
let joins = |unit: &mut Unit| {
!unit.closing
&& unit.place + 1 == place
&& unit.events == events
&& unit.dispatch_type == dispatch_type
{
if unit.fresh() {
unit.opened_fresh.push(place);
}
unit.place = place;
return std::mem::take(&mut unit.carried);
};
if let Some(unit) = self.unit.take_if(joins) {
if unit.fresh() {
self.opened_fresh.push(place);
}
// The encoder takes the bodies its unit carried; the unit goes on with it, carrying
// none until it ends.
let carried = unit.carried;
self.unit = Some(Unit {
place,
carried: Vec::new(),
..unit
});
return carried;
}
self.end_unit();
self.opened_fresh.push(place);
self.unit = Some(Unit::new(place, events, dispatch_type));
Vec::new()
}
/// Reset in place for the command buffer that takes its state next (`spare_states.rs`):
/// every part as [`Predication::default`] makes it, what it held going here, its lists
/// emptied with their room kept.
pub(super) fn reset(&mut self) {
let Predication {
unit,
runs,
open_checks,
records,
loops,
laying,
laid,
waited,
left_out,
opened,
alone,
opened_fresh,
} = self;
*unit = None;
runs.clear();
open_checks.clear();
*records = 0;
*loops = 0;
*laying = None;
*laid = 0;
*waited = 0;
*left_out = None;
opened.clear();
alone.clear();
opened_fresh.clear();
}
/// The room of its lists, each in entries: its runs, its open units' check words, its
/// opened encoders, those that encode again alone and the current unit's fresh ones.
pub(super) fn room(&self) -> [usize; 5] {
[
self.runs.capacity(),
self.open_checks.capacity(),
self.opened.capacity(),
self.alone.capacity(),
self.opened_fresh.capacity(),
]
}
/// [`room`](Self::room) in bytes.
pub(super) fn room_bytes(room: [usize; 5]) -> usize {
let [runs, open_checks, opened, alone, opened_fresh] = room;
runs * std::mem::size_of::<Run>()
+ open_checks * std::mem::size_of::<(Upload, u32)>()
+ opened * std::mem::size_of::<Opened>()
+ (alone + opened_fresh) * std::mem::size_of::<usize>()
}
/// The open compute encoder updated a fence: its unit ends with it.
pub(super) fn fence_updated(&mut self) {
if let Some(unit) = &mut self.unit {
@@ -702,13 +763,14 @@ impl Predication {
// Where the unit laid a step, the last of `opened_fresh` is the encoder that
// laid its first: that one gates the commands of the unit's later encoders, so
// it encodes again alone only where the unit ended with it.
let first_step_at = unit.opened_fresh.len().saturating_sub(1);
for (at, &place) in unit.opened_fresh.iter().enumerate() {
let first_step_at = self.opened_fresh.len().saturating_sub(1);
for (at, &place) in self.opened_fresh.iter().enumerate() {
if !stepped || at < first_step_at || place == unit.place {
self.alone.push(place);
}
}
}
self.opened_fresh.clear();
if let (true, Some(check), Some(outermost)) =
(unit.live_open(), unit.check, unit.stack.first())
{
@@ -764,6 +826,7 @@ impl Predication {
Some(Predication {
unit: Some(Unit::new(place, opened.events, opened.dispatch_type)),
records: opened.records,
opened_fresh: vec![place],
..Predication::default()
})
}
+46 -24
View File
@@ -518,17 +518,23 @@ pub(super) const SPARE_LOG_BYTES: usize = 64 * 1024;
const SPARE_ROOM_BYTES: usize = SPARE_LOGS * SPARE_LOG_BYTES;
/// Cleared logs the device keeps for its next encoders (the module docs): of each kind,
/// [`SPARE_LOGS`], or for compute encoders as many as the last command buffer that held logs
/// for its commit gave back ([`give_held`](Self::give_held)) where that is more; each with at most [`SPARE_LOG_BYTES`] of
/// room, all of a kind together with at most [`SPARE_ROOM_BYTES`] (1 MiB), and no call or handle.
/// An encoder that logs takes one, or a new log where none is kept; its log comes back as its
/// encoder ends where its command buffer does not keep it, and else in the command buffer's
/// release, on its queue's handler thread.
/// [`SPARE_LOGS`], or for compute encoders as many as the last command buffer's release gave
/// back ([`give_compute`](Self::give_compute)) where that is more; each with at most
/// [`SPARE_LOG_BYTES`] of room, all of a kind together with at most [`SPARE_ROOM_BYTES`]
/// (1 MiB), and no call or handle. An encoder that logs takes one, or a new log where none is
/// kept; its log comes back as its encoder ends where its command buffer does not keep it, and
/// else in the command buffer's release, on its queue's handler thread, which keeps a compute
/// encoder's in the command buffer's state first, for the compute encoders of the command buffer
/// that takes the state next (`command_buffer/spare_states.rs`): those take theirs there, and
/// here only where it kept none.
#[derive(Default)]
pub(crate) struct SpareLogs {
compute: Spares<CallLog<ComputeCall>>,
blit: Spares<CallLog<BlitCall>>,
render: Spares<RenderRoom>,
/// The compute logs taken here: a device test's (`tests::spare_states`).
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
compute_taken: std::sync::atomic::AtomicU64,
}
/// One kind's [`SpareLogs`].
@@ -599,25 +605,48 @@ impl<T> Spares<T> {
impl SpareLogs {
/// A compute encoder's log: a kept one, or a new one.
pub(super) fn compute(&self) -> CallLog<ComputeCall> {
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
self.compute_taken
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
self.compute.take().unwrap_or_else(CallLog::new)
}
/// Clear `held`, the logs a command buffer held for its commit for its groups of compute
/// encoders and no split took (`command_buffer/fold.rs`), in its release, and keep them for
/// next encoders under one lock: as many as they are, within [`SPARE_ROOM_BYTES`], so a next
/// command buffer's encoders as many reuse their room rather than allocate. Their calls and
/// handles go now.
pub(super) fn give_held(&self, held: Vec<Replay>) {
if held.is_empty() {
return;
}
let mut compute = Vec::with_capacity(held.len());
for replay in held {
/// The compute logs taken here so far ([`compute`](Self::compute)): a device test's
/// (`tests::spare_states`).
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) fn compute_taken(&self) -> u64 {
self.compute_taken
.load(std::sync::atomic::Ordering::Relaxed)
}
/// Clear `logs`, those a command buffer's release lets go of (those its encoders kept and
/// those it held for its commit for its groups of encoders and no split took,
/// `command_buffer/fold.rs`): their calls and handles go now. The compute ones come back
/// cleared, with their room in bytes, for the command buffer's state to keep
/// (`State::keep_compute_logs`) and [`give_compute`](Self::give_compute) the rest; the others
/// are kept here ([`give`](Self::give)).
pub(super) fn cleared_compute(
&self,
logs: impl Iterator<Item = Replay>,
) -> Vec<(CallLog<ComputeCall>, usize)> {
let mut compute = Vec::new();
for replay in logs {
match replay {
Replay::Compute { log, .. } => compute.extend(log.cleared()),
other => self.give(other),
}
}
compute
}
/// Keep `compute`, cleared compute logs of a command buffer's release its state did not keep
/// ([`cleared_compute`](Self::cleared_compute)), for next encoders under one lock: as many as
/// they are, within [`SPARE_ROOM_BYTES`], so a next command buffer's encoders as many reuse
/// their room rather than allocate.
pub(super) fn give_compute(&self, compute: Vec<(CallLog<ComputeCall>, usize)>) {
if compute.is_empty() {
return;
}
self.compute.give_all(compute);
}
@@ -658,13 +687,6 @@ impl SpareLogs {
}
}
}
/// [`give`](Self::give) `replay` where this is its last hold; else the hold goes.
pub(super) fn give_last(&self, replay: Arc<Replay>) {
if let Some(replay) = Arc::into_inner(replay) {
self.give(replay);
}
}
}
/// Append `items` to `arena`: their span.
@@ -11,6 +11,14 @@ use metal2vulkan::device::DriverFact;
use std::collections::BTreeSet;
use std::ops::Range;
/// The order of a group after the encoder whose summary is `summary`, as a second encoder's join
/// builds it (`State::join_fold`).
fn order_after(summary: &Summary<ResourceKey>) -> FoldOrder<ResourceKey> {
let mut order = FoldOrder::none();
order.join(summary);
order
}
fn copy_read() -> Access {
Access::new(
vk::PipelineStageFlags2::COPY,
@@ -103,7 +111,7 @@ fn a_joining_encoder_meets_what_the_group_wrote() {
Use::reads(fill, true, UseRange::Bytes(0..16384), copy_read()),
bytes_written(heap, 0..16384),
]);
let order = FoldOrder::after(&first);
let order = order_after(&first);
let written: Vec<_> = order.byte_writes().collect();
assert_eq!(written, [(heap, 0..16384)]);
let joined = AliasWrites::joining(Some(&order));
@@ -124,7 +132,7 @@ fn a_joining_encoder_meets_what_the_group_wrote() {
fn a_draw_noted_apart_over_written_bytes_splits_the_next_command() {
let heap = ResourceKey::new();
let first = Summary::outside_encoders(vec![bytes_written(heap, 0..16384)]);
let order = FoldOrder::after(&first);
let order = order_after(&first);
let mut writes = AliasWrites::joining(Some(&order));
let buffer_read = Use::reads(heap, true, UseRange::Bytes(0..16384), copy_read());
writes.noted_apart(&[image_read(heap, 16384..32768), buffer_read]);
@@ -187,7 +195,7 @@ fn a_write_after_a_draw_noted_apart_over_its_image_splits_the_next_command() {
#[test]
fn a_pass_continues_where_no_memory_it_uses_meets_the_group_s_writes() {
let heap = ResourceKey::new();
let order = FoldOrder::after(&Summary::outside_encoders(vec![bytes_written(
let order = order_after(&Summary::outside_encoders(vec![bytes_written(
heap,
0..16384,
)]));
@@ -216,7 +224,7 @@ fn a_pass_continues_where_no_memory_it_uses_meets_the_group_s_writes() {
);
let bytes_read = Use::reads(heap, true, UseRange::Bytes(8192..8256), copy_read());
assert!(!AliasWrites::default().continues(&order, &[bytes_read]));
let quiet = FoldOrder::after(&Summary::outside_encoders(Vec::new()));
let quiet = order_after(&Summary::outside_encoders(Vec::new()));
assert!(drawn_over.continues(&quiet, &[image_read(heap, 0..64)]));
}
@@ -1,9 +1,11 @@
//! A command buffer takes the state a released command buffer of its device left, reset by that
//! one's release, its lists of records emptied with their room kept
//! (`command_buffer/spare_states.rs`): one of no more encoders than that one grows none of its
//! lists (`WorkCounts::record_lists_grown`); one made after another's release builds no state
//! (`WorkCounts::command_buffer_states_made`); the state carries nothing of the command buffer
//! before; and the device keeps at most 64 states, none whose lists hold past 8 MiB.
//! lists (`WorkCounts::record_lists_grown`), its command predication's and its groups' order's
//! among them, and its compute encoders take the logs the state kept, none the device's spares';
//! one made after another's release builds no state (`WorkCounts::command_buffer_states_made`);
//! the state carries nothing of the command buffer before; and the device keeps at most 64
//! states, none whose lists hold past 8 MiB.
//!
//! Device tests: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`,
//! `m2v_cpu_icd`), on the kind of device the cfg selects. The kernel is `compute_parked.rs`'s.
@@ -63,6 +65,64 @@ fn a_command_buffer_of_as_many_encoders_as_the_last_grows_no_list() {
}
}
/// A command buffer of `encoders` compute encoders of `queue`, one dispatch each, committed,
/// completed and dropped: read once its device kept its state, at its release, how many of its
/// lists grew, how many of its encoders joined a group (`WorkCounts::encoders_folded`) and how
/// many compute logs its encoders took from the device's spares (`SpareLogs::compute`).
fn reused(kernel: &Kernel, queue: &CommandQueue, output: &Buffer, encoders: u64) -> [u64; 3] {
let before = kernel.device.work_counts();
let spares = kernel.device.shared().scheduler.spare_logs();
let taken = spares.compute_taken();
let command_buffer = queue.command_buffer().unwrap();
for _ in 0..encoders {
kernel.dispatch(&command_buffer, (output, 0));
}
let taken = spares.compute_taken() - taken;
kernel.run(&command_buffer);
drop(command_buffer);
until("the command buffer's release kept its state", || {
kernel.device.work_counts().record_storage_kept > before.record_storage_kept
});
let after = kernel.device.work_counts();
[
after.record_lists_grown - before.record_lists_grown,
after.encoders_folded - before.encoders_folded,
taken,
]
}
/// Command buffers of five compute encoders each, one after another's release, as a guest's
/// frame of a few one-dispatch encoders: past the first, each starts on the state the one before
/// left and grows none of its lists, its command predication's (each compute encoder enters a
/// unit) and its group's order's (its last four encoders join its first's group) among them, and
/// its compute encoders take the logs that state kept, none the device's spares'.
#[test]
fn a_reused_command_buffer_of_five_compute_encoders_grows_no_list_and_takes_no_spare_log() {
let scratch = Scratch::new("spare-states-five");
let kernel = Kernel::new(&scratch);
kernel.warm();
until(
"the warming command buffer's release kept its state",
|| kernel.device.work_counts().record_storage_kept > 0,
);
let queue = kernel.device.new_command_queue().unwrap();
let output = kernel.output(1);
let [_, folded, _] = reused(&kernel, &queue, &output, 5);
assert_eq!(
folded, 4,
"the first command buffer's encoders that joined a group"
);
for round in 1..4 {
let [grown, folded, taken] = reused(&kernel, &queue, &output, 5);
assert_eq!(folded, 4, "round {round}: the encoders that joined a group");
assert_eq!(grown, 0, "round {round}: the lists grown");
assert_eq!(
taken, 0,
"round {round}: the logs taken from the device's spares"
);
}
}
/// The longest a command buffer is waited for.
const WAIT: Duration = Duration::from_secs(30);
@@ -60,6 +60,14 @@ fn barrier(src: Access, dst: Access) -> Option<Barrier> {
Some(Barrier { src, dst })
}
/// The order of a group after the encoder whose summary is `summary`, as a second encoder's join
/// builds it (`State::join_fold`).
fn order_after(summary: &Summary<Key>) -> FoldOrder<Key> {
let mut order = FoldOrder::none();
order.join(summary);
order
}
/// An ordered encoder with one command per entry of `commands`.
fn encoder(commands: &[&[Use<Key>]]) -> Summary<Key> {
let mut uses = EncoderUses::new(true);
@@ -1658,7 +1666,7 @@ fn a_folded_encoder_s_first_dispatch_takes_a_serial_encoder_s_barrier() {
// (`encoder_fold.rs`): its own order needs nothing, the group's order the same barrier.
let mut first = EncoderUses::<Key>::new(true);
first.order(COMPUTE, &bump(), Reach::Unnamed);
let order = FoldOrder::after(&first.finish());
let order = order_after(&first.finish());
let mut second = EncoderUses::<Key>::new(true);
let own = second.order(COMPUTE, &bump(), Reach::Unnamed);
assert_eq!(own, None);
@@ -1670,6 +1678,43 @@ fn a_folded_encoder_s_first_dispatch_takes_a_serial_encoder_s_barrier() {
);
}
/// A group's order cleared for the command buffer's next group (`FoldOrder::clear`, the room
/// the groups of a command buffer and of the ones that take its state pass on): it answers as
/// one built fresh, nothing of the group before left (its writes and its fenced writes), and the
/// same uses again take no more room than the clear kept.
#[test]
fn a_cleared_fold_order_answers_as_a_fresh_one_in_the_room_it_kept() {
let written = [
Use::writes(5, true, bytes(0..64), shader_write()),
Use::writes(6, true, bytes(0..256), shader_write()),
];
let read = [Use::reads(5, true, bytes(0..64), shader_read())];
let group = |fence: bool| {
let mut first = EncoderUses::<Key>::new(true);
first.order(COMPUTE, &written, Reach::Unnamed);
if fence {
first.update_fence(100, None);
}
first.finish()
};
let mut order = order_after(&group(true));
assert!(order.barrier(&read).is_some(), "the group's write");
assert!(order.fence_barrier(COMPUTE, &read).is_some(), "the fence");
order.clear();
let room = order.room();
assert_eq!(order.barrier(&read), None, "the write of the group before");
assert_eq!(order.fence_barrier(COMPUTE, &read), None, "its fence");
order.join(&group(false));
let fresh = order_after(&group(false));
assert!(fresh.barrier(&read).is_some());
assert_eq!(order.barrier(&read), fresh.barrier(&read));
assert_eq!(
order.fence_barrier(COMPUTE, &read),
fresh.fence_barrier(COMPUTE, &read)
);
assert_eq!(order.room(), room, "the room it kept");
}
/// A group's encoder after one that wrote an untracked buffer and updated a fence
/// (`encoder_fold.rs`'s **Fences**): its first dispatch orders after the fenced writes by the
/// least barrier between dispatches; a later dispatch that reaches no more records none; one that
@@ -1684,7 +1729,7 @@ fn a_folded_encoder_after_a_fence_update_takes_the_least_barrier_widened_only_by
if let Some(fence) = fence {
first.update_fence(fence, None);
}
FoldOrder::after(&first.finish())
order_after(&first.finish())
};
let unfenced = writer(None);
let mut order = writer(Some(100));
@@ -7871,7 +7871,8 @@ pub struct WorkCounts {
pub parked_compute_taken: u64,
/// The lists a released command buffer keeps of what its encoders ended with (its ended
/// encoders' records, their recordings, a group's logs its members did not keep and those held
/// for its commit) that held more room as it was released than the storage it started on:
/// for its commit, its command predication's lists, and its groups' order's map and lists)
/// that held more room as it was released than the storage it started on:
/// counted once each, at the release. A command buffer starts on the state a released one of
/// the device left (`record_storage_kept`), its lists emptied with their room kept, so one of
/// no more encoders than that one's grows none.
+1 -1
View File
@@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 524;
/// changes no behaviour, and then updates that hash alone with the commit saying why, or changes
/// behaviour and also bumps this version. The commit that bumps it says what changed; this comment
/// keeps no history.
pub const RUNTIME_VERSION: u32 = 2478;
pub const RUNTIME_VERSION: u32 = 2479;
/// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex,
/// of the manifest, the build script, and exactly the files the crate roots' module tree compiles