🆕 Name a host command buffer's images and blit sources at a loss

A device loss's lines called a command buffer of the host's own just that,
with its encoders' kinds: no blit operand was recorded and no host image named,
so a report (issue 173, an RX 6600 XT whose lost command buffer was a host blit
or render at the display's start, its fault address in no rt range) could not
tell a window swapchain's image from an image of rt's own.

Objects now carry a role beside their guest id: the platform names a window
swapchain's image, and the host names the scanout's import, a presented
surface's texture and the display's view of it, the display colour's table and
ramps, the cursor's glyph, the overlay's image and a host read's target. In a
command buffer of the host's own, each encoder names its operands: a blit what
its copies read and what its copies, fills and mipmap generations write; a
render encoder the textures it binds. The list of command buffers in flight
says, for each of the host's own, what each encoder renders into, binds, reads
and writes, by role or guest id ("render into colour 0 a window's swapchain
image, blit from the scanout's import into a window's swapchain image"); the
oldest's attachments and lists name roles where there is no guest id; and the
line of a host command buffer lost in flight names its encoders the same way.

A window swapchain's clear at its retire, committed on rt outside the
platform's command buffers, is now on that list from before its commit until
its wait returns, named as such. It holds no index given back: the commit order
the platform's own indices wait on passes over it, as before it was listed.

Diagnostics only: nothing the guest or the C API sees changes, and nothing is
committed differently or at another time.
This commit is contained in:
Anees Iqbal committed 2026-11-25 19:17:48 -08:00
1 parent d2c27d16be
commit 96cd80e053
15 files changed
+1040 -177

No files matched your search

@@ -34,6 +34,10 @@
//! buffers ([`Unbuilt::Icb`]). Each encodes nothing, counted.
//! - **The guest's RAM** is copied by no blit: the device copies none
//! (`GpuDevice::copies_guest_ram`), so each copy of it answers false.
//! - **Its names for a lost device's lines** (`super::fault`'s docs, "The command buffers in
//! flight"): its kind, and, in a command buffer of the host's own, what its copies read and what
//! its copies, fills and mipmap generations write, by the guest's ids and the host's roles; they
//! join its command buffer's as it ends, or as it goes unended.
//!
//! A command rt refuses encodes nothing, counted under the refusal's kind
//! ([`rt_refused_texture`]), the first texture copy of each kind naming its textures (with each
@@ -53,13 +57,14 @@ use crate::core::sync::Mutex;
use super::command::{Kept, OpenMark};
use super::diag::Use;
use super::fault::{EncoderKind, EncoderNames, Naming, Operands};
use super::unbuilt::{RtRefusal, Unbuilt, refuse, refused_as, rt_refused_texture};
use super::{RtObj, RtPlatform, RtTexture};
/// `id<MTLBlitCommandEncoder>` on metal2vulkan-runtime.
pub struct RtBlitEncoder {
/// rt's encoder, until `endEncoding` ends it.
rt: Mutex<Option<rt::BlitCommandEncoder>>,
/// rt's encoder, until `endEncoding` ends it, and what it names.
rt: Mutex<Open>,
/// Its command buffer's mark of it open, until it ends.
open: OpenMark,
/// What its command buffer keeps: its uses of textures, for the boot diagnostics
@@ -67,12 +72,32 @@ pub struct RtBlitEncoder {
kept: Kept,
}
/// A blit encoder's rt encoder, until `endEncoding` ends it, and what it names.
struct Open {
/// rt's encoder.
encoder: Option<rt::BlitCommandEncoder>,
/// What it names, for a lost device's lines (`super::fault`'s docs, "The command buffers in
/// flight"): in a command buffer of the host's own, what its copies read and what its copies,
/// fills and mipmap generations write; it joins its command buffer's as it ends or goes.
naming: Naming,
}
impl RtBlitEncoder {
/// The encoder over rt's `encoder`, open as `open` marks it, its uses of textures noted in its
/// command buffer's `kept`.
pub fn new(encoder: rt::BlitCommandEncoder, open: OpenMark, kept: Kept) -> RtBlitEncoder {
/// command buffer's `kept`, naming its operands where `operands` (`super::fault`'s
/// `Operands`).
pub fn new(
encoder: rt::BlitCommandEncoder,
open: OpenMark,
kept: Kept,
operands: bool,
) -> RtBlitEncoder {
let names = EncoderNames::new(EncoderKind::Blit).naming_operands(operands);
RtBlitEncoder {
rt: Mutex::new(Some(encoder)),
rt: Mutex::new(Open {
encoder: Some(encoder),
naming: Naming::new(kept.encoded(), names),
}),
open,
kept,
}
@@ -173,6 +198,96 @@ impl RtBlitEncoder {
}
}
/// Notes in `operands` what `cmd`, a command of an encoder of a command buffer of the host's own,
/// reads and writes, by name (`super::fault`'s docs, "The command buffers in flight"): a copy's
/// source and destination, a fill's buffer and a mipmap generation's texture, each named or not,
/// refused or not.
fn note_operands(operands: &mut Operands, cmd: &BlitCmd<'_, RtPlatform>) {
let (reads, writes) = (&mut operands.reads, &mut operands.writes);
match *cmd {
BlitCmd::CopyBufferToTexture {
source_buffer,
destination_texture,
..
} => {
reads.add_named(source_buffer.named());
writes.add_named(destination_texture.named());
}
BlitCmd::CopyBufferToTextureOptions {
source_buffer,
destination_texture,
..
} => {
if let Some(buffer) = source_buffer {
reads.add_named(buffer.named());
}
if let Some(texture) = destination_texture {
writes.add_named(texture.named());
}
}
BlitCmd::CopyBufferToBuffer {
source_buffer,
destination_buffer,
..
} => {
if let Some(buffer) = source_buffer {
reads.add_named(buffer.named());
}
if let Some(buffer) = destination_buffer {
writes.add_named(buffer.named());
}
}
BlitCmd::CopyTextureToBuffer {
source_texture,
destination_buffer,
..
} => {
reads.add_named(source_texture.named());
writes.add_named(destination_buffer.named());
}
BlitCmd::CopyTextureToBufferOptions {
source_texture,
destination_buffer,
..
} => {
if let Some(texture) = source_texture {
reads.add_named(texture.named());
}
if let Some(buffer) = destination_buffer {
writes.add_named(buffer.named());
}
}
BlitCmd::CopyTextureRegion {
source_texture,
destination_texture,
..
}
| BlitCmd::CopyTextureRegionOptions {
source_texture,
destination_texture,
..
}
| BlitCmd::CopyTextureSlices {
source_texture,
destination_texture,
..
} => {
reads.add_named(source_texture.named());
writes.add_named(destination_texture.named());
}
BlitCmd::FillBuffer { buffer, .. } | BlitCmd::FillBufferPattern4 { buffer, .. } => {
writes.add_named(buffer.named());
}
BlitCmd::FillTexture { texture, .. } | BlitCmd::FillTextureColor { texture, .. } => {
writes.add_named(texture.named());
}
BlitCmd::GenerateMipmaps {
texture: Some(texture),
} => writes.add_named(texture.named()),
_ => {}
}
}
/// Why a command encodes nothing before rt sees it, or after: an encoder's ([`report`]).
pub(super) enum Stop {
/// Metal's validation stops it: counted as Metal's refusal, with what it was.
@@ -755,13 +870,17 @@ impl BlitEncoder<RtPlatform> for RtObj<RtBlitEncoder> {
let mut open = self.rt.lock();
let ending = matches!(cmd, BlitCmd::EndEncoding);
self.note_uses(&cmd);
let stopped = match open.as_mut() {
if let Some(operands) = (open.naming.names()).and_then(|n| n.operands.as_mut()) {
note_operands(operands, &cmd);
}
let stopped = match open.encoder.as_mut() {
Some(e) => encode(e, cmd).err(),
None => Some(Stop::Metal("a command after endEncoding")),
};
if ending && let Some(e) = open.take() {
if ending && let Some(e) = open.encoder.take() {
e.end_encoding();
self.open.end();
open.naming.end();
}
drop(open);
report(sel, stopped);
@@ -812,7 +931,7 @@ impl BlitEncoder<RtPlatform> for RtObj<RtBlitEncoder> {
#[cfg(unix)]
fn release_to_external(&self, buffer: &<RtPlatform as Platform>::Buffer) -> Result<(), String> {
let mut open = self.rt.lock();
let encoder = open.as_mut().ok_or("the encoder has ended")?;
let encoder = open.encoder.as_mut().ok_or("the encoder has ended")?;
(encoder.release_to_external(buffer.rt())).map_err(|error| format!("rt's release: {error}"))
}
}
@@ -40,16 +40,21 @@
//! and above where none holds it, and among the tables' objects' ranges released before the
//! loss. Two lines follow, whether rt named the call or not: the command buffers committed and
//! not complete, the oldest committed first, each with its context, its commit's time and its
//! encoders' kinds, and what the oldest's encoders name: its render passes' attachments, the
//! heaps and resources they declare and the buffers they bind (`super::fault`'s docs, "The
//! command buffers in flight"). Each commit adds its command buffer to its device's list before
//! rt has it, and its first completed handler takes it off.
//! encoders' kinds, and, for one of the host's own, what its encoders render into and bind and
//! what its blits read and write, by the guest's ids and the host's roles (a window
//! swapchain's image, the scanout's import, ...); and what the oldest's encoders name: its
//! render passes' attachments, the heaps and resources they declare and the buffers they bind
//! (`super::fault`'s docs, "The command buffers in flight"). Each commit adds its command buffer
//! to its device's list before rt has it, and its first completed handler takes it off; a
//! window swapchain's clear at its retire, which the swapchain commits on rt itself, is listed
//! from before its commit until the swapchain's wait for it returns ([`DeviceLoss::listing`]).
//! Each command buffer that fails with the device lost is counted, `rt-device-lost`, in the
//! process's degradation counts (docs/conventions.md). Then each command buffer rt ends as in
//! flight writes a line of its own, naming the work the guest knows it by, as its caller named
//! it (`CommandBuffer::names_work`): the guest's command buffer, by its object id, and the
//! object ids of the first compute and the first render pipeline state its encoders set, or
//! `none`; one the caller named nothing for, the host's own, says so. A command buffer cut in
//! `none`; one the caller named nothing for, the host's own, says so, with its encoders as its
//! entry on the list names them (`super::fault::Flights::told`). A command buffer cut in
//! parts writes one line however many of its parts are lost in flight. The first
//! [`IN_FLIGHT_NAMED`] write theirs, and the next a line that the rest are counted only: each is
//! counted, `rt-device-lost-in-flight`. The device is lost from rt's
@@ -519,9 +524,10 @@ impl Failure {
fn read(&self, error: Option<rt::CommandBufferError>) -> Option<NsErrorText> {
let error = error?;
let work = self.work.get().map(Arc::as_ref);
let flight = self.flight.load(Ordering::SeqCst);
Some(
self.error
.get_or_init(|| ns_error(error, &self.loss, &*self.cause, work))
.get_or_init(|| ns_error(error, &self.loss, &*self.cause, work, flight))
.clone(),
)
}
@@ -591,11 +597,25 @@ impl DeviceLoss {
&self.flights
}
/// Lists `flight`, a command buffer of rt's that the platform commits on rt itself rather than
/// through its command buffers (a window swapchain's clear at its retire, `super::swapchain`),
/// among the device's command buffers committed and not complete, as a commit lists its
/// command buffer, before rt has it: counted among them, and on their list (`super::fault`'s
/// docs, "The command buffers in flight"), until the answer goes, once the caller's wait for
/// it returned or rt refused its commit.
pub(super) fn listing(&self, flight: super::fault::Flight) -> Listed<'_> {
let number = self.flights.add(flight);
self.open.fetch_add(1, Ordering::SeqCst);
Listed { loss: self, number }
}
/// rt ended a command buffer as in flight at the loss, the guest's names for its work `work`
/// where its caller named them: counted, once however many of its parts it ends so, and, of
/// the first [`IN_FLIGHT_NAMED`], each writes a line naming them; the next writes that the
/// rest are counted only (the module's docs, "A lost device's line").
fn lost_in_flight(&self, work: Option<&WorkNames>) {
/// where its caller named them, else its number on the list of those in flight, `flight`:
/// counted, once however many of its parts it ends so, and, of the first [`IN_FLIGHT_NAMED`],
/// each writes a line naming them, or, for one of the host's own, its encoders as its entry
/// on the list names them ([`super::fault::Flights::told`]); the next writes that the rest are
/// counted only (the module's docs, "A lost device's line").
fn lost_in_flight(&self, work: Option<&WorkNames>, flight: u64) {
if work.is_some_and(|work| !work.first_told()) {
return;
}
@@ -625,12 +645,18 @@ impl DeviceLoss {
named(render)
)
}
(std::cmp::Ordering::Less, None) => format!(
"reims-vgpu: a command buffer of the host's own, which the guest does not \
number, was lost in flight on the rt platform's device on {} \
({DEVICE_LOST_IN_FLIGHT})\n",
self.gpu
),
(std::cmp::Ordering::Less, None) => {
let encoders = match self.flights.told(flight) {
Some(encoders) => format!(", {encoders}"),
None => String::new(),
};
format!(
"reims-vgpu: a command buffer of the host's own, which the guest does not \
number, was lost in flight on the rt platform's device on {}{encoders} \
({DEVICE_LOST_IN_FLIGHT})\n",
self.gpu
)
}
};
say_lost(&line);
}
@@ -670,6 +696,23 @@ impl DeviceLoss {
}
}
/// A command buffer the platform committed on rt itself, listed among its device's command
/// buffers committed and not complete ([`DeviceLoss::listing`]) until this goes.
pub(super) struct Listed<'a> {
/// The device's loss, which lists it.
loss: &'a DeviceLoss,
/// Its number on the list.
number: u64,
}
impl Drop for Listed<'_> {
/// It is complete, or rt refused its commit: off the count and the list.
fn drop(&mut self) {
self.loss.open.fetch_sub(1, Ordering::SeqCst);
self.loss.flights.remove(self.number);
}
}
/// The lost devices' lines the process wrote, on whichever thread: rt's completion thread runs
/// the completed handler that writes one (`Failure::completed`).
#[cfg(test)]
@@ -782,6 +825,13 @@ impl RtCommandBuffer {
OpenMark::new(&self.open)
}
/// Whether its encoders name their operands (`super::fault`'s `Operands`): a command buffer of
/// the host's own, which its caller named no work for (`names_work`, which names it before
/// any encoder).
fn names_operands(&self) -> bool {
self.failure.work.get().is_none()
}
/// A compute encoder of `dispatch_type`, made by `sel`: nil where rt refuses it, counted.
fn compute_encoder_of(
&self,
@@ -1079,17 +1129,19 @@ fn status(status: rt::CommandBufferStatus) -> CommandBufferStatus {
/// lost in flight on the device whose loss is `loss`, `Internal` for any other; a command buffer
/// that fails with its device lost tells `loss`, with rt's cause, which `cause` reads
/// ([`DeviceLoss::lost`]), and one lost in flight the guest's names for its work, `work`, where
/// its caller named them ([`DeviceLoss::lost_in_flight`]).
/// its caller named them, or its number on the device's list of command buffers in flight,
/// `flight`, 0 for none ([`DeviceLoss::lost_in_flight`]).
fn ns_error(
error: rt::CommandBufferError,
loss: &DeviceLoss,
cause: &dyn Fn() -> Option<rt::DeviceLoss>,
work: Option<&WorkNames>,
flight: u64,
) -> NsErrorText {
if let rt::CommandBufferError::DeviceLost { in_flight } = error {
loss.lost(cause);
if in_flight {
loss.lost_in_flight(work);
loss.lost_in_flight(work, flight);
}
}
let code = match error {
@@ -1168,10 +1220,9 @@ impl CommandBuffer<RtPlatform> for RtObj<RtCommandBuffer> {
let _ = on;
Ok(match self.rt.blit_command_encoder() {
Ok(encoder) => {
let kept = self.kept.clone();
let blit = super::fault::EncoderNames::new(super::fault::EncoderKind::Blit);
kept.encoded().push(blit);
Some(RtObj::new(RtBlitEncoder::new(encoder, self.opened(), kept)))
let (mark, kept) = (self.opened(), self.kept.clone());
let operands = self.names_operands();
Some(RtObj::new(RtBlitEncoder::new(encoder, mark, kept, operands)))
}
Err(error) => {
rt_refused_create("blitCommandEncoder", &error);
@@ -1276,6 +1327,7 @@ impl CommandBuffer<RtPlatform> for RtObj<RtCommandBuffer> {
let loss = &self.failure.loss;
let number = loss.flights.add(super::fault::Flight {
cb: self.failure.work.get().map(|work| work.cb()),
by: super::fault::CommittedBy::Platform,
committed: super::fault::wall_now(),
encoders,
});
@@ -1451,8 +1503,9 @@ impl CommandBuffer<RtPlatform> for RtObj<RtCommandBuffer> {
for tiled in render_pass_descriptor.tiled() {
kept.takes().used_tiled(&tiled);
}
let operands = self.names_operands();
Some(RtObj::new(RtRenderEncoder::new(
encoder, mark, kept, targets,
encoder, mark, kept, targets, operands,
)))
}
Err(error) => {
@@ -1692,7 +1745,7 @@ mod tests {
let codes = |errors: &[rt::CommandBufferError]| {
let loss = DeviceLoss::new("a GPU".to_owned());
(errors.iter())
.map(|&e| ns_error(e, &loss, &|| None, None))
.map(|&e| ns_error(e, &loss, &|| None, None, 0))
.inspect(|e| assert_eq!(e.domain, ERROR_DOMAIN))
.map(|e| e.code)
.collect::<Vec<_>>()
@@ -1814,12 +1867,15 @@ mod tests {
/// device's, naming the guest's command buffer and the first compute and render pipeline
/// states its encoders set, `none` for a kind it set none of, as its caller named them; one cut
/// in parts, which share its names, writes one however many of them are lost in flight, and
/// one its caller named nothing for says it is the host's own. One rt ends held, not in
/// flight, writes none. Of the first [`IN_FLIGHT_NAMED`] each writes its line, the next that
/// the rest are counted only, and each is counted once (the module's docs, "A lost device's
/// line").
/// one its caller named nothing for says it is the host's own, with its encoders as its entry
/// on the device's list of command buffers in flight names them, where it is on it. One rt
/// ends held, not in flight, writes none. Of the first [`IN_FLIGHT_NAMED`] each writes its
/// line, the next that the rest are counted only, and each is counted once (the module's
/// docs, "A lost device's line").
#[test]
fn each_command_buffer_lost_in_flight_names_the_guest_s_work() {
use super::super::diag::Point;
use super::super::fault::{CommittedBy, EncoderKind, EncoderNames, Flight, Name, Role};
use rt::CommandBufferError::DeviceLost;
let gpu = "C GPU (1234:def0)";
let before = counted(DEVICE_LOST_IN_FLIGHT);
@@ -1857,6 +1913,27 @@ mod tests {
lost(failure(Some(&Arc::new(WorkNames::new(0x2c)))), false);
lost(failure(Some(&Arc::new(WorkNames::new(0x2b)))), true);
lost(failure(None), true);
// A window's frame of the host's own, on the list: a clear of a swapchain image, then a
// blit into it from the scanout's import.
let image = Name::of_role(Role::SwapchainImage);
let clear = EncoderNames {
attachments: vec![(Point::Color(0), image)],
..EncoderNames::new(EncoderKind::Render).naming_operands(true)
};
let mut blit = EncoderNames::new(EncoderKind::Blit).naming_operands(true);
let operands = blit.operands.as_mut().expect("it names its operands");
operands.reads.note(Name::of_role(Role::ScanoutImport));
operands.writes.note(image);
let frame = failure(None);
let listed = loss.flights.add(Flight {
cb: None,
by: CommittedBy::Platform,
committed: 0,
encoders: vec![clear, blit],
});
frame.flight.store(listed, Ordering::SeqCst);
lost(frame, true);
assert!(loss.flights.is_empty());
let named = [
"reims-vgpu: the guest's command buffer 0x2a was lost in flight on the rt platform's \
device on C GPU (1234:def0), its encoders' first compute pipeline state 0xb and first \
@@ -1867,24 +1944,28 @@ mod tests {
"reims-vgpu: a command buffer of the host's own, which the guest does not number, was \
lost in flight on the rt platform's device on C GPU (1234:def0) \
(rt-device-lost-in-flight)\n",
"reims-vgpu: a command buffer of the host's own, which the guest does not number, was \
lost in flight on the rt platform's device on C GPU (1234:def0), its encoders (2): \
render into colour 0 a window's swapchain image, blit from the scanout's import into \
a window's swapchain image (rt-device-lost-in-flight)\n",
];
assert_eq!(in_flight(), named);
assert_eq!(counted(DEVICE_LOST_IN_FLIGHT), before + 3);
// Seven more: the first five write theirs, the sixth that the rest are counted only.
assert_eq!(counted(DEVICE_LOST_IN_FLIGHT), before + 4);
// Seven more: the first four write theirs, the fifth that the rest are counted only.
for cb in 0x30..0x37 {
lost(failure(Some(&Arc::new(WorkNames::new(cb)))), true);
}
let lines = in_flight();
assert_eq!(lines.len(), IN_FLIGHT_NAMED + 1, "{lines:#?}");
assert_eq!(lines[..3], named);
assert!(lines[7].contains("command buffer 0x34 was lost in flight"));
assert_eq!(lines[..4], named);
assert!(lines[7].contains("command buffer 0x33 was lost in flight"));
assert_eq!(
lines[8],
"reims-vgpu: more command buffers were lost in flight on the rt platform's device on \
C GPU (1234:def0): the degradation counts give how many in all \
(rt-device-lost-in-flight)\n"
);
assert_eq!(counted(DEVICE_LOST_IN_FLIGHT), before + 10);
assert_eq!(counted(DEVICE_LOST_IN_FLIGHT), before + 11);
}
/// The lost devices' lines the process wrote that hold `part`.
@@ -2012,6 +2093,123 @@ mod tests {
assert!(flights.is_empty(), "{:#?}", flights.lines(gpu, 0));
}
/// On the GPU the test holds, a command buffer of the host's own (its caller named it no work)
/// committed and not complete is listed with what its encoders render into and bind and what
/// its blits read and write, by the host's roles and the guest's ids: here a blit from a
/// buffer the host named the scanout's import into a texture it named a window's swapchain
/// image, then a pass that clears that texture and binds a presented surface's texture twice,
/// named once. The oldest's line names the pass's attachment by its role.
#[test]
fn a_host_command_buffer_in_flight_is_listed_with_its_operands_on_vulkan() {
use super::super::fault::{self, Role};
use crate::core::platform::descriptor::RenderPassDescriptor as _;
use crate::core::platform::render::{RenderCmd, RenderEncoder as _};
use crate::core::platform::types::{MtlOrigin, MtlSize};
use crate::core::platform::values::{ColorAttachmentSet, TextureDesc};
let platform = RtPlatform::new();
let device = (platform.system_default_device()).expect("an rt device on the GPU it holds");
let on = OnFault::Return;
let queue = device.new_command_queue().expect("a command queue");
let scanout = device.new_buffer_of_length(on, 64, 0);
let scanout = scanout.expect("never a raise").expect("a buffer");
fault::name_role_buffer(&scanout, Role::ScanoutImport);
let texture = |usage: u64| {
let desc = TextureDesc {
pixel_format: 80,
width: 4,
height: 4,
usage,
..TextureDesc::default()
};
let made = device.new_texture(on, &platform.texture_descriptor(&desc));
made.expect("never a raise").expect("a texture")
};
// Render target and shader read; shader read.
let image = texture(0x4 | 0x1);
fault::name_role_texture(&image, Role::SwapchainImage);
let surface = texture(0x1);
fault::name_texture(&surface, 0x500_0000_0012);
fault::name_role_texture(&surface, Role::Presented);
let shared = device.new_shared_event().expect("a shared event");
let made = queue.command_buffer(on).expect("never a raise");
let made = made.expect("a command buffer");
assert_eq!(made.encode_wait(Some(EventRef::Shared(&shared)), 1), Ok(()));
let blit = made.blit_encoder(on).expect("never a raise");
let blit = blit.expect("a blit encoder");
let copy = BlitCmd::CopyBufferToTexture {
source_buffer: &scanout,
source_offset: 0,
source_bytes_per_row: 16,
source_bytes_per_image: 64,
source_size: MtlSize::new(4, 4, 1),
destination_texture: &image,
destination_slice: 0,
destination_level: 0,
destination_origin: MtlOrigin::new(0, 0, 0),
};
assert_eq!(blit.encode(on, copy), Ok(()));
assert_eq!(blit.encode(on, BlitCmd::EndEncoding), Ok(()));
let pass = platform.new_render_pass_descriptor();
let clear = ColorAttachmentSet {
texture: Some(Some(&image)),
load_action: Some(2),
store_action: Some(1),
..ColorAttachmentSet::default()
};
assert_eq!(pass.set_color_attachment(on, 0, &clear), Ok(()));
let render = made.render_encoder(on, &pass).expect("never a raise");
let render = render.expect("a render encoder");
for index in [0, 1] {
let bind = RenderCmd::SetFragmentTexture {
texture: Some(&surface),
index,
};
assert_eq!(render.encode(on, bind), Ok(()));
}
assert_eq!(render.encode(on, RenderCmd::EndEncoding), Ok(()));
assert_eq!(made.commit(on), Ok(()));
let flights = &device.loss().flights;
let gpu = "GPU (1234:def0)";
let lines = flights.lines(gpu, super::super::fault::wall_now());
assert_eq!(lines.len(), 2, "{lines:#?}");
assert!(
lines[0].contains(
", the oldest committed first: a command buffer of the host's own, committed at "
),
"{}",
lines[0]
);
assert!(
lines[0].ends_with(
" s before the loss), its encoders (2): blit from the scanout's import into a \
window's swapchain image, render into colour 0 a window's swapchain image, \
binding the textures 0x50000000012 (a presented surface's texture)\n"
),
"{}",
lines[0]
);
assert_eq!(
lines[1],
"reims-vgpu: the oldest command buffer committed and not complete at the loss of the \
rt platform's device on GPU (1234:def0), a command buffer of the host's own: its \
render passes' attachments: encoder 2: colour 0 a window's swapchain image; the \
heaps its encoders declare (useHeap:): none; the buffers they declare \
(useResource:): none; the textures they declare (useResource:): none; the buffers \
they bind: none\n"
);
assert_eq!(shared.set_signaled_value(1), Ok(()));
assert_eq!(made.wait_until_completed(on), Ok(()));
assert_eq!(made.status(), CommandBufferStatus::COMPLETED);
let mut waited = 0;
while !flights.is_empty() && waited < 1000 {
std::thread::sleep(std::time::Duration::from_millis(10));
waited += 1;
}
assert!(flights.is_empty(), "{:#?}", flights.lines(gpu, 0));
}
/// On the GPU the test holds: a command buffer its caller failed for a deferred buffer's
/// memory ends with Metal's `MTLCommandBufferErrorOutOfMemory` (8) once rt completes it, its
/// status an error, as its completed handlers are told; one not failed completes with none
@@ -519,18 +519,18 @@ fn note_copies(used: &Used, cmd: &ComputeCmd<'_, RtPlatform>) {
}
/// Notes in `names` what `cmd` names (`super::fault`'s docs, "The command buffers in flight"): the
/// buffers it binds, and the heaps and resources it declares, by their guest ids.
/// buffers it binds, and the heaps and resources it declares, by their names.
fn note_names(names: &mut EncoderNames, cmd: &ComputeCmd<'_, RtPlatform>) {
match cmd {
ComputeCmd::SetBuffers { buffers, .. }
| ComputeCmd::SetBuffersAttributeStrides { buffers, .. } => {
for buffer in buffers.iter().flatten() {
names.bound_buffers.add(buffer.named().id());
names.bound_buffers.add_named(buffer.named());
}
}
ComputeCmd::UseHeaps { heaps } => {
for heap in heaps.iter().flatten() {
names.heaps.add(heap.named().id());
names.heaps.add_named(heap.named());
}
}
ComputeCmd::UseResources { resources, .. } => note_declared(names, resources),
@@ -538,16 +538,16 @@ fn note_names(names: &mut EncoderNames, cmd: &ComputeCmd<'_, RtPlatform>) {
}
}
/// Notes in `names` the resources a `useResources:` call declares, by their guest ids (an
/// indirect command buffer, which rt builds none of, as none).
/// Notes in `names` the resources a `useResources:` call declares, by their names (an indirect
/// command buffer, which rt builds none of, as none).
pub(super) fn note_declared(
names: &mut EncoderNames,
resources: &[Option<ResourceRef<'_, RtPlatform>>],
) {
for resource in resources.iter().flatten() {
match resource {
ResourceRef::Buffer(buffer) => names.declared_buffers.add(buffer.named().id()),
ResourceRef::Texture(texture) => names.declared_textures.add(texture.named().id()),
ResourceRef::Buffer(buffer) => names.declared_buffers.add_named(buffer.named()),
ResourceRef::Texture(texture) => names.declared_textures.add_named(texture.named()),
ResourceRef::Icb(_) => {}
}
}
@@ -544,7 +544,7 @@ impl PassFields {
texture_type: d.texture_type.as_raw(),
samples: d.sample_count,
index: texture.rt().gpu_resource_id().index,
id: texture.named().id(),
name: texture.named().name(),
made: std::sync::Arc::clone(texture.made()),
})
};
@@ -1326,8 +1326,9 @@ pub struct Target {
pub samples: u32,
/// Its texture's index, 0 for one with none: rt reads a fetched attachment through it.
pub index: u32,
/// Its texture's guest object id, 0 for none (`super::fault`'s `Named`).
pub id: u64,
/// Its texture's name on a lost device's lines: its guest object id and its role
/// (`super::fault`'s `Named`).
pub name: super::fault::Name,
/// Its texture.
pub made: Arc<Made>,
}
@@ -3249,7 +3250,7 @@ mod tests {
texture_type: 2,
samples: 1,
index,
id: 0,
name: super::super::fault::Name::default(),
made: Arc::clone(made),
};
let render_only = Made::new(Call::Plain, &shape(0x4));
+536 -100
View File
@@ -94,32 +94,50 @@
//!
//! **The command buffers in flight** ([`Flights`]): a command buffer joins its device's list as
//! its commit hands it to rt, and leaves it as its first completed handler runs (`super::command`'s
//! commit), so the list holds those committed and not complete. Each is kept with the object id of
//! the guest's command buffer (`CommandBuffer::names_work`), whose bits from 40 are its context, or
//! none for the host's own; its commit's time on the wall clock; and its encoders' names
//! ([`EncoderNames`]), in their order. An encoder's names are its kind; a render encoder's pass's
//! attachments, each by its texture's guest id; and, by guest id, the heaps its `useHeap:` calls
//! declare, the buffers and textures its `useResource:` calls declare, and the buffers its
//! `set*Buffer:` calls bind, refused or not. Of each list an encoder keeps the first [`IDS_KEPT`]
//! ids, each once, and counts the names of others past them, and those of objects with no guest
//! id ([`Ids`]). An encoder's names join its command buffer's as it ends, or as it goes unended
//! ([`Naming`]). A command buffer cut in parts is one entry for each part rt has.
//! commit), so the list holds those committed and not complete; and so does a window swapchain's
//! clear, at its retire, of an image taken and not presented, which the swapchain commits on rt
//! itself (`super::swapchain`, "Destroying a swapchain"), from before its commit until its wait
//! for it returns ([`CommittedBy`]). Each is kept with the object id of the guest's command buffer
//! (`CommandBuffer::names_work`), whose bits from 40 are its context, or none for the host's own;
//! its commit's time on the wall clock; and its encoders' names ([`EncoderNames`]), in their
//! order. An encoder's names are its kind; a render encoder's pass's attachments, each by its
//! texture's name; and, by name, the heaps its `useHeap:` calls declare, the buffers and textures
//! its `useResource:` calls declare, and the buffers its `set*Buffer:` calls bind, refused or not.
//! An encoder of a command buffer of the host's own (one its caller named no work for) names its
//! operands too ([`Operands`]): a blit encoder, the buffers and textures its copies read, and
//! those its copies, fills and mipmap generations write; a render encoder, the textures its
//! `set*Texture:` calls bind. An object's name ([`Name`]) is its guest object id, where a
//! decoder's table stores it, and what the host made it for, where the host or the platform told
//! it ([`Role`]): a window swapchain's image, the scanout's import, a presented surface's texture
//! and the display's view of it, the display colour's table and its ramps, the guest cursor's
//! glyph, the window overlay's image, or a host read's target. Of each list an encoder keeps the
//! first [`IDS_KEPT`] names, each once, and counts the names of others past them, and those of
//! objects with neither a guest id nor a role ([`Ids`]). An encoder's names join its command
//! buffer's as it ends, or as it goes unended ([`Naming`]). A command buffer cut in parts is one
//! entry for each part rt has.
//!
//! The list's numbers are its device's commit order, across all its queues, which the platform's
//! own texture and sampler indices go back by (`super::texture`'s `OwnIndices`): the number of the
//! last command buffer committed ([`Flights::last`]), and the highest number up to which every
//! command buffer has left the list ([`Flights::done_through`]).
//! command buffer has left the list ([`Flights::done_through`]). A swapchain's clear at its retire
//! takes a number, and the highest number passes over it: an index given back while it runs
//! waits for the platform's command buffers alone, as where the clear is not listed. What the
//! clear renders, a swapchain image's texture, goes only once the swapchain's wait for it returned.
//!
//! At the loss, two lines follow the fault's ([`Flights::lines`]): the first [`FLIGHTS_LISTED`]
//! command buffers committed and not complete, the oldest committed first, each with its context,
//! its commit's time against the loss and its encoders' kinds in order (runs of one kind counted,
//! the first [`KINDS_LISTED`] runs listed), and a count of the rest; then the oldest's render
//! passes, the first [`PASSES_LISTED`], and the resources its encoders name, the first
//! [`IDS_KEPT`] of each list. The list costs, for each command buffer, a read of the wall clock
//! and an entry added and removed under the list's lock; for each encoder, one push under its
//! command buffer's lock; and for each buffer bound or object declared, under the encoder's lock,
//! which each command takes already, a load of its id and a look through the at most [`IDS_KEPT`]
//! ids its list keeps.
//! its commit's time against the loss and its encoders in order, each by its kind and, where it
//! names its operands, what it renders into, what it binds and what its blits read and write
//! (runs of encoders told alike counted, the first [`KINDS_LISTED`] runs listed), and a count of
//! the rest; then the oldest's render passes, the first [`PASSES_LISTED`], and the resources its
//! encoders name, the first [`IDS_KEPT`] of each list. A command buffer of the host's own that rt
//! ends as in flight names its encoders so on its own line too (`super::command`'s docs, "A lost
//! device's line"; [`Flights::told`]). The list costs, for each command buffer, a read of the wall
//! clock and an entry added and removed under the list's lock; for each encoder, one push under
//! its command buffer's lock; and for each buffer bound or object declared, and in a command
//! buffer of the host's own for each operand, under the encoder's lock, which each command takes
//! already, a load of its id and its role and a look through the at most [`IDS_KEPT`] names its
//! list keeps.
//!
//! **What is kept before the loss.** The tables are walked at the loss, with no record of them
//! kept before it beside the history of their objects' releases. The rest is kept as it changes,
@@ -141,7 +159,7 @@
use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};
use std::time::Duration;
use metal2vulkan_runtime as rt;
@@ -525,13 +543,133 @@ fn context_of(id: u64) -> u32 {
/// which the history names it by as it goes ([`Releases`]), and a command buffer's line where an
/// encoder named it ([`EncoderNames`]): 0, none, for one no table stored, the host's own. The last
/// id told is kept. The `Shared` buffer over a two-copy `Managed` texture's CPU copy is told the
/// texture's id.
/// texture's id. What the host made it for is told too, where the host or the platform tells it
/// ([`Role`], [`name_role_buffer`], [`name_role_texture`]); the last told is kept.
#[derive(Debug, Default)]
pub struct Named {
/// The guest's object id, 0 for none.
id: AtomicU64,
/// Whether it is the CPU-copy buffer of the `Managed` texture whose id it holds.
copy: AtomicBool,
/// What the host made it for ([`Role`]'s value), 0 for nothing told.
role: AtomicU8,
}
/// What the host made an object for, which a lost device's lines name it by (the module's docs,
/// "The command buffers in flight"): told by the host as it makes the object or presents it
/// (`reims_vgpu`'s `graphics::fault_walk::name_role`), or by the platform as it makes a window
/// swapchain's image's texture (`super::texture`'s `drawable`). The host's own objects have no
/// guest id, so this is all a line can say of them; a presented surface's texture is the guest's,
/// and is named by both.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum Role {
/// The texture over a window swapchain's image (`super::swapchain`), which a window's frame
/// draws into.
SwapchainImage = 1,
/// The no-copy buffer over the guest's scanout pages that a display's draws read
/// (`reims_vgpu`'s `graphics::sink`, "The import").
ScanoutImport = 2,
/// The guest's texture over an IOSurface a display presented (`PRESENT_SURFACE`), which a
/// window's frame copies from (`graphics::sink`, "A presented surface").
Presented = 3,
/// The display's own view of a presented surface's texture, which a window's passes sample
/// (`graphics::ShownView`).
DisplayView = 4,
/// The display colour's table (`graphics::sink`, "The colour as a table").
ColorTable = 5,
/// A ramp the display colour's table is drawn from, a texture's or the scanout's.
ColorRamp = 6,
/// The guest cursor's glyph, which a window draws over its frame (`graphics::sink`, "The
/// guest's cursor").
CursorGlyph = 7,
/// The window overlay's image (`graphics::sink`, "The window's overlay").
OverlayImage = 8,
/// The texture a host's read of the display draws into (`graphics::read`).
ReadTarget = 9,
}
impl Role {
/// The role of value `raw`; `None` for 0, nothing told, and for any value no role has.
fn from_raw(raw: u8) -> Option<Role> {
Some(match raw {
1 => Role::SwapchainImage,
2 => Role::ScanoutImport,
3 => Role::Presented,
4 => Role::DisplayView,
5 => Role::ColorTable,
6 => Role::ColorRamp,
7 => Role::CursorGlyph,
8 => Role::OverlayImage,
9 => Role::ReadTarget,
_ => return None,
})
}
/// Its name on the line.
fn text(self) -> &'static str {
match self {
Role::SwapchainImage => "a window's swapchain image",
Role::ScanoutImport => "the scanout's import",
Role::Presented => "a presented surface's texture",
Role::DisplayView => "the display's view of a presented surface's texture",
Role::ColorTable => "the display colour's table",
Role::ColorRamp => "a ramp of the display colour's table",
Role::CursorGlyph => "the guest cursor's glyph",
Role::OverlayImage => "the window overlay's image",
Role::ReadTarget => "a host read's target",
}
}
}
/// An object as a lost device's lines name it (the module's docs, "The command buffers in
/// flight"): by its guest object id, 0 for none, and what the host made it for, where it was told.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Name {
/// The guest's object id, 0 for none.
pub id: u64,
/// What the host made it for, where it was told.
pub role: Option<Role>,
}
impl Name {
/// The object of guest id `id`, with no role told.
pub fn of_id(id: u64) -> Name {
Name { id, role: None }
}
/// The host's object made for `role`, with no guest id.
pub fn of_role(role: Role) -> Name {
Name {
id: 0,
role: Some(role),
}
}
/// Whether it names the object: by a guest id or a role.
fn names(&self) -> bool {
self.id != 0 || self.role.is_some()
}
/// It as a list says it, an object it names: its id, with its role after it where it has one,
/// or its role.
fn text(&self) -> String {
match (self.id, self.role) {
(0, Some(role)) => role.text().to_owned(),
(id, Some(role)) => format!("{id:#x} ({})", role.text()),
(id, None) => format!("{id:#x}"),
}
}
/// It as a pass's attachment's texture: `texture <id>`, with its role after it where it has
/// one; its role; or a texture with neither.
fn texture_text(&self) -> String {
match (self.id, self.role) {
(0, None) => "a texture with no guest id or role".to_owned(),
(0, Some(role)) => role.text().to_owned(),
_ => format!("texture {}", self.text()),
}
}
}
impl Named {
@@ -540,6 +678,24 @@ impl Named {
self.id.load(Ordering::Relaxed)
}
/// What the host made it for, where it was told.
pub fn role(&self) -> Option<Role> {
Role::from_raw(self.role.load(Ordering::Relaxed))
}
/// Its name on a lost device's lines: its id and its role, two loads.
pub fn name(&self) -> Name {
Name {
id: self.id(),
role: self.role(),
}
}
/// Tells it `role`: one store.
fn name_role(&self, role: Role) {
self.role.store(role as u8, Ordering::Relaxed);
}
/// The kind of object it is as the history records it: `object`, or a `Managed` texture's
/// CPU-copy buffer where it was told it is one.
pub fn kind(&self, object: ObjectKind) -> ObjectKind {
@@ -550,7 +706,7 @@ impl Named {
}
/// Tells it `id`: one store.
fn name(&self, id: u64) {
fn name_id(&self, id: u64) {
self.id.store(id, Ordering::Relaxed);
}
@@ -563,7 +719,7 @@ impl Named {
/// Tells `buffer` the guest's id `id`, under which a decoder's table stores it ([`Named`]).
pub fn name_buffer(buffer: &RtObj<RtBuffer>, id: u64) {
buffer.named().name(id);
buffer.named().name_id(id);
}
/// Tells `buffer` that it is the `Shared` buffer over the CPU copy of the two-copy `Managed`
@@ -574,12 +730,22 @@ pub fn name_managed_copy(buffer: &RtObj<RtBuffer>, id: u64) {
/// Tells `texture` the guest's id `id`, under which a decoder's table stores it ([`Named`]).
pub fn name_texture(texture: &RtObj<RtTexture>, id: u64) {
texture.named().name(id);
texture.named().name_id(id);
}
/// Tells `heap` the guest's id `id`, under which a decoder's table stores it ([`Named`]).
pub fn name_heap(heap: &RtObj<RtHeap>, id: u64) {
heap.named().name(id);
heap.named().name_id(id);
}
/// Tells `buffer` what the host made it for, `role` ([`Named`]).
pub fn name_role_buffer(buffer: &RtObj<RtBuffer>, role: Role) {
buffer.named().name_role(role);
}
/// Tells `texture` what the host made it for, or presents it as, `role` ([`Named`]).
pub fn name_role_texture(texture: &RtObj<RtTexture>, role: Role) {
texture.named().name_role(role);
}
/// How many released ranges a device's history keeps ([`Releases`]): the last so many, each older
@@ -783,75 +949,107 @@ impl EncoderKind {
}
}
/// The guest's object ids an encoder names in one of its lists ([`EncoderNames`]): each once, in
/// the order first named, the first [`IDS_KEPT`]; past them, the names of others counted; and the
/// names of objects with no guest id ([`Named`]), counted.
/// The objects an encoder names in one of its lists ([`EncoderNames`]), by their names
/// ([`Name`]): each once, by its guest id, or by its role where it has no guest id, in the order
/// first named, the first [`IDS_KEPT`]; past them, the names of others counted; and the names of
/// objects with neither a guest id nor a role ([`Named`]), counted.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Ids {
/// The ids named, each once, in the order first named: the first [`IDS_KEPT`].
kept: Vec<u64>,
/// How many names of ids past those kept.
/// The objects named, each once, in the order first named: the first [`IDS_KEPT`].
kept: Vec<Name>,
/// How many names of objects past those kept.
past: u64,
/// How many names of objects with no guest id.
unnumbered: u64,
/// How many names of objects with neither a guest id nor a role.
unnamed: u64,
}
impl Ids {
/// Notes a name of `id`, 0 for an object with no guest id: a look through the at most
/// [`IDS_KEPT`] ids kept.
/// Notes a name of the object of guest id `id`, 0 for one with none, with no role told
/// ([`Self::note`]).
pub fn add(&mut self, id: u64) {
if id == 0 {
self.unnumbered += 1;
} else if !self.kept.contains(&id) {
self.note(Name::of_id(id));
}
/// Notes a name of the object `named` names: its id and role loaded ([`Self::note`]).
pub fn add_named(&mut self, named: &Named) {
self.note(named.name());
}
/// Notes a name of the object `name` names: a look through the at most [`IDS_KEPT`] names kept,
/// for its guest id where it has one, else for its role.
pub fn note(&mut self, name: Name) {
if !name.names() {
self.unnamed += 1;
return;
}
let seen = match name.id {
0 => self.kept.contains(&name),
id => self.kept.iter().any(|kept| kept.id == id),
};
if !seen {
match self.kept.len() < IDS_KEPT {
true => self.kept.push(id),
true => self.kept.push(name),
false => self.past += 1,
}
}
}
/// Notes `other`'s ids and counts in this list.
/// Whether it holds no name.
fn is_empty(&self) -> bool {
self.kept.is_empty() && self.past == 0 && self.unnamed == 0
}
/// Notes `other`'s names and counts in this list.
fn join(&mut self, other: &Ids) {
for &id in &other.kept {
self.add(id);
for &name in &other.kept {
self.note(name);
}
self.past += other.past;
self.unnumbered += other.unnumbered;
self.unnamed += other.unnamed;
}
/// The list as the line says it.
fn text(&self) -> String {
if self.kept.is_empty() && self.past == 0 && self.unnumbered == 0 {
if self.is_empty() {
return "none".to_owned();
}
let mut parts = (self.kept.iter())
.map(|id| format!("{id:#x}"))
.collect::<Vec<_>>();
let mut parts = self.kept.iter().map(Name::text).collect::<Vec<_>>();
if self.past > 0 {
parts.push(format!(
"{} more names past the first {IDS_KEPT} ids",
"{} more names past the first {IDS_KEPT} objects",
self.past
));
}
if self.unnumbered > 0 {
if self.unnamed > 0 {
parts.push(format!(
"{} names of objects with no guest id",
self.unnumbered
"{} names of objects with no guest id or role",
self.unnamed
));
}
parts.join(", ")
}
}
/// What an encoder of a command buffer of the host's own reads and writes beside its pass's
/// attachments and the buffers it binds, by name (the module's docs, "The command buffers in
/// flight").
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Operands {
/// What it reads: a blit encoder's copies' sources; the textures a render encoder's
/// `set*Texture:` calls bind.
pub reads: Ids,
/// What a blit encoder's copies, fills and mipmap generations write.
pub writes: Ids,
}
/// What an encoder of a command buffer names (the module's docs, "The command buffers in
/// flight").
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EncoderNames {
/// Its kind.
pub kind: EncoderKind,
/// A render encoder's pass's attachments: each one's point and its texture's guest id, 0 for
/// one with none.
pub attachments: Vec<(Point, u64)>,
/// A render encoder's pass's attachments: each one's point and its texture's name.
pub attachments: Vec<(Point, Name)>,
/// The heaps its `useHeap:` calls declare.
pub heaps: Ids,
/// The buffers its `useResource:` calls declare.
@@ -860,10 +1058,13 @@ pub struct EncoderNames {
pub declared_textures: Ids,
/// The buffers its `set*Buffer:` calls bind (`setTessellationFactorBuffer:` among them).
pub bound_buffers: Ids,
/// What it reads and writes beside those, for an encoder that names its operands, of a
/// command buffer of the host's own; `None` for any other, which notes none.
pub operands: Option<Operands>,
}
impl EncoderNames {
/// An encoder of `kind` that names nothing yet.
/// An encoder of `kind` that names nothing yet, nor its operands.
pub fn new(kind: EncoderKind) -> EncoderNames {
EncoderNames {
kind,
@@ -872,8 +1073,66 @@ impl EncoderNames {
declared_buffers: Ids::default(),
declared_textures: Ids::default(),
bound_buffers: Ids::default(),
operands: None,
}
}
/// It, naming its operands from now on where `operands`: an encoder of a command buffer of
/// the host's own.
pub fn naming_operands(mut self, operands: bool) -> EncoderNames {
self.operands = operands.then(Operands::default);
self
}
/// The encoder as its command buffer's entry on the line lists it: its kind; and, where it
/// names its operands, a render encoder's attachments and the textures and buffers it binds,
/// a blit encoder's sources and destinations, a compute encoder's buffers bound.
fn told(&self) -> String {
let kind = self.kind.name();
let Some(operands) = &self.operands else {
return kind.to_owned();
};
let buffers = (!self.bound_buffers.is_empty())
.then(|| format!("the buffers {}", self.bound_buffers.text()));
match self.kind {
EncoderKind::Render => {
let into = attachments_text(&self.attachments);
let textures = (!operands.reads.is_empty())
.then(|| format!("the textures {}", operands.reads.text()));
let bound = textures.into_iter().chain(buffers).collect::<Vec<_>>();
match bound.is_empty() {
true => format!("{kind} into {into}"),
false => format!("{kind} into {into}, binding {}", bound.join(" and ")),
}
}
EncoderKind::Blit => format!(
"{kind} from {} into {}",
operands.reads.text(),
operands.writes.text()
),
EncoderKind::Compute => match buffers {
Some(buffers) => format!("{kind}, binding {buffers}"),
None => kind.to_owned(),
},
}
}
}
/// A render pass's attachments as a line says them: each one's point and its texture's name, or
/// that there are none.
fn attachments_text(attachments: &[(Point, Name)]) -> String {
if attachments.is_empty() {
return "no attachments".to_owned();
}
let attachments = attachments.iter().map(|&(point, name)| {
let point = match point {
Point::Color(i) => format!("colour {i}"),
Point::Depth => "depth".to_owned(),
Point::Stencil => "stencil".to_owned(),
};
format!("{point} {}", name.texture_text())
});
attachments.collect::<Vec<_>>().join(", ")
}
/// A command buffer's encoders' names, in their order: each joins as its encoder ends or goes
@@ -931,12 +1190,30 @@ impl Drop for Naming {
}
}
/// A window swapchain's clear at its retire, as the line names it
/// ([`CommittedBy::SwapchainRetire`]).
const SWAPCHAIN_RETIRE: &str = "a command buffer of the host's own, a window swapchain's clear at \
its retire of an image taken and not presented";
/// What committed a command buffer the list holds ([`Flight`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CommittedBy {
/// The platform's command buffer (`super::command`), in its device's commit order.
Platform,
/// A window swapchain's retire, its clear of an image taken and not presented, committed on rt
/// itself (`super::swapchain`, "Destroying a swapchain"): outside the commit order, which
/// [`Flights::done_through`] passes over.
SwapchainRetire,
}
/// A command buffer committed and not complete (the module's docs, "The command buffers in
/// flight").
#[derive(Debug)]
pub struct Flight {
/// The object id of the guest's command buffer, `None` for one of the host's own.
pub cb: Option<u64>,
/// What committed it.
pub by: CommittedBy,
/// When it was committed: nanoseconds since 1970, on the wall clock.
pub committed: u64,
/// Its encoders' names, in their order.
@@ -946,36 +1223,39 @@ pub struct Flight {
impl Flight {
/// The command buffer as the line names it.
fn who(&self) -> String {
match self.cb {
Some(cb) => format!(
match (self.cb, self.by) {
(Some(cb), _) => format!(
"the guest's command buffer {cb:#x} of context {}",
context_of(cb)
),
None => "a command buffer of the host's own".to_owned(),
(None, CommittedBy::Platform) => "a command buffer of the host's own".to_owned(),
(None, CommittedBy::SwapchainRetire) => SWAPCHAIN_RETIRE.to_owned(),
}
}
/// Its encoders' kinds in order, as the line says them: each run of one kind once, with its
/// count where more than one; the first [`KINDS_LISTED`] runs, then a count of the rest.
/// Its encoders in order, as the line says them ([`EncoderNames::told`]): each run of encoders
/// told alike once, with its count where more than one; the first [`KINDS_LISTED`] runs, then
/// a count of the rest.
fn kinds(&self) -> String {
if self.encoders.is_empty() {
return "with no encoders".to_owned();
}
let mut runs: Vec<(EncoderKind, usize)> = Vec::new();
let mut runs: Vec<(String, usize)> = Vec::new();
for encoder in &self.encoders {
let told = encoder.told();
match runs.last_mut() {
Some((kind, n)) if *kind == encoder.kind => *n += 1,
_ => runs.push((encoder.kind, 1)),
Some((last, n)) if *last == told => *n += 1,
_ => runs.push((told, 1)),
}
}
let listed = (runs.iter().take(KINDS_LISTED))
.map(|&(kind, n)| match n {
1 => kind.name().to_owned(),
n => format!("{n} {}", kind.name()),
.map(|(told, n)| match n {
1 => told.clone(),
n => format!("{n} {told}"),
})
.collect::<Vec<_>>();
let rest = (runs.iter().skip(KINDS_LISTED))
.map(|&(_, n)| n)
.map(|(_, n)| n)
.sum::<usize>();
let rest = match rest {
0 => String::new(),
@@ -989,8 +1269,8 @@ impl Flight {
}
/// What its encoders name, as the oldest's line says it: its render passes' attachments by
/// texture, the first [`PASSES_LISTED`] passes, then the heaps and resources its encoders
/// declare and the buffers they bind.
/// their textures' names, the first [`PASSES_LISTED`] passes, then the heaps and resources its
/// encoders declare and the buffers they bind.
fn names(&self) -> String {
let (mut passes, mut more_passes) = (Vec::new(), 0);
let mut lists: [Ids; 4] = Default::default();
@@ -1011,23 +1291,7 @@ impl Flight {
more_passes += 1;
continue;
}
let attachments = (encoder.attachments.iter())
.map(|&(point, id)| {
let point = match point {
Point::Color(i) => format!("colour {i}"),
Point::Depth => "depth".to_owned(),
Point::Stencil => "stencil".to_owned(),
};
match id {
0 => format!("{point} a texture with no guest id"),
id => format!("{point} texture {id:#x}"),
}
})
.collect::<Vec<_>>();
let attachments = match attachments.is_empty() {
true => "no attachments".to_owned(),
false => attachments.join(", "),
};
let attachments = attachments_text(&encoder.attachments);
passes.push(format!("encoder {}: {attachments}", at + 1));
}
let passes = match (passes.is_empty(), more_passes) {
@@ -1079,13 +1343,26 @@ impl Flights {
self.0.lock().0
}
/// The highest number N such that every command buffer numbered N or less has left the list,
/// its first completed handler run or its commit refused, whatever the order they left in,
/// across all its device's queues: the oldest's in it less one, or [`Flights::last`] where it
/// is empty. A later command buffer that completed first moves it nowhere.
/// The highest number N such that every command buffer of the platform's numbered N or less
/// has left the list, its first completed handler run or its commit refused, whatever the
/// order they left in, across all its device's queues: the oldest's in it less one, or
/// [`Flights::last`] where it holds none. A later command buffer that completed first moves it
/// nowhere, and a swapchain's clear at its retire holds it nowhere
/// ([`CommittedBy::SwapchainRetire`], the module's docs): an index given back waits for the
/// platform's command buffers committed before alone, as where the clear is not listed. The
/// list holds a clear only while its swapchain waits for it, so it passes over at most a few.
pub fn done_through(&self) -> u64 {
let flights = self.0.lock();
(flights.1.keys().next()).map_or(flights.0, |&oldest| oldest.saturating_sub(1))
let oldest = (flights.1.iter()).find(|(_, f)| f.by == CommittedBy::Platform);
oldest.map_or(flights.0, |(&oldest, _)| oldest.saturating_sub(1))
}
/// The encoders of the command buffer of number `number`, as its entry on the line says them
/// (`its encoders (n): ...`); `None` where it is not on the list. For the line of a command
/// buffer of the host's own that rt ends as in flight (`super::command`'s docs, "A lost
/// device's line"), before its first completed handler takes it off.
pub fn told(&self, number: u64) -> Option<String> {
self.0.lock().1.get(&number).map(Flight::kinds)
}
/// How many command buffers are committed and not complete.
@@ -2364,9 +2641,9 @@ mod tests {
);
let render = EncoderNames {
attachments: vec![
(Point::Color(0), 0x300_0000_0020),
(Point::Color(1), 0),
(Point::Depth, 0x300_0000_0021),
(Point::Color(0), Name::of_id(0x300_0000_0020)),
(Point::Color(1), Name::default()),
(Point::Depth, Name::of_id(0x300_0000_0021)),
],
heaps: ids(&[0x300_0000_0030]),
bound_buffers: ids(&[0x300_0000_0040, 0, 0x300_0000_0040]),
@@ -2380,6 +2657,7 @@ mod tests {
};
let oldest = flights.add(Flight {
cb: Some(0x300_0000_0010),
by: CommittedBy::Platform,
committed: LOSS - 40 * MS,
encoders: vec![
render,
@@ -2390,16 +2668,19 @@ mod tests {
});
let completed = flights.add(Flight {
cb: Some(0x400_0000_0010),
by: CommittedBy::Platform,
committed: LOSS - 30 * MS,
encoders: Vec::new(),
});
flights.add(Flight {
cb: None,
by: CommittedBy::Platform,
committed: LOSS - 20 * MS,
encoders: vec![EncoderNames::new(EncoderKind::Blit)],
});
flights.add(Flight {
cb: Some(0x400_0000_0011),
by: CommittedBy::Platform,
committed: LOSS - 10 * MS,
encoders: Vec::new(),
});
@@ -2421,11 +2702,11 @@ mod tests {
"reims-vgpu: the oldest command buffer committed and not complete at the loss of \
the rt platform's device on GPU (10de:2204), the guest's command buffer \
0x30000000010 of context 3: its render passes' attachments: encoder 1: colour 0 \
texture 0x30000000020, colour 1 a texture with no guest id, depth texture \
0x30000000021; the heaps its encoders declare (useHeap:): 0x30000000030; the \
buffers they declare (useResource:): 0x30000000041; the textures they declare \
(useResource:): 0x30000000022; the buffers they bind: 0x30000000040, \
0x30000000042, 1 names of objects with no guest id\n",
texture 0x30000000020, colour 1 a texture with no guest id or role, depth \
texture 0x30000000021; the heaps its encoders declare (useHeap:): \
0x30000000030; the buffers they declare (useResource:): 0x30000000041; the \
textures they declare (useResource:): 0x30000000022; the buffers they bind: \
0x30000000040, 0x30000000042, 1 names of objects with no guest id or role\n",
]
);
flights.remove(oldest);
@@ -2463,12 +2744,14 @@ mod tests {
encoders[0].bound_buffers = ids(&many);
flights.add(Flight {
cb: Some(0x100_0000_0001),
by: CommittedBy::Platform,
committed: LOSS - 50 * MS,
encoders,
});
for at in 0..FLIGHTS_LISTED as u64 + 1 {
flights.add(Flight {
cb: Some(0x100_0000_0002 + at),
by: CommittedBy::Platform,
committed: LOSS - 40 * MS,
encoders: Vec::new(),
});
@@ -2502,7 +2785,7 @@ mod tests {
.collect::<Vec<_>>();
assert!(
lines[1].ends_with(&format!(
"; the buffers they bind: {}, 3 more names past the first 32 ids\n",
"; the buffers they bind: {}, 3 more names past the first 32 objects\n",
bound.join(", ")
)),
"{}",
@@ -2510,6 +2793,159 @@ mod tests {
);
}
/// A command buffer of the host's own is listed with what its encoders render into and bind
/// and what its blits read and write, each object by its guest id and its role, or by its
/// role where it has no guest id (a window's frame: a clear of the swapchain image, the
/// scanout's blits into it, the cursor's pass; a frame that copies a presented surface's
/// texture), runs of encoders told alike counted; a guest's command buffer by its encoders'
/// kinds alone. A swapchain's clear at its retire is listed as the host's own, saying what it
/// is. A host's command buffer's encoders are told so for its line as one lost in flight too,
/// while it is listed.
#[test]
fn a_host_command_buffer_is_listed_with_what_its_encoders_render_bind_read_and_write() {
let flights = Flights::default();
let image = Name::of_role(Role::SwapchainImage);
let render = || EncoderNames {
attachments: vec![(Point::Color(0), image)],
..EncoderNames::new(EncoderKind::Render).naming_operands(true)
};
let blit = |from: Name| {
let mut blit = EncoderNames::new(EncoderKind::Blit).naming_operands(true);
let operands = blit.operands.as_mut().expect("it names its operands");
operands.reads.note(from);
operands.writes.note(image);
operands.writes.note(image);
blit
};
let scanout = blit(Name::of_role(Role::ScanoutImport));
let mut cursor = render();
let operands = cursor.operands.as_mut().expect("it names its operands");
operands.reads.note(Name::of_role(Role::CursorGlyph));
cursor.bound_buffers.add(0);
cursor.bound_buffers.add(0);
let frame = flights.add(Flight {
cb: None,
by: CommittedBy::Platform,
committed: LOSS - 20 * MS,
encoders: vec![render(), scanout.clone(), scanout, cursor],
});
flights.add(Flight {
cb: None,
by: CommittedBy::SwapchainRetire,
committed: LOSS - 10 * MS,
encoders: vec![render()],
});
let presented = Name {
id: 0x500_0000_0012,
role: Some(Role::Presented),
};
flights.add(Flight {
cb: None,
by: CommittedBy::Platform,
committed: LOSS - 5 * MS,
encoders: vec![blit(presented)],
});
flights.add(Flight {
cb: Some(0x500_0000_0010),
by: CommittedBy::Platform,
committed: LOSS - 4 * MS,
encoders: vec![
EncoderNames::new(EncoderKind::Render),
EncoderNames::new(EncoderKind::Blit),
],
});
let frame_encoders = "its encoders (4): render into colour 0 a window's swapchain image, 2 \
blit from the scanout's import into a window's swapchain image, \
render into colour 0 a window's swapchain image, binding the \
textures the guest cursor's glyph and the buffers 2 names of \
objects with no guest id or role";
assert_eq!(flights.told(frame).as_deref(), Some(frame_encoders));
assert_eq!(flights.told(0), None);
let lines = flights.lines("GPU (1002:73ff)", LOSS);
assert_eq!(
lines[0],
format!(
"reims-vgpu: the rt platform's device on GPU (1002:73ff), at its loss, had 4 \
command buffers committed and not complete, the oldest committed first: a \
command buffer of the host's own, committed at 1795560000.230000 s since 1970 \
(0.020000 s before the loss), {frame_encoders}; a command buffer of the host's \
own, a window swapchain's clear at its retire of an image taken and not \
presented, committed at 1795560000.240000 s since 1970 (0.010000 s before the \
loss), its encoders (1): render into colour 0 a window's swapchain image; a \
command buffer of the host's own, committed at 1795560000.245000 s since 1970 \
(0.005000 s before the loss), its encoders (1): blit from 0x50000000012 (a \
presented surface's texture) into a window's swapchain image; the guest's \
command buffer 0x50000000010 of context 5, committed at 1795560000.246000 s \
since 1970 (0.004000 s before the loss), its encoders (2): render, blit\n"
)
);
assert_eq!(
lines[1],
"reims-vgpu: the oldest command buffer committed and not complete at the loss of the \
rt platform's device on GPU (1002:73ff), a command buffer of the host's own: its \
render passes' attachments: encoder 1: colour 0 a window's swapchain image; encoder \
4: colour 0 a window's swapchain image; the heaps its encoders declare (useHeap:): \
none; the buffers they declare (useResource:): none; the textures they declare \
(useResource:): none; the buffers they bind: 2 names of objects with no guest id or \
role\n"
);
}
/// A list names each object once: by its guest id where it has one, whatever its role, and
/// by its role where it has none, each role once; an object with neither is counted.
#[test]
fn a_list_names_each_object_once_by_its_guest_id_or_its_role() {
let mut ids = Ids::default();
ids.note(Name::of_role(Role::ColorRamp));
ids.note(Name::of_role(Role::ColorTable));
ids.note(Name::of_role(Role::ColorRamp));
ids.note(Name {
id: 0x7,
role: Some(Role::Presented),
});
ids.add(0x7);
ids.add(0);
let named = Named::default();
assert_eq!(named.name(), Name::default());
named.name_role(Role::DisplayView);
assert_eq!(named.name(), Name::of_role(Role::DisplayView));
ids.add_named(&named);
assert_eq!(
ids.text(),
"a ramp of the display colour's table, the display colour's table, 0x7 (a presented \
surface's texture), the display's view of a presented surface's texture, 1 names of \
objects with no guest id or role"
);
}
/// A swapchain's clear at its retire takes a number on the list, but holds no index given back:
/// the highest number up to which every command buffer has left the list passes over it, as
/// where it is not listed.
#[test]
fn a_swapchain_s_clear_at_its_retire_holds_nothing_given_back() {
let flights = Flights::default();
let add = |by| {
flights.add(Flight {
cb: None,
by,
committed: LOSS,
encoders: Vec::new(),
})
};
let first = add(CommittedBy::Platform);
let clear = add(CommittedBy::SwapchainRetire);
let third = add(CommittedBy::Platform);
assert_eq!((first, clear, third), (1, 2, 3));
assert_eq!(flights.done_through(), 0);
flights.remove(first);
assert_eq!(flights.done_through(), 2);
flights.remove(third);
assert_eq!((flights.done_through(), flights.last()), (3, 3));
assert_eq!(flights.len(), 1);
flights.remove(clear);
assert_eq!(flights.done_through(), 3);
}
/// A decoder's table of one buffer, walked at the loss as a graphics device's is
/// ([`buffer_parts`]).
struct OneBuffer {
@@ -166,16 +166,18 @@ struct Seen {
impl RtRenderEncoder {
/// The encoder over rt's `encoder`, open as `mark` marks it, its pipeline states kept in
/// `kept`, of a pass of `targets`.
/// `kept`, of a pass of `targets`, naming its operands where `operands` (`super::fault`'s
/// `Operands`).
pub fn new(
encoder: rt::RenderCommandEncoder,
mark: OpenMark,
kept: Kept,
targets: Vec<Target>,
operands: bool,
) -> RtRenderEncoder {
let names = EncoderNames {
attachments: targets.iter().map(|t| (t.point, t.id)).collect(),
..EncoderNames::new(EncoderKind::Render)
attachments: targets.iter().map(|t| (t.point, t.name)).collect(),
..EncoderNames::new(EncoderKind::Render).naming_operands(operands)
};
RtRenderEncoder {
open: ReentrantMutex::new(RefCell::new(Open {
@@ -915,26 +917,41 @@ fn note_copies(used: &Used, cmd: &RenderCmd<'_, RtPlatform>) {
/// Notes in `names` what `cmd` names (`super::fault`'s docs, "The command buffers in flight"): the
/// buffers it binds to a vertex or fragment slot or as the tessellation factor buffer, and the
/// heaps and resources it declares, by their guest ids (rt keeps no mesh, object or tile buffers).
/// heaps and resources it declares, by their names (rt keeps no mesh, object or tile buffers);
/// and, where the encoder names its operands, in a command buffer of the host's own, the textures
/// it binds to a vertex or fragment slot.
fn note_names(names: &mut EncoderNames, cmd: &RenderCmd<'_, RtPlatform>) {
match cmd {
RenderCmd::SetFragmentBuffer { buffer, .. }
| RenderCmd::SetVertexBuffer { buffer, .. }
| RenderCmd::SetTessellationFactorBuffer { buffer, .. } => {
if let Some(buffer) = buffer {
names.bound_buffers.add(buffer.named().id());
names.bound_buffers.add_named(buffer.named());
}
}
RenderCmd::SetFragmentBuffers { buffers, .. }
| RenderCmd::SetVertexBuffersAttributeStrides { buffers, .. }
| RenderCmd::SetVertexBuffers { buffers, .. } => {
for buffer in buffers.iter().flatten() {
names.bound_buffers.add(buffer.named().id());
names.bound_buffers.add_named(buffer.named());
}
}
RenderCmd::SetFragmentTexture { texture, .. } => {
if let (Some(operands), Some(texture)) = (&mut names.operands, texture) {
operands.reads.add_named(texture.named());
}
}
RenderCmd::SetFragmentTextures { textures, .. }
| RenderCmd::SetVertexTextures { textures, .. } => {
if let Some(operands) = &mut names.operands {
for texture in textures.iter().flatten() {
operands.reads.add_named(texture.named());
}
}
}
RenderCmd::UseHeaps { heaps } | RenderCmd::UseHeapsStages { heaps, .. } => {
for heap in heaps.iter().flatten() {
names.heaps.add(heap.named().id());
names.heaps.add_named(heap.named());
}
}
RenderCmd::UseResources { resources, .. }
@@ -45,7 +45,10 @@
//! made (a frame that encoded nothing), has had a command buffer with commands committed after
//! that call complete, which carried its move home: the retire commits a clear of the image on a
//! queue of the swapchain's own and waits for it ([`RtSwapchain::settle_acquired`]). Then its
//! images' textures go, then their semaphores and the swapchain.
//! images' textures go, then their semaphores and the swapchain. The clear is on the device's list
//! of command buffers in flight from before its commit until the wait returns, so a loss's lines
//! name it, with the swapchain image it renders (`super::fault`'s docs, "The command buffers in
//! flight"), outside the commit order the platform's own indices go back by.
//!
//! **Without present fences** (no `swapchainMaintenance1` on the device), a retired swapchain's
//! last present is known complete from Vulkan's rules alone, and where it is not in time, the
@@ -89,6 +92,8 @@ use crate::swapchain::{
use super::RtObj;
use super::command::RtCommandBuffer;
use super::device::RtDevice;
use super::diag::Point;
use super::fault::{CommittedBy, EncoderKind, EncoderNames, Flight};
use super::texture::{self, RtTexture};
use super::unbuilt::rt_refused;
use super::window_times;
@@ -102,6 +107,24 @@ const NEXT_DRAWABLE: &str = "nextDrawable";
/// The call rt's refusals of a present are counted under.
const PRESENT_DRAWABLE: &str = "presentDrawable:";
/// A swapchain's clear at its retire of `texture`, an image's taken and not presented
/// ([`RtSwapchain::settle_acquired`]), as the device's list of command buffers in flight holds it
/// (`super::fault`'s docs, "The command buffers in flight"): a command buffer of the host's own,
/// committed now, outside the commit order, of one render pass into the image, a window's
/// swapchain image.
fn retire_clear(texture: &RtObj<RtTexture>) -> Flight {
let clear = EncoderNames {
attachments: vec![(Point::Color(0), texture.named().name())],
..EncoderNames::new(EncoderKind::Render).naming_operands(true)
};
Flight {
cb: None,
by: CommittedBy::SwapchainRetire,
committed: super::fault::wall_now(),
encoders: vec![clear],
}
}
/// One image of the swapchain.
struct Image {
/// rt's drawable texture over it.
@@ -805,7 +828,9 @@ impl RtSwapchain {
}
/// A clear of `texture` in a command buffer of the swapchain's own queue, committed and waited
/// for.
/// for: listed among the device's command buffers committed and not complete, for a loss's
/// lines, from before its commit until the wait returns (`super::fault`'s docs, "The command
/// buffers in flight"; [`retire_clear`]), which changes nothing it commits or when.
fn clear(&mut self, texture: &RtObj<RtTexture>) -> Result<(), rt::Error> {
let queue = match &self.settling {
Some(queue) => queue.clone(),
@@ -822,6 +847,7 @@ impl RtSwapchain {
attachment.load_action = rt::LoadAction::Clear;
attachment.store_action = rt::StoreAction::Store;
command_buffer.render_command_encoder(&pass)?.end_encoding();
let _listed = self.device.loss().listing(retire_clear(texture));
command_buffer.commit()?;
command_buffer.wait_until_completed()
}
@@ -644,7 +644,8 @@ const USAGE_RENDER_TARGET: u64 = 0x4;
/// The texture over a window swapchain's image (`super::swapchain`): rt's drawable `texture`, made
/// of [`drawable_descriptor`]'s descriptor at `own`, one of the platform's own indices, which its
/// drop gives back.
/// drop gives back; named on a lost device's lines as a window's swapchain image
/// (`super::fault`'s `Role`).
pub(super) fn drawable(
device: &RtObj<RtDevice>,
texture: rt::Texture,
@@ -659,7 +660,7 @@ pub(super) fn drawable(
usage: USAGE_RENDER_TARGET,
};
let made = Made::new(Call::Drawable, &shape);
RtObj::new(RtTexture {
let drawable = RtObj::new(RtTexture {
named: super::fault::Named::default(),
rt: texture,
device: device.clone_ref(),
@@ -673,7 +674,9 @@ pub(super) fn drawable(
copied: OnceLock::new(),
over: OnceLock::new(),
held: OnceLock::new(),
})
});
super::fault::name_role_texture(&drawable, super::fault::Role::SwapchainImage);
drawable
}
/// The descriptor of a drawable's texture over a swapchain's image of `width` x `height` pixels:
@@ -1888,11 +1891,12 @@ mod tests {
/// with none committed waits for nothing, and one reserved since goes.
#[test]
fn own_indices_given_back_wait_for_every_command_buffer_committed_before() {
use super::super::fault::Flight;
use super::super::fault::{CommittedBy, Flight};
let order = Arc::new(Flights::default());
let commit = || {
order.add(Flight {
cb: None,
by: CommittedBy::Platform,
committed: 0,
encoders: Vec::new(),
})
+8 -1
View File
@@ -123,6 +123,7 @@ use reims_vgpu_vulkan::core::platform::values::TextureDesc;
use reims_vgpu_vulkan::core::platform::{Handle, Platform};
use reims_vgpu_vulkan::core::raise::{OnFault, Raise, RaiseResult};
use reims_vgpu_vulkan::core::sync::Mutex;
use reims_vgpu_vulkan::rt_platform::fault::Role;
use reims_vgpu_window::{FrameSink, Window, WindowConfig, geometry};
use zerocopy::{FromBytes, IntoBytes};
@@ -152,6 +153,7 @@ use crate::graphics::decode::{
Then, compile_refusing, complete, make_library, refused_reply, refusing,
};
use crate::graphics::device_info::device_info;
use crate::graphics::fault_walk::HostObject;
use crate::graphics::present::{Drawing, LetGo, PresentAnswers, PresentQueue};
use crate::graphics::read::DisplayRead;
use crate::graphics::slow_answers::{
@@ -1667,6 +1669,8 @@ impl<P: Platform> ShownView<P> {
return Some(view);
}
let view = no_catch(texture.new_texture_view(texture.pixel_format()))?;
// A lost device's lines name it so (`fault_walk::name_role`).
fault_walk::name_role::<P>(Role::DisplayView, HostObject::Texture(&view));
// A draw on another thread that made one first keeps its own: this one goes.
Some(self.0.get_or_init(|| view))
}
@@ -1759,7 +1763,9 @@ impl<P: Platform> Presented<P> {
/// `texture`, over a surface whose present was taken, held for the display from now, with
/// `view`, the display's view of it ([`ShownView`]): the block at `span` it lies in is not
/// given back until the display is done with it ([`DisplayHold`]). `queued`: every write of
/// the bytes it reads is the platform's work ([`DisplayHold`]'s `queued`).
/// the bytes it reads is the platform's work ([`DisplayHold`]'s `queued`). From now, a lost
/// device's lines name the texture as a presented surface's, beside its guest id
/// (`fault_walk::name_role`).
fn hold(
&self,
texture: P::Texture,
@@ -1767,6 +1773,7 @@ impl<P: Platform> Presented<P> {
span: Option<(u64, u64)>,
queued: bool,
) -> ShownTexture<P> {
fault_walk::name_role::<P>(Role::Presented, HostObject::Texture(&texture));
let hold = Arc::new(DisplayHold {
span,
answers: Mutex::default(),
+35 -1
View File
@@ -9,7 +9,12 @@
//!
//! As a table stores a buffer, texture or heap, the object is told the guest's id for it
//! ([`name`]), which the device's history of released ranges and its lines of the command buffers
//! in flight name it by (`fault::Named`).
//! in flight name it by (`fault::Named`). As the host makes a buffer or texture of its own that a
//! display's draws use, or presents a guest's texture, the object is told what the host made it
//! for ([`name_role`]: the scanout's import, a presented surface's texture and the display's view
//! of it, the display colour's table and ramps, the guest cursor's glyph, the window overlay's
//! image, a host read's target), which those lines name it by where it has no guest id
//! (`fault::Role`).
use std::any::Any;
use std::sync::Arc;
@@ -84,6 +89,35 @@ pub(super) fn name<P: Platform>(id: u64, object: TableObject<'_, P>) {
}
}
/// An object of the host's own, or a guest's it presents, to tell what the host made it for
/// ([`name_role`]).
pub(crate) enum HostObject<'a, P: Platform> {
/// A buffer.
Buffer(&'a P::Buffer),
/// A texture.
Texture(&'a P::Texture),
}
/// Tells `object` what the host made it for, or presents it as, `role` (`fault::Named`), where
/// the platform is the rt platform: a downcast, which each platform's build settles, and an atomic
/// store; nothing for any other platform.
pub(crate) fn name_role<P: Platform>(role: fault::Role, object: HostObject<'_, P>) {
type Rt = RtPlatform;
match object {
HostObject::Buffer(buffer) => {
if let Some(buffer) = (buffer as &dyn Any).downcast_ref::<<Rt as Platform>::Buffer>() {
fault::name_role_buffer(buffer, role);
}
}
HostObject::Texture(texture) => {
let texture = (texture as &dyn Any).downcast_ref::<<Rt as Platform>::Texture>();
if let Some(texture) = texture {
fault::name_role_texture(texture, role);
}
}
}
}
/// Tells `device` of the decoder's tables `walk`, where the platform is the rt platform; nothing
/// for any other.
pub(super) fn watch<P: Platform>(device: &P::Device, walk: TableWalk<P>) {
+7 -1
View File
@@ -35,8 +35,10 @@ use reims_vgpu_vulkan::core::platform::device::GpuDevice as _;
use reims_vgpu_vulkan::core::platform::types::CommandBufferStatus;
use reims_vgpu_vulkan::core::raise::OnFault;
use reims_vgpu_vulkan::core::sync::Mutex;
use reims_vgpu_vulkan::rt_platform::fault::Role;
use reims_vgpu_window::PixelRect;
use super::fault_walk::{HostObject, name_role};
use super::sink::ScanoutDraw;
use super::{Presented, Shown};
use crate::entry::no_catch;
@@ -216,6 +218,10 @@ impl<P: ApiPlatform> DisplayRead<P> {
));
descriptor.set_usage(READ_USAGE);
descriptor.set_resource_options(READ_RESOURCE_OPTIONS);
no_catch(draw.device.new_texture(OnFault::Die, &descriptor)).ok_or(Error::Metal)
let texture = no_catch(draw.device.new_texture(OnFault::Die, &descriptor));
let texture = texture.ok_or(Error::Metal)?;
// A lost device's lines name it so (`fault_walk::name_role`).
name_role::<P>(Role::ReadTarget, HostObject::Texture(&texture));
Ok(texture)
}
}
+12 -4
View File
@@ -150,6 +150,7 @@ use reims_vgpu_vulkan::core::platform::types::{MtlScissorRect, MtlViewport};
use self::cursor::CursorPass;
use super::color::DisplayColor;
use super::decode::unkept::Kind;
use super::fault_walk::{HostObject, name_role};
use super::{DisplayHold, Drawable, DrawnPresents, Presented, Shown};
use crate::entry::no_catch;
use crate::platform::ApiPlatform;
@@ -158,6 +159,7 @@ use reims_vgpu_graphics::wire::{
};
use reims_vgpu_vulkan::core::platform::resource::Library as _;
use reims_vgpu_vulkan::core::platform::values::RenderPipelineDesc;
use reims_vgpu_vulkan::rt_platform::fault::Role;
mod cursor;
@@ -680,12 +682,14 @@ impl<P: ApiPlatform> ScanoutDraw<P> {
Some(Box::new(move || drop(keep))),
))
});
if buffer.is_none() {
log::warn!(
match &buffer {
// A lost device's lines name it so (`fault_walk::name_role`).
Some(buffer) => name_role::<P>(Role::ScanoutImport, HostObject::Buffer(buffer)),
None => log::warn!(
target: "reims_vgpu::graphics",
"the platform refused the scanout's pages (0x{length:x} bytes at 0x{start:x} in \
the region): the window shows nothing of this scanout"
);
),
}
buffer
}
@@ -1195,6 +1199,7 @@ impl<P: ApiPlatform> ScanoutDraw<P> {
}
_ => {
let texture = self.new_texture(format, values, TABLE_USAGE, Some(PRIVATE))?;
name_role::<P>(Role::ColorTable, HostObject::Texture(&texture));
let drawn = Arc::new(AtomicBool::new(false));
*kept = Some(ColorTable {
made_for,
@@ -1278,6 +1283,7 @@ impl<P: ApiPlatform> ScanoutDraw<P> {
}
let (values, pixel) = table_values(format)?;
let ramp = self.new_texture(format, values, RAMP_USAGE, None)?;
name_role::<P>(Role::ColorRamp, HostObject::Texture(&ramp));
let bytes: Vec<u8> = (0..u32::try_from(values).ok()?).flat_map(pixel).collect();
let length = u64::try_from(bytes.len()).ok()?;
// SAFETY: the bytes live across the call, which copies them out and keeps no pointer.
@@ -1304,8 +1310,10 @@ impl<P: ApiPlatform> ScanoutDraw<P> {
fn scanout_ramp(&self) -> Option<Arc<ScanoutRead<P>>> {
self.scanout_ramp.get_or_make(|| {
let bytes: Vec<u8> = (0..=u8::MAX).flat_map(|k| [k; 4]).collect();
let buffer = self.buffer_of(&bytes)?;
name_role::<P>(Role::ColorRamp, HostObject::Buffer(&buffer));
Some(ScanoutRead {
buffer: self.buffer_of(&bytes)?,
buffer,
origin: (0, 0),
stride_words: u32::try_from(SCANOUT_VALUES).ok()?,
first_word: 0,
+11 -4
View File
@@ -48,10 +48,12 @@ use reims_vgpu_vulkan::core::platform::values::{
ColorAttachmentDesc, FullRenderPipelineDesc, TextureDesc,
};
use reims_vgpu_vulkan::core::platform::{Handle as _, HostRange, Platform};
use reims_vgpu_vulkan::rt_platform::fault::Role;
use reims_vgpu_window::{DrawnCursor, DrawnOverlay, Glyph, PixelRect};
use super::Converter;
use crate::entry::no_catch;
use crate::graphics::fault_walk::{HostObject, name_role};
use crate::platform::ApiPlatform;
/// The least `viewportBoundsRange` Vulkan sets every device: a viewport's edges lie inside it.
@@ -75,6 +77,8 @@ pub(super) struct CursorPass<P: Platform> {
label: &'static str,
/// What it draws, for its refusals' lines.
draws: &'static str,
/// Its glyph's texture's name on a lost device's lines (`fault_walk::name_role`).
role: Role,
/// The blending pipelines made so far, by the drawable's pixel format.
pipelines: Vec<(u64, P::RenderPipeline)>,
/// The glyph last drawn, and its texture.
@@ -84,19 +88,21 @@ pub(super) struct CursorPass<P: Platform> {
impl<P: Platform> CursorPass<P> {
/// The guest's cursor's pass.
pub(super) fn cursor() -> Self {
CursorPass::new(CURSOR_PIPELINE_LABEL, "guest cursor")
CursorPass::new(CURSOR_PIPELINE_LABEL, "guest cursor", Role::CursorGlyph)
}
/// The window's overlay's pass.
pub(super) fn overlay() -> Self {
CursorPass::new(OVERLAY_PIPELINE_LABEL, "overlay")
CursorPass::new(OVERLAY_PIPELINE_LABEL, "overlay", Role::OverlayImage)
}
/// A pass whose pipelines are labelled `label`, drawing what `draws` names.
fn new(label: &'static str, draws: &'static str) -> Self {
/// A pass whose pipelines are labelled `label`, drawing what `draws` names, its glyph's
/// texture named `role` on a lost device's lines.
fn new(label: &'static str, draws: &'static str, role: Role) -> Self {
CursorPass {
label,
draws,
role,
pipelines: Vec::new(),
glyph: None,
}
@@ -160,6 +166,7 @@ impl<P: ApiPlatform> CursorPass<P> {
let Some(texture) = glyph_texture(platform, device, glyph) else {
return refused(self.draws, "a texture for its image");
};
name_role::<P>(self.role, HostObject::Texture(&texture));
self.glyph = Some((Arc::clone(glyph), texture.clone_ref()));
texture
}
+1 -1
View File
@@ -219,4 +219,4 @@ too the platform answers the encode as one it refuses.
| What runs instead of Metal's answer | Where |
|---|---|
| The loss of rt's `VkDevice` is never recovered from, where Metal's device survives its GPU's recovery: rt makes its device once (`crates/reims-vgpu-vulkan/src/rt_platform/swapchain.rs`, "No device recovery"). Of the work the loss ends, the earliest submitted command buffer rt ends in flight fails as the hang, `Timeout` (2), once for the device, and every other as a victim, `Internal` (1), never `DeviceRemoved` (11) (`crates/reims-vgpu-vulkan/src/rt_platform/command.rs`). Every later commit ends at once, `Internal` (1), its handlers run (metal2vulkan-runtime's `CommandBuffer::commit`), and a wait for a shared event's value that lost work owed answers false (its `SharedEvent::wait_until_signaled_value`). rt checks for no loss where it makes an object: a new one is made where the driver's Vulkan calls make it, and any call rt refuses after the loss answers as Metal's call answers where it fails, a nil object or nothing, counted under `rt-refused-<kind>` (`crates/reims-vgpu-vulkan/src/rt_platform/unbuilt.rs`); none of its GPU work runs. The window presents no frame after the loss: a frame whose command buffer did not run is never presented (`RtSwapchain::present`), and a take the lost device fails ends its presenter's draws, a new presenter made at most 3 times in a row before the window stays as it is (`crates/reims-vgpu/src/graphics/rt_window.rs`, `crates/reims-vgpu-window/src/present.rs`). The guest's presents are still answered at the display's refreshes, a failed command buffer finishing as a completed one does (`crates/reims-vgpu/src/graphics.rs`, `Presented`; `crates/reims-vgpu/src/graphics/present.rs`). Nothing on the platform ends the process at the loss or after it: the guest runs on, every command buffer failing, until the VM ends. The first command buffer that fails with the device lost writes one line on stderr, once for the device, naming the GPU (its name, PCI vendor and device IDs) and how many command buffers were committed and not complete then, and each command buffer that fails so is counted, `rt-device-lost` (`crates/reims-vgpu-vulkan/src/rt_platform/command.rs`, "A lost device's line"); rt itself writes nothing at a loss. Lines of the driver's report of the fault follow it, where rt read one (`VK_EXT_device_fault`): each address it names, placed among the decoders' live objects and the blocks the host sees, with the nearest below and above where none holds it (`crates/reims-vgpu-vulkan/src/rt_platform/fault.rs`); the guest sees none of it. Each command buffer rt ends as in flight then writes a line of its own, once however many of its parts it ends so, naming the guest's command buffer and the first compute and render pipeline states its encoders set, by their object ids, or that it is the host's own: the first 8, then one line that the rest are counted only, each counted, `rt-device-lost-in-flight`. What the guest's apps and compositor do with these codes is not measured. Two rt walks lost their device while the platform answered 11 (`DeviceRemoved`) for every command buffer the loss ended: m3-max-53777 on an RTX 3090 and m3-max-54078 on an RX 7900 XTX. In each, the guest's running app logged nothing for its last ~3 minutes until the walk stopped it | device loss |
| The loss of rt's `VkDevice` is never recovered from, where Metal's device survives its GPU's recovery: rt makes its device once (`crates/reims-vgpu-vulkan/src/rt_platform/swapchain.rs`, "No device recovery"). Of the work the loss ends, the earliest submitted command buffer rt ends in flight fails as the hang, `Timeout` (2), once for the device, and every other as a victim, `Internal` (1), never `DeviceRemoved` (11) (`crates/reims-vgpu-vulkan/src/rt_platform/command.rs`). Every later commit ends at once, `Internal` (1), its handlers run (metal2vulkan-runtime's `CommandBuffer::commit`), and a wait for a shared event's value that lost work owed answers false (its `SharedEvent::wait_until_signaled_value`). rt checks for no loss where it makes an object: a new one is made where the driver's Vulkan calls make it, and any call rt refuses after the loss answers as Metal's call answers where it fails, a nil object or nothing, counted under `rt-refused-<kind>` (`crates/reims-vgpu-vulkan/src/rt_platform/unbuilt.rs`); none of its GPU work runs. The window presents no frame after the loss: a frame whose command buffer did not run is never presented (`RtSwapchain::present`), and a take the lost device fails ends its presenter's draws, a new presenter made at most 3 times in a row before the window stays as it is (`crates/reims-vgpu/src/graphics/rt_window.rs`, `crates/reims-vgpu-window/src/present.rs`). The guest's presents are still answered at the display's refreshes, a failed command buffer finishing as a completed one does (`crates/reims-vgpu/src/graphics.rs`, `Presented`; `crates/reims-vgpu/src/graphics/present.rs`). Nothing on the platform ends the process at the loss or after it: the guest runs on, every command buffer failing, until the VM ends. The first command buffer that fails with the device lost writes one line on stderr, once for the device, naming the GPU (its name, PCI vendor and device IDs) and how many command buffers were committed and not complete then, and each command buffer that fails so is counted, `rt-device-lost` (`crates/reims-vgpu-vulkan/src/rt_platform/command.rs`, "A lost device's line"); rt itself writes nothing at a loss. Lines of the driver's report of the fault follow it, where rt read one (`VK_EXT_device_fault`): each address it names, placed among the decoders' live objects and the blocks the host sees, with the nearest below and above where none holds it (`crates/reims-vgpu-vulkan/src/rt_platform/fault.rs`); the guest sees none of it. Each command buffer rt ends as in flight then writes a line of its own, once however many of its parts it ends so, naming the guest's command buffer and the first compute and render pipeline states its encoders set, by their object ids, or that it is the host's own, with what its encoders render into and bind and what its blits read and write (a window swapchain's image, the scanout's import, a presented surface's texture, ...): the first 8, then one line that the rest are counted only, each counted, `rt-device-lost-in-flight`. What the guest's apps and compositor do with these codes is not measured. Two rt walks lost their device while the platform answered 11 (`DeviceRemoved`) for every command buffer the loss ended: m3-max-53777 on an RTX 3090 and m3-max-54078 on an RX 7900 XTX. In each, the guest's running app logged nothing for its last ~3 minutes until the walk stopped it | device loss |