From 965eb0b538b4c212d46fb1e8b60ecfc9fe90bfd8 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Wed, 14 Oct 2026 12:15:42 +0300 Subject: [PATCH] Wake the scheduler thread at once for a check a commit's pass finds A commit whose pass finds a submission check or a host step for the scheduler thread now wakes that thread at once, instead of after its own later passes and submission handlers. The scheduler thread runs one check or host step at a time, taking in waiting commits between them, and a commit handed to another thread waits at most for that thread's current pass and its handlers. The commit-latency lane measures a checked commit's wait for its submission under a consumer-like load (400 host imports, checked command buffers from one and three threads, event waits). Gain: the consumer's guest A/B on a Radeon 780M and an RX 7900 XTX (RADV): window drags +13-20% frames/s, and the commit's off-CPU wait from 9.3 to 0 ms a frame. The new test's hold fell from 71-75 ms (RADV, ANV) to prompt. Verified on the original branch: the scheduler lanes, 62 of 62 on RADV and ANV, and the runtime crate's tests. This squashed commit was not re-tested on its own. --- .../src/scheduler/inbox.rs | 35 +- .../metal2vulkan-runtime/src/scheduler/mod.rs | 187 +++++----- .../metal2vulkan-runtime/src/tests/inbox.rs | 64 +++- .../runtime-sources.sha256 | 2 +- .../src/runtime_lane.rs | 2 + .../src/runtime_lane/commit_latency.rs | 343 ++++++++++++++++++ .../src/runtime_lane/queue_order.rs | 109 +++++- .../src/runtime_lane/submit_costs.rs | 39 +- scripts/i915-execbuffers/counter.c | 161 ++++++-- 9 files changed, 789 insertions(+), 153 deletions(-) create mode 100644 crates/metal2vulkan-validation/src/runtime_lane/commit_latency.rs diff --git a/crates/metal2vulkan-runtime/src/scheduler/inbox.rs b/crates/metal2vulkan-runtime/src/scheduler/inbox.rs index c73d60498..0ac6a83db 100644 --- a/crates/metal2vulkan-runtime/src/scheduler/inbox.rs +++ b/crates/metal2vulkan-runtime/src/scheduler/inbox.rs @@ -21,6 +21,13 @@ //! a commit is either seen by a passer's look or finds no passer, and passes itself. The lock's //! other holders (a wake, a decode count, the thread's look for work) make no pass and are not //! counted: a commit that finds only one of them waits for its short hold, and then passes. +//! - **The scheduler's thread looks again until its passes leave it work** ([`Inbox::pass`]). +//! Its passes may leave it work to do without the lock first (a submission check, a host step), +//! which the batches behind it wait for: it stops looking again at the first pass that leaves +//! some, rather than pass on for the commits that keep coming while that work waits, and looks +//! at the inbox itself ([`Inbox::holds_commits`]) before each piece of that work and before it +//! sleeps. A commit is left to it only while it holds the lock for a pass, so one waits at most +//! for that pass and the submission handlers the thread runs right after it, never for a wake. //! - **Who runs the after-work.** A pass's thread lets go, outside the lock, of what its passes //! submitted (the holds, the submission handlers) in submission order, as the scheduler does //! for its own: a commit handed off runs its submission handlers on that thread. @@ -67,6 +74,10 @@ impl Inbox { /// /// [`look_again`]: Self::look_again pub(crate) fn commit(&self, commit: C, mut pass: impl FnMut(&mut S, Vec)) -> bool { + let mut pass = |state: &mut S, commits: Vec| { + pass(state, commits); + true + }; self.passers.fetch_add(1, Ordering::SeqCst); let state = match self.state.try_lock() { Ok(state) => Some(state), @@ -93,21 +104,26 @@ impl Inbox { } /// A pass by a thread that waits for the lock (the scheduler's own), `pass` taking in what the - /// inbox holds; then look at the inbox again ([`look_again`](Self::look_again)). - pub(crate) fn pass(&self, mut pass: impl FnMut(&mut S, Vec)) { + /// inbox holds and answering whether to look again; then look at the inbox again + /// ([`look_again`](Self::look_again)) while each pass answers so. Where one answers no, the + /// inbox may hold commits left to this thread, which it looks for itself + /// ([`holds_commits`](Self::holds_commits)) and passes for before it sleeps (the module docs). + pub(crate) fn pass(&self, mut pass: impl FnMut(&mut S, Vec) -> bool) { self.passers.fetch_add(1, Ordering::SeqCst); let mut state = lock(&self.state); let commits = self.take(); - pass(&mut state, commits); + let again = pass(&mut state, commits); drop(state); self.passers.fetch_sub(1, Ordering::SeqCst); - self.look_again(&mut pass); + if again { + self.look_again(&mut pass); + } } /// After a passer is counted out: while the inbox holds a commit and no other passer is - /// counted, take the lock and pass for it (waiting only for a holder that makes no pass). - /// Whether this made a pass. - fn look_again(&self, pass: &mut impl FnMut(&mut S, Vec)) -> bool { + /// counted, take the lock and pass for it (waiting only for a holder that makes no pass), + /// until a pass answers not to look again. Whether this made a pass. + fn look_again(&self, pass: &mut impl FnMut(&mut S, Vec) -> bool) -> bool { let mut passed = false; loop { fence(Ordering::SeqCst); @@ -127,10 +143,13 @@ impl Inbox { Err(TryLockError::WouldBlock) => lock(&self.state), }; let commits = self.take(); - pass(&mut state, commits); + let again = pass(&mut state, commits); drop(state); passed = true; self.passers.fetch_sub(1, Ordering::SeqCst); + if !again { + return passed; + } } } diff --git a/crates/metal2vulkan-runtime/src/scheduler/mod.rs b/crates/metal2vulkan-runtime/src/scheduler/mod.rs index ba40060e4..c72c1986e 100644 --- a/crates/metal2vulkan-runtime/src/scheduler/mod.rs +++ b/crates/metal2vulkan-runtime/src/scheduler/mod.rs @@ -5,12 +5,17 @@ //! thread, under the scheduler's lock, where it finds the lock free: the batches ready then go //! to the `VkQueue` before it returns, in the same order, with no wake of the thread on their //! path. The thread runs what that pass leaves (a host step, a submission check, a wait for an -//! event the host raises later), as before. +//! event the host raises later), as before: the pass that finds a step or a check wakes it at +//! once, under the lock, not after the committing thread's further passes or its submission +//! handlers. //! - **Handed to the pass under way** ([`Inbox`]). Where another thread holds the lock for a pass //! (this one, or another commit), `commit` leaves its batches in the inbox and returns at once: //! that thread takes them in, in commit order, as soon as it lets go of the lock, and submits //! what is ready in a pass of its own, as the commit would once it had the lock. The order sees -//! every commit in commit order, and every batch is planned as it is submitted, as before. +//! every commit in commit order, and every batch is planned as it is submitted, as before. This +//! thread stops looking at the inbox again at a pass that leaves it a check or a host step, and +//! looks at it before each one it runs and before it sleeps: a commit left to it waits for the +//! pass under way and the submission handlers that pass leaves, never for a wake. //! //! - **The order** ([`Order`]). Each logical queue's batches wait in commit order; the head //! committed first among those ready goes next. A batch is ready once every event it waits for @@ -88,7 +93,7 @@ use ash::vk; use binary::{BinarySignals, Needs}; use inbox::Inbox; use order::{Behind, Order}; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, VecDeque}; use std::sync::atomic::{fence, AtomicBool, Ordering}; use std::sync::{Arc, Condvar, Mutex}; use std::thread::JoinHandle; @@ -225,7 +230,7 @@ impl Scheduler { /// the `VkQueue` before `commit` returns, without the thread's wake on its path. Where another /// thread is making a pass, leave the batches to it and return at once (the module docs). A /// host step or a submission check found ready, and the process's exit, are left to the - /// thread, which this wakes for them. + /// thread, which the pass that found them wakes for them at once. pub(crate) fn commit( &self, buffer: &Arc, @@ -238,19 +243,16 @@ impl Scheduler { queue, batches, }; - let mut passed = Passed::default(); - let left = (shared.inbox).commit(committed, |state, commits| { - pass(state, commits, &mut passed, &shared.gated, false); + let (mut passed, mut left) = (Passed::default(), Left::default()); + let handed_off = (shared.inbox).commit(committed, |state, commits| { + pass(state, commits, (&mut passed, &mut left), shared, false); }); - if left { + if handed_off { buffer.device().shared().counts.commit_handed_off(); } - let thread = passed.for_thread(); let Passed { spent, settled, - steps, - checks, handlers, .. } = passed; @@ -258,13 +260,9 @@ impl Scheduler { // On the committing thread, before `commit` returns. run_submission_handlers(handlers); // Without the lock, as the thread lets go of them: the thread finds the steps and the - // checks again in its own pass. + // checks again in its own pass, which the pass that found them woke it for. drop(spent); - drop(steps); - drop(checks); - if thread { - shared.wake.notify_all(); - } + drop(left); } /// What makes the thread look for work again from any thread: a pipeline a held batch's @@ -369,7 +367,8 @@ impl Scheduler { fn run(shared: &SchedulerShared) { loop { let mut state = lock(shared.inbox.state()); - while !state.dirty && !state.stopping { + // A commit left to this thread's pass may wait in the inbox (`inbox.rs`). + while !state.dirty && !state.stopping && !shared.inbox.holds_commits() { state = shared .wake .wait_timeout(state, WAIT_SLICE) @@ -382,88 +381,111 @@ fn run(shared: &SchedulerShared) { // The pass takes the lock again, counted as a passer from before (`inbox.rs`): a commit // that finds it taken leaves its batches to this thread. drop(state); - let mut passed = Passed::default(); - (shared.inbox).pass(|state, commits| { - pass(state, commits, &mut passed, &shared.gated, true); - }); - let Passed { - spent, - settled, - steps, - checks, - handlers, - exiting, - } = passed; - settle(settled); - // On this thread, before its next pass; none once the process is exiting, as the thread - // then runs nothing more (their command buffers stay `Committed`). - if exiting { - drop(handlers); - } else { - run_submission_handlers(handlers); - } - // Without the lock: the last reference to a command buffer may be among them, and with - // it its device, whose drop stops this thread. - drop(spent); - if exiting { + let mut left = Left::default(); + if !round(shared, &mut left) { return; } - if steps.is_empty() && checks.is_empty() { + if left.is_empty() { continue; } - // The submission checks, without the lock (they run the program's code), each pass a - // section; once the process is exiting the thread ends at the next. - for (buffer, index) in &checks { - let Some(_busy) = exit_guard::enter() else { + loop { + // A commit left to this thread meanwhile goes before the next piece of work. + if shared.inbox.holds_commits() && !round(shared, &mut left) { return; - }; - buffer.run_checks(*index); - } - drop(checks); - // The host steps, without the lock (they record, and may make what a dispatch makes), - // each a section; once the process is exiting the thread ends at the next. - for (buffer, index) in &steps { - let Some(_busy) = exit_guard::enter() else { - return; - }; - buffer.host_step(*index); - for &call in exit_guard::HOST_STEP { - exit_guard::called(call); } + // The submission checks, then the host steps, without the lock (a check runs the + // program's code; a step records, and may make what a dispatch makes), each a + // section; once the process is exiting the thread ends at the next. + let (work, step) = match left.checks.pop_front() { + Some(check) => (check, false), + None => match left.steps.pop_front() { + Some(step) => (step, true), + None => break, + }, + }; + let Some(busy) = exit_guard::enter() else { + return; + }; + let (buffer, index) = &work; + if step { + buffer.host_step(*index); + for &call in exit_guard::HOST_STEP { + exit_guard::called(call); + } + } else { + buffer.run_checks(*index); + } + drop(busy); + // Out of the section: it may be the command buffer's last reference. + drop(work); } - drop(steps); lock(shared.inbox.state()).dirty = true; } } -/// What passes leave for their thread to do without the lock ([`submit_ready`]'s outputs), and -/// whether the process is exiting. +/// One round of the thread's: a pass, looking at the inbox again while the passes leave the +/// thread no work ([`Inbox::pass`]), what they leave added to `left`; then, without the lock, +/// what they let go of: the storage forms settled, the submission handlers run (on this thread, +/// before its next pass; none once the process is exiting, as the thread then runs nothing +/// more, their command buffers staying `Committed`), the holds dropped (the last reference to a +/// command buffer may be among them, and with it its device, whose drop stops this thread). +/// False once the process is exiting. +fn round(shared: &SchedulerShared, left: &mut Left) -> bool { + let mut passed = Passed::default(); + (shared.inbox).pass(|state, commits| { + pass(state, commits, (&mut passed, &mut *left), shared, true); + !passed.exiting && left.is_empty() + }); + let Passed { + spent, + settled, + handlers, + exiting, + } = passed; + settle(settled); + if exiting { + drop(handlers); + } else { + run_submission_handlers(handlers); + } + drop(spent); + !exiting +} + +/// What passes let go of for their thread to finish without the lock ([`submit_ready`]'s +/// outputs), and whether the process is exiting. #[derive(Default)] struct Passed { spent: Spent, settled: Settled, - steps: Steps, - checks: Steps, handlers: Handlers, exiting: bool, } -impl Passed { - /// Whether the thread has work the passes found for it: a host step, a check, the exit. - fn for_thread(&self) -> bool { - self.exiting || !self.steps.is_empty() || !self.checks.is_empty() +/// What passes leave the scheduler's thread to run without the lock before the batches go: the +/// submission checks, then the host steps ([`submit_ready`]'s outputs). +#[derive(Default)] +struct Left { + steps: Steps, + checks: Steps, +} + +impl Left { + fn is_empty(&self) -> bool { + self.steps.is_empty() && self.checks.is_empty() } } /// A pass: take `commits` into the order, in commit order, then submit what is ready -/// ([`submit_ready`]) into `passed`. A pass on a thread other than the scheduler's (`own` false) -/// was the thread's but for what it runs without the lock: the thread looks again only for that, -/// or for the exit, and the caller wakes it (what woke it before, this pass saw). +/// ([`submit_ready`]) into `passed` and `left`. A pass on a thread other than the scheduler's +/// (`own` false) was the thread's but for what it leaves it: the thread looks again only for +/// that, or for the exit, for which this wakes it at once, under the lock (what woke it before, +/// this pass saw). fn pass( state: &mut State, commits: Vec, - passed: &mut Passed, - gated: &AtomicBool, + (passed, left): (&mut Passed, &mut Left), + shared: &SchedulerShared, own: bool, ) { for Committed { @@ -493,14 +515,15 @@ fn pass( let exiting = submit_ready( state, (&mut passed.spent, &mut passed.settled), - (&mut passed.steps, &mut passed.checks), + (&mut left.steps, &mut left.checks), &mut passed.handlers, - gated, + &shared.gated, ) .is_err(); passed.exiting |= exiting; - if !own { - state.dirty = passed.for_thread(); + if !own && (passed.exiting || !left.is_empty()) { + state.dirty = true; + shared.wake.notify_all(); } } @@ -682,7 +705,7 @@ fn run_submission_handlers(handlers: Handlers) { /// Batches for the thread to work on without its lock: each command buffer with the batch's /// index. -type Steps = Vec<(Hold, usize)>; +type Steps = VecDeque<(Hold, usize)>; /// Look at each line's head of a command buffer with a submission check that is otherwise /// ready (its binary semaphores' signals submitted, its events' values reached, its host step @@ -716,7 +739,7 @@ fn check_heads(state: &mut State, behind: &[u64], checks: &mut Steps, gated: &At } Some(_) => {} } - checks.push((held.buffer.hold(), held.index)); + checks.push_back((held.buffer.hold(), held.index)); } landing } @@ -753,7 +776,7 @@ fn gate_heads(state: &mut State, behind: &[u64], steps: &mut Steps, gated: &Atom continue; } if !waits.gpu { - steps.push((held.buffer.hold(), held.index)); + steps.push_back((held.buffer.hold(), held.index)); continue; } let gate = held.gate.get_or_insert_with(|| values.clone()); @@ -768,7 +791,7 @@ fn gate_heads(state: &mut State, behind: &[u64], steps: &mut Steps, gated: &Atom .zip(gate.iter()) .all(|(queue, &value)| queue.completed_value() >= value); if reached { - steps.push((held.buffer.hold(), held.index)); + steps.push_back((held.buffer.hold(), held.index)); } else { waiting = true; } diff --git a/crates/metal2vulkan-runtime/src/tests/inbox.rs b/crates/metal2vulkan-runtime/src/tests/inbox.rs index 797891d07..7dcbe2a06 100644 --- a/crates/metal2vulkan-runtime/src/tests/inbox.rs +++ b/crates/metal2vulkan-runtime/src/tests/inbox.rs @@ -1,7 +1,9 @@ //! `scheduler/inbox.rs`: a commit that finds a pass under way on another thread returns at once //! and its commit goes next, in commit order; one that finds the lock held for no pass passes -//! itself; and commits from many threads racing passes and short holds are all passed, each -//! thread's in its order, with no pass made for them at the end. +//! itself; the scheduler's pass looks again for a commit left to it until a pass answers it has +//! work of its own first; and commits from many threads racing passes, ones that stop looking +//! again, and short holds are all passed, each thread's in its order, with no pass made for them +//! at the end. use crate::device::lock; use crate::scheduler::inbox::Inbox; @@ -90,6 +92,53 @@ fn a_commit_finding_the_lock_held_for_no_pass_passes_itself() { assert!(!inbox.holds_commits()); } +#[test] +fn the_scheduler_s_pass_looks_again_until_a_pass_answers_it_has_work_first() { + for again in [true, false] { + let inbox = Arc::new(Log::new(Vec::new())); + let (entered, in_pass) = mpsc::channel(); + let (release, released) = mpsc::channel::<()>(); + let scheduler = { + let inbox = Arc::clone(&inbox); + thread::spawn(move || { + let mut passes = 0; + inbox.pass(|log, commits| { + take_in(log, commits); + passes += 1; + // The first pass stays under way until the test lets it end. + if passes == 1 { + entered.send(()).unwrap(); + released.recv_timeout(WAIT).unwrap(); + } + again + }); + passes + }) + }; + in_pass.recv_timeout(WAIT).unwrap(); + assert!(inbox.commit(1, take_in), "left to the pass under way"); + release.send(()).unwrap(); + let passes = scheduler.join().unwrap(); + if again { + // It looked again and took the commit in. + assert_eq!(passes, 2); + assert_eq!(*lock(inbox.state()), [1]); + assert!(!inbox.holds_commits()); + } else { + // It stopped: the commit waits for its own look. + assert_eq!(passes, 1); + assert!(lock(inbox.state()).is_empty()); + assert!(inbox.holds_commits()); + inbox.pass(|log, commits| { + take_in(log, commits); + true + }); + assert_eq!(*lock(inbox.state()), [1]); + assert!(!inbox.holds_commits()); + } + } +} + #[test] fn commits_racing_passes_and_short_holds_are_all_passed_each_thread_s_in_its_order() { const THREADS: u32 = 4; @@ -112,12 +161,17 @@ fn commits_racing_passes_and_short_holds_are_all_passed_each_thread_s_in_its_ord }) }) .collect(); - // The scheduler's thread: passes of its own. + // The scheduler's thread: passes of its own, every other one answering it has work first, + // which the thread's next pass follows, as its own look before it sleeps would; the last one + // looks again. let scheduler = { let inbox = Arc::clone(&inbox); thread::spawn(move || { - for _ in 0..COMMITS { - inbox.pass(slow); + for round in 0..COMMITS { + inbox.pass(|log, commits| { + slow(log, commits); + round % 2 == 0 || round + 1 == COMMITS + }); thread::yield_now(); } }) diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index d760717b4..88a07c3ab 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -43a04a0813c01a195ffce7622fa05ab95a3a3eec4b496a1ea73c3c19e32c6917 +eee78c1455ebb277a20369af1245c7bea94a52380f562edce1ef652f2da8ff83 diff --git a/crates/metal2vulkan-validation/src/runtime_lane.rs b/crates/metal2vulkan-validation/src/runtime_lane.rs index 45d47ee42..e16714c35 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane.rs @@ -180,6 +180,8 @@ mod command_render_states; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod commit_costs; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +mod commit_latency; +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod commit_work; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod compressed_blits; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/commit_latency.rs b/crates/metal2vulkan-validation/src/runtime_lane/commit_latency.rs new file mode 100644 index 000000000..c107fb2cc --- /dev/null +++ b/crates/metal2vulkan-validation/src/runtime_lane/commit_latency.rs @@ -0,0 +1,343 @@ +//! How long a checked command buffer waits from its commit to its submission under a consumer's +//! load, on the device the cfg selects, without the validation layer: report only, in release +//! builds. +//! +//! A consumer commits every command buffer with a submission check +//! (`CommandBuffer::set_submission_check`), so the device's scheduler thread runs each check and +//! submits each batch, and its host memory is hundreds of no-copy buffers, which every kernel +//! submission lists (`submit_costs`). The load: [`IMPORTS`] live host imports of +//! [`IMPORT_BYTES`] each, and frames of [`PER_FRAME`] command buffers committed at [`PER_MS`] a +//! millisecond, [`FRAMES`] frames a phase. Each command buffer is a blit fill of a buffer of its +//! committing thread's with a check that lets it run and a completed handler that notes the time; +//! at most [`FLIGHT`] of a thread's are in flight. The phases: +//! +//! - **One thread** (`one thread`): one committing thread. +//! - **Threads** (`threads`): [`THREADS`] committing threads at once, of queues of their own, each +//! at its share of the rate. +//! - **Waiting for the GPU** (`event waits`): one thread whose every other command buffer waits +//! for an event the one before it signals on another queue: the check waits until that signal +//! landed, so the completion thread's wakes release it. +//! +//! Printed as `COMMIT-LATENCY` lines, per phase: the commits a millisecond the threads kept; per +//! command buffer, the time from the host's clock just before `commit` to its `kernelStartTime` +//! (the scheduler began submitting it), its `kernelEndTime` (its `vkQueueSubmit` returned) and its +//! completed handler, as their 50th and 95th percentiles and their longest; and per frame, the CPU +//! time of the device's scheduler thread, of its completion thread, of the process and of the +//! committing threads (and their wall time in `commit`), the runtime's `vkQueueSubmit` calls +//! (`WorkCounts::queue_submissions`), the commits handed off to another thread's pass +//! (`WorkCounts::commits_handed_off`), and where the kernel-submission counter +//! (`scripts/i915-execbuffers/counter.c`) is preloaded, the kernel's submissions, the buffer +//! objects each lists and the host imports among them, and the time each spent in the ioctl. +//! +//! Ignored by default: a measurement, not a check. Run it by name with `--run-ignored all`. + +use super::commit_costs::{process_cpu_us, since}; +use super::submit_costs::{import, thread_cpu_us, Execbuffers}; +use super::{validated_device_with, Messages, ScratchCache, WAIT}; +use crate::gpu::TEST_DEVICE; +use metal2vulkan_runtime::{ + host_time, Buffer, CommandBuffer, CommandBufferStatus, CommandQueue, Device, EventRef, + ResourceOptions, Submission, SubmissionCheck, WorkCounts, +}; +use std::collections::VecDeque; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +/// The host imports live while the phases run. +const IMPORTS: usize = 400; +/// The bytes of each: a guest page. amdgpu's cost for each userptr object a command submission +/// lists was about the same for one page and for 64 (6.8 and 7.6 us per object, on a Radeon 780M, +/// Linux 7.2, a loaded host): it is per object. +const IMPORT_BYTES: usize = 4 << 10; +/// Command buffers committed a millisecond, of all the phase's threads. +const PER_MS: u32 = 6; +/// Command buffers a frame. +const PER_FRAME: usize = 96; +/// Frames a phase. +const FRAMES: usize = 30; +/// Committing threads at once in `threads`. +const THREADS: usize = 3; +/// A thread's command buffers in flight at most. +const FLIGHT: usize = 2 * PER_FRAME; +/// The linux name (15 bytes) of the device's scheduler thread. +const SCHEDULER: &str = "metal2vulkan-sc"; +/// The linux name (15 bytes) of the device's completion thread. +const COMPLETION: &str = "metal2vulkan-co"; + +/// A check that lets every submission run. +fn check() -> SubmissionCheck { + Arc::new(|_: &Submission<'_>| None) +} + +/// A checked command buffer of `queue` filling `buffer`'s first 4 KiB with `value`, not +/// committed. +fn checked(queue: &CommandQueue, buffer: &Buffer, value: u8) -> CommandBuffer { + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.fill_buffer(buffer, 0..4096, value).unwrap(); + blit.end_encoding().unwrap(); + command_buffer.set_submission_check(check()).unwrap(); + command_buffer +} + +/// A committed command buffer, the host time of its commit and the host time its completed +/// handler ran (the bits of an `f64`, 0 before). +struct Committed { + command_buffer: CommandBuffer, + at: f64, + completed: Arc, +} + +/// Commit `command_buffer`, with a completed handler that notes the time: the committed command +/// buffer. +fn commit(command_buffer: CommandBuffer) -> Committed { + let completed = Arc::new(AtomicU64::new(0)); + let noted = Arc::clone(&completed); + let handler = move |_: &CommandBuffer| noted.store(host_time().to_bits(), Ordering::Relaxed); + command_buffer + .add_completed_handler(Box::new(handler)) + .unwrap(); + let at = host_time(); + command_buffer.commit().unwrap(); + Committed { + command_buffer, + at, + completed, + } +} + +/// Wait for `committed` and require it completed. +fn completed(committed: &Committed) { + let command_buffer = &committed.command_buffer; + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); +} + +/// One committing thread's command buffers and its costs. +struct Thread { + committed: Vec, + /// The thread's CPU time, in microseconds. + cpu: f64, + /// The thread's wall time in `commit`, in microseconds. + in_commit: f64, + /// The thread's wall time, in microseconds. + wall: f64, +} + +/// Commit what `encode` makes of each of `units`, one unit every `pace`, with at most +/// [`FLIGHT`] command buffers in flight. +fn paced( + units: usize, + pace: Duration, + mut encode: impl FnMut(usize) -> Vec, +) -> Thread { + let mut flight = VecDeque::new(); + let mut done = Vec::new(); + let mut in_commit = 0.0; + let cpu = thread_cpu_us(); + let start = Instant::now(); + for unit in 0..units { + let due = start + pace * unit as u32; + if let Some(early) = due.checked_duration_since(Instant::now()) { + std::thread::sleep(early); + } + for command_buffer in encode(unit) { + let begin = Instant::now(); + flight.push_back(commit(command_buffer)); + in_commit += since(begin); + } + while flight.len() > FLIGHT { + let oldest = flight.pop_front().unwrap(); + completed(&oldest); + done.push(oldest); + } + } + for committed in flight { + completed(&committed); + done.push(committed); + } + Thread { + committed: done, + cpu: thread_cpu_us() - cpu, + in_commit, + wall: since(start), + } +} + +/// One committing thread of `count` command buffers at `per_ms` a millisecond. +fn committer(device: &Device, count: usize, per_ms: u32) -> Thread { + let queue = device.new_command_queue().unwrap(); + let buffer = device.new_buffer(4096, ResourceOptions::private()).unwrap(); + let pace = Duration::from_millis(1) / per_ms; + paced(count, pace, |at| vec![checked(&queue, &buffer, at as u8)]) +} + +/// One committing thread whose every other command buffer waits for the event the one before it +/// signals on another queue (the module docs). +fn event_waits(device: &Device) -> Thread { + let (signaling, waiting) = ( + device.new_command_queue().unwrap(), + device.new_command_queue().unwrap(), + ); + let event = device.new_shared_event().unwrap(); + let buffer = device + .new_buffer(1 << 20, ResourceOptions::private()) + .unwrap(); + let pace = Duration::from_millis(2) / PER_MS; + paced(FRAMES * PER_FRAME / 2, pace, |at| { + let value = at as u64 + 1; + let signal = checked(&signaling, &buffer, value as u8); + signal + .encode_signal_event(EventRef::from(&event), value) + .unwrap(); + let wait = waiting.command_buffer().unwrap(); + wait.encode_wait_for_event(EventRef::from(&event), value) + .unwrap(); + let mut blit = wait.blit_command_encoder().unwrap(); + blit.fill_buffer(&buffer, 4096..8192, !(value as u8)) + .unwrap(); + blit.end_encoding().unwrap(); + wait.set_submission_check(check()).unwrap(); + vec![signal, wait] + }) +} + +/// The CPU time so far of the process's threads named `name`, in microseconds (0 where Linux's +/// `/proc` is not). +fn named_cpu_us(name: &str) -> f64 { + let Ok(tasks) = std::fs::read_dir("/proc/self/task") else { + return 0.0; + }; + let named = |task: &std::fs::DirEntry| { + std::fs::read_to_string(task.path().join("comm")).is_ok_and(|comm| comm.trim_end() == name) + }; + let on_cpu_ns = |task: std::fs::DirEntry| { + let stat = std::fs::read_to_string(task.path().join("schedstat")).ok()?; + stat.split_whitespace().next()?.parse::().ok() + }; + let tasks = tasks.flatten().filter(named); + tasks.filter_map(on_cpu_ns).sum::() / 1e3 +} + +/// The 50th and 95th percentiles and the longest of `values`, in milliseconds. +fn spread(mut values: Vec) -> String { + values.sort_by(f64::total_cmp); + let at = |p: usize| values[(values.len() * p / 100).min(values.len() - 1)] * 1e3; + let longest = values.last().copied().unwrap_or(0.0) * 1e3; + format!("p50 {:.3} p95 {:.3} max {longest:.3} ms", at(50), at(95)) +} + +/// The counts and clocks at a phase's start. +struct Phase { + counts: WorkCounts, + execbuffers: Option, + process: f64, + scheduler: f64, + completion: f64, +} + +impl Phase { + fn start(device: &Device) -> Phase { + Phase { + counts: device.work_counts(), + execbuffers: Execbuffers::read(), + process: process_cpu_us(), + scheduler: named_cpu_us(SCHEDULER), + completion: named_cpu_us(COMPLETION), + } + } + + /// Print the phase's latencies and costs as `what` (the module docs). + fn print(&self, device: &Device, what: &str, threads: &[Thread]) { + let committed = || threads.iter().flat_map(|thread| &thread.committed); + let count = committed().count(); + let frames = count as f64 / PER_FRAME as f64; + let wall = threads.iter().map(|thread| thread.wall).fold(0.0, f64::max); + let latency = + |time: fn(&Committed) -> Option| spread(committed().filter_map(time).collect()); + eprintln!( + "COMMIT-LATENCY {}: {what}: {count} command buffers at {:.2} a ms; commit to \ + submitting {}; to submitted {}; to completed handler {}", + device.name(), + count as f64 / (wall / 1e3), + latency(|c| Some(c.command_buffer.kernel_start_time() - c.at)), + latency(|c| Some(c.command_buffer.kernel_end_time() - c.at)), + // A handler that has not run yet is left out. + latency(|c| { + let handled = f64::from_bits(c.completed.load(Ordering::Relaxed)); + (handled > 0.0).then_some(handled - c.at) + }), + ); + let after = device.work_counts(); + let per_frame = |after: u64, before: u64| (after - before) as f64 / frames; + let ms = |after: f64, before: f64| (after - before) / 1e3 / frames; + let threads_ms = |time: fn(&Thread) -> f64| threads.iter().map(time).sum::() / 1e3; + let kernel = Execbuffers::read() + .zip(self.execbuffers) + .map(|(after, before)| { + let submissions = after.execbuffers - before.execbuffers; + let each = |after: u64, before: u64| (after - before) as f64 / submissions as f64; + format!( + "; {:.1} kernel submissions, {:.0} objects each ({:.0} host imports), {:.1} us \ + each in the ioctl", + submissions as f64 / frames, + each(after.objects, before.objects), + each(after.userptr, before.userptr), + each(after.nanos, before.nanos) / 1e3, + ) + }) + .unwrap_or_default(); + eprintln!( + "COMMIT-LATENCY {}: {what}: a frame of {PER_FRAME}: scheduler thread cpu {:.2} ms, \ + completion thread {:.2} ms, process {:.2} ms, committing threads {:.2} ms ({:.2} ms \ + in commit); {:.1} vkQueueSubmit calls, {:.1} commits handed off{kernel}", + device.name(), + ms(named_cpu_us(SCHEDULER), self.scheduler), + ms(named_cpu_us(COMPLETION), self.completion), + ms(process_cpu_us(), self.process), + threads_ms(|thread| thread.cpu) / frames, + threads_ms(|thread| thread.in_commit) / frames, + per_frame(after.queue_submissions, self.counts.queue_submissions), + per_frame(after.commits_handed_off, self.counts.commits_handed_off), + ); + } +} + +/// The latencies, printed (the module docs). +#[test] +#[ignore = "a measurement, not a check: run by name with --run-ignored all"] +fn commit_latency() { + let cache = ScratchCache::new().unwrap(); + let messages = Messages::default(); + let device = validated_device_with(TEST_DEVICE, &messages, cache.path(), |options| { + options.layers.clear(); + // A consumer's device keeps no execution record. + options.record_executions = false; + }) + .unwrap(); + let imports: Vec = (0..IMPORTS) + .map(|_| import(&device, IMPORT_BYTES)) + .collect(); + // Warm: the fills' pipelines and the pools. + drop(committer(&device, PER_FRAME, PER_MS)); + let phase = Phase::start(&device); + let one = committer(&device, FRAMES * PER_FRAME, PER_MS); + phase.print(&device, "one thread", &[one]); + let phase = Phase::start(&device); + let (each, per_ms) = (FRAMES * PER_FRAME / THREADS, PER_MS / THREADS as u32); + let threads: Vec = std::thread::scope(|scope| { + let threads: Vec<_> = (0..THREADS) + .map(|_| scope.spawn(|| committer(&device, each, per_ms))) + .collect(); + (threads.into_iter()) + .map(|thread| thread.join().unwrap()) + .collect() + }); + phase.print(&device, "threads", &threads); + let phase = Phase::start(&device); + let waits = event_waits(&device); + phase.print(&device, "event waits", &[waits]); + assert_eq!(device.work_counts().host_imports_live, IMPORTS as u64); + drop(imports); +} diff --git a/crates/metal2vulkan-validation/src/runtime_lane/queue_order.rs b/crates/metal2vulkan-validation/src/runtime_lane/queue_order.rs index 936c78732..bff2b0b89 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/queue_order.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/queue_order.rs @@ -13,20 +13,22 @@ //! //! And within one queue, commits from two threads while one's submission waits for the `VkQueue` //! (the test holds it): the other's commits return at once, left to the submitting thread -//! (`scheduler/inbox.rs`), and every command buffer runs in commit order. +//! (`scheduler/inbox.rs`), and every command buffer runs in commit order. A checked command buffer +//! so left is checked and submitted by the scheduler's thread at once, not after the submitting +//! thread's submission handlers. use super::degrade_notices::{assert_made_once, on_device}; use super::indirect_host_steps::{expected, Setup, HOST_STEPS}; use super::shared_kinds; use super::{buffer_with, read_buffer, WAIT}; use metal2vulkan_runtime::{ - Buffer, CommandBuffer, CommandBufferStatus, CommandQueue, Device, ResourceOptions, Submission, - SubmissionCheck, + host_time, Buffer, CommandBuffer, CommandBufferStatus, CommandQueue, Device, ResourceOptions, + Submission, SubmissionCheck, }; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::mpsc; use std::sync::{Arc, Mutex}; -use std::time::Duration; +use std::time::{Duration, Instant}; /// The bytes A's fill writes. const FILLED: u8 = 0x5a; @@ -293,3 +295,102 @@ fn commits_made_while_another_thread_submits_return_at_once_and_run_in_commit_or } }); } + +/// A check that lets every submission run. +fn passes() -> SubmissionCheck { + Arc::new(|_: &Submission<'_>| None) +} + +/// How soon after the `VkQueue` is free the scheduler's thread submits the left command buffer, at +/// most: well under the 100 ms it sleeps for at a time. +const PROMPTLY: Duration = Duration::from_millis(40); + +/// A command buffer with a submission check, committed while another thread's commit submits +/// (the test holds the `VkQueue`), is left to that thread (`scheduler/inbox.rs`), whose pass +/// finds its check once the `VkQueue` is free: the scheduler's thread runs the check and submits +/// it at once, [`PROMPTLY`], while the other thread's submission handler still waits for it, and +/// not once that handler returned, nor when the scheduler's thread looks for work by itself. The +/// scheduler's thread is made to sleep afresh first (it checks and submits a command buffer), so +/// that it would look by itself only about 100 ms later. +#[test] +fn a_checked_command_buffer_left_to_another_thread_is_submitted_promptly() { + on_device(|device, _| { + let queue = device.new_command_queue().unwrap(); + let tracked = buffer_with(device, &[0; 4]).unwrap(); + let seen = buffer_with(device, &[0xff; 12]).unwrap(); + let first = numbered(&queue, &tracked, &seen, 1); + first.set_submission_check(passes()).unwrap(); + let submitting = numbered(&queue, &tracked, &seen, 2); + let left = numbered(&queue, &tracked, &seen, 3); + left.set_submission_check(passes()).unwrap(); + // The submitting thread's handler waits for the left command buffer's submission. + let waited = Arc::new(Mutex::new(None)); + let handler = { + let (left, waited) = (left.clone(), Arc::clone(&waited)); + move |_: &CommandBuffer| { + let until = Instant::now() + Duration::from_secs(1); + while left.kernel_end_time() == 0.0 && Instant::now() < until { + std::thread::sleep(Duration::from_micros(100)); + } + *waited.lock().unwrap() = Some(left.kernel_end_time() != 0.0); + } + }; + submitting + .add_submission_handler(Box::new(handler)) + .unwrap(); + // The scheduler's thread checks and submits it, then sleeps afresh, its pass over. + first.commit().unwrap(); + first.wait_until_scheduled().unwrap(); + std::thread::sleep(Duration::from_millis(5)); + let (held, holding) = mpsc::channel(); + let (release, released) = mpsc::channel::<()>(); + let holder = { + let queue = queue.clone(); + std::thread::spawn(move || { + // SAFETY: the closure keeps no handle and calls nothing of the runtime's; it waits + // only for this test's release. + unsafe { + queue.with_vk_queue(|_, _| { + held.send(()).unwrap(); + let _ = released.recv_timeout(WAIT); + }) + } + }) + }; + holding.recv_timeout(WAIT).unwrap(); + let handed_off = || device.work_counts().commits_handed_off; + let before = handed_off(); + let committer = { + let submitting = submitting.clone(); + std::thread::spawn(move || submitting.commit().unwrap()) + }; + // Its pass waits for the `VkQueue` under the scheduler's lock. + std::thread::sleep(Duration::from_millis(20)); + left.commit().unwrap(); + assert_eq!( + handed_off() - before, + 1, + "the checked command buffer was left to the submitting thread" + ); + let free = host_time(); + release.send(()).unwrap(); + holder.join().unwrap(); + committer.join().unwrap(); + completed(&[&first, &submitting, &left]); + let after = left.kernel_end_time() - free; + assert_eq!( + *waited.lock().unwrap(), + Some(true), + "submitted while the submitting thread's handler waited ({after:.4} s after the \ + VkQueue was free)" + ); + assert!( + after < PROMPTLY.as_secs_f64(), + "submitted {after:.4} s after the VkQueue was free, on {}", + device.name() + ); + // In commit order: each copied the number the one before it filled. + let ran = read_buffer(&seen, 0, 12).unwrap(); + assert_eq!(ran, [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2]); + }); +} diff --git a/crates/metal2vulkan-validation/src/runtime_lane/submit_costs.rs b/crates/metal2vulkan-validation/src/runtime_lane/submit_costs.rs index 2a9ef1cd9..41e479fcd 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/submit_costs.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/submit_costs.rs @@ -80,14 +80,19 @@ enum Kind { Fresh, } -/// The counts of the i915 counter (`scripts/i915-execbuffers/counter.c`), as it exports them. +/// The counts of the kernel-submission counter (`scripts/i915-execbuffers/counter.c`), as it +/// exports them. #[repr(C)] #[derive(Clone, Copy, Debug, Default)] -struct Execbuffers { - execbuffers: u64, - objects: u64, - nanos: u64, - userptr: u64, +pub(super) struct Execbuffers { + /// The kernel submissions: i915's execbuffers, amdgpu's command submissions. + pub(super) execbuffers: u64, + /// The buffer objects they listed. + pub(super) objects: u64, + /// The nanoseconds they spent in the ioctl. + pub(super) nanos: u64, + /// The listed objects that were host imports (userptrs). + pub(super) userptr: u64, prime: u64, block64: u64, created_other: u64, @@ -98,7 +103,7 @@ struct Execbuffers { impl Execbuffers { /// The counter's counts so far, where it is loaded. - fn read() -> Option { + pub(super) fn read() -> Option { // SAFETY: a lookup of a symbol by its name among the process's loaded objects. let found = unsafe { libc::dlsym(libc::RTLD_DEFAULT, c"m2v_i915_shim_counts".as_ptr()) }; if found.is_null() { @@ -132,7 +137,7 @@ impl Execbuffers { } /// The calling thread's CPU time so far, in microseconds. -fn thread_cpu_us() -> f64 { +pub(super) fn thread_cpu_us() -> f64 { let mut now = libc::timespec { tv_sec: 0, tv_nsec: 0, @@ -143,18 +148,18 @@ fn thread_cpu_us() -> f64 { now.tv_sec as f64 * 1e6 + now.tv_nsec as f64 / 1e3 } -/// A no-copy buffer over pages of its own, which its deallocator unmaps. -fn import(work: &Workload) -> Buffer { - let pages = Mapping::anonymous(IMPORT_BYTES); +/// A no-copy buffer of `device` over `bytes` of pages of its own, which its deallocator unmaps. +pub(super) fn import(device: &Device, bytes: usize) -> Buffer { + let pages = Mapping::anonymous(bytes); pages.fill(0x5a); let pointer = pages.pointer(); // SAFETY: the pages are this process's, mapped read and write, and unmapped only by the // deallocator, once the runtime let go of them. unsafe { no_copy( - &work.device, + device, pointer, - IMPORT_BYTES, + bytes, ResourceOptions::shared(), Some(Box::new(move |_, _| drop(pages))), ) @@ -208,7 +213,7 @@ impl Lane { fn churn_imports(&mut self, frame: usize) { for at in 0..IMPORTS_A_FRAME { let at = (frame * IMPORTS_A_FRAME + at) % IMPORTS; - self.imports[at] = import(&self.work); + self.imports[at] = import(&self.work.device, IMPORT_BYTES); } } } @@ -337,7 +342,7 @@ fn handed_off(lane: &Lane) -> u64 { /// Keep the device's scheduler thread busy until `stop` (the module docs): the batches it had /// it submit. -fn side_load(device: &Device, stop: &AtomicBool) -> u64 { +pub(super) fn side_load(device: &Device, stop: &AtomicBool) -> u64 { let queue = device.new_command_queue().unwrap(); let event = device.new_shared_event().unwrap(); let target = device.new_buffer(4096, ResourceOptions::private()).unwrap(); @@ -380,7 +385,9 @@ fn submit_costs() { }) .unwrap(); let work = Workload::new(device); - let imports = (0..IMPORTS).map(|_| import(&work)).collect(); + let imports = (0..IMPORTS) + .map(|_| import(&work.device, IMPORT_BYTES)) + .collect(); let mut lane = Lane { work, imports, diff --git a/scripts/i915-execbuffers/counter.c b/scripts/i915-execbuffers/counter.c index 63dba0cd4..da7d76801 100644 --- a/scripts/i915-execbuffers/counter.c +++ b/scripts/i915-execbuffers/counter.c @@ -1,17 +1,19 @@ -// A counter of the i915 kernel submissions a process makes, loaded with LD_PRELOAD: each -// DRM_IOCTL_I915_GEM_EXECBUFFER2, the buffer objects it lists (by how each was made: created with -// its size, a userptr import, a dma-buf import) and the time the ioctl took, by thread. It reads -// the ioctls' arguments and results and changes nothing. ANV on i915 lists every VkDeviceMemory -// of the device, and its own buffer objects, in every execbuffer (Mesa 26.2.4, -// src/intel/vulkan/i915/anv_batch_chain.c, setup_execbuf_for_cmd_buffers), and the kernel's cost -// of each is per object. +// A counter of the kernel submissions a process makes on i915 and amdgpu, loaded with LD_PRELOAD: +// each DRM_IOCTL_I915_GEM_EXECBUFFER2 and DRM_IOCTL_AMDGPU_CS, the buffer objects it lists (by how +// each was made: created with its size, a userptr import, a dma-buf import) and the time the ioctl +// took, by thread. It reads the ioctls' arguments and results and changes nothing. ANV on i915 +// lists every VkDeviceMemory of the device, and its own buffer objects, in every execbuffer (Mesa +// 26.2.4, src/intel/vulkan/i915/anv_batch_chain.c, setup_execbuf_for_cmd_buffers), RADV on amdgpu +// in every command submission's BO list (src/amd/vulkan/winsys/amdgpu), and the kernel's cost of +// each is per object. // // gcc -O2 -Wall -shared -fPIC -o counter.so counter.c // LD_PRELOAD=$PWD/counter.so M2V_I915_SHIM_OUT=counts.txt // // At exit it appends its totals, the objects' origins and sizes, and the execbuffers per thread to -// M2V_I915_SHIM_OUT (stderr without it). A program reads the totals so far through the exported -// m2v_i915_shim_counts (the validation lane runtime_lane::submit_costs does). +// M2V_I915_SHIM_OUT (stderr without it); "execbuffers" counts amdgpu's command submissions too. A +// program reads the totals so far through the exported m2v_i915_shim_counts (the validation lanes +// runtime_lane::submit_costs and runtime_lane::commit_latency do). #define _GNU_SOURCE #include #include @@ -25,6 +27,7 @@ #include #include #include +#include enum origin { O_NONE = 0, O_CREATE, O_CREATE_EXT, O_USERPTR, O_PRIME, O_COUNT }; static const char *origin_names[] = {"unknown", "create", "create_ext", "userptr", "prime"}; @@ -57,6 +60,28 @@ static int ntids; static pthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER; static int (*real_ioctl)(int, unsigned long, ...); +// Each file descriptor's kernel driver, by DRM_IOCTL_VERSION, so one driver's ioctl numbers are +// not read as another's. +enum driver { D_UNKNOWN = 0, D_OTHER, D_I915, D_AMDGPU }; +#define MAX_DRIVER_FDS 1024 +static uint8_t drivers[MAX_DRIVER_FDS]; + +static enum driver driver_of(int fd) { + if (fd < 0 || fd >= MAX_DRIVER_FDS) return D_OTHER; + if (drivers[fd] != D_UNKNOWN) return (enum driver)drivers[fd]; + char name[32] = {0}; + struct drm_version v = {0}; + v.name = name; + v.name_len = sizeof name - 1; + enum driver d = D_OTHER; + if (real_ioctl(fd, DRM_IOCTL_VERSION, &v) == 0) { + if (strcmp(name, "i915") == 0) d = D_I915; + else if (strcmp(name, "amdgpu") == 0) d = D_AMDGPU; + } + drivers[fd] = d; + return d; +} + static struct bo *table_for(int fd, int make) { for (int i = 0; i < nfds; i++) if (fds[i] == fd) return tables[i]; @@ -91,30 +116,20 @@ void m2v_i915_shim_counts(struct m2v_shim_counts *out) { pthread_mutex_unlock(&mu); } -int ioctl(int fd, unsigned long request, ...) { - va_list ap; - va_start(ap, request); - void *arg = va_arg(ap, void *); - va_end(ap); - if (!real_ioctl) real_ioctl = (int (*)(int, unsigned long, ...))dlsym(RTLD_NEXT, "ioctl"); - if (request == DRM_IOCTL_I915_GEM_EXECBUFFER2 || request == DRM_IOCTL_I915_GEM_EXECBUFFER2_WR) { - struct drm_i915_gem_execbuffer2 *eb = arg; - uint64_t t0 = now_ns(); - int r = real_ioctl(fd, request, arg); - uint64_t dt = now_ns() - t0; +// One kernel submission of `n` objects, the handle of object i at `handles + i * stride`, that +// took `dt` nanoseconds; under `mu`. +static void count_submission(int fd, uint32_t n, const uint8_t *handles, size_t stride, uint64_t dt) { pid_t tid = (pid_t)syscall(SYS_gettid); - pthread_mutex_lock(&mu); struct bo *t = table_for(fd, 1); - uint32_t n = eb->buffer_count; counts.execbuffers++; counts.objects += n; counts.nanos += dt; if (n > counts.max_objects) counts.max_objects = n; if (n < counts.min_objects) counts.min_objects = n; per_eb[n < 2047 ? n : 2047]++; - struct drm_i915_gem_exec_object2 *objs = (void *)(uintptr_t)eb->buffers_ptr; for (uint32_t i = 0; i < n; i++) { - uint32_t h = objs[i].handle; + uint32_t h; + memcpy(&h, handles + (size_t)i * stride, sizeof h); struct bo b = (t && h < MAX_HANDLES) ? t[h] : (struct bo){0, O_NONE}; switch (b.origin) { case O_USERPTR: counts.userptr++; break; @@ -137,6 +152,91 @@ int ioctl(int fd, unsigned long request, ...) { if (f) { if (fgets(tids[ntids].comm, sizeof tids[ntids].comm, f)) tids[ntids].comm[strcspn(tids[ntids].comm, "\n")] = 0; fclose(f); } ntids++; } +} + +// The objects of an amdgpu command submission: its BO handles chunk's entries. +static void count_cs(int fd, union drm_amdgpu_cs *cs, uint64_t dt) { + const uint64_t *chunks = (const uint64_t *)(uintptr_t)cs->in.chunks; + uint32_t n = 0; + const uint8_t *entries = NULL; + size_t stride = sizeof(struct drm_amdgpu_bo_list_entry); + for (uint32_t i = 0; i < cs->in.num_chunks; i++) { + const struct drm_amdgpu_cs_chunk *chunk = (const void *)(uintptr_t)chunks[i]; + if (chunk->chunk_id != AMDGPU_CHUNK_ID_BO_HANDLES) continue; + const struct drm_amdgpu_bo_list_in *list = (const void *)(uintptr_t)chunk->chunk_data; + n = list->bo_number; + stride = list->bo_info_size; + entries = (const uint8_t *)(uintptr_t)list->bo_info_ptr; + } + count_submission(fd, entries ? n : 0, entries, stride, dt); +} + +// An amdgpu file's ioctl: its command submissions counted, its buffers' origins noted. +static int amdgpu_ioctl(int fd, unsigned long request, void *arg) { + if (request == DRM_IOCTL_AMDGPU_CS) { + // The result overwrites the argument's first words; the chunks stay. + union drm_amdgpu_cs copy = *(union drm_amdgpu_cs *)arg; + uint64_t t0 = now_ns(); + int r = real_ioctl(fd, request, arg); + uint64_t dt = now_ns() - t0; + pthread_mutex_lock(&mu); + count_cs(fd, ©, dt); + pthread_mutex_unlock(&mu); + return r; + } + // A buffer's size is in the argument the result overwrites. + uint64_t size = 0; + if (request == DRM_IOCTL_AMDGPU_GEM_CREATE) + size = ((union drm_amdgpu_gem_create *)arg)->in.bo_size; + int r = real_ioctl(fd, request, arg); + if (r != 0) return r; + if (request == DRM_IOCTL_AMDGPU_GEM_CREATE) + note(fd, ((union drm_amdgpu_gem_create *)arg)->out.handle, size, O_CREATE); + if (request == DRM_IOCTL_AMDGPU_GEM_USERPTR) { + struct drm_amdgpu_gem_userptr *u = arg; + note(fd, u->handle, u->size, O_USERPTR); + } + return r; +} + +int ioctl(int fd, unsigned long request, ...) { + va_list ap; + va_start(ap, request); + void *arg = va_arg(ap, void *); + va_end(ap); + if (!real_ioctl) real_ioctl = (int (*)(int, unsigned long, ...))dlsym(RTLD_NEXT, "ioctl"); + // Only a DRM driver's own ioctls, of a DRM device's file. + if (_IOC_TYPE(request) != DRM_IOCTL_BASE) return real_ioctl(fd, request, arg); + if (request == DRM_IOCTL_GEM_CLOSE) { + int r = real_ioctl(fd, request, arg); + if (r == 0) { + struct drm_gem_close *c = arg; + pthread_mutex_lock(&mu); + struct bo *t = table_for(fd, 0); + if (t && c->handle < MAX_HANDLES) t[c->handle] = (struct bo){0, O_NONE}; + pthread_mutex_unlock(&mu); + } + return r; + } + if (request == DRM_IOCTL_PRIME_FD_TO_HANDLE) { + int r = real_ioctl(fd, request, arg); + if (r == 0) { + struct drm_prime_handle *p = arg; + note(fd, p->handle, 0, O_PRIME); + } + return r; + } + enum driver driver = driver_of(fd); + if (driver == D_AMDGPU) return amdgpu_ioctl(fd, request, arg); + if (driver != D_I915) return real_ioctl(fd, request, arg); + if (request == DRM_IOCTL_I915_GEM_EXECBUFFER2 || request == DRM_IOCTL_I915_GEM_EXECBUFFER2_WR) { + struct drm_i915_gem_execbuffer2 *eb = arg; + uint64_t t0 = now_ns(); + int r = real_ioctl(fd, request, arg); + uint64_t dt = now_ns() - t0; + pthread_mutex_lock(&mu); + count_submission(fd, eb->buffer_count, (const uint8_t *)(uintptr_t)eb->buffers_ptr, + sizeof(struct drm_i915_gem_exec_object2), dt); pthread_mutex_unlock(&mu); return r; } @@ -158,19 +258,6 @@ int ioctl(int fd, unsigned long request, ...) { note(fd, u->handle, u->user_size, O_USERPTR); break; } - case DRM_IOCTL_PRIME_FD_TO_HANDLE: { - struct drm_prime_handle *p = arg; - note(fd, p->handle, 0, O_PRIME); - break; - } - case DRM_IOCTL_GEM_CLOSE: { - struct drm_gem_close *c = arg; - pthread_mutex_lock(&mu); - struct bo *t = table_for(fd, 0); - if (t && c->handle < MAX_HANDLES) t[c->handle] = (struct bo){0, O_NONE}; - pthread_mutex_unlock(&mu); - break; - } } return r; }