diff --git a/crates/metal2vulkan-runtime/src/command_buffer/first_submission.rs b/crates/metal2vulkan-runtime/src/command_buffer/first_submission.rs index ea2723901..e946e2851 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/first_submission.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/first_submission.rs @@ -38,11 +38,13 @@ //! nothing and the command buffer completes with `CommandBufferError::EncodedUseRebound`, every //! other submission running, its signals firing and its handlers running: the gap until the //! encoded uses resolve at submission, announced once -//! (`Degradation::EncodedUseRebound`). Work recorded on the GPU alone, whose preprocess's -//! resident set and named buffers the commit resolved (`gpu_execute.rs`, -//! `render/executions/gpu.rs`), is recorded again at each rebind before then (`reencode.rs`); -//! it fails alike where a range of that set lies elsewhere by then all the same (a buffer of it -//! released meanwhile), or the rebind could not record it on the GPU alone again. +//! (`Degradation::EncodedUseRebound`). Work recorded on the GPU alone (`gpu_execute.rs`, +//! `render/executions/gpu.rs`) resolves its commands' records through the resident set its +//! preprocess's table names: where the list changed or a buffer of it moved since the commit, +//! the submission points every such table at the set as it lies now, with its entries' +//! extents (`State::point_replay_tables`, `ResidentSet::replay_bytes`), so a rebind or a +//! release meanwhile takes effect in its commands, which are recorded once. What its commands +//! named is encoded or recorded again as an encoder's commands are (`reencode.rs`). //! - **Each submission at its own batch**. The first submission finds which of Metal's submissions //! are rebound, against the pages and the table it fixes for every later batch; each fails only //! as its own batch is submitted, after that batch's submission checks (`checks.rs`). One its @@ -57,15 +59,15 @@ use super::checks::metal_submissions; use super::rebound_use::{ReboundAt, ReboundUse, Recording}; use super::{write_fields, CommandBufferShared, Resident, State}; use crate::buffer::HostPages; -use crate::error::{CommandBufferError, Error}; +use crate::error::{internal, CommandBufferError, Error}; use crate::live_buffers::LiveTable; use crate::rebind::SubmittedHolds; use crate::residency::Residency; use crate::upload::Upload; use crate::used_resources::UsedResources; use crate::Device; -use metal2vulkan::bind::{ResidentRange, ResidentSet}; -use std::collections::{BTreeMap, BTreeSet, HashSet}; +use metal2vulkan::bind::{ResidentRange, ResidentSet, RootTable}; +use std::collections::{BTreeMap, BTreeSet}; use std::ops::Range; use std::sync::{Arc, Weak}; @@ -77,6 +79,16 @@ pub(crate) struct NotedTable { pub(crate) address: u64, } +/// A replay preprocess's resident root table (`render/executions/gpu.rs`, `gpu_execute.rs`): its +/// upload, where it lies there, and its device address. The command buffer's first submission +/// points it at the resident set as it lies then, where that changed since the commit +/// (`State::point_replay_tables`). +pub(crate) struct ReplayTable { + pub(crate) upload: Upload, + pub(crate) at: u64, + pub(crate) address: u64, +} + /// The live buffers' table a command buffer's resident set was made of (the module docs). pub(super) enum Live { /// Weakly, with the generation of the list it was made of: from the commit to the first @@ -211,6 +223,38 @@ impl State { self.remake_resident(device, &fresh) } + /// Its work on the GPU alone, at its first submission: each preprocess's resident root table + /// (`replay_tables`), recorded with the resident set as it lay then, pointed at the set as + /// the live buffers and what its encoders made resident lie now, where that changed + /// (`moved`), with its extents (`ResidentSet::replay_bytes`), uploaded once for all: a + /// rebind or a release since takes effect in its commands, as Metal resolves them at the + /// submission, and nothing is recorded again. The live buffers' table is held until it + /// completes either way, as their ranges lie in its pages. + fn point_replay_tables(&mut self, device: &Device, moved: bool) -> Result<(), Error> { + let live = device.shared().live_buffers.table(device)?; + if moved { + let ranges = live.ranges().chain(self.fresh_ranges()); + let (bytes, count) = ResidentSet::replay_bytes(ranges); + let len = bytes.len() as u64; + let upload = + (self.uploads).upload_aligned(device, &bytes, len, RootTable::ENTRY_ALIGNMENT)?; + let set = (upload.device_address()) + .ok_or_else(|| internal("a replay's resident set without a device address"))?; + for table in &self.replay_tables { + let fields = RootTable::resident_fields(table.address, set, count) + .ok_or_else(|| internal("a replay's resident table off its set's alignment"))?; + let at = table.at + u64::from(RootTable::RESIDENT_FIELDS_OFFSET); + table.upload.write_at(at, &fields); + } + let pointed = self.replay_tables.len() as u64; + device.shared().counts.replay_tables_pointed(pointed); + self.retained.push(Box::new(upload)); + } + self.replay_tables.clear(); + self.retained.push(Box::new(live)); + Ok(()) + } + /// The ranges of what its encoders made resident, as it lies now. fn fresh_ranges(&self) -> Vec { self.residency @@ -293,7 +337,6 @@ impl State { let shared = device.shared(); let mut verdicts = BTreeMap::new(); let mut moved = false; - let mut replays = false; let mut holds = SubmittedHolds::new(device); { let mut submitting = shared.rebinds.submitting(); @@ -340,7 +383,6 @@ impl State { let found = submitting.submit(&mut done.taken, retained, &mut holds); moved |= found.moved; judge(&mut verdicts, part.encoder, found.failure()); - replays |= !done.taken.resolved().is_empty(); if let (Some(CommandBufferError::EncodedUseRebound), Some(kind)) = (found.failure(), kind) { @@ -374,48 +416,15 @@ impl State { for earlier in self.stepped_tables.drain(..) { device.let_go_elsewhere(Box::new(earlier)); } - // A replay's resident set holds where every range of it lies as it did at the commit. - if replays { - let live = shared.live_buffers.table(device)?; - if changed || moved { - let now: HashSet = - live.ranges().chain(self.fresh_ranges()).collect(); - for part in &self.recorded { - let stale = part - .segments - .iter() - .filter_map(|segment| segment.recorded.as_ref()) - .find_map(|done| done.taken.resolved().iter().find(|r| !now.contains(r))); - let Some(stale) = stale else { - continue; - }; - judge( - &mut verdicts, - part.encoder, - Some(CommandBufferError::EncodedUseRebound), - ); - // Released where no range holds its Metal address now; else rebound. - let holds = |range: &ResidentRange| { - (range.guest..range.guest.saturating_add(range.length.max(1))) - .contains(&stale.guest) - }; - let released = !now.iter().any(holds); - if let Some(record) = self.ended.get(part.encoder) { - self.rebound_use.get_or_insert(ReboundUse { - encoder: part.encoder, - kind: record.kind, - at: ReboundAt::ResidentSet { released }, - }); - } - } - } - // Its pages held from now on, as the replay's ranges lie in them. - self.retained.push(Box::new(live)); + // The resident tables of its work on the GPU alone, pointed at the set as it lies now + // where the list changed or a buffer of it moved since the commit. + if !self.replay_tables.is_empty() { + self.point_replay_tables(device, changed || moved)?; } // Found here, against the pages and the table fixed for every later batch; each fails // at its own batch, after its check. self.failing = self.failing_submissions(&verdicts); - // Their names and resolved ranges let go; the listing released without the lock. + // Their names let go; the listing released without the lock. let State { ended, recorded, diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index 5ac8705a8..375d52801 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -44,7 +44,7 @@ mod storage_form; mod submit; pub(super) use completion::Completion; -pub(super) use first_submission::NotedTable; +pub(super) use first_submission::{NotedTable, ReplayTable}; pub(super) use group::{Group, GroupEnd, GROUP_BATCHES}; use rebound_use::{ReboundUse, Unlogged}; pub(super) use submit::{BatchLists, Submitting}; @@ -576,6 +576,10 @@ pub(super) struct State { /// Where its first submission, or a later batch's, found the first use rebound, for the /// notice (`rebound_use.rs`). rebound_use: Option, + /// The resident root tables of its work on the GPU alone recorded before its first + /// submission, which that submission points at the set as it lies then + /// (`first_submission.rs`). + replay_tables: Vec, /// The ended encoders whose submissions failed so: no part of one goes to a queue with work /// (`submit.rs` holds it to that). unrunnable: BTreeSet, @@ -666,6 +670,16 @@ impl State { self.ended.len() - 1 } + /// Note `table`, the resident root table of work recorded on the GPU alone: its first + /// submission points it at the resident set as it lies then (`first_submission.rs`). One + /// recorded after the first submission searches the set as it lay as it was recorded, which + /// the submitted command buffer holds. + pub(super) fn replay_table(&mut self, table: ReplayTable) { + if !self.submitted { + self.replay_tables.push(table); + } + } + /// Ended encoder `encoder` kept no log a rebind encodes it again from (`replay.rs`), as /// `why` says, for the rebound notice (`rebound_use.rs`). pub(super) fn encoder_unlogged(&mut self, encoder: usize, why: Unlogged) { @@ -1449,6 +1463,7 @@ impl CommandBuffer { submitted: false, failing: Vec::new(), rebound_use: None, + replay_tables: Vec::new(), unrunnable: BTreeSet::new(), submitted_holds: Vec::new(), failed_at_commit: None, @@ -1864,14 +1879,7 @@ impl CommandBuffer { .filter(|recorded| runs(recorded.encoder)) .flat_map(|encoder| &encoder.segments) .map(|segment| (segment.work.clone(), segment.needs_step())) - .collect::>(); - // Work it may record on the GPU alone below resolves the live buffers as they lie - // then, with this lock free: any rebind from here to its first submission records - // it again (`reencode.rs`), one before its recording ends once the commit ended. - let alone = (segments.iter()).any(|(work, step)| *step && work.may_run_on_gpu_alone()); - if alone { - device.shared().rebinds.wait_for_rerecord(&self.0); - } + .collect(); // What of it the live buffers list once used, held weakly: the device's registries' // locks, which take no other, inside this one. let reached = state.reached(device.shared(), runs); @@ -1966,8 +1974,9 @@ impl CommandBuffer { for heap in state.used_heaps.drain(..) { heap.mark_used(); } - // A rebind before its first submission of a buffer its replayable encoders named - // encodes them again (`reencode.rs`): noted while their holds still refuse one. + // A rebind before its first submission of a buffer its replayable encoders, or its + // work on the GPU alone, named encodes or records them again (`reencode.rs`): noted + // while their holds still refuse one. let (unreplayable, keys) = state.keep_replays(); if !keys.is_empty() { device.shared().rebinds.wait_for_replay(&self.0, keys); @@ -2058,11 +2067,6 @@ impl CommandBuffer { } } drop(unreplayable); - // A rebind while it recorded its work on the GPU alone left that work to record again - // here, now that the commit ended (`reencode.rs`). - if self.0.reencode_pending() { - self.0.reencode(); - } // The storage-sink degrade's trigger decides, in the program's call, before the // scheduler sees the command buffer (`detach.rs`). device.reach_storage_sinks(reaches); diff --git a/crates/metal2vulkan-runtime/src/command_buffer/rebound_use.rs b/crates/metal2vulkan-runtime/src/command_buffer/rebound_use.rs index a095eb911..6b91627d0 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/rebound_use.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/rebound_use.rs @@ -48,9 +48,6 @@ pub(crate) enum ReboundAt { NotEncodedAgain, /// Work it left for later named it. Segment(Recording), - /// The resident set its work on the GPU alone resolved at the commit holds a buffer's range - /// that lies elsewhere now (rebound) or that no buffer holds now (`released`). - ResidentSet { released: bool }, } /// Where the first submission found a use rebound: the command buffer's ended encoder `encoder`, @@ -87,7 +84,10 @@ impl fmt::Display for ReboundUse { write!(f, "found in its {kind} encoder {}: ", self.encoder)?; match &self.at { ReboundAt::Unlogged(Some(why)) => { - write!(f, "a command of its own named it, not encoded again as {why}") + write!( + f, + "a command of its own named it, not encoded again as {why}" + ) } ReboundAt::Unlogged(None) => { f.write_str("a command of its own named it, and it kept no log") @@ -109,14 +109,6 @@ impl fmt::Display for ReboundUse { ReboundAt::Segment(Recording::HostStep) => { f.write_str("work a host step recorded named it, which a rebind does not record") } - ReboundAt::ResidentSet { released: false } => f.write_str( - "the resident set its work on the GPU alone resolved at the commit holds a range \ - rebound since, and no rebind recorded that work again", - ), - ReboundAt::ResidentSet { released: true } => f.write_str( - "the resident set its work on the GPU alone resolved at the commit holds the range \ - of a buffer released since, which records nothing again", - ), } } } diff --git a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs index e403c39ca..aa42612fb 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs @@ -20,20 +20,20 @@ //! same turns: Vulkan synchronizes a pool's recordings externally. //! - **Work recorded on the GPU alone, recorded again.** Work its commit recorded on the GPU //! alone, for good (a GPU-written execution's preprocess and its dispatches or draws, -//! `gpu_execute.rs`, `render/executions/gpu.rs`), resolved there what its commands named and -//! the resident set its preprocess searches: the live buffers and what the encoders made -//! resident, as they lay then. An encoder that left such work keeps its log as one that left -//! none does, and its encoding again records that work at once, on the GPU alone, in segments -//! of the same parts (`EncoderCore::finish_replay`), its own commands (a render pass's -//! shadowed textures' copies and its other steps among them) recorded again around them. Its -//! commit notes the command buffer for any rebind too (`Rebinds::wait_for_rerecord`): each -//! rebind before the first submission records the work of the encoders it does not encode -//! again in its place, as the commit did, over where the buffers lie now: its recording, what -//! its commands took and what its host step needs. The commit notes it before it records that -//! work, with its lock free: a rebind meanwhile marks it, and leaves the mark to the commit, -//! which records the work again once it ended. Work a host step recorded again since -//! (with the barriers between its commands, `gpu_execute::Rerecord`, or as a route outgrew -//! it, `DeferredPass::outgrown`) keeps that step's recording. +//! `gpu_execute.rs`, `render/executions/gpu.rs`), reaches what its commands' records name +//! through the resident set its preprocess's table names, which the first submission points +//! at the set as it lies then (`first_submission.rs`): no rebind or release records it again +//! for that. What its commands named (the pass's attachments, say) was resolved as it was +//! recorded: an encoder that left such work keeps its log as one that left none does, and its +//! encoding again records that work at once, on the GPU alone, in segments of the same parts +//! (`EncoderCore::finish_replay`), its own commands (a render pass's shadowed textures' +//! copies and its other steps among them) recorded again around them. Its commit notes the +//! keys that work named too (`State::keep_replays`): a rebind of one of them before the first +//! submission records the work of the encoders it does not encode again in its place, as the +//! commit did, over where the buffers lie now: its recording, what its commands took and what +//! its host step needs. Work a host step recorded again since (with the barriers between its +//! commands, `gpu_execute::Rerecord`, or as a route outgrew it, `DeferredPass::outgrown`) +//! keeps that step's recording. //! - **What cannot be encoded again stays as before.** An encoder whose log is gone (a command //! predication's command buffer, failed at the commit) or whose second //! encoding is refused or records otherwise (`EncoderCore::finish_replay`), its work among @@ -46,7 +46,7 @@ use super::{lock, CommandBuffer, CommandBufferShared, State}; use crate::buffer::HostPages; use crate::deferred::{Deferred, StepInputs}; use crate::device::functions::Vk; -use crate::encoder::{RecordedSegment, Replayed, ReplayedPart}; +use crate::encoder::{RecordedSegment, Replayed, ReplayedPart, Segment}; use crate::replay::Replay; use crate::residency::Residency; use crate::resource::ResourceKey; @@ -79,11 +79,6 @@ impl CommandBufferShared { if marked == 0 { return; } - // Its commit records its work on the GPU alone with the lock free: the mark stays, and - // the commit records that work again once it ended. - if lock(&self.state).committing { - return; - } let device = &self.device; let moved: Vec<(usize, Arc)> = { let state = lock(&self.state); @@ -136,23 +131,32 @@ impl CommandBufferShared { } } } - // Its work recorded on the GPU alone in encoders not encoded again, each segment by its - // part and its place there, which hold through this turn: only the first submission - // places segments, and it waits for the turn; a host step, which records one, takes the - // turn too. + // Its work recorded on the GPU alone in encoders not encoded again that named a buffer + // over host pages that lies elsewhere now, each segment by its part and its place + // there, which hold through this turn: only the first submission places segments, and + // it waits for the turn; a host step, which records one, takes the turn too. What it + // reaches through its resident set its first submission points it at as it lies then. let alone: Vec<((usize, usize), Deferred)> = { let state = lock(&self.state); match state.submitted { true => Vec::new(), - false => (state.recorded.iter().enumerate()) - .filter(|(_, recorded)| !spliced.contains(&recorded.encoder)) - .flat_map(|(part, recorded)| { - let segments = recorded.segments.iter().enumerate(); - segments - .filter(|(_, segment)| segment.gpu_alone && segment.recorded.is_some()) - .map(move |(at, segment)| ((part, at), segment.work.clone())) - }) - .collect(), + false => { + let submitting = device.shared().rebinds.submitting(); + let moved = |segment: &Segment| { + segment.gpu_alone + && (segment.recorded.as_ref()) + .is_some_and(|done| submitting.rebound(&done.taken)) + }; + (state.recorded.iter().enumerate()) + .filter(|(_, recorded)| !spliced.contains(&recorded.encoder)) + .flat_map(|(part, recorded)| { + let segments = recorded.segments.iter().enumerate(); + segments + .filter(|(_, segment)| moved(segment)) + .map(move |(at, segment)| ((part, at), segment.work.clone())) + }) + .collect() + } } }; for (place, work) in alone { @@ -375,8 +379,9 @@ impl State { /// As it commits: the logs of encoders no rebind encodes again go, for the caller to let go /// of without this lock: every log where an encoder used command predication, and those of - /// encoders the commit's failure fails (they run nothing). The keys the encoders whose logs - /// stay named of buffers over host pages, sorted, each once (`Rebinds::wait_for_replay`). + /// encoders the commit's failure fails (they run nothing). The keys of buffers over host pages + /// the encoders whose logs stay named, and the work its commit recorded on the GPU alone, + /// sorted, each once (`Rebinds::wait_for_replay`). pub(super) fn keep_replays(&mut self) -> (Vec>, Box<[ResourceKey]>) { let mut gone = Vec::new(); let mut keys = Vec::new(); @@ -400,6 +405,13 @@ impl State { keys.extend(record.taken.named_pins()); } } + let alone = (self.recorded.iter()) + .flat_map(|part| &part.segments) + .filter(|segment| segment.gpu_alone) + .filter_map(|segment| segment.recorded.as_ref()); + for done in alone { + keys.extend(done.taken.named_pins()); + } keys.sort_unstable(); keys.dedup(); (gone, keys.into_boxed_slice()) diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index 0f66d5be9..7e96403c8 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -1287,9 +1287,8 @@ degradations! { /// calls; a command predication's command buffer; a render pass a host step records, or /// whose end captured its draws' tile reach; work recorded on the GPU alone that no longer /// runs there; a call refused again; `replay.rs`). Its reason names where the first such - /// submission found the use (the encoder, and its own commands, work it left for later, - /// or the resident set work on the GPU alone resolved at the commit) and why no rebind - /// encoded or recorded it again. Announced once, as + /// submission found the use (the encoder, and its own commands or work it left for later) + /// and why no rebind encoded or recorded it again. Announced once, as /// the first such submission is made, on the scheduler's thread, which makes it: /// `DeviceOptions::announce_each` does not repeat it, as no program /// call or host step meets it. diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index d417857ce..83de9d82c 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -58,7 +58,7 @@ use super::Device; use crate::device::functions::Vk; use crate::work_counts::Begun; use ash::vk; -use metal2vulkan::bind::{ReplayFaults, ResidentRange}; +use metal2vulkan::bind::ReplayFaults; use std::any::Any; use std::collections::BTreeSet; use std::marker::PhantomData; @@ -575,12 +575,6 @@ impl EncoderCore { self.id } - /// Note `ranges`, the resident set a GPU-alone replay resolved as it was recorded - /// (`Taken::resolve`). - pub(super) fn resolved(&mut self, ranges: impl IntoIterator) { - self.taken.resolve(ranges); - } - /// The command buffer the encoder records into. pub(super) fn command_buffer(&self) -> &CommandBuffer { &self.open.command_buffer diff --git a/crates/metal2vulkan-runtime/src/gpu_execute.rs b/crates/metal2vulkan-runtime/src/gpu_execute.rs index db45dad7a..18548d580 100644 --- a/crates/metal2vulkan-runtime/src/gpu_execute.rs +++ b/crates/metal2vulkan-runtime/src/gpu_execute.rs @@ -77,7 +77,7 @@ use super::argument_table::ArgumentTable; use super::binding; use super::blit::reads; -use super::command_buffer::CommandBuffer; +use super::command_buffer::{CommandBuffer, ReplayTable}; use super::degradation::CompiledPipeline; use super::device::lock; use super::dispatch_execute::{self, Template}; @@ -193,14 +193,13 @@ pub(super) enum Form { } /// What [`total`] found: the variants, the replay's preprocess, the bind state they were -/// planned for, the ranges of the live buffers its resident set holds, and the recording. The -/// command buffer keeps the live buffers' ranges, not their pages, until its first submission, -/// which finds whether they still lie there and holds the table then current until it completes. +/// planned for, and the recording. Its resident set holds the live buffers as they lay then; the +/// command buffer's first submission points it at the set as it lies then, and holds the table +/// then current until it completes (`command_buffer/first_submission.rs`). struct Total { prepared: Vec, pre: ReplayPreprocess, state: BindState, - live: Vec, form: Form, } @@ -341,7 +340,7 @@ fn total( let mut state = BindState::default(); state.stages.insert(Stage::Kernel, StageTable::default()); state.used_resources = residency.used_resources(); - state.resident_ranges = live.clone(); + state.resident_ranges = live; let shape = state.shape(); let states = execute.states(device); // Where only the indirect dispatches could run it, none past their bounds, before a variant is @@ -373,7 +372,6 @@ fn total( prepared, pre, state, - live, form, })) } @@ -539,7 +537,6 @@ fn record_total( prepared, pre, state, - live, form, } = total; let kernel = device.owned_kernel(OwnedModule::ReplayPreprocess)?; @@ -655,10 +652,13 @@ fn record_total( }); announce(&device, p, objects); } - // Its resident set, resolved now: the command buffer's first submission finds whether the - // live buffers and what its encoders made resident still lie there, holding the table from - // then on; until then a release or a rebind lets their pages go. - core.resolved(live.iter().copied().chain(residency.resident_ranges())); + // Its resident set as the live buffers and what its encoders made resident lie now: the + // command buffer's first submission points its table at the set as it lies then. + command_buffer.state().replay_table(ReplayTable { + upload: scratch.upload.clone(), + at: pre.layout.resident_offset, + address: scratch.address + pre.layout.resident_offset, + }); core.retain(scratch.upload); let variants: Vec> = prepared.iter().map(|p| Arc::clone(&p.variant)).collect(); core.retain(variants); diff --git a/crates/metal2vulkan-runtime/src/rebind.rs b/crates/metal2vulkan-runtime/src/rebind.rs index bd8e20c14..b3d9ee708 100644 --- a/crates/metal2vulkan-runtime/src/rebind.rs +++ b/crates/metal2vulkan-runtime/src/rebind.rs @@ -69,7 +69,6 @@ use super::key_hash::KeyMap; use super::program_objects; use super::resource::{ObjectId, ResourceKey}; use super::Device; -use metal2vulkan::bind::ResidentRange; use std::any::Any; use std::collections::BTreeSet; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -113,26 +112,19 @@ pub(super) struct Rebinds { /// How many there are: the check at each submission costs one load while none is. pub(super) stale_count: AtomicUsize, /// The command buffers committed and not yet first submitted that an encoder of theirs can - /// encode again (`replay.rs`), with the keys of the buffers over host pages those encoders - /// named: a rebind of one of them has them encoded again before their first submission. And - /// those with work recorded on the GPU alone, which any rebind has recorded again. - /// Taken under `buffers`' lock, after it. + /// encode again (`replay.rs`), or work of theirs on the GPU alone can be recorded again, with + /// the keys of the buffers over host pages those encoders and that work named: a rebind of + /// one of them has them encoded or recorded again before their first submission. Taken under + /// `buffers`' lock, after it. waiting: Mutex, } -/// The command buffers waiting for their first submission whose encoders a rebind encodes again -/// ([`Rebinds::wait_for_replay`]), each with the keys its replayable encoders named, sorted; and -/// those whose work recorded on the GPU alone a rebind records again -/// ([`Rebinds::wait_for_rerecord`]). +/// The command buffers waiting for their first submission whose encoders a rebind encodes again, +/// or whose work on the GPU alone it records again ([`Rebinds::wait_for_replay`]), each with the +/// keys they named, sorted. #[derive(Default)] struct Waiting { buffers: Vec<(Weak, Box<[ResourceKey]>)>, - /// The command buffers committing or committed with work they may record on the GPU alone (a - /// GPU-written execution's preprocess and its draws or dispatches) and not yet first - /// submitted: its resident set is resolved as the commit records it, so a rebind of any - /// buffer from then to the first submission records that work again - /// ([`Rebinds::wait_for_rerecord`]). - resolved: Vec>, /// The length past which the next registration first lets go of the entries whose command /// buffer went or was submitted. prune_at: usize, @@ -143,12 +135,11 @@ impl Waiting { /// command buffer went before its first submission (its submission failed first), never /// upgraded, so none goes under the lock. fn prune(&mut self) { - if self.buffers.len() + self.resolved.len() < self.prune_at { + if self.buffers.len() < self.prune_at { return; } self.buffers.retain(|(buffer, _)| buffer.strong_count() > 0); - self.resolved.retain(|buffer| buffer.strong_count() > 0); - self.prune_at = (2 * (self.buffers.len() + self.resolved.len())).max(16); + self.prune_at = (2 * self.buffers.len()).max(16); } } @@ -270,16 +261,6 @@ impl Rebinds { waiting.buffers.push((Arc::downgrade(buffer), keys)); } - /// Note `buffer`, committing now, with work it may record on the GPU alone, before it - /// records it: a rebind of any buffer from now to its first submission records that work - /// again ([`Rebinds::replace`], `command_buffer/reencode.rs`). Its first submission lets go of - /// it ([`Submitting::submitted_now`]). - pub(super) fn wait_for_rerecord(&self, buffer: &Arc) { - let mut waiting = lock(&self.waiting); - waiting.prune(); - waiting.resolved.push(Arc::downgrade(buffer)); - } - /// Whether one of `keys` names a detached buffer (`detach.rs`): at no cost while none is. pub(super) fn any_detached(&self, keys: impl IntoIterator) -> bool { if self.detached.load(Ordering::Acquire) == 0 { @@ -375,11 +356,10 @@ impl Rebinds { /// Give the buffer of `key`, whose hold on its pages is `cell`, `pages` from now on, unless /// a hold refuses it: where it lay (a detached one is attached again), and the command - /// buffers waiting for their first submission whose replayable encoders named it - /// ([`Rebinds::wait_for_replay`]) or that hold work recorded on the GPU alone, whose resident - /// set held where it lay ([`Rebinds::wait_for_rerecord`]), each marked under this lock to - /// encode or record them again before that submission (`CommandBufferShared::reencode`), - /// which the caller runs; `Err` gives `pages` back. + /// buffers waiting for their first submission whose replayable encoders or work on the GPU + /// alone named it ([`Rebinds::wait_for_replay`]), each marked under this lock to encode or + /// record them again before that submission (`CommandBufferShared::reencode`), which the + /// caller runs; `Err` gives `pages` back. pub(super) fn replace( &self, key: ResourceKey, @@ -408,7 +388,7 @@ impl Rebinds { let named = (waiting.buffers.iter()) .filter(|(_, keys)| keys.binary_search(&key).is_ok()) .map(|(buffer, _)| buffer); - for buffer in named.chain(&waiting.resolved) { + for buffer in named { let Some(buffer) = buffer.upgrade() else { continue; }; @@ -486,14 +466,11 @@ impl Submitting<'_> { waiting .buffers .retain(|(waiting, _)| !std::ptr::eq(Weak::as_ptr(waiting), buffer)); - waiting - .resolved - .retain(|waiting| !std::ptr::eq(Weak::as_ptr(waiting), buffer)); } /// Judge `taken`, and hold every pin whose pages still live in `retained` until the command - /// buffer completes, counted in `holds` for a detach to wait for. Its named keys and - /// resolved ranges stay for the caller. (Every key was named where the command buffer's root + /// buffer completes, counted in `holds` for a detach to wait for. Its named keys stay for the + /// caller. (Every key was named where the command buffer's root /// tables searched their own sets, past the search's capacity, which a set of any count no /// longer meets.) pub(super) fn submit( @@ -637,18 +614,12 @@ pub(super) enum Pinned { /// indirect command's resolved buffer. A key no command named is reached through the resident set /// alone (an encoder's `use_resource`, `use_heap`, a bound buffer no command reads), whose ranges /// the command buffer resolves again as it is first submitted. -/// -/// A GPU-alone replay of an indirect command buffer (`gpu_execute.rs`) resolves its -/// resident set as the commit records it, into its scratch: its ranges (`resolved`) hold as the -/// command buffer is first submitted only where the live buffers and what its encoders made -/// resident still lie there. #[derive(Default)] pub(super) struct Taken { pins: Vec<(ResourceKey, Pinned)>, /// The objects of releasable imports its blits took ([`ImportHold`]). imports: Vec, named: BTreeSet, - resolved: Vec, /// A command named a detached buffer, and the encoder recorded nothing from it on /// (`EncoderCore::skips`): its submission never runs. dead: bool, @@ -727,21 +698,10 @@ impl Taken { keys } - /// Note `ranges`, a resident set its commands resolved as they were recorded. - pub(super) fn resolve(&mut self, ranges: impl IntoIterator) { - self.resolved.extend(ranges); - } - - /// The resident ranges its commands resolved as they were recorded. - pub(super) fn resolved(&self) -> &[ResidentRange] { - &self.resolved - } - - /// Join `other`'s pins, names and resolved ranges. + /// Join `other`'s pins and names. pub(super) fn join(&mut self, other: Taken) { self.pins.extend(other.pins); self.named.extend(other.named); - self.resolved.extend(other.resolved); self.dead |= other.dead; } @@ -772,10 +732,9 @@ impl Taken { } } - /// Its named keys and resolved ranges let go, once judged (`Submitting::submit`). + /// Its named keys let go, once judged (`Submitting::submit`). pub(super) fn judged(&mut self) { self.named.clear(); - self.resolved.clear(); } /// Hand every pin's pages that still live to `retained`, upgraded, which the command buffer @@ -791,7 +750,6 @@ impl Taken { retained.extend(live.map(|pages| Box::new(pages) as Box)); retained.extend(self.imports.drain(..).filter_map(ImportHold::retained)); self.named.clear(); - self.resolved.clear(); } } diff --git a/crates/metal2vulkan-runtime/src/render/executions/gpu.rs b/crates/metal2vulkan-runtime/src/render/executions/gpu.rs index dba172f04..a1886406a 100644 --- a/crates/metal2vulkan-runtime/src/render/executions/gpu.rs +++ b/crates/metal2vulkan-runtime/src/render/executions/gpu.rs @@ -78,14 +78,13 @@ use super::super::{Assembly, DrawBuffers, Recording, RenderLowering}; use super::{HostStepCause, PassStorage, RenderExecution, Rendered, CALL}; use crate::binding::PushWrite; use crate::blit::{reads_by, writes_by}; -use crate::command_buffer::CommandBuffer; +use crate::command_buffer::{CommandBuffer, ReplayTable}; use crate::device::lock; use crate::draw_source::DrawSource; use crate::encoder::EncoderCore; use crate::error::{internal, Error}; use crate::executed_commands::RecordsRead; use crate::indirect_execute::ExecutionRange; -use crate::live_buffers::LiveTable; use crate::owned_kernel::OwnedModule; use crate::pipeline::{BufferForms, GraphicsState, RenderStateKind, Settled}; use crate::residency::Residency; @@ -117,10 +116,10 @@ pub(super) struct GpuForm { pub(super) decided: CommandWrites, /// The primitive type every command that draws draws. primitive_type: PrimitiveType, - /// The replay's preprocess over the command buffer's resident set and `live`'s buffers. + /// The replay's preprocess over the command buffer's resident set and the device's live + /// buffers as they lay then, which the command buffer's first submission points at the set as + /// it lies then. pre: DrawReplayPreprocess, - /// The device's live buffers the resident set holds. - live: Arc, } /// The slot table one push hole of a replayed draw names: the vertex function's or the fragment @@ -470,7 +469,6 @@ impl RenderExecution { decided, primitive_type, pre, - live, }) } @@ -606,9 +604,13 @@ impl RenderExecution { core.barrier(Barrier::everything()); } } - // Its resident set, resolved now: the command buffer's first submission finds whether - // the live buffers and what its encoders made resident still lie there. - core.resolved(form.live.ranges().chain(residency.resident_ranges())); + // Its resident set as the live buffers and what its encoders made resident lie now: the + // command buffer's first submission points its table at the set as it lies then. + command_buffer.state().replay_table(ReplayTable { + upload: scratch.clone(), + at: pre.layout.resident_offset, + address: address + pre.layout.resident_offset, + }); let draws = command_buffer.begin_draws(&snapshot.compatible)?; let raw = device.shared().vk(); let visibility = diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 16829dce2..2138aad84 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -313,6 +313,7 @@ pub(crate) struct Counters { replay_log_bytes: AtomicU64, encoders_reencoded: AtomicU64, segments_recorded_again: AtomicU64, + replay_tables_pointed: AtomicU64, reencodes_refused: AtomicU64, pipeline_libraries_made: AtomicU64, fragment_shader_libraries_made: AtomicU64, @@ -2033,6 +2034,13 @@ impl Counters { self.segments_recorded_again.fetch_add(1, Ordering::Relaxed); } + /// A command buffer's first submission pointed `tables` resident root tables of its work on + /// the GPU alone at the resident set as it lay then (`command_buffer/first_submission.rs`). + pub(crate) fn replay_tables_pointed(&self, tables: u64) { + self.replay_tables_pointed + .fetch_add(tables, Ordering::Relaxed); + } + /// A rebind could not encode an ended encoder again, or record again work recorded on the /// GPU alone, which keeps its first recording. pub(crate) fn reencode_refused(&self) { @@ -3601,8 +3609,14 @@ pub struct WorkCounts { /// (`command_buffer/reencode.rs`). pub encoders_reencoded: u64, /// Work a command buffer's commit recorded on the GPU alone (a GPU-written execution's) that - /// a rebind before its first submission recorded again (`command_buffer/reencode.rs`). + /// a rebind before its first submission of a buffer it named recorded again + /// (`command_buffer/reencode.rs`). pub segments_recorded_again: u64, + /// Resident root tables of work recorded on the GPU alone that their command buffer's first + /// submission pointed at the resident set as it lay then, the live buffers having changed or + /// moved since the commit (`command_buffer/first_submission.rs`): a rebind or a release + /// meanwhile that records nothing again. + pub replay_tables_pointed: u64, /// Ended encoders a rebind could not encode again (a call refused the second time, or a /// recording unlike the first), and work recorded on the GPU alone it could not record there /// again, which keep their first recording and fail `EncodedUseRebound`. @@ -4180,6 +4194,7 @@ impl Device { replay_log_bytes: counters.replay_log_bytes.load(Ordering::Relaxed), encoders_reencoded: counters.encoders_reencoded.load(Ordering::Relaxed), segments_recorded_again: counters.segments_recorded_again.load(Ordering::Relaxed), + replay_tables_pointed: counters.replay_tables_pointed.load(Ordering::Relaxed), reencodes_refused: counters.reencodes_refused.load(Ordering::Relaxed), fences_made: self.shared().fences.made(), pipeline_libraries_made: counters.pipeline_libraries_made.load(Ordering::Relaxed), diff --git a/crates/metal2vulkan-validation/src/runtime_lane/dispatch_executions.rs b/crates/metal2vulkan-validation/src/runtime_lane/dispatch_executions.rs index 2bad41d7b..45981a726 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/dispatch_executions.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/dispatch_executions.rs @@ -16,7 +16,8 @@ //! commit, before its batch is submitted (it waits for an event), recorded again with the //! barriers, still on the GPU alone; //! - one whose command buffer waits for an event while a buffer over host pages it never uses is -//! rebound, recorded again on the GPU alone at the rebind; +//! rebound, recorded once, its resident table pointed at the set as it lies at the first +//! submission; //! - a range its own commands alone; //! - with as many live states as the GPU-alone path takes in its encoder's order on the GPU alone, //! and with one more in the host step, which runs it faster; @@ -470,11 +471,12 @@ fn a_barrier_set_after_the_commit_records_the_commands_again() { /// A rebind between the commit and the first submission (an event wait holds the command buffer) /// of a buffer over host pages the commands never use moves the live buffers the preprocess -/// searches, which the commit resolved: the rebind records the execution again on the GPU alone -/// (`command_buffer/reencode.rs`), and it runs what it runs without the rebind, the command -/// buffer completing with a clean report (not `EncodedUseRebound`) and announcing nothing. +/// searches: the first submission points the execution's resident table at the set as it lies +/// then (`command_buffer/first_submission.rs`), nothing is recorded again, and it runs what it +/// runs without the rebind, the command buffer completing with a clean report (not +/// `EncodedUseRebound`) and announcing nothing. #[test] -fn a_rebind_before_the_first_submission_records_the_execution_again() { +fn a_rebind_before_the_first_submission_reaches_the_execution_s_records_as_they_lie() { on_device(|device, messages| { let seen = Arc::new(Seen::default()); let Some(unused) = buffer_over(device, pages(buffer_len(), 0, &[1]), &seen) else { @@ -500,15 +502,18 @@ fn a_rebind_before_the_first_submission_records_the_execution_again() { let before = device.work_counts(); let rebound = Arc::new(Seen::default()); rebind(&unused, pages(buffer_len(), 0, &[2]), &rebound).unwrap(); - let after = device.work_counts(); - assert_eq!( - after.segments_recorded_again, - before.segments_recorded_again + 1, - "the rebind recorded the execution again" - ); - assert_eq!(after.reencodes_refused, before.reencodes_refused); event.set_signaled_value(1); command_buffer.wait_until_completed_for(WAIT).unwrap(); + let after = device.work_counts(); + assert_eq!( + after.segments_recorded_again, before.segments_recorded_again, + "recorded once" + ); + assert_eq!(after.reencodes_refused, before.reencodes_refused); + assert!( + after.replay_tables_pointed > before.replay_tables_pointed, + "its resident table pointed at the first submission" + ); assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); assert_eq!( command_buffer.execution_report(), diff --git a/crates/metal2vulkan-validation/src/runtime_lane/render_merged_executions.rs b/crates/metal2vulkan-validation/src/runtime_lane/render_merged_executions.rs index b6f70c1f4..ea5a12b6e 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/render_merged_executions.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/render_merged_executions.rs @@ -17,10 +17,12 @@ //! - into a target over a buffer whose rows the device lays out otherwise (a shadowed texture, //! copied back after the pass): the kernel's triangles in one merged draw, and triangle strips //! the CPU wrote one indirect draw per command, the same pixels as the host step's there; -//! - after a rebind between the commit and the first submission, of a buffer over host pages -//! the commands' vertices lie in or of one they never use: recorded again at the rebind, the -//! new pages' points, the command buffer completing; and of the buffer a shadowed target lies -//! over: the render encoder encoded again, its copies and its merged draw into the new pages. +//! - after a rebind between the commit and the first submission of a buffer over host pages the +//! commands' vertices lie in, or of one they never use, or the release of one they never use: +//! the records' buffers as they lie at the first submission, which points the merged draw's +//! resident table at them, nothing recorded again, the new pages' points; and after a rebind of +//! the buffer a shadowed target lies over: the render encoder encoded again, its copies and its +//! merged draw into the new pages. use super::degrade_notices::{assert_made_once, assert_once, counts, expected_once, on_device}; use super::host_memory::Mapping; @@ -493,10 +495,12 @@ fn gpu_forms_draw_into_a_shadowed_target_what_the_host_step_draws() { } /// The points `draws` of the kernel's commands draw over `scene`, committed behind an event wait -/// and first submitted only after `rebind` ran: the commit records them in one merged draw, and -/// the rebind records them again (`command_buffer/reencode.rs`), once, over where the buffers lie -/// then: as a segment of its own, or in its render encoder encoded again (`pass_encoded`), with -/// `encoded` of the command buffer's encoders encoded again; the command buffer completes with a +/// and first submitted only after `rebind` ran (a rebind, or a release): the commit records them +/// in one merged draw. `encoded` of the command buffer's encoders are encoded again at the rebind +/// (`command_buffer/reencode.rs`), where a command of theirs named what moved, the merged draw +/// recorded again with the render encoder (`pass_encoded`); nothing records it again as a +/// segment of its own. The first submission points the merged draw's resident table at the set +/// as it lies then (`WorkCounts::replay_tables_pointed`), and the command buffer completes with a /// clean report and announces `kinds` alone. fn rebound_run( device: &Device, @@ -545,6 +549,7 @@ fn rebound_run( ); event.set_signaled_value(1); command_buffer.wait_until_completed_for(WAIT).unwrap(); + let pointed = device.work_counts().replay_tables_pointed - before.replay_tables_pointed; let ended = (command_buffer.status(), command_buffer.error()); let expected = expected_once(messages, kinds, &forced_with(device, &[])); let notices = messages.take_notices(); @@ -552,27 +557,31 @@ fn rebound_run( .filter_map(|message| message.degradation.as_ref()) .map(|notice| format!("{:?}: {}", notice.degradation, notice.reason)) .collect(); - // Recorded again once, in one merged draw: as a segment of its own, or with its encoder. - let recorded = (u64::from(!pass_encoded), encoded, 0, 8, 0); + // Recorded again only with an encoder encoded again, in one merged draw. + let again = 8 * u64::from(pass_encoded); + let recorded = (0, encoded, 0, again, 0); assert_eq!( - (counted, ended), - (recorded, (CommandBufferStatus::Completed, None)), + (counted, pointed > 0, ended), + (recorded, true, (CommandBufferStatus::Completed, None)), "(segments recorded again, encoders encoded again, refused, merged commands, records \ - read), and the command buffer's end; notices: {reasons:#?}" + read), tables pointed at the first submission, and the command buffer's end; notices: \ + {reasons:#?}" ); assert_once(¬ices, &expected); } -/// A GPU-written execution the commit recorded on the GPU alone is recorded again by a rebind -/// between the commit and the first submission (an event wait holds the command buffer), as -/// Metal resolves what its commands reach as it submits the command buffer. A rebind of a buffer -/// over host pages the commands never use moves the live buffers the preprocess searches, and the -/// draws draw as without it; a rebind of the buffer the commands' vertices lie in, from pages -/// holding vertices off the target to pages holding the row of points, draws the new pages' -/// points, pixel for pixel. Neither fails the command buffer (`EncodedUseRebound`) or announces -/// anything. +/// A GPU-written execution the commit recorded on the GPU alone reaches what its commands' records +/// name as it lies at the command buffer's first submission (an event wait holds it after a rebind +/// or a release), as Metal resolves them as it submits the command buffer: the submission points +/// the merged draw's resident table at the set as it lies then, and nothing is recorded again. A +/// rebind of a buffer over host pages the commands never use, and the release of a buffer they +/// never use, change the live buffers the preprocess searches, and the draws draw as without them; +/// a rebind of the buffer the commands' vertices lie in (the kernel writes its address into the +/// records, and the render encoder makes it resident), from pages holding vertices off the +/// target to pages holding the row of points, draws the new pages' points, pixel for pixel. None +/// fails the command buffer (`EncodedUseRebound`) or announces anything. #[test] -fn a_rebind_before_the_first_submission_records_the_gpu_form_again_over_the_new_pages() { +fn a_rebind_or_a_release_before_the_first_submission_reaches_the_gpu_form_s_records_as_they_lie() { on_device(|device, messages| { let draws: Vec = vec![[0, 5, 1, 0], [8, 3, 2, 1], [30, 6, 3, 2]]; let points = @@ -594,6 +603,19 @@ fn a_rebind_before_the_first_submission_records_the_gpu_form_again_over_the_new_ "an unused buffer rebound" ); + let released = std::cell::RefCell::new(Some( + device.new_buffer(4096, ResourceOptions::shared()).unwrap(), + )); + let release = || drop(released.borrow_mut().take()); + let gone = (&release as &dyn Fn(), 0, false); + rebound_run(device, (messages, &[]), (&scene, &draws), gone); + assert!(released.borrow().is_none()); + assert_eq!( + scene.pixels(), + drawn_points(&draws), + "an unused buffer released" + ); + let off: Vec<[f32; 2]> = point_row().iter().map(|_| [-4.0, -4.0]).collect(); let xy = buffer_over(device, points(&off), &seen).unwrap(); let scene = Scene { @@ -610,8 +632,8 @@ fn a_rebind_before_the_first_submission_records_the_gpu_form_again_over_the_new_ rebound_run(device, (messages, &[]), (&scene, &draws), rebound); assert_eq!(scene.pixels(), drawn_points(&draws), "the vertices rebound"); eprintln!( - "ICB-REBIND {}: GPU forms recorded again at rebinds before the first submission drew \ - the new pages", + "ICB-REBIND {}: GPU forms reached their records' buffers as they lay at the first \ + submission, after a rebind or a release, recorded once", device.name() ); }); diff --git a/crates/metal2vulkan/src/bind/instantiate.rs b/crates/metal2vulkan/src/bind/instantiate.rs index bfeb0e298..3e30952a7 100644 --- a/crates/metal2vulkan/src/bind/instantiate.rs +++ b/crates/metal2vulkan/src/bind/instantiate.rs @@ -387,6 +387,25 @@ impl ResidentSet { end <= u128::from(e.size) && e.host.wrapping_add(into) == range.host } + /// What a consumer points a replay preprocess's resident root table at + /// ([`ReplayPreprocess::resident`](crate::bind::ReplayPreprocess::resident), + /// [`DrawReplayPreprocess::resident`](crate::bind::DrawReplayPreprocess::resident)) for its + /// commands' addresses to resolve through `ranges` as they lie then (the first submission of + /// the command buffer that records it, say): the set of `ranges` ([`ResidentSet::new`]) in its + /// entries' layout, then each entry's unpadded extent (a `u64`: how many bytes from its Metal + /// address the ranges hold without a gap, at their own lengths), then one zero; and the set's + /// count `N`. The consumer uploads the bytes at a 32-byte-aligned device address `set` and + /// writes [`RootTable::resident_fields`] of the table, `set` and `N` over the table's own. + pub fn replay_bytes(ranges: impl IntoIterator) -> (Vec, u64) { + let ranges: Vec = ranges.into_iter().collect(); + let set = ResidentSet::new(ranges.iter().copied()); + let allocations = ranges.iter().map(|range| (range.guest, range.length)); + let extents = crate::bind::resident::extents_of(allocations, &set.entries); + let mut bytes = set.bytes(); + bytes.extend(crate::bind::resident::extents_bytes(extents)); + (bytes, set.len()) + } + /// The set of its entries and `ranges`, coalesced. pub fn with(&self, ranges: impl IntoIterator) -> ResidentSet { let own = self diff --git a/crates/metal2vulkan/src/bind/replay.rs b/crates/metal2vulkan/src/bind/replay.rs index 31c099b76..e5c94ef22 100644 --- a/crates/metal2vulkan/src/bind/replay.rs +++ b/crates/metal2vulkan/src/bind/replay.rs @@ -108,7 +108,7 @@ use std::num::NonZeroU64; use std::sync::Arc; use crate::bind::instantiate::{PushHole, RootTable}; -use crate::bind::resident::{resident_entries, resident_extents, stage_root_table}; +use crate::bind::resident::{replay_extents, resident_entries, stage_root_table}; use crate::bind::state::BindState; use crate::bind::status::{ReplayFaults, StatusBits, StatusWord}; use crate::budget::{Budget, Meter}; @@ -202,23 +202,21 @@ const P_TABLES_BELOW: u64 = 16; const P_VARIANTS_AT: u64 = 20; const P_PARENT_AT: u64 = 24; const P_ARGUMENTS_AT: u64 = 28; -/// `extents - resident`: each resident root's unpadded extent. -const P_EXTENTS_AT: u64 = 32; /// The regions recorded per command, and `regions - resident`. -const P_REGIONS: u64 = 36; -const P_REGIONS_AT: u64 = 40; +const P_REGIONS: u64 = 32; +const P_REGIONS_AT: u64 = 36; /// The generated-commands path: the sequence stride (0: K14c's arguments instead), the push token's /// bytes, the most commands of one execution, and `templates - resident`, `counts - resident`, /// `sequences - resident`. -const P_STRIDE: u64 = 44; -const P_PUSH_BYTES: u64 = 48; -const P_SEGMENT: u64 = 52; -const P_TEMPLATES_AT: u64 = 56; -const P_COUNTS_AT: u64 = 60; -const P_SEQUENCES_AT: u64 = 64; +const P_STRIDE: u64 = 40; +const P_PUSH_BYTES: u64 = 44; +const P_SEGMENT: u64 = 48; +const P_TEMPLATES_AT: u64 = 52; +const P_COUNTS_AT: u64 = 56; +const P_SEQUENCES_AT: u64 = 60; /// The device's `max_threadgroup_memory_length`, which a command's lengths are clamped to before /// they are rounded up to 16 bytes. -const P_MAX_LENGTH: u64 = 68; +const P_MAX_LENGTH: u64 = 64; /// The parameters' flag bits: the descriptor's inheritance. const INHERIT_PIPELINE: u32 = 1 << 0; @@ -405,7 +403,8 @@ pub struct ReplayLayout { /// The resident root table ([`ReplayPreprocess::resident`]); the parameters /// ([`ReplayPreprocess::params`]) end here. pub resident_offset: u64, - /// Each resident root's unpadded extent ([`ReplayPreprocess::extents`]). + /// Each resident root's unpadded extent ([`ReplayPreprocess::extents`]): right after the + /// resident root table, whose set ends with it. pub extents_offset: u64, /// The registered variants ([`ReplayPreprocess::variants`]). pub variants_offset: u64, @@ -467,10 +466,13 @@ pub struct ReplayPreprocess { /// The resident root table, at `layout.resident_offset`: its sink entry's `host` field /// ([`RootTable::SINK_HOST_OFFSET`]) takes the sink's device address, as any root table's. pub resident: RootTable, - /// One `u64` per root of `resident`, at `layout.extents_offset`: how many bytes from the - /// root's guest address its allocations hold at their own lengths, without the padding (zero - /// for the null and sink roots). A kernel buffer resolves only below it, as the host resolves a - /// record's address (`BufferBinding::resolve_buffer`). + /// One `u64` per entry of `resident`'s set, at `layout.extents_offset`, right after the set, + /// then one zero: how many bytes from the entry's guest address its allocations hold at their + /// own lengths, without the padding. A kernel buffer resolves only below it, as the host + /// resolves a record's address (`BufferBinding::resolve_buffer`). The preprocess reads them + /// after the set the table names, wherever a consumer points it: one that points the table at + /// a set uploaded later puts that set's extents after it + /// ([`ResidentSet::replay_bytes`](crate::bind::ResidentSet::replay_bytes)). pub extents: Vec, /// The registered variants, at `layout.variants_offset`. pub variants: Vec, @@ -614,15 +616,14 @@ fn preprocess( let entries = resident_entries(state); let resident = stage_root_table(&[], 2, &entries); - let mut extents = vec![0u8; 2 * 8]; - for x in resident_extents(state, &entries) { - extents.extend_from_slice(&x.to_le_bytes()); - } + let extents = replay_extents(state, &entries); let slots = u64::from(execution.count); let count = variants.len() as u64; let regions = u64::from(execution.regions); let resident_offset = slots * SLOT_TABLE_BYTES + PARAMS_BYTES; - let extents_offset = section(resident_offset + resident.bytes.len() as u64); + // The extents right after the set, which the table holds from its root 2 to its end + // (`memory::roots::ResidentView`). + let extents_offset = resident_offset + resident.bytes.len() as u64; let variants_offset = section(extents_offset + extents.len() as u64); let parent_offset = section(variants_offset + count * VARIANT_BYTES); let regions_offset = section(parent_offset + COMMAND_BYTES as u64); @@ -687,7 +688,6 @@ fn preprocess( (variants_offset - resident_offset) as u32, (parent_offset - resident_offset) as u32, (arguments_offset - resident_offset) as u32, - (extents_offset - resident_offset) as u32, execution.regions, (regions_offset - resident_offset) as u32, generated_layout.map_or(0, |g| g.stride), @@ -1251,7 +1251,6 @@ pub fn typed_module(limits: [u32; 3]) -> BResult { let variants_at = param(fb, P_VARIANTS_AT)?; let parent_at = param(fb, P_PARENT_AT)?; let arguments_at = param(fb, P_ARGUMENTS_AT)?; - let extents_at = param(fb, P_EXTENTS_AT)?; let regions_n = param(fb, P_REGIONS)?; let regions_at = param(fb, P_REGIONS_AT)?; let stride = param(fb, P_STRIDE)?; @@ -1473,12 +1472,11 @@ pub fn typed_module(limits: [u32; 3]) -> BResult { let sink_entry = roots::SINK_ROOT * roots::ENTRY_BYTES; let sink_at = at(fb, resident, sink_entry + roots::HOST)?; let sink = load64(fb, t, sink_at)?; - let count_at = at(fb, resident, sink_entry + roots::RESIDENT_COUNT)?; - let resident_count = load64(fb, t, count_at)?; - // `R0` of the slot table is the distance in entries from it to the resident set, which the - // resident root table holds from its root 2. - let resident_first = at(fb, resident, 2 * roots::ENTRY_BYTES)?; - let distance = fb.binary(BinOp::ISub, resident_first, table)?; + // `R0` of the slot table is the distance in entries from it to the resident set the resident + // root table names, wherever it lies (`roots::ResidentView`), of its count. + let view = roots::resident_view(fb, resident)?; + let resident_count = view.count; + let distance = fb.binary(BinOp::ISub, view.set, table)?; let entry_shift = k64(fb, roots::ENTRY_BYTES.trailing_zeros().into())?; let r0 = fb.binary(BinOp::ShiftRightLogical, distance, entry_shift)?; for (field, v) in [ @@ -1498,8 +1496,6 @@ pub fn typed_module(limits: [u32; 3]) -> BResult { // bind offset, which holds a nil buffer's address word, so the kernel sees the offset as // the buffer's address, as Metal's does. A dynamic stride of a bound buffer is no replayed // template's. - let extents_off = wide(fb, t, extents_at)?; - let extents = fb.binary(BinOp::IAdd, resident, extents_off)?; let source = fb.select(inherit_buffers, parent, rec)?; let bindings = k32(fb, BINDING_COUNT as u32)?; count_loop(fb, t, bindings, |fb, n| { @@ -1525,10 +1521,7 @@ pub fn typed_module(limits: [u32; 3]) -> BResult { let found = fb.binary(BinOp::INotEqual, root, null)?; let size = roots::entry_field(fb, resident, root, roots::SIZE)?; // The allocation's own extent, not its padded size: as the host's resolve. - let eight = k64(fb, 8)?; - let extent_rel = fb.binary(BinOp::IMul, root, eight)?; - let extent_at = fb.binary(BinOp::IAdd, extents, extent_rel)?; - let extent = load64(fb, t, extent_at)?; + let extent = roots::extent_of(fb, &view, root, found)?; let inside = fb.binary(BinOp::ULessThan, offset, extent)?; let hit = fb.binary(BinOp::LogicalAnd, found, inside)?; let missed = fb.unary(UnOp::LogicalNot, hit)?; diff --git a/crates/metal2vulkan/src/bind/replay/draws.rs b/crates/metal2vulkan/src/bind/replay/draws.rs index 11776e64c..80b228719 100644 --- a/crates/metal2vulkan/src/bind/replay/draws.rs +++ b/crates/metal2vulkan/src/bind/replay/draws.rs @@ -66,7 +66,7 @@ use super::{ store64, wide, ReplayRefusal, Types, PARAMS_BYTES, }; use crate::bind::instantiate::{PushHole, RootTable}; -use crate::bind::resident::{resident_entries, resident_extents, stage_root_table}; +use crate::bind::resident::{replay_extents, resident_entries, stage_root_table}; use crate::bind::state::BindState; use crate::bind::status::{ReplayFaults, StatusBits, StatusWord}; use crate::budget::{Budget, Meter}; @@ -105,16 +105,15 @@ const P_COUNT: u64 = 4; const P_FLAGS: u64 = 8; /// `tables - resident`: how far past the resident root table the slot tables start. const P_TABLES_AT: u64 = 12; -/// `parent - resident`, `arguments - resident`, `extents - resident`. +/// `parent - resident`, `arguments - resident`. const P_PARENT_AT: u64 = 16; const P_ARGUMENTS_AT: u64 = 20; -const P_EXTENTS_AT: u64 = 24; /// The buffer slots each stage's slot table holds. -const P_VERTEX_SLOTS: u64 = 28; -const P_FRAGMENT_SLOTS: u64 = 32; +const P_VERTEX_SLOTS: u64 = 24; +const P_FRAGMENT_SLOTS: u64 = 28; /// The primitive types named, then each (`MAX_DRAW_REPLAY_TYPES` words). -const P_TYPES: u64 = 36; -const P_TYPE: u64 = 40; +const P_TYPES: u64 = 32; +const P_TYPE: u64 = 36; /// The parameters' flag bit: the commands inherit the encoder's buffers. const INHERIT_BUFFERS: u32 = 1; @@ -183,7 +182,8 @@ pub struct DrawReplayLayout { /// The resident root table ([`DrawReplayPreprocess::resident`]); the parameters /// ([`DrawReplayPreprocess::params`]) end here. pub resident_offset: u64, - /// Each resident root's unpadded extent ([`DrawReplayPreprocess::extents`]). + /// Each resident root's unpadded extent ([`DrawReplayPreprocess::extents`]): right after the + /// resident root table, whose set ends with it. pub extents_offset: u64, /// The encoder's buffers ([`DrawReplayPreprocess::parent`]). pub parent_offset: u64, @@ -243,8 +243,9 @@ pub struct DrawReplayPreprocess { /// The resident root table, at `layout.resident_offset`: its sink entry's `host` field /// ([`RootTable::SINK_HOST_OFFSET`]) takes the sink's device address, as any root table's. pub resident: RootTable, - /// One `u64` per root of `resident`, at `layout.extents_offset`: the unpadded extent a buffer - /// resolves below, as a compute replay's (`ReplayPreprocess::extents`). + /// One `u64` per entry of `resident`'s set, at `layout.extents_offset`, right after the set, + /// then one zero: the unpadded extent a buffer resolves below, as a compute replay's, read + /// after whatever set a consumer points the table at (`ReplayPreprocess::extents`). pub extents: Vec, /// The encoder's vertex and fragment buffers in a record's layout, at `layout.parent_offset`. pub parent: Vec, @@ -315,15 +316,14 @@ pub fn draw_replay_preprocess( let entries = resident_entries(state); let resident = stage_root_table(&[], 2, &entries); - let mut extents = vec![0u8; 2 * 8]; - for x in resident_extents(state, &entries) { - extents.extend_from_slice(&x.to_le_bytes()); - } + let extents = replay_extents(state, &entries); let commands = u64::from(replay.count); let types = replay.primitive_types.len() as u64; let tables = table_bytes(replay.vertex_slots) + table_bytes(replay.fragment_slots); let resident_offset = PARAMS_BYTES; - let extents_offset = section(resident_offset + resident.bytes.len() as u64); + // The extents right after the set, which the table holds from its root 2 to its end + // (`memory::roots::ResidentView`). + let extents_offset = resident_offset + resident.bytes.len() as u64; let parent_offset = section(extents_offset + extents.len() as u64); let header_offset = section(parent_offset + COMMAND_BYTES as u64); let uploaded = match corners { @@ -391,7 +391,6 @@ pub fn draw_replay_preprocess( as_param(tables_offset - resident_offset)?, as_param(parent_offset - resident_offset)?, as_param(arguments_offset - resident_offset)?, - as_param(extents_offset - resident_offset)?, replay.vertex_slots, replay.fragment_slots, types as u32, @@ -517,21 +516,17 @@ fn no_binding(_: &Symbol) -> Option { None } -/// The root `guest` resolves to in the resident set at `resident`, its offset there, and whether -/// it lies inside the root's unpadded extent (`extents`, a `u64` per root): a hit. +/// The root `guest` resolves to in the resident set the resident root table at `resident` names +/// (`view`), its offset there, and whether it lies inside the root's unpadded extent: a hit. fn resolved( fb: &mut FunctionBuilder<'_>, - t: Types, - (resident, extents): (Value, Value), + (resident, view): (Value, &roots::ResidentView), guest: Value, ) -> BResult<(Value, Value, Value)> { let (root, offset) = roots::resolve(fb, resident, guest)?; let null = k64(fb, roots::NULL_ROOT)?; let found = fb.binary(BinOp::INotEqual, root, null)?; - let eight = k64(fb, 8)?; - let extent_rel = fb.binary(BinOp::IMul, root, eight)?; - let extent_at = fb.binary(BinOp::IAdd, extents, extent_rel)?; - let extent = load64(fb, t, extent_at)?; + let extent = roots::extent_of(fb, view, root, found)?; let inside = fb.binary(BinOp::ULessThan, offset, extent)?; let hit = fb.binary(BinOp::LogicalAnd, found, inside)?; Ok((root, offset, hit)) @@ -612,7 +607,6 @@ pub fn typed_module() -> BResult { let tables_at = param(fb, P_TABLES_AT)?; let parent_at = param(fb, P_PARENT_AT)?; let arguments_at = param(fb, P_ARGUMENTS_AT)?; - let extents_at = param(fb, P_EXTENTS_AT)?; let vertex_slots = param(fb, P_VERTEX_SLOTS)?; let fragment_slots = param(fb, P_FRAGMENT_SLOTS)?; let types = param(fb, P_TYPES)?; @@ -716,8 +710,7 @@ pub fn typed_module() -> BResult { let static_stride = k64(fb, u64::MAX)?; let bad_bindings = counter(fb, t, 0)?; let unresolved = counter(fb, t, 0)?; - let extents_off = wide(fb, t, extents_at)?; - let extents = fb.binary(BinOp::IAdd, resident, extents_off)?; + let view = roots::resident_view(fb, resident)?; let all = k32(fb, layout::ALL_BINDINGS as u32)?; count_loop(fb, t, all, |fb, n| { let n64 = wide(fb, t, n)?; @@ -785,7 +778,7 @@ pub fn typed_module() -> BResult { let counted = fb.binary(BinOp::LogicalAnd, counted, uncovered)?; let counted = fb.binary(BinOp::LogicalAnd, counted, own)?; let count: ArmFn<'_, ()> = Box::new(move |fb, _| { - let (_, _, hit) = resolved(fb, t, (resident, extents), address)?; + let (_, _, hit) = resolved(fb, (resident, &view), address)?; let missed = fb.unary(UnOp::LogicalNot, hit)?; let one = k32(fb, 1)?; let zero = k32(fb, 0)?; @@ -859,9 +852,7 @@ pub fn typed_module() -> BResult { let sink_entry = roots::SINK_ROOT * roots::ENTRY_BYTES; let sink_at = at(fb, resident, sink_entry + roots::HOST)?; let sink = load64(fb, t, sink_at)?; - let count_at = at(fb, resident, sink_entry + roots::RESIDENT_COUNT)?; - let resident_count = load64(fb, t, count_at)?; - let resident_first = at(fb, resident, 2 * roots::ENTRY_BYTES)?; + let resident_count = view.count; for (stage, table, slots) in [ (BufferStage::Vertex, vertex_table, vertex_slots), (BufferStage::Fragment, fragment_table, fragment_slots), @@ -870,8 +861,9 @@ pub fn typed_module() -> BResult { let a = at(fb, table, roots::NULL_ROOT * roots::ENTRY_BYTES + field)?; store64(fb, t, a, zero64)?; } - // `R0` of the slot table is the distance in entries from it to the resident set. - let distance = fb.binary(BinOp::ISub, resident_first, table)?; + // `R0` of the slot table is the distance in entries from it to the resident set the + // resident root table names, wherever it lies. + let distance = fb.binary(BinOp::ISub, view.set, table)?; let entry_shift = k64(fb, roots::ENTRY_BYTES.trailing_zeros().into())?; let r0 = fb.binary(BinOp::ShiftRightLogical, distance, entry_shift)?; for (field, v) in [ @@ -895,7 +887,7 @@ pub fn typed_module() -> BResult { let first_address = k64(fb, BufferBinding::MIN_BUFFER_ADDRESS)?; let bound = fb.binary(BinOp::UGreaterThanEqual, guest, first_address)?; let live = fb.binary(BinOp::LogicalAnd, runs, bound)?; - let (root, offset, hit) = resolved(fb, t, (resident, extents), guest)?; + let (root, offset, hit) = resolved(fb, (resident, &view), guest)?; let size = roots::entry_field(fb, resident, root, roots::SIZE)?; let missed = fb.unary(UnOp::LogicalNot, hit)?; let miss = fb.binary(BinOp::LogicalAnd, live, missed)?; diff --git a/crates/metal2vulkan/src/bind/replay/tests.rs b/crates/metal2vulkan/src/bind/replay/tests.rs index 18569b501..719fd4f08 100644 --- a/crates/metal2vulkan/src/bind/replay/tests.rs +++ b/crates/metal2vulkan/src/bind/replay/tests.rs @@ -435,7 +435,11 @@ fn the_layout_keeps_every_section_apart() { assert_eq!((l.slots, l.variants, l.regions), (5, 3, 2)); assert_eq!(l.table_offset(4) + SLOT_TABLE_BYTES, l.params_offset()); assert_eq!(pre.params.len() as u64, PARAMS_BYTES); - assert!(l.resident_offset + pre.resident.bytes.len() as u64 <= l.extents_offset); + // The extents right after the resident set, which ends the resident root table. + assert_eq!( + l.resident_offset + pre.resident.bytes.len() as u64, + l.extents_offset + ); assert!(l.extents_offset + pre.extents.len() as u64 <= l.variants_offset); assert!(l.variants_offset + pre.variants.len() as u64 <= l.parent_offset); assert!(l.parent_offset + pre.parent.len() as u64 <= l.regions_offset); @@ -453,7 +457,6 @@ fn the_layout_keeps_every_section_apart() { ); assert!(l.argument_offset(4, 1, 2) + ARGUMENT_BYTES <= l.bytes); for at in [ - l.extents_offset, l.variants_offset, l.parent_offset, l.regions_offset, @@ -470,8 +473,8 @@ fn the_layout_keeps_every_section_apart() { &pre.params[..12], [2u32, 5, 3].map(u32::to_le_bytes).concat().as_slice() ); - // One extent per root: none for the null and sink roots, then each allocation's own length - // (B's 60 bytes, not its padded 64). + // One extent per entry of the set, each allocation's own length (B's 60 bytes, not its padded + // 64), then the zero a search that found no entry reads. let extents: Vec = pre .extents .as_chunks::<8>() @@ -479,11 +482,7 @@ fn the_layout_keeps_every_section_apart() { .iter() .map(|c| u64::from_le_bytes(*c)) .collect(); - assert_eq!(extents, [0, 0, A.2, B.2]); - assert_eq!( - u64::from(word(&pre.params, P_EXTENTS_AT as usize)), - l.extents_offset - l.resident_offset - ); + assert_eq!(extents, [A.2, B.2, 0]); assert_eq!(word(&pre.params, P_REGIONS as usize), 2); assert_eq!( u64::from(word(&pre.params, P_REGIONS_AT as usize)), diff --git a/crates/metal2vulkan/src/bind/resident.rs b/crates/metal2vulkan/src/bind/resident.rs index 1887211f5..70cc35f77 100644 --- a/crates/metal2vulkan/src/bind/resident.rs +++ b/crates/metal2vulkan/src/bind/resident.rs @@ -106,9 +106,33 @@ fn resident_allocations(state: &BindState) -> impl Iterator Vec { - let mut ranges: Vec<(u128, u128)> = resident_allocations(state) - .filter(|&(_, _, length)| length > 0) - .map(|(_, guest, length)| (u128::from(guest), u128::from(guest) + u128::from(length))) + let allocations = resident_allocations(state).map(|(_, guest, length)| (guest, length)); + extents_of(allocations, resident) +} + +/// The unpadded extents a replay preprocess reads right after its resident set +/// (`memory::roots::ResidentView`): a `u64` per entry of `resident`, `state`'s resident set +/// ([`resident_extents`]), then one zero, which a search that found no entry reads. +pub(crate) fn replay_extents(state: &BindState, resident: &[RootEntry]) -> Vec { + extents_bytes(resident_extents(state, resident)) +} + +/// `extents`, little-endian, then one zero. +pub(crate) fn extents_bytes(extents: impl IntoIterator) -> Vec { + let mut bytes: Vec = extents.into_iter().flat_map(u64::to_le_bytes).collect(); + bytes.extend_from_slice(&0u64.to_le_bytes()); + bytes +} + +/// [`resident_extents`] of the entries `resident` over the allocations `allocations`, each its +/// `(guest, length)` at its own length. +pub(crate) fn extents_of( + allocations: impl Iterator, + resident: &[RootEntry], +) -> Vec { + let mut ranges: Vec<(u128, u128)> = allocations + .filter(|&(_, length)| length > 0) + .map(|(guest, length)| (u128::from(guest), u128::from(guest) + u128::from(length))) .collect(); ranges.sort_unstable(); // The furthest end of the allocations up to each one. diff --git a/crates/metal2vulkan/src/bind/resident/tests.rs b/crates/metal2vulkan/src/bind/resident/tests.rs index f041057bd..604380282 100644 --- a/crates/metal2vulkan/src/bind/resident/tests.rs +++ b/crates/metal2vulkan/src/bind/resident/tests.rs @@ -373,3 +373,47 @@ fn a_resident_set_holds_what_its_entries_resolve_alike() { assert_eq!(with.len(), 3); assert!(with.holds(&other) && with.holds(&own) && with.holds(&placed)); } + +/// What a consumer points a replay preprocess's resident root table at holds the set of its +/// ranges in their entries' layout, then each entry's unpadded extent, then a zero: the same +/// set, and the same extents, as the binder lays out after the table it builds of those +/// allocations, so a table pointed there resolves as the binder's own does. +#[test] +fn replay_bytes_are_the_binders_set_then_its_extents() { + use crate::bind::{ResidentRange, ResidentSet}; + // Three allocations, one inside another and one of a length the padding rounds up. + let ranges = [ + ResidentRange::new(0x9000, 0x1_0000_0000, 64), + ResidentRange::new(0x9010, 0x1_0000_0010, 16), + ResidentRange::new(0x5000, 0x2_0000_0000, 60), + ]; + let (bytes, count) = ResidentSet::replay_bytes(ranges); + let set = ResidentSet::new(ranges); + assert_eq!(count, set.len()); + assert_eq!(count, 2); + let entries = set.bytes(); + assert_eq!(&bytes[..entries.len()], &entries[..]); + let extents: Vec = bytes[entries.len()..] + .as_chunks::<8>() + .0 + .iter() + .map(|c| u64::from_le_bytes(*c)) + .collect(); + assert_eq!(extents, [64, 60, 0]); + let allocations = ranges.iter().map(|r| (r.guest, r.length)); + let entries: Vec = (set.bytes().as_chunks::<32>().0.iter()) + .map(|e| { + let field = |at: usize| u64::from_le_bytes(e[at..at + 8].try_into().unwrap()); + RootEntry { + host: field(0), + guest: field(8), + size: field(16), + bind_offset: field(24), + } + }) + .collect(); + assert_eq!( + extents_bytes(extents_of(allocations, &entries)), + bytes[set.bytes().len()..] + ); +} diff --git a/crates/metal2vulkan/src/memory/roots.rs b/crates/metal2vulkan/src/memory/roots.rs index 0c0104b88..e6df8663d 100644 --- a/crates/metal2vulkan/src/memory/roots.rs +++ b/crates/metal2vulkan/src/memory/roots.rs @@ -198,6 +198,65 @@ pub fn entry_field( ) } +/// The resident set a replay preprocess's resident root table at `table` names +/// (`bind::ReplayPreprocess::resident`, `bind::DrawReplayPreprocess::resident`): its first root +/// `R0` and count `N`, from the sink entry, which a consumer points anywhere +/// (`RootTable::resident_fields`), the set's address (`table + 32·R0`, modulo 2⁶⁴), and the +/// address of its entries' unpadded extents, a `u64` each, right after the set, then one zero +/// (`ResidentSet::replay_bytes`; the binder lays its own set out so). +#[derive(Clone, Copy)] +pub struct ResidentView { + pub first: Value, + pub count: Value, + pub set: Value, + pub extents: Value, +} + +/// [`ResidentView`] of the resident root table at `table`. +pub fn resident_view(fb: &mut FunctionBuilder<'_>, table: Value) -> BResult { + let e = entries(fb, table)?; + let sink = k64(fb, SINK_ROOT)?; + let first = field_of(fb, e, sink, RESIDENT_FIRST)?; + let count = field_of(fb, e, sink, RESIDENT_COUNT)?; + let stride = k64(fb, ENTRY_BYTES)?; + let skip = fb.binary(BinOp::IMul, first, stride)?; + let set = fb.binary(BinOp::IAdd, table, skip)?; + let bytes = fb.binary(BinOp::IMul, count, stride)?; + let extents = fb.binary(BinOp::IAdd, set, bytes)?; + Ok(ResidentView { + first, + count, + set, + extents, + }) +} + +/// The unpadded extent of root `root` of `view`'s set, which a search of it found where `found` +/// holds; where it does not, the first entry's (or the zero after an empty set's), a read that +/// stays in the set's bytes and that the caller's test of `found` discards. +pub fn extent_of( + fb: &mut FunctionBuilder<'_>, + view: &ResidentView, + root: Value, + found: Value, +) -> BResult { + let index = fb.binary(BinOp::ISub, root, view.first)?; + let zero = k64(fb, 0)?; + let index = fb.select(found, index, zero)?; + let eight = k64(fb, 8)?; + let rel = fb.binary(BinOp::IMul, index, eight)?; + let addr = fb.binary(BinOp::IAdd, view.extents, rel)?; + let u64_ = u64_ty(fb)?; + let p = fb.device_place(addr, u64_)?; + fb.load( + p, + MemAccess { + aligned: Some(8), + ..MemAccess::default() + }, + ) +} + /// Define the module's resident-set search: a function `fn(table: u64, guest: u64) -> wide` /// (`wide` a `u64vec2`), the wide pointer `(root, offset)` of `guest` through the root table at /// `table` ([`resolve`]). Every search of the module calls it, so its words are paid once. diff --git a/docs/API.md b/docs/API.md index ffaebd3e3..d41eed62d 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1794,8 +1794,7 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. (EncodedUseRebound), where Metal resolves the use as it submits the command buffer and reaches the pages the buffer lies in then; the rebind encodes compute, blit and render encoders again, but not this one. The reason names where the first such submission found the use (the encoder; its own - commands, work it left for later, or the resident set work on the GPU alone resolved at the - commit) and why no rebind encoded or recorded it again. + commands or work it left for later) and why no rebind encoded or recorded it again. - `metal2vulkan-degrade-stale-detached-reach` (precision). `StaleDetachedReach`: A command buffer that bound a heap set, whose commands may reach any texture through its resource ID without naming it, was submitted while a texture's bytes (a no-copy buffer's or heap's, the texture over them or