From d6152c3247c0e1e9ea7c190252dc6b02a2fb6fcf Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 16 Nov 2026 08:48:53 -0800 Subject: [PATCH] RUNTIME 2461: Scheduler: a pass at commit asks whether a batch's host step is due, not whether it holds segments What: scheduler::plain(), which decides what the pass of a committing thread (commit_and_submit) and of a thread about to block may submit, left every batch that holds segments to the scheduler's thread as a host step (LeftAtCommit::HostStep). It now asks the command buffer whether a step is due (needs_host_step), as the thread's own look does (holds_back, check_heads, gate_heads, place_of). Why: BatchSync::segments is a gate alone: since a730cf1e96 it is also true for every batch one of whose encoders kept its log for a rebind, which an encoder does whenever a command of it names a no-copy buffer over host pages (replay.rs). A guest on a host of unified memory keeps all its memory in place as such buffers, so on the Radeon 780M every one of the consumer's batches was left to the scheduler's thread: its passes at commit ran (about 7.5k a window) and submitted none, where on the RX 7900 XTX, whose guest resources lie in VRAM, they submitted about 4k a window. An unshared head so left made the committing pass leave every other queue's batch on its VkQueue too (first_for_the_thread). The thread's own pass submitted those batches with no step, after a wake and a pass. A head whose step was recorded now goes from such a pass too. How they meet the joined completions (RUNTIME 2459): the segments test comes first in plain(), the group test after it. A batch of a command buffer marked to join the next, naming host pages, now reaches that group test as any marked batch does: a committing thread sends it alone where its VkQueue runs at most one earlier submission (goes_alone_at_commit) and leaves it to the scheduler's thread to hold in the group otherwise; a waiting thread leaves it. No pass of a thread other than the scheduler's runs while the group holds a batch, so none closes a group. Docs: plain_ready's first condition; first_for_the_thread and unshared_hold.rs (Passes of other threads) no longer name a recorded host step among what such a pass leaves. Tests: commit_and_submit::a_command_buffer_naming_host_pages_is_submitted_at_its_commit, now in a plain leg (a Private buffer) and a host-pages leg, 200 rounds each, printing the share at commit and commit -> submission returned p50/p99; at the parent it failed on lavapipe with 40 of 40 left for a host step (m3-max-36852). queue_share_device's committing-pass test is renamed a_committing_thread_s_pass_sends_an_unshared_head_with_its_step_recorded_first: under Exact the committing pass now submits both command buffers, the unshared head first. Verified: in the jobs named in the lane's report. With it, the check and the bench legs (folded): commit_and_submit: a command buffer naming host pages is submitted at its commit What: a device test that fills a no-copy buffer over host pages with commit_and_submit, 40 rounds on an idle device, and asserts every encoder kept its log for a rebind (replay_logs_kept, so each batch holds segments), no host step was recorded, no pass at commit left a batch for a host step (scheduler_at_commit_left_host_steps) and at least half the batches went at commit. Why: scheduler::plain() leaves any batch that holds segments to the scheduler's thread as a host step, though segments are a gate alone and an encoder that names a buffer over host pages holds them with no step due. A guest's command buffers on a host of unified memory all name its memory so, and the 780M's passes at commit submitted none of them. Verified: run in the job named in the lane's report; it fails at this commit, before the fix. completion_latency: a guest-shaped leg naming host pages, and why passes at commit left their command buffers What: guest_shaped_completion_latency gains a HostPages leg: as Plain, each command buffer's blit also fills 64 KiB of a no-copy buffer over host pages of its queue's own, as a guest's command buffers name its memory over the guest's pages on a host of unified memory. Every leg now prints a second line: the passes and batches at commit a frame, why those passes left their command buffers to the scheduler's thread (WorkCounts::scheduler_at_commit_left_*), the host steps recorded, the batches waiting threads submitted, the device's unified memory, its VkQueues, the VkQueue each queue is on and which of them hold other queues' work back for the unshared compositor. Why: on the 780M a consumer's guest commits every command buffer with commit_and_submit, its passes at commit run, and they submit nothing, where on the RX 7900 XTX they submit about 4k batches a window. This leg puts the 780M guest's memory shape beside the plain one on the same device, so one run on each GPU shows which condition leaves the batches. Verified: built and run in the jobs named in the lane's report (a measurement, ignored by default). completion_latency: the guest-shaped bench times each commit call to its submission's return What: each leg's at-commit line now opens with the time from each command buffer's commit_and_submit call to the return of the driver's submission of its batch (p50, p99, max, whichever thread submitted it), and counts the encoders' logs kept for a rebind a frame. Why: the fix for batches over host pages left at commit is judged by that time on the 780M, before and after, beside the share of batches submitted at commit. Verified: in the build and bench jobs named in the lane's report. Verified: m3-max-36888 (msi) at 3fbf10d3e1: clippy -p metal2vulkan-runtime --all-targets --all-features 0; lavapipe scheduler|commit_and_submit|queue_share_device|joined_completions|grouped_submissions 84/84. At the parent (m3-max-36852) 40 commit_and_submit fills of a no-copy buffer gave 0 batches at commit, all left for a host step with none recorded; at the fix 200/200 at commit (commit to submission returned p50 97.9 us, p99 104.1). The PHOENIX before/after, clippy --cfg m2v_gpu and m2v_cpu_icd and rustdoc run after the merge. --- .../metal2vulkan-runtime/src/scheduler/mod.rs | 13 +- .../src/tests/commit_and_submit.rs | 98 +++++++- .../src/tests/completion_latency.rs | 236 +++++++++++++----- .../src/tests/queue_share_device.rs | 42 ++-- .../metal2vulkan-runtime/src/unshared_hold.rs | 2 +- crates/metal2vulkan/src/cache/mod.rs | 2 +- 6 files changed, 308 insertions(+), 85 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/scheduler/mod.rs b/crates/metal2vulkan-runtime/src/scheduler/mod.rs index 42a8633af..a23e32393 100644 --- a/crates/metal2vulkan-runtime/src/scheduler/mod.rs +++ b/crates/metal2vulkan-runtime/src/scheduler/mod.rs @@ -2641,8 +2641,8 @@ fn submit_plain_ready( /// the scheduler's thread's own look would send first ([`goes_first`]), or hold another queue's /// batch behind ([`on_its_way`]): nothing holds it back from that look ([`holds_back`]) and every /// event value it waits for is reached, though the pass of a thread other than the scheduler's -/// leaves it (its submission or scheduled handlers for a thread about to block, its host step -/// recorded, a switch of storage forms riding on it); or it is on its way (its host step or +/// leaves it (its submission or scheduled handlers for a thread about to block, a switch of +/// storage forms riding on it); or it is on its way (its host step or /// checks to come, a submitted signal to land). Whether it waits behind an earlier commit that /// thread's look asks. fn first_for_the_thread( @@ -2870,7 +2870,9 @@ pub(crate) enum Hand { /// read, and every event value it waits for reached by a submitted signal or by the host. And /// neither the thread nor the program has anything to do for it: /// -/// - no segments, so no host step the thread records, and none in its [`Left`] work; +/// - no host step due (`CommandBufferShared::needs_host_step`), so none the thread records, and +/// none in its [`Left`] work: a batch that holds segments with none due (an encoder that kept +/// its log for a rebind, a step recorded) goes, as from the thread's own look; /// - no submission check left to run, which runs the program's code on the thread that runs it /// (a committing thread runs the checks of a head left itself first, where /// [`claim_check`] takes them); @@ -2906,7 +2908,10 @@ fn plain( untracked_decodes: usize, passer: Passer, ) -> Result<(), LeftAtCommit> { - if held.segments { + // Segments are a gate alone (`BatchSync::segments`): a batch whose encoder kept its log for a + // rebind (it named a buffer over host pages, `replay.rs`) holds them with no step due, and one + // whose step was recorded needs none, as the thread's own look asks ([`holds_back`]). + if held.segments && held.buffer.needs_host_step(held.index) { return Err(LeftAtCommit::HostStep); } if !binary.ready(&held.binary_needs) { diff --git a/crates/metal2vulkan-runtime/src/tests/commit_and_submit.rs b/crates/metal2vulkan-runtime/src/tests/commit_and_submit.rs index a054a8dfe..0f5099dd3 100644 --- a/crates/metal2vulkan-runtime/src/tests/commit_and_submit.rs +++ b/crates/metal2vulkan-runtime/src/tests/commit_and_submit.rs @@ -8,7 +8,9 @@ //! thread too, just before it submits it (`WorkCounts::batches_checked_at_commit`): a check that //! answers a code fails its submission as on the scheduler's thread, and checks keep commit order //! whichever thread runs them. A head another queue holds for its check holds back only the -//! commits that wait behind it: one of a third queue is checked and submitted at its commit. +//! commits that wait behind it: one of a third queue is checked and submitted at its commit. A +//! command buffer naming a no-copy buffer over host pages, whose encoder keeps its log for a +//! rebind, needs no host step and is submitted at its commit too. //! //! Device tests: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, //! `m2v_cpu_icd`), on the kind of device the cfg selects. @@ -748,3 +750,97 @@ fn a_head_held_for_its_check_holds_back_only_the_commits_behind_it() { "C alone checked and submitted at commit" ); } + +/// The bytes of host pages the no-copy buffer of +/// [`a_command_buffer_naming_host_pages_is_submitted_at_its_commit`] lies over. +const PAGES: usize = 64 << 10; + +/// The command buffers each leg of +/// [`a_command_buffer_naming_host_pages_is_submitted_at_its_commit`] commits and waits for, one +/// at a time. +const PAGE_ROUNDS: u64 = 200; + +/// Host pages a no-copy buffer lies over, released once they go: made before the device, so they +/// outlive every buffer over them. +struct Pages(std::ptr::NonNull); + +impl Drop for Pages { + fn drop(&mut self) { + super::host_os::release(self.0, PAGES); + } +} + +/// A command buffer whose blit fills a no-copy buffer over host pages keeps its encoder's log for +/// a rebind (`replay.rs`), so its batch holds segments, though no host step is due for it: on an +/// idle device, `commit_and_submit` submits it on the committing thread, as it submits one that +/// fills a `Private` buffer (the plain leg), and no host step is recorded. Counted, in each leg: +/// a batch at commit for each, and none left for a host step +/// (`WorkCounts::scheduler_at_commit_left_host_steps`); before the committing thread asked whether +/// a step was due, every one of the host pages' leg was left so. Each leg prints its share of +/// batches at commit and the time from each commit call to its submission's return. +#[test] +fn a_command_buffer_naming_host_pages_is_submitted_at_its_commit() { + let pages = Pages(super::host_os::private(PAGES)); + let device = device(); + device.shared().timing.note_queue_times(); + let queue = device.new_command_queue().unwrap(); + // SAFETY: the pages, read and write, outlive every buffer over them (made before the device). + let memory = unsafe { crate::HostMemory::new(pages.0) }; + let shared = ResourceOptions::shared(); + // SAFETY: `memory` is `PAGES` bytes of fresh pages. + let over_pages = + unsafe { device.new_buffer_with_bytes_no_copy(memory, PAGES as u64, shared, None) } + .unwrap(); + let private = (device.new_buffer(PAGES as u64, ResourceOptions::private())).unwrap(); + for (leg, target, host_pages) in [ + ("plain", &private, false), + ("host pages", &over_pages, true), + ] { + let before = device.work_counts(); + let mut to_submission = Vec::new(); + for round in 0..PAGE_ROUNDS { + let command_buffer = fill(&queue, target, round as u8); + let committed = crate::gpu_time::host_nanos(); + command_buffer.commit_and_submit().unwrap(); + command_buffer.wait_until_completed().unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + if host_pages { + assert_eq!(first_byte(target), round as u8, "{leg}: round {round}"); + } + let returned = command_buffer.submit_returned_time() * 1e9; + to_submission.push((returned - committed as f64) / 1e3); + } + let after = device.work_counts(); + let moved = |count: fn(&crate::WorkCounts) -> u64| count(&after) - count(&before); + let logs = moved(|c| c.replay_logs_kept); + let batches = moved(|c| c.batches_submitted_at_commit); + let left = moved(|c| c.scheduler_at_commit_left_host_steps); + let steps = moved(|c| c.host_steps_recorded); + to_submission.sort_by(f64::total_cmp); + let at = |p: usize| to_submission[(to_submission.len() * p).div_ceil(100) - 1]; + println!( + "{leg} ({}): batches at commit {batches} of {PAGE_ROUNDS}; commit -> its submission \ + returned, us: p50 {:.1} p99 {:.1} max {:.1}; logs kept {logs}, left for a host step \ + {left}, host steps recorded {steps}", + device.name(), + at(50), + at(99), + at(100), + ); + assert!( + !host_pages || logs >= PAGE_ROUNDS, + "{leg}: an encoder kept no log, so the batches held no segments" + ); + assert_eq!(steps, 0, "{leg}: a host step was recorded"); + assert_eq!( + left, 0, + "{leg}: a pass at commit left a batch for a host step none was due for" + ); + // A pass of the scheduler's thread under way at the commit (a completion's nudge) takes it + // in instead: rarely, on an idle device. + assert!( + batches >= PAGE_ROUNDS / 2, + "{leg}: {batches} of {PAGE_ROUNDS} batches at commit" + ); + } +} diff --git a/crates/metal2vulkan-runtime/src/tests/completion_latency.rs b/crates/metal2vulkan-runtime/src/tests/completion_latency.rs index e1f14eac3..498200143 100644 --- a/crates/metal2vulkan-runtime/src/tests/completion_latency.rs +++ b/crates/metal2vulkan-runtime/src/tests/completion_latency.rs @@ -54,8 +54,10 @@ //! `CompletionPolicy::Exact`, three queues committing a guest's command buffers each frame from //! their own threads and an unshared compositor queue after them, at a guest's present rate, //! each command buffer with a completion-seen and a completed handler; plain, with submission -//! handlers, and with them and a stand-in for a slow driver's submission. From the GPU end to -//! the queue waiter's wait returned, the completion seen and each handler. +//! handlers, with them and a stand-in for a slow driver's submission, and plain with each +//! command buffer naming a no-copy buffer over host pages. From the GPU end to the queue +//! waiter's wait returned, the completion seen and each handler; and why the passes at commit +//! left command buffers to the scheduler's thread. //! //! Each line also counts the waits entered after the GPU end: there, the time to the wait's return //! holds the wake of the thread that waits, not the driver's wake alone. @@ -1434,6 +1436,27 @@ enum GuestLeg { SubmissionHandlers, /// And the stand-in submission cost ([`GUEST_SUBMIT_COST`]). SubmitCost, + /// As [`Plain`](Self::Plain), each command buffer's blit also filling [`GUEST_PAGE`] bytes of + /// a no-copy buffer over host pages of its queue's own, as a guest's command buffers name its + /// memory over the guest's pages on a host of unified memory: its encoder keeps its log for a + /// rebind (`replay.rs`), so its batch holds segments and needs no host step. + HostPages, +} + +/// The bytes of host pages each queue's no-copy buffer of [`GuestLeg::HostPages`] lies over, and +/// that each of its command buffers fills. +const GUEST_PAGE: usize = 64 << 10; + +/// The host pages of [`GuestLeg::HostPages`]'s no-copy buffers, [`GUEST_PAGE`] bytes each, +/// released once they go: made before the device, so they outlive every buffer over them. +struct GuestPages(Vec>); + +impl Drop for GuestPages { + fn drop(&mut self) { + for &start in &self.0 { + super::host_os::release(start, GUEST_PAGE); + } + } } /// One command buffer of the measurement once it completed: host nanoseconds of its GPU end, of @@ -1446,6 +1469,8 @@ struct GuestSeen { seen: u64, seen_handler: u64, completed_handler: u64, + /// The host nanoseconds just before its `commit_and_submit` call. + committed: u64, /// The return of the driver's submission that carried its last batch /// (`CommandBuffer::submit_returned_time`), and the start of its submission handler (0 in a /// leg without one). @@ -1471,11 +1496,16 @@ fn tail(mut values: Vec) -> String { /// [`GUEST_RUNS`] and an unshared compositor queue [`GUEST_COMPOSITOR`], every one with /// `commit_and_submit`, a completion-seen handler (where the consumer answers its guest) and a /// completed handler; legs adding the guest's submission handlers, then the stand-in submission -/// cost. Each prints a `COMPLETION-LATENCY guest-shaped` line: from each command buffer's GPU end -/// to the return of its queue waiter's wait (the latest before its completion was seen; negative -/// where the waiter's read after an earlier wait found it), to its completion seen (the turn's -/// time), to its completion-seen handler, and to its completed handler, in microseconds, with the -/// scheduler's passes and submissions at commit a frame. A leg with submission handlers prints a +/// cost, and one naming a no-copy buffer over host pages in each command buffer. Each prints a +/// `COMPLETION-LATENCY guest-shaped` line: from each command buffer's GPU end to the return of its +/// queue waiter's wait (the latest before its completion was seen; negative where the waiter's read +/// after an earlier wait found it), to its completion seen (the turn's time), to its +/// completion-seen handler, and to its completed handler, in microseconds, with the scheduler's +/// passes and submissions at commit a frame; then a line from each command buffer's commit call +/// to its submission's return, and why those passes left command buffers to the scheduler's +/// thread (`WorkCounts::scheduler_at_commit_left_*`, a frame) with the host steps recorded, the +/// encoders' logs kept for a rebind, the device's memory and its `VkQueue`s, which of them each queue is on, and +/// which hold other queues' work back for the compositor. A leg with submission handlers prints a /// second line: from each command buffer's own submission's return to its submission handler's /// start, and how many were seen complete before that handler started (their completion-seen /// handler waits for it). A measurement, not a check: run by name with `--run-ignored all`, in a @@ -1487,6 +1517,7 @@ fn guest_shaped_completion_latency() { GuestLeg::Plain, GuestLeg::SubmissionHandlers, GuestLeg::SubmitCost, + GuestLeg::HostPages, ] { guest_leg(leg); } @@ -1497,6 +1528,13 @@ fn guest_leg(leg: GuestLeg) { let scratch = Scratch(std::env::temp_dir().join(format!("m2v-guest-latency-{}", std::process::id()))); std::fs::create_dir_all(&scratch.0).unwrap(); + let host_pages = matches!(leg, GuestLeg::HostPages); + let pages = GuestPages(match host_pages { + true => (0..=GUEST_RUNS.len()) + .map(|_| super::host_os::private(GUEST_PAGE)) + .collect(), + false => Vec::new(), + }); // The device's own queue plan: four queues, as many `VkQueue`s as it spares for them. let mut options = DeviceOptions { kinds: kinds(), @@ -1553,62 +1591,89 @@ fn guest_leg(leg: GuestLeg) { device.new_buffer(most, ResourceOptions::private()).unwrap() }) .collect(); + // Each queue's no-copy buffer over its host pages, where the leg names them. + let page_buffers: Vec = (pages.0.iter()) + .map(|&start| { + // SAFETY: the pages, read and write, outlive every buffer over them (made before the + // device). + let memory = unsafe { crate::HostMemory::new(start) }; + // SAFETY: `memory` is `GUEST_PAGE` bytes of fresh pages. + unsafe { + device.new_buffer_with_bytes_no_copy( + memory, + GUEST_PAGE as u64, + ResourceOptions::shared(), + None, + ) + } + .unwrap() + }) + .collect(); let seen: Arc>> = Arc::default(); let done = Arc::new(std::sync::atomic::AtomicUsize::new(0)); let a_frame: usize = runs.iter().map(|runs| runs.len()).sum(); - let handlers = !matches!(leg, GuestLeg::Plain); - let commit = - |queue: &CommandQueue, buffer: &Buffer, micros: u64, sync_file: bool, noted: bool| { - let command_buffer = queue.command_buffer().unwrap(); - let mut blit = command_buffer.blit_command_encoder().unwrap(); - blit.fill_buffer(buffer, 0..bytes(micros), 9).unwrap(); - blit.end_encoding().unwrap(); - let submitted_at = Arc::new(std::sync::atomic::AtomicU64::new(0)); - if handlers { - let at = Arc::clone(&submitted_at); - command_buffer - .add_submission_handler(Box::new(move |_: &CommandBuffer| { - at.store(host_nanos(), std::sync::atomic::Ordering::SeqCst); - })) - .unwrap(); - } - let seen_at = Arc::new(std::sync::atomic::AtomicU64::new(0)); - let at = Arc::clone(&seen_at); + let handlers = matches!(leg, GuestLeg::SubmissionHandlers | GuestLeg::SubmitCost); + let commit = |(queue, buffer, page): (&CommandQueue, &Buffer, Option<&Buffer>), + micros: u64, + sync_file: bool, + noted: bool| { + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.fill_buffer(buffer, 0..bytes(micros), 9).unwrap(); + if let Some(page) = page { + blit.fill_buffer(page, 0..GUEST_PAGE as u64, 9).unwrap(); + } + blit.end_encoding().unwrap(); + let submitted_at = Arc::new(std::sync::atomic::AtomicU64::new(0)); + if handlers { + let at = Arc::clone(&submitted_at); command_buffer - .add_completion_seen_handler(Box::new(move |_: &CommandBuffer| { + .add_submission_handler(Box::new(move |_: &CommandBuffer| { at.store(host_nanos(), std::sync::atomic::Ordering::SeqCst); })) .unwrap(); - let (seen, done) = (Arc::clone(&seen), Arc::clone(&done)); - command_buffer - .add_completed_handler(Box::new(move |finished: &CommandBuffer| { - let completed_handler = host_nanos(); - if noted { - let (queue, seen_at_turn) = trace::seen_of(finished); - let gpu_end = (finished.gpu_end_time().unwrap() * 1e9).round() as u64; - let seen_handler = seen_at.load(std::sync::atomic::Ordering::SeqCst); - let returned = (finished.submit_returned_time() * 1e9).round() as u64; - let submission_handler = - submitted_at.load(std::sync::atomic::Ordering::SeqCst); - seen.lock().unwrap().push(GuestSeen { - queue, - gpu_end, - seen: seen_at_turn, - seen_handler, - completed_handler, - returned, - submission_handler, - }); - } - done.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - })) - .unwrap(); - let sync_file = sync_file && command_buffer.add_completion_sync_file().is_ok(); - command_buffer.commit_and_submit().unwrap(); - if sync_file { - drop(command_buffer.export_completion_sync_file().unwrap()); - } - }; + } + let committed_at = Arc::new(std::sync::atomic::AtomicU64::new(0)); + let commit_at = Arc::clone(&committed_at); + let seen_at = Arc::new(std::sync::atomic::AtomicU64::new(0)); + let at = Arc::clone(&seen_at); + command_buffer + .add_completion_seen_handler(Box::new(move |_: &CommandBuffer| { + at.store(host_nanos(), std::sync::atomic::Ordering::SeqCst); + })) + .unwrap(); + let (seen, done) = (Arc::clone(&seen), Arc::clone(&done)); + command_buffer + .add_completed_handler(Box::new(move |finished: &CommandBuffer| { + let completed_handler = host_nanos(); + if noted { + let (queue, seen_at_turn) = trace::seen_of(finished); + let gpu_end = (finished.gpu_end_time().unwrap() * 1e9).round() as u64; + let seen_handler = seen_at.load(std::sync::atomic::Ordering::SeqCst); + let returned = (finished.submit_returned_time() * 1e9).round() as u64; + let submission_handler = submitted_at.load(std::sync::atomic::Ordering::SeqCst); + let committed = committed_at.load(std::sync::atomic::Ordering::SeqCst); + seen.lock().unwrap().push(GuestSeen { + queue, + gpu_end, + seen: seen_at_turn, + seen_handler, + completed_handler, + committed, + returned, + submission_handler, + }); + } + done.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + })) + .unwrap(); + let sync_file = sync_file && command_buffer.add_completion_sync_file().is_ok(); + commit_at.store(host_nanos(), std::sync::atomic::Ordering::SeqCst); + command_buffer.commit_and_submit().unwrap(); + if sync_file { + drop(command_buffer.export_completion_sync_file().unwrap()); + } + }; let wait_done = |count: usize| { let deadline = Instant::now() + Duration::from_secs(10); while done.load(std::sync::atomic::Ordering::SeqCst) < count { @@ -1636,18 +1701,22 @@ fn guest_leg(leg: GuestLeg) { let noted = frame >= GUEST_WARM; let start = Instant::now(); std::thread::scope(|scope| { - for (queue, (buffer, runs)) in apps.iter().zip(buffers.iter().zip(&runs)) { - let commit = &commit; + for (at, (queue, (buffer, runs))) in + (apps.iter().zip(buffers.iter().zip(&runs))).enumerate() + { + let (commit, page) = (&commit, page_buffers.get(at)); scope.spawn(move || { for µs in *runs { - commit(queue, buffer, micros, false, noted); + commit((queue, buffer, page), micros, false, noted); } }); } std::thread::sleep(GUEST_COMPOSITOR_AFTER.saturating_sub(start.elapsed())); let (buffer, runs) = (&buffers[GUEST_RUNS.len()], runs[GUEST_RUNS.len()]); + let page = page_buffers.get(GUEST_RUNS.len()); for (at, µs) in runs.iter().enumerate() { - commit(&compositor, buffer, micros, at + 1 == runs.len(), noted); + let last = at + 1 == runs.len(); + commit((&compositor, buffer, page), micros, last, noted); } }); std::thread::sleep(GUEST_PERIOD.saturating_sub(start.elapsed())); @@ -1700,6 +1769,53 @@ fn guest_leg(leg: GuestLeg) { per_frame(|c| c.batches_submitted_at_commit), per_frame(|c| c.wakes_handler_threads), ); + // Why the passes at commit left their command buffers to the scheduler's thread, and what + // decides it: the batches that waited for a host step, the `VkQueue`s, and which hold other + // queues' work back for the unshared compositor. + let held_back: Vec = (0..device.shared().queues.len()) + .filter(|&index| device.holds_back_for_unshared(index)) + .collect(); + let on: Vec = (apps.iter().chain([&compositor])) + .map(|queue| queue.vk_queue_sharing().0) + .collect(); + // From each command buffer's `commit_and_submit` call to the return of the driver's + // submission of its batch, whichever thread made it. + let to_submission: Vec = (seen.iter()) + .filter(|one| one.committed > 0 && one.returned >= one.committed) + .map(|one| us(one.committed, one.returned)) + .collect(); + let (timed, to_submission) = (to_submission.len(), tail(to_submission)); + eprintln!( + "COMPLETION-LATENCY guest-shaped, {leg:?} ({}), us: commit -> its submission returned {} \ + ({} of {}); at commit a frame: {:.2} passes, {:.2} batches; left: taken in {:.2}, \ + passing {:.2}, gone {:.2}, behind its queue {:.2}, behind another queue {:.2}, event \ + waits {:.2}, checks {:.2}, host steps {:.2}, binary waits {:.2}, unshared {:.2}, other \ + {:.2}; host steps recorded {:.2}; logs kept {:.2}; batches by waiters {:.2}; unified \ + memory {}; {} VkQueues, the queues on {on:?} (the compositor last), held back for an \ + unshared queue {held_back:?}", + device.name(), + to_submission, + timed, + seen.len(), + per_frame(|c| c.scheduler_passes_at_commit), + per_frame(|c| c.batches_submitted_at_commit), + per_frame(|c| c.scheduler_at_commit_left_taken_in), + per_frame(|c| c.scheduler_at_commit_left_passing), + per_frame(|c| c.scheduler_at_commit_left_gone), + per_frame(|c| c.scheduler_at_commit_left_behind_its_queue), + per_frame(|c| c.scheduler_at_commit_left_behind_another_queue), + per_frame(|c| c.scheduler_at_commit_left_event_waits), + per_frame(|c| c.scheduler_at_commit_left_checks), + per_frame(|c| c.scheduler_at_commit_left_host_steps), + per_frame(|c| c.scheduler_at_commit_left_binary_waits), + per_frame(|c| c.scheduler_at_commit_left_unshared), + per_frame(|c| c.scheduler_at_commit_left_other), + per_frame(|c| c.host_steps_recorded), + per_frame(|c| c.replay_logs_kept), + per_frame(|c| c.batches_submitted_by_waiters), + device.properties().has_unified_memory, + device.shared().queues.len(), + ); if handlers { // From each command buffer's own submission's return to its submission handler's start; // and those seen complete before their submission handler started, whose completion-seen diff --git a/crates/metal2vulkan-runtime/src/tests/queue_share_device.rs b/crates/metal2vulkan-runtime/src/tests/queue_share_device.rs index 02ef39921..9d83f3ac6 100644 --- a/crates/metal2vulkan-runtime/src/tests/queue_share_device.rs +++ b/crates/metal2vulkan-runtime/src/tests/queue_share_device.rs @@ -52,9 +52,10 @@ //! - **Passes of other threads** (`unshared_hold.rs`). A thread about to block, and a committing //! thread (`commit_and_submit`), each pass for itself with the scheduler's thread held in a //! submission handler, and take in an application's command buffer beside the unshared queue's -//! head, which that pass may not submit (a scheduled handler; a host step recorded, the steps' -//! thread held at trace points): the unshared one goes first, as the scheduler's own pass sends -//! it. +//! head, which a waiting thread's pass may not submit (a scheduled handler): the unshared one +//! goes first, as the scheduler's own pass sends it. A committing thread's pass submits an +//! unshared head whose host step was recorded itself (the steps' thread held at trace points), +//! first, and the application's command buffer after it. //! - **Commits on their way** (`unshared_hold.rs`). The unshared queue's head committed and taken //! in, held at its host step (the steps' thread held at a trace point) or waiting for a shared //! event's value whose signal, at the end of a long command buffer, was submitted: an @@ -1629,7 +1630,7 @@ fn an_unshared_commit_posted_during_a_pass_goes_before_work_let_go_after_it() { } /// The threads one threadgroup of the held dispatch runs in -/// [`a_committing_thread_s_pass_leaves_work_behind_an_unshared_head_with_its_step_recorded`]. +/// [`a_committing_thread_s_pass_sends_an_unshared_head_with_its_step_recorded_first`]. const STEP_THREADS: u64 = 64; /// A device for [`unshared_went_first`]'s tests: `PerQueue` (no queue moves), the unshared hold @@ -1742,22 +1743,22 @@ fn a_waiting_thread_s_pass_leaves_work_behind_an_unshared_head_it_cannot_send() /// A committing thread's own pass (`CommandBuffer::commit_and_submit`) takes in an application's /// command buffer while the unshared queue's head waits in the order with its host step recorded -/// (a dispatch whose pipeline's making the device's pool held, `pool::held`), which such a pass -/// never submits, where the scheduler's own pass would send it first: the steps' thread is held -/// before the step (`trace::Point::Step`) while the scheduler's thread is held once it submitted -/// a command buffer (`waiter_submits::Held`), its pass finding the dispatch stepping, then let go -/// to record it. The holding command -/// buffer is another unshared queue's, held back for none: an application's would wait behind the -/// dispatch on its way (`unshared_hold.rs`, "Commits on their way"). So the committing -/// thread's pass leaves the application's command buffer to the scheduler's thread too -/// (`unshared_hold.rs`, "Passes of other threads"). Under the default `CompletionPolicy`: where -/// the device's batches group, the committing thread's pass sends the application's batch alone, -/// its `VkQueue` running at most one earlier submission; without the rule it sends it ahead of -/// the dispatch. +/// (a dispatch whose pipeline's making the device's pool held, `pool::held`): the steps' thread is +/// held before the step (`trace::Point::Step`) while the scheduler's thread is held once it +/// submitted a command buffer (`waiter_submits::Held`), its pass finding the dispatch stepping, +/// then let go to record it and held after the step ended (`trace::Point::Stepped`). The holding +/// command buffer is another unshared queue's, held back for none: an application's would wait +/// behind the dispatch on its way (`unshared_hold.rs`, "Commits on their way"). With its step +/// recorded, no host step is due for the dispatch, so the committing thread's pass submits it +/// itself, first, as the scheduler's own pass would send it (`order.rs`, "Heads put first"), and +/// the application's command buffer after it, both at commit. Under `CompletionPolicy::Exact`, +/// where neither waits in a group. Before the pass asked whether a step was due, it left the +/// dispatch, and the application's command buffer with it, to the scheduler's thread +/// (`unshared_hold.rs`, "Passes of other threads"). #[test] -fn a_committing_thread_s_pass_leaves_work_behind_an_unshared_head_with_its_step_recorded() { +fn a_committing_thread_s_pass_sends_an_unshared_head_with_its_step_recorded_first() { let scratch = Scratch::new("unshared-hold-committer"); - let (device, app, unshared) = beside_unshared(&scratch, CompletionPolicy::default()); + let (device, app, unshared) = beside_unshared(&scratch, CompletionPolicy::Exact); let state = dispatch_pending::state(&device); let buffers = Buffers::new(&device); let [target, holder] = @@ -1792,6 +1793,11 @@ fn a_committing_thread_s_pass_leaves_work_behind_an_unshared_head_with_its_step_ let submitted = after.batches_submitted_at_commit - before.batches_submitted_at_commit; println!("the committing thread's passes {passes}, batches it submitted {submitted}"); assert_eq!(passes, 1, "the committing thread passed for its commit"); + assert_eq!( + submitted, 2, + "the committing thread's pass left the dispatch with its step recorded, or the \ + application's command buffer, to the scheduler's thread" + ); unshared_went_first("a committing thread's pass", &drawn, &other); assert!( buffers.written(STEP_THREADS), diff --git a/crates/metal2vulkan-runtime/src/unshared_hold.rs b/crates/metal2vulkan-runtime/src/unshared_hold.rs index fda1152e5..bec8177e6 100644 --- a/crates/metal2vulkan-runtime/src/unshared_hold.rs +++ b/crates/metal2vulkan-runtime/src/unshared_hold.rs @@ -97,7 +97,7 @@ //! need nothing of the scheduler's thread (`scheduler/mod.rs`'s `submit_plain_ready`). Where //! such a pass leaves an unshared queue's head that the scheduler's own look would find ready //! and send first (one with a submission or scheduled handler, for a thread about to block; one -//! whose host step is recorded; one a switch of storage forms rides on), or one on its way +//! a switch of storage forms rides on), or one on its way //! (above), it leaves the other queues' batches held back on that head's `VkQueue` to the //! scheduler's thread too, which it wakes: that thread's next pass sends the unshared one first //! and them next, or holds them while it is on its way. They wait for that wake and pass, or the diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index bb50f008a..9b9173ac2 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 524; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 2460; +pub const RUNTIME_VERSION: u32 = 2461; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles