🆕 Write a timeline of the device's work with REIMS_VGPU_TRACE

Profiling the guest's frames on an Intel iGPU needs the chain of each frame:
which FIFO commands ran, how long each held its thread, which command buffers
they committed, what each waited for and signalled, when the runtime submitted
and completed it, and when the guest heard of it. The per-queue summaries and
the stats line give none of that per frame.

With REIMS_VGPU_TRACE=<file>, the library writes one line per event, timed by
the runtime's host clock, which the platform installs, so a command buffer's
own times share the clock: FIFO commands read, their barriers met and their
handlers' return, stamps written and interrupts raised, the guest's doorbells,
presents and their wait for frames in flight, and on the Vulkan platform each
commit, its completion with its times, its event waits and signals, host sets,
and the runtime's work counts with the draws encoded so far.
REIMS_VGPU_TRACE_DEGRADE=1 also writes every occurrence of every degradation,
which the runtime then announces each time; a kind it announces once without
the trace is still relayed once.

Each import of host memory writes `imp` (its site, the first byte given, its
length, the first byte imported) and its keep-alive writes `impfree` as the
runtime lets it go, dropped after the memory it holds. Core writes `tobj` (the
guest object's kind, page and length) and `tbuf` (the task page, length, host
task and guest task id) before a buffer over task pages, so the ~200 userptr
imports ANV lists in each i915 execbuffer can be attributed.

Nothing changes with the variables unset: no event is written and no clock is
read.
This commit is contained in:
Anees Iqbal committed 2026-10-14 12:43:58 +03:00
1 parent 565e650907
commit 9b93b71db3
21 files changed
+523 -11

No files matched your search

@@ -350,6 +350,8 @@ impl<P: Platform> DeviceCore<P> {
}
self.on_fifo_queue(move |d| {
if let Some(child) = d.child_slot(fifo) {
// poke: the child FIFO woken
crate::trace::event("poke", &[u64::from(fifo)]);
child.poke();
}
});
@@ -377,6 +379,8 @@ impl<P: Platform> DeviceCore<P> {
);
self.interrupt_stamp
.fetch_or(crate::num::bit32(stamp), Ordering::SeqCst);
// stamp: slot, value: written for the guest
crate::trace::event("stamp", &[u64::from(stamp), u64::from(stamp_value)]);
self.signal_cond.notify_all();
self.interrupt();
}
@@ -422,6 +426,8 @@ impl<P: Platform> DeviceCore<P> {
let Some(raise) = &self.blocks.raise_interrupt else {
crate::fatal!(DeviceDeath::NilBlock("raiseInterrupt"))
};
// irq: the guest interrupt raised
crate::trace::event("irq", &[]);
raise(0);
}
}
@@ -197,6 +197,13 @@ impl<P: Platform> DeviceCore<P> {
let Some(register) = Register::decode(index) else {
return;
};
if matches!(
register,
Register::WakeFifo | Register::FifoWritten | Register::DisplayDoorbell
) {
// mmio: register index, value: the guest's doorbells
crate::trace::event("mmio", &[u64::from(index), u64::from(value)]);
}
match register {
// A nonzero value other than the current nonzero one reaches the enable's assert; an
// equal value does nothing.
@@ -74,7 +74,14 @@ impl<P: Platform> DisplayCore<P> {
completion: Box<dyn FnOnce() + Send>,
) -> RaiseResult<()> {
let mut g = self.display_mutex.lock();
// present: frames in flight, waited for next
crate::trace::event(
"present",
&[u64::from(self.in_flight_frame_count.load(Ordering::SeqCst))],
);
self.wait_for_pending_frames(&mut g);
// presented: frames in flight were waited for
crate::trace::event("presented", &[]);
if self.guest_color_space_dirty() {
// The guest display's colour space (nil without a guest display). The guest display
// pointer is read without its lock held across the call; the cell is a leaf.
+44
View File
@@ -213,6 +213,31 @@ impl<P: Platform> Fifo<P> {
if !self.read_bytes(body) {
continue;
}
if crate::trace::on() {
// cmd: FIFO, opcode, stamp value, barrier count, first barrier's slot and value
let first = |at: usize| {
barriers
.get(at..at.wrapping_add(4))
.and_then(|b| <[u8; 4]>::try_from(b).ok())
.map_or(0, |b| u64::from(u32::from_le_bytes(b)))
};
let (index, value) = if barrier_count == 0 {
(0, 0)
} else {
(first(0), first(4))
};
crate::trace::event(
"cmd",
&[
u64::from(self.stamp_index()),
u64::from(command.command_id),
u64::from(command.stamp_value),
u64::from(barrier_count),
index,
value,
],
);
}
let waited = (|| -> RaiseResult<_> {
if barrier_count == 0 {
return Ok(true);
@@ -243,9 +268,28 @@ impl<P: Platform> Fifo<P> {
}
// The read count publishes before the push, which may block.
self.advance();
if barrier_count != 0 {
// bar: FIFO, stamp value: its barriers were met
crate::trace::event(
"bar",
&[
u64::from(self.stamp_index()),
u64::from(command.stamp_value),
],
);
}
self.push_stamp(command.stamp_value, command.command_id);
let body = payload.get(..payload_len).unwrap_or(&[]);
self.dispatch(&command, body);
// ran: FIFO, opcode, stamp value: its handler returned
crate::trace::event(
"ran",
&[
u64::from(self.stamp_index()),
u64::from(command.command_id),
u64::from(command.stamp_value),
],
);
}
drop(payload);
// Outside the lock
+1
View File
@@ -54,3 +54,4 @@ pub mod sync;
pub mod tasks;
#[cfg(any(test, feature = "testkit"))]
pub mod testkit;
pub mod trace;
@@ -83,6 +83,9 @@ impl<P: Platform> PrivateBufferResource<P> {
if self.transfer_buffer.lock().is_some() {
return Ok(());
}
// Trace `tobj`: the guest object whose pages the next `tbuf` imports (2, a private buffer),
// its page and its length.
crate::trace::event("tobj", &[2, u64::from(self.page), self.length]);
let tb = match self.task.upgrade() {
Some(t) => Some(t.new_buffer_for_virtual_page(hold, self.page, self.length)?),
None => None,
@@ -70,6 +70,9 @@ impl<P: Platform> SharedBufferResource<P> {
if self.buffer.lock().is_some() {
return Ok(());
}
// Trace `tobj`: the guest object whose pages the next `tbuf` imports (1, a shared buffer),
// its page and its length.
crate::trace::event("tobj", &[1, u64::from(self.page), self.length]);
let buffer = match self.task.upgrade() {
Some(t) => Some(t.new_buffer_for_virtual_page(hold, self.page, self.length)?),
None => None,
@@ -145,6 +145,9 @@ impl<P: Platform> LegacyHeapResource<P> {
if self.transfer_buffer.lock().is_some() {
return Ok(());
}
// Trace `tobj`: the guest object whose pages the next `tbuf` imports (3, a legacy heap),
// its page and its length.
crate::trace::event("tobj", &[3, u64::from(self.page), self.length]);
let tb = match self.task.upgrade() {
Some(t) => Some(t.new_buffer_for_virtual_page(hold, self.page, self.length)?),
None => None,
@@ -390,6 +390,9 @@ impl<P: Platform> PagedTexture<P> {
let Some(task) = self.task.upgrade() else {
crate::fatal!(DeathKind::GoneTaskPages)
};
// Trace `tobj`: the guest object whose pages the next `tbuf` imports (4, a texture), its
// page and its length.
crate::trace::event("tobj", &[4, u64::from(self.page), self.length]);
// The task raises rather than answer nothing.
let buffer = task.new_buffer_for_virtual_page(hold, self.page, self.length)?;
*self.transfer_buffer.lock() = Some(buffer);
@@ -173,6 +173,9 @@ impl<P: Platform> BackingResource<P> {
let io_surface = platform.surfaces().create_backing(&spec);
// A torn-down task answers nothing: no buffer.
let host = task.upgrade();
// Trace `tobj`: the guest object whose pages the next `tbuf` imports (6, a new shared
// texture backing), its page and its length.
crate::trace::event("tobj", &[6, u64::from(page), length]);
let transfer_buffer = match &host {
Some(t) => match t.new_buffer_for_virtual_page(hold, page, length) {
Ok(b) => Some(b),
@@ -269,6 +272,9 @@ impl<P: Platform> BackingResource<P> {
if let Some(b) = self.transfer_buffer.lock().as_ref() {
return Ok(b.clone_ref());
}
// Trace `tobj`: the guest object whose pages the next `tbuf` imports (7, a shared texture
// backing bound again), its page and its length.
crate::trace::event("tobj", &[7, u64::from(self.page), self.length]);
let made = match self.task.upgrade() {
Some(t) => Some(t.new_buffer_for_virtual_page(hold, self.page, self.length)?),
None => None,
@@ -189,6 +189,9 @@ impl<P: Platform> DualPlaneCompute<P> {
let Some(task) = paged.task.upgrade() else {
crate::fatal!(DeathKind::GoneTaskPages)
};
// Trace `tobj`: the guest object whose pages the next `tbuf` imports (5, a compute
// texture), its page and its length.
crate::trace::event("tobj", &[5, u64::from(paged.page), paged.length]);
// The task raises rather than answer nothing.
let buffer = task.new_buffer_for_virtual_page(hold, paged.page, paged.length)?;
drop(task);
@@ -322,6 +322,13 @@ impl<P: Platform> LocalTask<P> {
// (the host's `map_memory` callback's), which the host keeps until the guest unmaps
// it; Metal gets the same memory with no deallocator.
let bytes = unsafe { crate::platform::HostRange::new(pointer, length) };
// Trace `tbuf`: the task page, the length, the host address, 0 (the blocks setup) and
// the guest's task id.
let task = u64::from(self.task_id);
crate::trace::event(
"tbuf",
&[u64::from(page), length, pointer.addr().to_u64(), 0, task],
);
match device {
Some(d) => d.new_buffer_over_host_memory(OnFault::Return, bytes, 0, None)?,
None => None,
@@ -342,6 +349,13 @@ impl<P: Platform> LocalTask<P> {
// mapping's own, page-aligned: `virtual_mapping` refused anything else), and the
// deallocator owns the mapping, so the range stays mapped until Metal runs it.
let bytes = unsafe { crate::platform::HostRange::new(pointer, length) };
// Trace `tbuf`: the task page, the length, the host address, 1 (the map setup) and
// the guest's task id.
let task = u64::from(self.task_id);
crate::trace::event(
"tbuf",
&[u64::from(page), length, pointer.addr().to_u64(), 1, task],
);
let buffer = match device {
Some(d) => {
d.new_buffer_over_host_memory(OnFault::Return, bytes, 0, Some(deallocator))
+161
View File
@@ -0,0 +1,161 @@
//! A timeline of the device's work for profiling, one line per event, written to the file
//! `REIMS_VGPU_TRACE` names: `<ns> <thread> <kind> <values...>`, the time in nanoseconds of the
//! clock the platform installs ([`set_clock`]), the thread a number of this process's (its name
//! written once, as `thread <number> <name>`).
//!
//! It is a diagnostic: with the variable unset, or before a platform installed its clock, no
//! event is written and [`on`] answers `false`, and no event reads anything with an effect. Each
//! site's comment names its event and its values.
//!
//! Lines are buffered and written when the buffer fills or a quarter second after the last
//! write: a process that ends loses at most that quarter second.
use std::cell::Cell;
use std::fmt::Write as _;
use std::fs::File;
use std::io::{BufWriter, Write as _};
use std::sync::OnceLock;
use std::sync::atomic::{AtomicU64, Ordering};
use crate::sync::Mutex;
/// The environment variable naming the file.
pub const ENV_VAR: &str = "REIMS_VGPU_TRACE";
/// How long a line may wait in the buffer, in nanoseconds.
const FLUSH_NS: u64 = 250_000_000;
/// The open file and when it was last written, or `None` with the variable unset or the file
/// refused.
static WRITER: OnceLock<Option<Mutex<Writer>>> = OnceLock::new();
/// The platform's clock, in nanoseconds.
static CLOCK: OnceLock<fn() -> u64> = OnceLock::new();
/// The next thread number.
static THREADS: AtomicU64 = AtomicU64::new(1);
thread_local! {
/// This thread's number, 0 before its first event.
static THREAD: Cell<u64> = const { Cell::new(0) };
}
struct Writer {
out: BufWriter<File>,
flushed: u64,
}
/// Installs the clock events are timed by: the platform's, once per process. Without it nothing
/// is written.
pub fn set_clock(clock: fn() -> u64) {
let _ = CLOCK.set(clock);
}
/// The clock now, 0 without one.
pub fn now() -> u64 {
CLOCK.get().map_or(0, |clock| clock())
}
/// Whether events are written.
pub fn on() -> bool {
CLOCK.get().is_some() && writer().is_some()
}
fn writer() -> Option<&'static Mutex<Writer>> {
WRITER
.get_or_init(|| {
let path = std::env::var_os(ENV_VAR)?;
let file = File::create(&path)
.inspect_err(|e| log::warn!("{ENV_VAR}: {}: {e}", path.to_string_lossy()))
.ok()?;
Some(Mutex::new(Writer {
out: BufWriter::with_capacity(1 << 20, file),
flushed: 0,
}))
})
.as_ref()
}
/// Writes one event, `kind` and `values`, timed now.
pub fn event(kind: &str, values: &[u64]) {
if !on() {
return;
}
event_at(now(), kind, values);
}
/// Writes one event, `kind` and `values`, timed `at`.
pub fn event_at(at: u64, kind: &str, values: &[u64]) {
let mut line = String::with_capacity(96);
let _ = write!(line, "{at} {} {kind}", thread_number());
for v in values {
let _ = write!(line, " {v}");
}
line.push('\n');
write_line(&line);
}
/// Writes one event whose last value is text (a label: its spaces become `_`).
pub fn event_text(kind: &str, values: &[u64], text: &str) {
if !on() {
return;
}
let mut line = String::with_capacity(96);
let _ = write!(line, "{} {} {kind}", now(), thread_number());
for v in values {
let _ = write!(line, " {v}");
}
line.push(' ');
line.extend(
text.chars()
.map(|c| if c.is_whitespace() { '_' } else { c }),
);
line.push('\n');
write_line(&line);
}
fn write_line(line: &str) {
let Some(writer) = writer() else {
return;
};
let mut w = writer.lock();
let _ = w.out.write_all(line.as_bytes());
let t = now();
if t.saturating_sub(w.flushed) >= FLUSH_NS {
let _ = w.out.flush();
w.flushed = t;
}
}
/// This thread's number; its first event writes its name.
fn thread_number() -> u64 {
THREAD.with(|n| {
if n.get() == 0 {
let number = THREADS.fetch_add(1, Ordering::Relaxed);
n.set(number);
let name = std::thread::current()
.name()
.unwrap_or("unnamed")
.replace(char::is_whitespace, "_");
write_line(&format!("{} {number} thread {number} {name}\n", now()));
}
n.get()
})
}
#[cfg(test)]
mod tests {
use super::*;
/// Without the variable nothing is written, whatever the clock
#[test]
fn off_without_the_variable() {
// nextest runs each test in a process of its own, where the variable is not set
assert!(std::env::var_os(ENV_VAR).is_none());
set_clock(|| 7);
assert!(!on());
event("cmd", &[1, 2]);
event_text("cbcommit", &[1], "a label");
assert_eq!(now(), 7);
}
}
+26
View File
@@ -1289,6 +1289,19 @@ fn fate(kind: rt::Degradation, placement: native::Placement, census: bool, stric
}
}
/// Whether every occurrence of every degradation is written to the trace
/// (`REIMS_VGPU_TRACE_DEGRADE`, with `REIMS_VGPU_TRACE`): a diagnostic, which only the sink's
/// relaying and the trace see.
pub fn trace_degradations() -> bool {
static ON: std::sync::LazyLock<bool> =
std::sync::LazyLock::new(|| std::env::var_os("REIMS_VGPU_TRACE_DEGRADE").is_some());
*ON
}
/// The kinds the trace saw, which the runtime announces once without it.
static TRACED_KINDS: reims_vgpu_core::sync::Mutex<Vec<rt::Degradation>> =
reims_vgpu_core::sync::Mutex::new(Vec::new());
/// The runtime's message sink (`DeviceOptions::messages`, [`crate::platform`]): a degradation
/// of [`DIES`] is relayed and counted, or in strict mode kept for the call here it was announced
/// inside to die at, or, announced outside every call here, dies now, ending the process (the
@@ -1302,6 +1315,19 @@ pub fn notice(message: &rt::DebugMessage) {
relay(message);
return;
};
if trace_degradations() && reims_vgpu_core::trace::on() {
let kind = notice.degradation;
// deg: an occurrence of a degradation, its code
reims_vgpu_core::trace::event_text("deg", &[], kind.code());
// A kind announced once without the trace goes on only at its first occurrence.
if !DIES.contains(&kind) && !HEARD.contains(&kind) {
let mut seen = TRACED_KINDS.lock();
if seen.contains(&kind) {
return;
}
seen.push(kind);
}
}
if !DIES.contains(&notice.degradation) {
if HEARD.contains(&notice.degradation) {
HEARING.with(|h| {
+64 -3
View File
@@ -152,6 +152,7 @@ use std::sync::{Arc, OnceLock, Weak};
use metal2vulkan_runtime as rt;
use reims_vgpu_core::host::HostPtr;
use reims_vgpu_core::num::ToU64;
use reims_vgpu_core::platform::os::vm::{HostVm, KernReturn, VmProt};
use reims_vgpu_core::platform::types::ResourceAddressRange;
use reims_vgpu_core::raise::RaiseResult;
@@ -499,7 +500,7 @@ impl Backing {
return Ok(false);
};
let alias = Arc::new(alias);
let (first, keep) = Arc::clone(&alias).into_runtime();
let (first, keep) = Arc::clone(&alias).into_runtime(ImportSite::Replace);
rebind(first, keep)?;
let own = {
let mut aliased = self.alias.lock();
@@ -852,13 +853,14 @@ impl Alias {
/// they are mapped (read-only, on Linux), a writable twin of them ([`crate::os::import_view`]),
/// whose first byte this answers, and which the keep-alive holds too: the GPU's writes then
/// reach the pages, where Metal drops them ([`Alias::writes_kept`]).
pub(crate) fn into_runtime(self: Arc<Self>) -> (NonNull<u8>, rt::KeepAlive) {
pub(crate) fn into_runtime(self: Arc<Self>, site: ImportSite) -> (NonNull<u8>, rt::KeepAlive) {
let first = self.at;
let view = crate::os::import_view(first, self.length);
let imported = view.at();
self.kept.store(view.writes_kept(), Ordering::Release);
let (_, twin) = view.release(first, None);
(imported, keep_alive((twin, self)))
let traced = ImportTrace::new(site, first, self.length, imported);
(imported, keep_alive((twin, self, traced)))
}
/// Whether the runtime imports the alias through a writable twin of read-only pages, whose
@@ -881,6 +883,65 @@ impl Drop for Alias {
}
}
/// Where an import of host memory was made, as the trace names it ([`ImportTrace`]).
#[derive(Debug, Clone, Copy)]
pub(crate) enum ImportSite {
/// A no-copy buffer over host memory core gives (`newBufferWithBytesNoCopy`: task pages, the
/// EFI framebuffer).
NoCopyBytes,
/// A no-copy buffer a descriptor names (a detached buffer).
NoCopyDescriptor,
/// A buffer over a surface's alias.
Surface,
/// A heap over guest ranges.
Heap,
/// A buffer's replaced backing.
Replace,
/// A buffer over a surface, imported at its base address.
SurfaceBase,
}
impl ImportSite {
/// The site's number in the trace.
fn code(self) -> u64 {
match self {
Self::NoCopyBytes => 1,
Self::NoCopyDescriptor => 2,
Self::Surface => 3,
Self::Heap => 4,
Self::Replace => 5,
Self::SurfaceBase => 6,
}
}
}
/// The trace of one import of host memory by the runtime, with `REIMS_VGPU_TRACE` set
/// ([`reims_vgpu_core::trace`]): `imp` as it is made (the site, the first byte given, its
/// length, the first byte imported), and `impfree` as its keep-alive goes, once the runtime
/// freed the import (the first byte imported). A diagnostic: it holds nothing and reads nothing
/// with an effect, and the keep-alive drops it last.
pub(crate) struct ImportTrace(u64);
impl ImportTrace {
pub(crate) fn new(
site: ImportSite,
given: NonNull<u8>,
length: u64,
imported: NonNull<u8>,
) -> Self {
let at = imported.as_ptr().addr().to_u64();
let given = given.as_ptr().addr().to_u64();
reims_vgpu_core::trace::event("imp", &[site.code(), given, length, at]);
Self(at)
}
}
impl Drop for ImportTrace {
fn drop(&mut self) {
reims_vgpu_core::trace::event("impfree", &[self.0]);
}
}
/// The runtime's keep-alive of `kept`, what keeps the memory of a no-copy buffer's or heap's
/// import mapped (an [`Alias`], a twin, an [`UnmapHold`](crate::remap::UnmapHold)): the runtime
/// drops it once it freed the device's import of the memory, after the deallocator ran, on
+39 -1
View File
@@ -1395,6 +1395,8 @@ impl CommandBuffer<VulkanPlatform> for VulkanCommandBuffer {
value: u64,
) -> RaiseResult<()> {
let sel = "encodeSignalEvent:value:";
// evsig: command buffer, event, value
trace_event("evsig", &self.raw, event.as_ref(), value);
let event = self::event(sel, event);
predication::boundary(&self.predication, sel);
encoding(sel, Policy::Dies, || {
@@ -1410,10 +1412,17 @@ impl CommandBuffer<VulkanPlatform> for VulkanCommandBuffer {
value: u64,
) -> RaiseResult<()> {
let sel = "encodeSignalEventScheduled:value:";
let traced = signal_event_scheduled.map_or(0, event_id);
// evsched: command buffer, event, value
trace_event_id("evsched", &self.raw, traced, value);
let event = signal_event_scheduled
.map(|e| rt::SharedEvent::clone(e))
.unwrap_or_else(|| unrepresentable(sel, "a nil event"));
let handler: rt::Handler = Box::new(move |_| event.set_signaled_value(value));
let handler: rt::Handler = Box::new(move |_| {
// evschedset: event, value: the scheduled handler sets it
reims_vgpu_core::trace::event("evschedset", &[traced, value]);
event.set_signaled_value(value)
});
encoding(sel, Policy::Dies, || {
self.raw.add_scheduled_handler(handler)
})
@@ -1425,6 +1434,8 @@ impl CommandBuffer<VulkanPlatform> for VulkanCommandBuffer {
value: u64,
) -> RaiseResult<()> {
let sel = "encodeWaitForEvent:value:";
// evwait: command buffer, event, value
trace_event("evwait", &self.raw, event.as_ref(), value);
let event = self::event(sel, event);
predication::boundary(&self.predication, sel);
encoding(sel, Policy::Dies, || {
@@ -1540,6 +1551,33 @@ impl CommandBuffer<VulkanPlatform> for VulkanCommandBuffer {
}
}
/// An event's number in the trace: its object's address.
pub(crate) fn event_id<T: Send + Sync + 'static>(event: &Obj<T>) -> u64 {
u64::try_from(std::ptr::from_ref::<T>(event).addr()).unwrap_or_default()
}
/// A traced encode of an event: its command buffer, the event and the value.
fn trace_event(
kind: &str,
cb: &rt::CommandBuffer,
event: Option<&EventRef<'_, VulkanPlatform>>,
value: u64,
) {
if !reims_vgpu_core::trace::on() {
return;
}
let id = match event {
Some(EventRef::Shared(e)) => event_id(*e),
Some(EventRef::Event(e)) => event_id(*e),
None => 0,
};
trace_event_id(kind, cb, id, value);
}
fn trace_event_id(kind: &str, cb: &rt::CommandBuffer, event: u64, value: u64) {
reims_vgpu_core::trace::event(kind, &[crate::gpu::timing::id(cb), event, value]);
}
#[cfg(test)]
mod tests {
use std::sync::mpsc;
+21 -6
View File
@@ -310,13 +310,20 @@ fn no_copy_release(
start: NonNull<u8>,
length: u64,
run: Option<rt::Deallocator>,
site: backing::ImportSite,
) -> (NonNull<u8>, Option<rt::Deallocator>, rt::KeepAlive, bool) {
let view = crate::os::import_view(start, length);
let imported = view.at();
let kept = view.writes_kept();
let (run, twin) = view.release(start, run);
let hold = crate::remap::UnmapHold::new(start, length);
(imported, run, backing::keep_alive((twin, hold)), kept)
let traced = backing::ImportTrace::new(site, start, length, imported);
(
imported,
run,
backing::keep_alive((twin, hold, traced)),
kept,
)
}
/// What Metal answers where the runtime refuses a buffer or heap made at `placing`'s address:
@@ -592,7 +599,9 @@ impl VulkanDevice {
// The runtime runs the deallocator as it lets go of the buffer, which may drop the
// surface's last reference, and frees its import once nothing else holds it.
let hold = crate::os::surface_memory_hold(surface);
(base, backing::keep_alive(hold))
let site = backing::ImportSite::SurfaceBase;
let traced = backing::ImportTrace::new(site, base, length, base);
(base, backing::keep_alive((hold, traced)))
} else {
let first = u64::try_from(base.as_ptr().addr())
.unwrap_or(u64::MAX)
@@ -625,7 +634,7 @@ impl VulkanDevice {
let Some(alias) = alias else {
return Ok(None);
};
let (at, keep) = alias.into_runtime();
let (at, keep) = alias.into_runtime(backing::ImportSite::Surface);
// The alias holds `offset` bytes more than the buffer, past its end.
let from = at
.as_ptr()
@@ -784,7 +793,8 @@ impl GpuDevice<VulkanPlatform> for VulkanDevice {
let token = placing.token();
// The bytes, or a writable twin of them where the runtime cannot import them as mapped,
// and what keeps them mapped until the runtime freed its import.
let (imported, run, keep, kept) = no_copy_release(start, bytes.len(), run);
let (imported, run, keep, kept) =
no_copy_release(start, bytes.len(), run, backing::ImportSite::NoCopyBytes);
let made = create(
sel,
Policy::Dies,
@@ -1533,7 +1543,12 @@ impl GpuDevice<VulkanPlatform> for VulkanDevice {
})
});
own = Some(backing::Own::new(start, held));
let (imported, run, keep, twinned) = no_copy_release(start, bytes.len(), run);
let (imported, run, keep, twinned) = no_copy_release(
start,
bytes.len(),
run,
backing::ImportSite::NoCopyDescriptor,
);
kept = twinned;
rt::BufferContents::NoCopy {
// SAFETY: `HostRange::new`'s contract keeps the bytes mapped until the
@@ -1670,7 +1685,7 @@ impl GpuDevice<VulkanPlatform> for VulkanDevice {
.map(Arc::new);
match made_over
.as_ref()
.map(|alias| Arc::clone(alias).into_runtime())
.map(|alias| Arc::clone(alias).into_runtime(backing::ImportSite::Heap))
{
None => None,
Some((first, keep)) => create(sel, Policy::Dies, nil, || {
@@ -2496,6 +2496,7 @@ impl VulkanRenderEncoder {
mut call: impl FnMut(&mut rt::RenderCommandEncoder, K) -> Result<(), rt::Error>,
) -> RaiseResult<()> {
self.pipelined(sel);
crate::gpu::timing::count_draw();
match drawn {
Some((shape, k)) => {
self.bfloat_drawn(sel);
@@ -32,6 +32,11 @@ impl SharedEvent<VulkanPlatform> for VulkanSharedEvent {
/// The value becomes at least `signaled_value`; the runtime refuses no value.
fn set_signaled_value(&self, signaled_value: u64) -> RaiseResult<()> {
// evset: event, value: the guest's or the device's host set
reims_vgpu_core::trace::event(
"evset",
&[crate::gpu::command::event_id(self), signaled_value],
);
plain(|| rt::SharedEvent::set_signaled_value(self, signaled_value));
Ok(())
}
+98 -1
View File
@@ -52,6 +52,7 @@ use crate::os::OsClock;
use reims_vgpu_core::platform::types::NsErrorText;
use reims_vgpu_core::raise::RaiseResult;
use reims_vgpu_core::sync::Mutex;
use reims_vgpu_core::trace;
/// An encoder command or a commit that takes this long or longer is written.
pub const SLOW_CALL: Duration = Duration::from_millis(5);
@@ -195,7 +196,8 @@ pub fn encoder_call<T>(sel: &str, pipeline: &AtomicU64, call: impl FnOnce() -> T
/// [`LATE_COMPLETION`] or more after the commit began. A handler the runtime refuses (the command buffer was committed
/// already, which the commit then refuses too) is no line.
pub fn commit<T>(cb: &rt::CommandBuffer, commit: impl FnOnce() -> T) -> T {
if !on() {
let traced = trace::on();
if !on() && !traced {
return commit();
}
let n = COMMITS.fetch_add(1, Ordering::Relaxed).wrapping_add(1);
@@ -203,6 +205,10 @@ pub fn commit<T>(cb: &rt::CommandBuffer, commit: impl FnOnce() -> T) -> T {
let start = now();
let host_start = rt::host_time();
let late = queue.clone();
if traced {
// cbcommit: command buffer, commit number, queue label
trace::event_text("cbcommit", &[id(cb), n], &queue);
}
let _ = cb.add_completed_handler(Box::new(move |cb: &rt::CommandBuffer| {
let elapsed = elapsed_since(start);
let times = Times {
@@ -213,6 +219,27 @@ pub fn commit<T>(cb: &rt::CommandBuffer, commit: impl FnOnce() -> T) -> T {
gpu_end: cb.gpu_end_time().unwrap_or(0.0),
handler: rt::host_time(),
};
if traced {
// cbdone (timed at its handler): command buffer, commit number, then its commit,
// submission start and end, GPU start and end, in the trace's nanoseconds
trace::event_at(
nanos(times.handler),
"cbdone",
&[
id(cb),
n,
nanos(times.commit),
nanos(times.kernel_start),
nanos(times.kernel_end),
nanos(times.gpu_start),
nanos(times.gpu_end),
],
);
work_counts(cb);
}
if !on() {
return;
}
let lines = SUMMARY.lock().add(&late, &times);
for line in lines {
log::debug!("{line}");
@@ -241,6 +268,10 @@ pub fn commit<T>(cb: &rt::CommandBuffer, commit: impl FnOnce() -> T) -> T {
);
}));
let out = commit();
if traced {
// committed: command buffer: its commit returned
trace::event("committed", &[id(cb)]);
}
let elapsed = elapsed_since(start);
if elapsed >= SLOW_CALL {
log::debug!(
@@ -252,6 +283,72 @@ pub fn commit<T>(cb: &rt::CommandBuffer, commit: impl FnOnce() -> T) -> T {
out
}
/// A command buffer's number in the trace: its address.
pub fn id(cb: &rt::CommandBuffer) -> u64 {
u64::try_from(std::ptr::from_ref(cb).addr()).unwrap_or_default()
}
/// Seconds of the runtime's host clock, in the trace's nanoseconds (its clock is the runtime's,
/// [`trace_clock`]); 0 stays 0.
fn nanos(seconds: f64) -> u64 {
if seconds <= 0.0 {
return 0;
}
std::time::Duration::try_from_secs_f64(seconds)
.map_or(0, |d| u64::try_from(d.as_nanos()).unwrap_or(u64::MAX))
}
/// The trace's clock: the runtime's host clock, in nanoseconds, so a command buffer's times and
/// the trace's events are of one clock.
pub fn trace_clock() -> u64 {
nanos(rt::host_time())
}
/// The draws encoded while the trace is on, which [`work_counts`] writes.
static DRAWS: AtomicU64 = AtomicU64::new(0);
/// Counts a draw for the trace ([`work_counts`]).
pub fn count_draw() {
if trace::on() {
DRAWS.fetch_add(1, Ordering::Relaxed);
}
}
/// The runtime's counts of what its commit path did, written to the trace at most every 100 ms,
/// and the draws encoded so far.
fn work_counts(cb: &rt::CommandBuffer) {
static LAST: AtomicU64 = AtomicU64::new(0);
let t = trace::now();
let last = LAST.load(Ordering::Relaxed);
if t.saturating_sub(last) < 100_000_000
|| LAST
.compare_exchange(last, t, Ordering::Relaxed, Ordering::Relaxed)
.is_err()
{
return;
}
let c = cb.command_queue().device().work_counts();
// wc: the counts named in the order written, then the draws
trace::event(
"wc",
&[
c.timeline_waits,
c.command_pools_made,
c.live_tables_uploaded,
c.pipelines_pooled,
c.variant_pipelines_made,
c.host_step_sampler_sets_made,
c.ahead_render_passes_made,
c.storage_forms_taken,
c.addressable_buffers_made,
c.dispatch_pipelines_pooled,
c.creation_pipelines_made,
c.kept_backings_made,
DRAWS.load(Ordering::Relaxed),
],
);
}
/// The host times of a command buffer, in seconds of the runtime's `host_time` clock, each 0
/// where the runtime kept none: its commit began, the runtime's kernel start and end, GPU start and
/// end ([`crate::platform`]'s device options), and its last completed handler ran.
+8
View File
@@ -311,6 +311,14 @@ pub(crate) fn device_options() -> &'static rt::DeviceOptions {
.into_iter()
.chain(crate::answer::HEARD)
.collect();
if std::env::var_os(reims_vgpu_core::trace::ENV_VAR).is_some() {
reims_vgpu_core::trace::set_clock(crate::gpu::timing::trace_clock);
if crate::answer::trace_degradations() {
// Every occurrence reaches the sink, which writes each to the trace and relays
// a kind the runtime announces once only the first time.
options.announce_each = rt::Degradation::ALL.iter().copied().collect();
}
}
if let Some(home) = std::env::var_os("HOME") {
options.shader_cache =
rt::ShaderCacheOptions::in_directory(PathBuf::from(home).join(SHADER_CACHE));