diff --git a/crates/metal2vulkan-runtime/src/command_buffer/rebound_use.rs b/crates/metal2vulkan-runtime/src/command_buffer/rebound_use.rs index 8d4d4d024..5223755de 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/rebound_use.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/rebound_use.rs @@ -13,10 +13,9 @@ pub(crate) enum Unlogged { /// over host pages, a compute encoder that recorded a loop of command predication /// (`predication.rs`), or one of a kind that logs none (a resource state encoder's). NoCalls, - /// It left work for later that an encoding again does not record at once: a host step's (a - /// GPU-written indirect dispatch's, a gather from a guest RAM staged through the CPU over a - /// chunk that takes no import or in a part of its own, `host_ram/copy.rs`), or a scrub's - /// (`Segment::records_again`). + /// It left work for later that an encoding again does not record at once: a GPU-written + /// indirect dispatch's host step, a scrub, or a shadow's copy in left to its batch's + /// submission (`shadow::GatedCopyIn`) (`Segment::records_again`). Segments, /// The command buffer's failure fails it, or a fault of its own, as it commits. Fails, diff --git a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs index 662b12700..2e1f44f43 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs @@ -669,11 +669,11 @@ impl State { /// left a segment of its own where it found them still being made), work its commit recorded /// on the GPU alone, a run's merge (which /// goes, the encoding again merging after itself, `pass_runs.rs`), a staged gather (which - /// goes, the encoding again copying through the imports, `host_ram/copy.rs`), or a splice's - /// or a merge on the host's CPU part (which goes, the encoding again leaving its own over the - /// new pages, `shadow_splice.rs`), or a staged scatter's steps (which go, the encoding again - /// staging it again, `host_ram/copy.rs`), or its group was submitted, or the command buffer - /// completed. + /// goes, the encoding again copying through the imports, or staging it again where the + /// imports would not copy it, `host_ram/copy.rs`), or a splice's or a merge on the host's CPU + /// part (which goes, the encoding again leaving its own over the new pages, + /// `shadow_splice.rs`), or a staged scatter's steps (which go, the encoding again staging it + /// again, `host_ram/copy.rs`), or its group was submitted, or the command buffer completed. pub(super) fn splice_replay( &mut self, at: usize, @@ -713,9 +713,9 @@ impl State { recorded.raws = raws; recorded.summary = summary; // Its first segments go: the encoding again left a segment of its own in each - // pending dispatch's, each splice's or merge on the host's and each staged scatter - // step's place, and its work on the GPU alone in segments of its own, and recorded - // each staged gather's copy at once. + // pending dispatch's, each splice's or merge on the host's and each staged copy + // step's place it staged again, and its work on the GPU alone in segments of its + // own, and recorded each other staged gather's copy at once. // What the commit recorded of one stays retained, never submitted, as the first // recording does. for segment in recorded.segments.drain(..) { diff --git a/crates/metal2vulkan-runtime/src/deferred.rs b/crates/metal2vulkan-runtime/src/deferred.rs index 29dd5fc28..0adf465c5 100644 --- a/crates/metal2vulkan-runtime/src/deferred.rs +++ b/crates/metal2vulkan-runtime/src/deferred.rs @@ -566,9 +566,9 @@ impl Deferred { /// Whether a rebind's encoding again of its encoder records it at once in its place, leaving /// no segment of it (`command_buffer/reencode.rs`): a staged gather, which an encoder encoded /// again copies through the imports (`host_ram/copy.rs`), but one over a chunk that takes no - /// import or in a part of its own (`StagedGather::encoded_again_through_imports`), whose - /// encoder keeps no log. The encoding again's parts are the first's: such a gather's segment - /// starts none. + /// import or in a part of its own (`StagedGather::encoded_again_through_imports`), which it + /// stages again ([`left_again_by_an_encoding_again`](Self::left_again_by_an_encoding_again)). + /// The encoding again's parts are the first's: such a gather's segment starts none. pub(super) fn recorded_by_an_encoding_again(&self) -> bool { match self { Deferred::GatherStage(gather) => gather.encoded_again_through_imports(), @@ -580,15 +580,20 @@ impl Deferred { /// (`command_buffer/reencode.rs`): a splice's and a merge on the host's CPU part /// (`shadow_splice.rs`), which the encoding again's copies back plan over the pages the /// buffer lies in then and leave again, in a part as the first's (a rebind keeps the bytes' - /// offset in their page, `rebind.rs`, so the copies cut alike); and a staged scatter's two + /// offset in their page, `rebind.rs`, so the copies cut alike); a staged scatter's two /// steps, which the encoding again stages again from where the buffer lies then, its CPU - /// copy in a part of its own as the first's (`host_ram/copy.rs`'s + /// copy in a part of its own as the first's; and a staged gather the imports would not copy + /// as the first staged it (over a chunk that takes no import, or in a part of its own: + /// `StagedGather::encoded_again_through_imports`), staged again so (`host_ram/copy.rs`'s /// `HostRamCall::staged_again`). The first's go unrun. pub(super) fn left_again_by_an_encoding_again(&self) -> bool { - matches!( - self, - Deferred::ShadowSplice(_) | Deferred::ScatterStage(_) | Deferred::ScatterDrain(_) - ) + match self { + Deferred::ShadowSplice(_) | Deferred::ScatterStage(_) | Deferred::ScatterDrain(_) => { + true + } + Deferred::GatherStage(gather) => !gather.encoded_again_through_imports(), + _ => false, + } } /// Whether a commit may record it on the GPU alone, for good diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 4e57d6101..7a7ca530a 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -312,9 +312,10 @@ impl Segment { /// run's pass's merge, which the pass encoded again records after itself as a pass alone /// does, leaving its run (`pass_runs.rs`), a staged gather, which the encoding again /// copies through the imports in its place (`Deferred::recorded_by_an_encoding_again`), or a - /// splice's or a merge on the host's CPU part, or a staged scatter's steps, which the encoding - /// again leaves again over the new pages (`Deferred::left_again_by_an_encoding_again`). Its - /// log is kept only where every segment does. + /// splice's or a merge on the host's CPU part, a staged scatter's steps, or a staged gather + /// the imports would not copy, which the encoding again leaves again over the new pages + /// (`Deferred::left_again_by_an_encoding_again`). Its log is kept only where every segment + /// does. pub(super) fn records_again(&self) -> bool { self.pends() || self.work.may_run_on_gpu_alone() @@ -4163,7 +4164,7 @@ impl EncoderCore { /// place (`State::splice_replay`), in its parts, each segment it left recorded at once on the /// GPU alone but one whose pipelines are being made or failed to make, left as the first /// encoding left it ([`Segment::keeps_pipelines`]), and a splice's or a merge on the host's - /// CPU part and a staged scatter's steps, left for their host steps + /// CPU part and a staged copy's steps, left for their host steps /// (`Deferred::left_again_by_an_encoding_again`). Refused /// (internal) where the encoder, encoded again, failed or faulted its command buffer, or met a /// detached buffer, which its first encoding kept none of, or left work that no longer runs on @@ -4228,7 +4229,7 @@ impl EncoderCore { // Its segments recorded at once on the GPU alone, as its commit recorded the first // encoding's (`command_buffer/reencode.rs`): work that no longer runs there refuses the // encoding again, but work whose pipelines are being made, a splice's CPU part and a - // staged scatter's steps, which keep their segments. + // staged copy's steps, which keep their segments. let mut parts = Vec::with_capacity(split.len()); for ((raws, mut segments), summary) in split.into_iter().zip(summaries) { for segment in &mut segments { @@ -4246,7 +4247,7 @@ impl EncoderCore { continue; } // A splice's or a merge on the host's CPU part, planned again over the pages the - // buffer lies in now, and a staged scatter's steps, staged again from there, are + // buffer lies in now, and a staged copy's steps, staged again from there, are // left for their host steps as the commit left the first's // (`Deferred::left_again_by_an_encoding_again`). if segment.work.left_again_by_an_encoding_again() { diff --git a/crates/metal2vulkan-runtime/src/host_ram/copy.rs b/crates/metal2vulkan-runtime/src/host_ram/copy.rs index a31317095..9da55f406 100644 --- a/crates/metal2vulkan-runtime/src/host_ram/copy.rs +++ b/crates/metal2vulkan-runtime/src/host_ram/copy.rs @@ -55,10 +55,10 @@ //! copy into those chunks was recorded, a buffer or heap over host pages lies over them: //! `RamOnDevice::written_over`), over any chunk, goes in a part of its own //! (`Staging::after_the_gpu`), so that the work before it in its command buffer is submitted, -//! and completed, before its step reads the pages; and its encoder keeps no log an encoding -//! again would copy it through the imports from (that copy would start no part of its own). So -//! a first fill over chunks an earlier download wrote waits for no chunk's import on the -//! encoding thread either. A gather over bytes a scatter wrote into a chunk that takes no +//! and completed, before its step reads the pages; an encoding again of its encoder stages it +//! again so (`HostRamCall::staged_again`), as a copy through the imports would start no part of +//! its own. So a first fill over chunks an earlier download wrote waits for no chunk's import on +//! the encoding thread either. A gather over bytes a scatter wrote into a chunk that takes no //! import is staged too, the scatter's bytes written by the CPU in a host step before the //! gather's. //! - A gather leaves its work to the host step of its batch (`Deferred::GatherStage`), before @@ -81,9 +81,11 @@ //! writes waits (`scheduler/mod.rs`), and reads after; one where that is so as it is encoded //! goes in a part of its own (above), since work before it in its own command buffer is not //! submitted before its step. A region the device has no memory for fails the command buffer -//! at the step. A -//! rebind's encoding again of its encoder (`command_buffer/reencode.rs`) records the copy -//! through the imports in its place. Counted: `WorkCounts::host_ram_copies_staged`, +//! at the step. A rebind's encoding again of its encoder (`command_buffer/reencode.rs`) +//! records the copy through the imports in its place; one staged over a chunk that takes no +//! import while it runs, or in a part of its own, it stages again as the first encoding did +//! (`HostRamCall::staged_again`), so its parts are the first's, and the first's step goes +//! unrun. Counted: `WorkCounts::host_ram_copies_staged` (such an encoding again's too), //! `host_ram_staged_fills_gated`, `host_ram_staged_fill_nanos`. //! - A scatter leaves its work to two host steps (`Deferred::ScatterStage`, //! `Deferred::ScatterDrain`). The host step of the copy's batch, which waits for no work on the @@ -666,18 +668,28 @@ pub(crate) struct StagedGather { #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) struct Staging { /// It is over a chunk that takes no import while it runs ([`CopyTake::CpuOnly`]): an encoding - /// again of its encoder could not copy it through the imports, so the encoder keeps no log one - /// encodes it again from (`Deferred::recorded_by_an_encoding_again`). + /// again of its encoder could not copy it through the imports, so it stages it again + /// ([`HostRamCall::staged_again`]). cpu_only: bool, /// A gather whose host bytes some use but a copy's read may write as it is encoded /// ([`RamOnDevice::written_over`]): its host step goes in a part of its own, after the work /// before it in its command buffer was submitted, and waits for every `VkQueue` to complete /// what was submitted before it (`Deferred::gpu_written`), so it reads the bytes a command - /// before it in its own command buffer wrote. Its encoder keeps no log either: an encoding - /// again through the imports would start no part, so its parts would not be the first's. + /// before it in its own command buffer wrote. An encoding again stages it again so too + /// ([`HostRamCall::staged_again`]): one through the imports would start no part, so its parts + /// would not be the first's. after_the_gpu: bool, } +impl Staging { + /// Whether an encoding again of a gather so staged copies it through the imports + /// ([`StagedGather::encoded_again_through_imports`]): neither [`Staging::cpu_only`] nor + /// [`Staging::after_the_gpu`]. + fn through_imports(self) -> bool { + !self.cpu_only && !self.after_the_gpu + } +} + impl StagedGather { /// Whether its host step goes in a part of its own after the work before it completed /// ([`Staging::after_the_gpu`]). @@ -687,9 +699,10 @@ impl StagedGather { /// Whether an encoding again of its encoder copies it through the imports in its place: not /// where one of its chunks takes no import while it runs ([`Staging::cpu_only`]), nor where it - /// goes in a part of its own ([`Staging::after_the_gpu`]), which that copy would not start. + /// goes in a part of its own ([`Staging::after_the_gpu`]), which that copy would not start; + /// those it stages again ([`HostRamCall::staged_again`]). pub(crate) fn encoded_again_through_imports(&self) -> bool { - !self.staging.cpu_only && !self.staging.after_the_gpu + self.staging.through_imports() } /// Whether its host step waits for every batch submitted before it to complete: some use but @@ -1391,7 +1404,8 @@ pub(crate) struct HostRamCall { /// Taken at the recording only while the RAM still keeps it ([`RamCopies::keeps`]). kept: Option>, /// How its first encoding staged it through the CPU, where it did ([`Takes::staging`]): an - /// encoding again of its encoder stages a scatter so again ([`HostRamCall::staged_again`]). + /// encoding again of its encoder stages a scatter so again, and a gather the imports would + /// not copy as the first staged it ([`HostRamCall::staged_again`]). staged: OnceLock, } @@ -1520,11 +1534,17 @@ impl HostRamCall { /// How an encoding again of its encoder (`replay.rs`, `command_buffer/reencode.rs`) stages /// it: as its first encoding did, where that staged a scatter, whose CPU copy goes in a part /// of its own that a copy through the imports would not start, and which a chunk that takes - /// no import while it runs could not take (`Deferred::left_again_by_an_encoding_again`). - /// `None` for every other copy, which an encoding again copies through the imports. + /// no import while it runs could not take; and where it staged a gather over such a chunk or + /// in a part of its own (`Staging::through_imports`), for the same two reasons + /// (`Deferred::left_again_by_an_encoding_again`). `None` for every other copy, which an + /// encoding again copies through the imports. fn staged_again(&self) -> Option { let staging = *self.staged.get()?; - (self.copy == PagesCopy::Scatter).then_some(staging) + let again = match self.copy { + PagesCopy::Scatter => true, + PagesCopy::Gather => !staging.through_imports(), + }; + again.then_some(staging) } /// The call's name, as its refusals give it. diff --git a/crates/metal2vulkan-runtime/src/tests/host_ram_copy_device.rs b/crates/metal2vulkan-runtime/src/tests/host_ram_copy_device.rs index 1956aa847..f993b7af7 100644 --- a/crates/metal2vulkan-runtime/src/tests/host_ram_copy_device.rs +++ b/crates/metal2vulkan-runtime/src/tests/host_ram_copy_device.rs @@ -74,7 +74,8 @@ //! buffer's arena. A rebind before the first submission of a no-copy buffer that a staged //! gather's encoder fills encodes that encoder again, and the command buffer completes with //! both copies' bytes in place; so does one of a staged scatter's encoder, which stages the -//! scatter again. +//! scatter again, and one of an encoder whose gather after such a scatter went in a part of its +//! own, which stages both again. //! //! - **Shared RAM, whenever the copy comes**: on a device whose thread imports ahead, a gather //! over a RAM of shared memory with no dma-buf source once the thread reached its chunk, a @@ -1952,6 +1953,121 @@ fn a_rebind_before_the_first_submission_encodes_a_staged_scatter_s_encoder_again drop((over, used, ram)); } +/// A staged gather in a part of its own (`Staging::after_the_gpu`: over chunks a scatter before it +/// wrote, in its own encoder, while the device's thread imports them, each import held in flight +/// a while by the test, `RamSource::making_pause`) leaves its encoder's log in place too: a +/// rebind, before the command buffer's first submission, of a no-copy buffer the same encoder +/// fills encodes the encoder again, which stages both copies again as the first encoding did +/// (`HostRamCall::staged_again`); the command buffer completes with the fill in the pages the +/// buffer lies in now, the scatter's bytes in the RAM's pages, and the gather's read of them in +/// its buffer. +#[test] +fn a_rebind_before_the_first_submission_encodes_a_gather_staged_after_the_gpu_again() { + // Declared before the device, so dropped after it. + let pages = [rebind::Page::new(), rebind::Page::new()]; + let Some((device, used, ram, start, _)) = ahead_ram() else { + return; + }; + let runs = scattered_pages(start); + let total: u64 = runs.iter().map(|run| run.end - run.start).sum(); + let source = shared(&device, total, |at| pattern(at, 17)); + let back = shared(&device, total, |_| 0); + let length = rebind::BYTES as u64; + // SAFETY: each page outlives every buffer over it (dropped after the device), and only the + // buffer's commands use it while it lives. + let made = unsafe { + device.new_buffer_with_bytes_no_copy( + pages[0].memory(), + length, + ResourceOptions::shared(), + None, + ) + }; + let over = match made { + Ok(buffer) => buffer, + Err(Error::Unsupported(gap)) => { + eprintln!("HOST-RAM-COPY: the device imports no such pages: {gap:?}"); + return; + } + Err(error) => panic!("new_buffer_with_bytes_no_copy: {error:?}"), + }; + *device.shared().host_ram.making_pause.lock().unwrap() = Some(Arc::new(|_span| { + std::thread::sleep(Duration::from_millis(300)) + })); + // Its command buffer waits for an event only the host signals, below: the rebind comes + // before its first submission. + let gate = device.new_shared_event().unwrap(); + let queue = device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + command_buffer + .encode_wait_for_event(EventRef::Shared(&gate), 1) + .unwrap(); + let encoding = device.work_counts(); + let mut encoder = command_buffer.blit_command_encoder().unwrap(); + encoder.copy_to_host_ram(&source, 0, &ram, &runs).unwrap(); + encoder.copy_from_host_ram(&ram, &runs, &back, 0).unwrap(); + encoder.fill_buffer(&over, 0..length, 0x5a).unwrap(); + encoder.end_encoding().unwrap(); + let encoded = device.work_counts(); + *device.shared().host_ram.making_pause.lock().unwrap() = None; + command_buffer.commit().unwrap(); + assert_eq!(over.detach_backing(), Ok(true)); + // SAFETY: as above. + unsafe { over.rebind_bytes_no_copy(pages[1].memory(), None, None) }.unwrap(); + let rebound = device.work_counts(); + gate.set_signaled_value(1); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + let staged = |from: &WorkCounts, to: &WorkCounts| { + ( + to.host_ram_scatters_staged - from.host_ram_scatters_staged, + to.host_ram_copies_staged - from.host_ram_copies_staged, + ) + }; + println!( + "HOST-RAM-COPY rebound gather after the GPU {}: {:?} {:?}; scatters and gathers staged at \ + the encoding {:?}, at the rebind {:?}; encoders encoded again {}, refused {}", + device.name(), + command_buffer.status(), + command_buffer.error(), + staged(&encoding, &encoded), + staged(&encoded, &rebound), + rebound.encoders_reencoded - encoding.encoders_reencoded, + rebound.reencodes_refused - encoding.reencodes_refused, + ); + assert_eq!( + (command_buffer.status(), command_buffer.error()), + (CommandBufferStatus::Completed, None) + ); + assert_eq!( + staged(&encoding, &encoded), + (1, 1), + "the first encoding staged the scatter and the gather" + ); + assert_eq!( + ( + rebound.encoders_reencoded - encoding.encoders_reencoded, + staged(&encoded, &rebound), + ), + (1, (1, 1)), + "the rebind encoded the encoder again, which staged both copies again" + ); + assert!( + pages[1].written() && !pages[0].written(), + "the fill in the pages the buffer lies in now" + ); + for (run, expected) in scattered(&runs, &contents(&source)) { + assert!( + bytes(run.clone()) == expected, + "the scatter's bytes at {run:x?}" + ); + } + assert!( + contents(&back) == contents(&source), + "the gather read the scatter's bytes" + ); + drop((over, used, ram)); +} + #[test] fn a_staged_gather_after_a_gpu_write_over_its_pages_waits_for_that_write() { let Some((device, used, ram, start, before)) = ahead_ram() else { diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 1e9c72d62..e4e88a7eb 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 = 523; /// 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 = 2448; +pub const RUNTIME_VERSION: u32 = 2449; /// 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 diff --git a/docs/HOWTO.md b/docs/HOWTO.md index a71fecbbe..2656f8a9c 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -1075,12 +1075,14 @@ submission, can give the device the guest's RAM once instead: command buffer's own, copies the runs from the pages into it by the CPU, and records the GPU's copy from there into the buffer (`WorkCounts::host_ram_copies_staged`, `host_ram_staged_fill_nanos`). A rebind before the first submission that encodes its encoder - again copies the gather through the imports instead. Where a buffer or heap over host pages lies over the runs' - bytes, or a scatter into those chunks was recorded, the CPU's copy first waits until every - queue completed the work submitted before it (`host_ram_staged_fills_gated`), and where that - is so at the encoding the copy goes in a batch of its own, after the work before it in its - command buffer (a rebind then encodes its encoder again no more): so a first fill over chunks - a download wrote waits for no import either. + again copies the gather through the imports instead, or stages it again where its first + encoding staged it over a chunk that takes no import while it runs. Where a buffer or heap + over host pages lies over the runs' bytes, or a scatter into those chunks was recorded, the + CPU's copy first waits until every queue completed the work submitted before it + (`host_ram_staged_fills_gated`), and where that is so at the encoding the copy goes in a + batch of its own, after the work before it in its command buffer (a rebind that encodes its + encoder again stages it so again): so a first fill over chunks a download wrote waits for no + import either. - A staged scatter's GPU copy is recorded by its batch's host step, off the encoding and committing threads, into memory of the command buffer's own that the step takes; the work after it goes in a batch of its own, whose host step waits until every queue completed the