From aee29a3bbbd2e18b2a759ca5672eee7dfc88d961 Mon Sep 17 00:00:00 2001 From: Tyler Smith <74526874+tylertms@users.noreply.github.com> Date: Sat, 14 Nov 2026 06:17:41 -0500 Subject: [PATCH] fix(gpu): finish a getBytes of a texture only host image copies reach outside the turn, each band's GPU copy answered Pending and copied to the caller from the published completion, where one 705,600-byte read held every process's calls for 623 ms and the display stuttered --- crates/stela-driver-gpu/src/metal/service.rs | 26 ++ .../src/metal/service/resources.rs | 29 +- .../src/metal/service/shared.rs | 39 ++ .../src/metal/service/shared/read_back.rs | 338 ++++++++++++++++++ .../src/metal/service/tests/gate.rs | 118 ++++++ 5 files changed, 548 insertions(+), 2 deletions(-) create mode 100644 crates/stela-driver-gpu/src/metal/service/shared/read_back.rs diff --git a/crates/stela-driver-gpu/src/metal/service.rs b/crates/stela-driver-gpu/src/metal/service.rs index 3f5aac12c6..353fb44a6f 100644 --- a/crates/stela-driver-gpu/src/metal/service.rs +++ b/crates/stela-driver-gpu/src/metal/service.rs @@ -138,6 +138,20 @@ pub struct StagedLibrary { pub digest: [u8; 32], } +/// A band of a `GetBytes` call whose GPU copy into host memory started +/// ([`crate::metal::device::resources::ReadBack`]): the shared service waits for it and +/// copies it to the caller outside the turn, then starts the next band in +/// the call's next turn. +pub struct StartedReadBack { + pub read_back: crate::metal::device::resources::ReadBack, + /// The band's index among the call's bands and its span of the caller's + /// bytes. + pub band: usize, + pub span: Span, + /// Whether no band follows it. + pub last: bool, +} + /// A device object a connection holds. #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] enum Object { @@ -353,6 +367,15 @@ pub struct Service { /// hold: its bytes are read again before the call's next turn, and the /// call is answered `Pending`. library_wanted: Option, + /// Whether a `GetBytes` call of a texture only host image copies reach + /// is answered `Pending` once the GPU copy of its next band starts + /// ([`StartedReadBack`]), for the shared service to finish outside the + /// turn; otherwise the call reads the image itself. + reads_back: bool, + /// The band of the call served now that its read-backs reached. + read_back_from: Option, + /// The read-back the call served now started. + read_back_started: Option, reopen: Option>, prepare: Option>, } @@ -375,6 +398,9 @@ impl Service { pins_reported: false, staged_library: None, library_wanted: None, + reads_back: false, + read_back_from: None, + read_back_started: None, reopen: None, prepare: None, } diff --git a/crates/stela-driver-gpu/src/metal/service/resources.rs b/crates/stela-driver-gpu/src/metal/service/resources.rs index 40411dc81f..86f90b50e3 100644 --- a/crates/stela-driver-gpu/src/metal/service/resources.rs +++ b/crates/stela-driver-gpu/src/metal/service/resources.rs @@ -1,6 +1,6 @@ //! Buffers, textures, samplers and heaps. use super::{ - Call, Object, Service, boolean, region, + Call, Object, Service, StartedReadBack, boolean, region, wire::{ AUTOMATIC, BufferRangeRequest, BufferResponse, Empty, Fault, FormatAlignmentsResponse, Handle, HeapBufferSizeRequest, HeapDescriptorRecord, HeapUsageRequest, HeapUsageResponse, @@ -209,7 +209,32 @@ impl Service { bytes: transfer.bands.iter().map(|(_, span)| span.length).sum(), }, ); - for (region, span) in transfer.bands { + // The bands before it were copied to the caller already. + let (from, count) = ( + self.read_back_from.take().unwrap_or(0), + transfer.bands.len(), + ); + for (band, (region, span)) in transfer.bands.into_iter().enumerate().skip(from) { + if self.reads_back { + let length = usize::try_from(span.length) + .map_err(|_| Fault::malformed("span length").value(span.length))?; + let started = self.device.begin_read_back( + call.connection.get(), + transfer.texture, + ®ion, + transfer.strides, + length, + )?; + if let Some(read_back) = started { + self.read_back_started = Some(StartedReadBack { + read_back, + band, + span, + last: band + 1 == count, + }); + return Err(Fault::new(Status::Pending, "")); + } + } let start = self.device.timing().now(); let mut bytes = call.memory.read(span)?; self.device.timing().since(Phase::BytesRead, start); diff --git a/crates/stela-driver-gpu/src/metal/service/shared.rs b/crates/stela-driver-gpu/src/metal/service/shared.rs index 102782b5d8..f1a3236a4f 100644 --- a/crates/stela-driver-gpu/src/metal/service/shared.rs +++ b/crates/stela-driver-gpu/src/metal/service/shared.rs @@ -89,6 +89,9 @@ use core::{ use stela_contracts::gate::{BundleReport, CallerFault, CallerMemory, GateService, MemoryRange}; use stela_crypto::{Sha256, digest::Digest}; +mod read_back; +use read_back::{ReadBacks, Step}; + pub struct SharedService { service: UnsafeCell>, locked: AtomicBool, @@ -162,6 +165,8 @@ pub struct SharedService { /// while it is not zero no poll is answered from the published serial, /// which cannot say which command buffer failed. refusals: Arc, + /// `GetBytes` calls whose GPU copies are finished outside the turn. + read_backs: ReadBacks, host: ServiceHost, } @@ -661,7 +666,13 @@ impl SharedService { let lock = compile_lock.clone(); let relax = host.relax; let counted = refusals.clone(); + // Texture reads copy out of host memory outside the turn; none + // outlives the lost device's memory. + service.reads_back = true; + let read_backs = ReadBacks::new(); + let generation = read_backs.generation.clone(); service.prepare_reopened(Box::new(move |device| { + generation.end(); device.count_failures(&counted); if let Some(lock) = &lock && let Some(compiler) = air(device.compiler_mut()) @@ -708,6 +719,7 @@ impl SharedService { upkeep_asked: AtomicBool::new(false), look_budget: AtomicU64::new(0), refusals, + read_backs, host, } } @@ -1466,8 +1478,10 @@ impl GateService for SharedServ }); self.staging .with(|staging| staging.retain(|staged| staged.connection != connection.get())); + self.forget_read_backs(connection); // The gate closes only connections it opened and holds. let closed = self.call(|service| { + self.free_read_backs(service); for slot in &self.polling { let _ = slot.compare_exchange(connection.get(), 0, Ordering::AcqRel, Ordering::Acquire); @@ -1504,6 +1518,16 @@ impl GateService for SharedServ served_at_once(operation, Status::Pending); return Ok(()); } + // A texture read's band whose GPU copy completed is copied to the + // caller here, holding no turn. + let read_back_from = match self.read_back_step(connection, record, caller)? { + Step::Not => None, + Step::From(band) => Some(band), + Step::Answered(status) => { + served_at_once(Operation::GetBytes.raw(), status); + return Ok(()); + } + }; // A poll answers from the completion a turn or the waiter published, // whether or not a call holds the service: a turn would ask the // device again, a timeline query the host's Linux environment @@ -1530,6 +1554,9 @@ impl GateService for SharedServ let Some(mut turn) = self.turn_within(rang) else { // Nothing of the call ran: it is made again once the frontend // has had its processor back. + if let Some(band) = read_back_from { + self.resume_read_back(connection, record, caller, band); + } let call = read_record(record, caller)?; answer_pending(record, call, caller)?; let left = (self.host.ticks)(); @@ -1554,8 +1581,10 @@ impl GateService for SharedServ turn.catch_up(); let job_lock = deferring.then_some(&self.job_lock); let mut answer = None; + let mut read_back = None; self.job_lock.lock.set_deferred(false); (self.host.run)(self.host.stack, &mut || { + self.free_read_backs(&mut turn); self.adopt_jobs(&mut turn); turn.device().compiler_mut().defer_compiles(deferring); turn.device().backend().defer_pipelines(job_lock); @@ -1566,7 +1595,14 @@ impl GateService for SharedServ if staged { turn.staged_library = self.staged_library(connection, record); } + turn.read_back_from = read_back_from; let served = turn.serve(connection, record, &mut deferrable); + turn.read_back_from = None; + // Read while the turn holds the device it came from. + read_back = turn + .read_back_started + .take() + .map(|started| (started, self.read_backs.generation.current())); turn.staged_library = None; if let Some(span) = turn.library_wanted.take() { self.keep_library(connection, record, span); @@ -1592,6 +1628,9 @@ impl GateService for SharedServ }); let (mut served, mut refused, noted, (mut operation, mut status), jobs) = answer.expect("the platform runs what it is given"); + if let Some((started, epoch)) = read_back { + self.started_read_back(connection, record, caller, started, epoch); + } if !jobs.is_empty() { // The call left nothing but the compilation: it is answered // `Pending`, and made again once the job has run. diff --git a/crates/stela-driver-gpu/src/metal/service/shared/read_back.rs b/crates/stela-driver-gpu/src/metal/service/shared/read_back.rs new file mode 100644 index 0000000000..e521148762 --- /dev/null +++ b/crates/stela-driver-gpu/src/metal/service/shared/read_back.rs @@ -0,0 +1,338 @@ +//! `GetBytes` calls finished outside the turn. +//! +//! A texture only host image copies reach lies in device memory the host +//! maps uncached, which a CPU read crosses at about a megabyte a second. +//! Its call's turn starts a GPU copy of the next band into host-cached +//! memory ([`crate::metal::device::resources::ReadBack`]) and answers the +//! call `Pending`. The call made again finds the copy complete from the +//! published completion, holding no turn, and copies the band to its caller +//! outside every lock; a band after it starts in the call's next turn. No +//! other process's call waits for the copy or for the CPU's. +use super::{ + POLL_UNAVAILABLE, SharedService, Spin, answer, answer_pending, read_call, read_record, +}; +use crate::metal::{ + device::resources::ReadBack, + service::{Service, StartedReadBack, wire::Status}, + shader::Compiler, + vulkan::backend::Backend, +}; +use alloc::{sync::Arc, vec::Vec}; +use core::{ + num::NonZeroU64, + sync::atomic::{AtomicU32, AtomicU64, Ordering}, +}; +use stela_contracts::gate::{CallerFault, CallerMemory}; + +/// More calls than wait for their read-backs at once: past this the oldest +/// is forgotten, and made again it reads from its first band. +pub(super) const WAITING: usize = 32; + +/// The read-backs of calls answered `Pending`, and those copied out, whose +/// memory the next turn frees. +pub(super) struct ReadBacks { + waiting: Spin>, + spent: Spin>, + pub(super) generation: Arc, +} + +impl ReadBacks { + pub(super) fn new() -> Self { + Self { + waiting: Spin::new(Vec::new()), + spent: Spin::new(Vec::new()), + generation: Arc::new(Generation::default()), + } + } +} + +/// A `GetBytes` call answered `Pending`, by its connection, record, +/// operation and request, which the frontend calls again with. +struct Waiting { + key: (u64, u64, u32, u64), + /// The device's [`Generation`] when the read-back started. + epoch: u64, + state: State, +} + +enum State { + /// The band's copy runs or ran. + Copying(StartedReadBack), + /// The bands before this one were copied to the caller: the next turn + /// starts its copy. + From(usize), +} + +/// The generation of the device read-backs come from, and the processors +/// copying out of one now. A device reopened after a loss ends the +/// generation before the lost device goes, waiting for those processors, +/// so no copy outlives the memory, and nothing of it is freed on its +/// successor. +#[derive(Default)] +pub(crate) struct Generation { + epoch: AtomicU64, + readers: AtomicU32, +} + +impl Generation { + pub(super) fn current(&self) -> u64 { + self.epoch.load(Ordering::SeqCst) + } + + /// The device of this generation goes: once no processor copies out of + /// its memory. + pub(crate) fn end(&self) { + self.epoch.fetch_add(1, Ordering::SeqCst); + while self.readers.load(Ordering::SeqCst) != 0 { + core::hint::spin_loop(); + } + } + + /// Runs `body` unless the device of generation `epoch` went. + fn read(&self, epoch: u64, body: impl FnOnce() -> R) -> Option { + self.readers.fetch_add(1, Ordering::SeqCst); + let result = (self.epoch.load(Ordering::SeqCst) == epoch).then(body); + self.readers.fetch_sub(1, Ordering::SeqCst); + result + } +} + +/// What a call's read-back answered before its turn. +pub(super) enum Step { + /// The call has none: its turn serves it. + Not, + /// The call was answered. + Answered(Status), + /// The call's bands before this one reached its caller: its turn + /// starts the copy of this one. + From(usize), +} + +impl SharedService { + /// Finishes the read-back of the call at `record` when its copy + /// completed, outside every lock, or answers it `Pending` when the copy + /// runs. A call with no read-back is left to its turn. + pub(super) fn read_back_step( + &self, + connection: NonZeroU64, + record: u64, + caller: &mut dyn CallerMemory, + ) -> Result { + if self.read_backs.waiting.with(|waiting| waiting.is_empty()) { + return Ok(Step::Not); + } + let Some(call) = read_call(record, caller) else { + return Ok(Step::Not); + }; + let key = ( + connection.get(), + record, + call.operation, + call.request.address, + ); + let found = self.read_backs.waiting.with(|waiting| { + let at = waiting.iter().position(|entry| entry.key == key)?; + Some(waiting.remove(at)) + }); + let Some(waiting) = found else { + return Ok(Step::Not); + }; + let started = match waiting.state { + State::From(band) => return Ok(Step::From(band)), + State::Copying(started) => started, + }; + let epoch = waiting.epoch; + match self.read_back_done(epoch, &started.read_back) { + Some(true) => {} + Some(false) => { + self.wait(key, epoch, State::Copying(started)); + answer_pending(record, call, caller)?; + return Ok(Step::Answered(Status::Pending)); + } + // The device was lost or replaced: the call's turn answers it. + None => { + self.retire_read_back(epoch, started.read_back); + return Ok(Step::Not); + } + } + let span = started.span; + let copied = self.read_backs.generation.read(epoch, || { + started + .read_back + .write_out(|offset, bytes| caller.write(span.address.wrapping_add(offset), bytes)) + }); + let status = match copied { + None => { + self.retire_read_back(epoch, started.read_back); + return Ok(Step::Not); + } + Some(Ok(())) => { + let (next, last) = (started.band + 1, started.last); + self.retire_read_back(epoch, started.read_back); + if !last { + return Ok(Step::From(next)); + } + Status::Ok + } + // The frontend maps the span and calls again: the copy stays. + Some(Err(CallerFault::Denied { .. })) => { + self.wait(key, epoch, State::Copying(started)); + Status::Unmapped + } + Some(Err(fault)) => { + self.retire_read_back(epoch, started.read_back); + match fault { + CallerFault::Unsupported(_) => Status::Unsupported, + _ => Status::Malformed, + } + } + }; + answer(record, call, status, caller)?; + Ok(Step::Answered(status)) + } + + /// Whether `read_back`'s copy completed: from the published completion + /// when it shows, else from a turn's poll unless a call holds the + /// service. `None` once its device was lost or replaced. + fn read_back_done(&self, epoch: u64, read_back: &ReadBack) -> Option { + if self.read_backs.generation.current() != epoch { + return None; + } + self.publish_marker(); + let reached = self.reached.load(Ordering::Acquire); + if reached != POLL_UNAVAILABLE && reached >= read_back.serial() { + return Some(true); + } + // A waiter publishes it, with no driver query here. + if reached != POLL_UNAVAILABLE && self.publishable.load(Ordering::Acquire) { + return Some(false); + } + let Some(mut turn) = self.try_turn() else { + return Some(false); + }; + if self.read_backs.generation.current() != epoch { + return None; + } + let mut done = Ok(false); + (self.host.run)(self.host.stack, &mut || { + done = turn.device().read_back_complete(read_back); + }); + drop(turn); + done.ok() + } + + /// Keeps the call of `key` waiting in `state`: past [`WAITING`] calls + /// the oldest is forgotten. + fn wait(&self, key: (u64, u64, u32, u64), epoch: u64, state: State) { + let forgotten = self.read_backs.waiting.with(|waiting| { + let forgotten = (waiting.len() >= WAITING).then(|| waiting.remove(0)); + waiting.push(Waiting { key, epoch, state }); + forgotten + }); + if let Some(Waiting { + epoch, + state: State::Copying(started), + .. + }) = forgotten + { + self.retire_read_back(epoch, started.read_back); + } + } + + /// Keeps the read-back the call at `record` started in its turn, which + /// answered it `Pending`, of the device of generation `epoch`. + pub(super) fn started_read_back( + &self, + connection: NonZeroU64, + record: u64, + caller: &mut dyn CallerMemory, + started: StartedReadBack, + epoch: u64, + ) { + match read_record(record, caller) { + Ok(call) => self.wait( + ( + connection.get(), + record, + call.operation, + call.request.address, + ), + epoch, + State::Copying(started), + ), + Err(_) => self.retire_read_back(epoch, started.read_back), + } + } + + /// The bands before `band` of the call at `record` reached its caller, + /// which a turn did not serve: the call made again starts at `band`. + pub(super) fn resume_read_back( + &self, + connection: NonZeroU64, + record: u64, + caller: &mut dyn CallerMemory, + band: usize, + ) { + if let Some(call) = read_call(record, caller) { + let key = ( + connection.get(), + record, + call.operation, + call.request.address, + ); + let epoch = self.read_backs.generation.current(); + self.wait(key, epoch, State::From(band)); + } + } + + fn retire_read_back(&self, epoch: u64, read_back: ReadBack) { + self.read_backs + .spent + .with(|spent| spent.push((epoch, read_back))); + } + + /// Forgets `connection`'s read-backs: it closed. + pub(super) fn forget_read_backs(&self, connection: NonZeroU64) { + let mut forgotten = Vec::new(); + self.read_backs.waiting.with(|waiting| { + waiting.retain_mut(|entry| { + let keep = entry.key.0 != connection.get(); + if !keep { + let state = core::mem::replace(&mut entry.state, State::From(0)); + if let State::Copying(started) = state { + forgotten.push((entry.epoch, started.read_back)); + } + } + keep + }); + }); + self.read_backs.spent.with(|spent| spent.extend(forgotten)); + } + + /// Frees the memory of read-backs copied out or forgotten, in a turn on + /// the service's stack. Those of a device since replaced went with it. + pub(super) fn free_read_backs(&self, service: &mut Service) { + let spent = self.read_backs.spent.with(core::mem::take); + let epoch = self.read_backs.generation.current(); + for (made, read_back) in spent { + if made == epoch { + service.device().end_read_back(read_back); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::Generation; + + #[test] + fn no_copy_outlives_its_generation() { + let generation = Generation::default(); + let epoch = generation.current(); + assert_eq!(generation.read(epoch, || 7), Some(7)); + generation.end(); + assert_eq!(generation.read(epoch, || 7), None, "its device went"); + assert_eq!(generation.read(generation.current(), || 7), Some(7)); + } +} diff --git a/crates/stela-driver-gpu/src/metal/service/tests/gate.rs b/crates/stela-driver-gpu/src/metal/service/tests/gate.rs index 23e72f773c..62d7811355 100644 --- a/crates/stela-driver-gpu/src/metal/service/tests/gate.rs +++ b/crates/stela-driver-gpu/src/metal/service/tests/gate.rs @@ -1229,3 +1229,121 @@ fn a_held_library_is_shared_without_a_block_of_its_size() { assert_eq!(call.status, Status::OutOfMemory.raw()); assert_ne!(refused, 0); } + +/// A texture only host image copies reach is read by a GPU copy into host +/// memory: the call's turn starts each band's copy and answers `Pending`, +/// and the call made again copies the band to its caller from the published +/// completion, holding no turn, while another call holds the service. +#[test] +fn a_texture_read_waits_for_its_gpu_copy_and_copies_out_holding_no_turn() { + use crate::metal::{ + abi::StorageMode, + device::resources::CPU_BAND_BYTES, + service::wire::{Empty, RegionRecord, TextureBytesRequest, TextureResponse}, + vulkan::backend::Object, + }; + let shared = SharedService::new(service(), HOST); + let connection = connect(&mut shared.try_turn().unwrap()); + let mut memory = Memory::default(); + let texture: TextureResponse = super::call( + &mut shared.try_turn().unwrap(), + connection, + Operation::NewTexture, + &super::texture(StorageMode::Shared), + &mut memory, + ) + .unwrap(); + // Two rows of eight texels, written whole. The test's GPU copies an + // image from its start, so the rows are alike; each band's copy names + // its own row. + let written: alloc::vec::Vec = (0..64).map(|byte| byte % 32).collect(); + let region = RegionRecord { + slice: 0, + level: 0, + origin: [0; 3], + size: [8, 2, 1], + }; + let replace = TextureBytesRequest { + texture: texture.handle, + region, + bytes: memory.put(&written), + bytes_per_row: 32, + bytes_per_image: 0, + }; + let _: Empty = super::call( + &mut shared.try_turn().unwrap(), + connection, + Operation::ReplaceRegion, + &replace, + &mut memory, + ) + .unwrap(); + // Rows a band apart: each is a band of its own. + let apart = CPU_BAND_BYTES as usize; + let read = TextureBytesRequest { + bytes: memory.put(&alloc::vec![0xee; apart + 32]), + bytes_per_row: CPU_BAND_BYTES, + ..replace + }; + let record = gate_call(&mut memory, Operation::GetBytes, wire::bytes(&read), 0); + let serve = |memory: &mut Memory| { + GateService::serve(&shared, connection, record, memory).unwrap(); + completed(memory, record).status + }; + // `HOST.relax` panics: a call that waited for the holder would fail. + let serve_held = |memory: &mut Memory| { + let held = shared.try_turn().unwrap(); + let status = serve(memory); + drop(held); + status + }; + let finish = || { + shared.try_turn().unwrap().device().backend().finish(); + shared.interrupted(); + }; + // The first band's turn starts its copy. + assert_eq!(serve(&mut memory), Status::Pending.raw()); + assert_eq!(serve_held(&mut memory), Status::Pending.raw(), "copy runs"); + finish(); + // Copied out, and the next band's copy starts in the call's turn. + assert_eq!(serve(&mut memory), Status::Pending.raw()); + let bytes = GuestMemory::read(&mut memory, read.bytes).unwrap(); + assert_eq!(bytes[..32], written[..32]); + assert_eq!(serve_held(&mut memory), Status::Pending.raw(), "copy runs"); + finish(); + // The last band is copied out holding no turn. + assert_eq!(serve_held(&mut memory), Status::Ok.raw()); + let rows: alloc::vec::Vec<(i32, [u32; 3])> = shared + .try_turn() + .unwrap() + .device() + .backend() + .submissions + .iter() + .flatten() + .flat_map(|segment| &segment.commands) + .filter_map(|command| match command { + crate::metal::vulkan::command::Command::CopyImageToBuffer { region, .. } => { + Some((region.offset[1], region.extent)) + } + _ => None, + }) + .collect(); + assert_eq!(rows, [(0, [8, 1, 1]), (1, [8, 1, 1])]); + let bytes = GuestMemory::read(&mut memory, read.bytes).unwrap(); + assert_eq!(bytes[..32], written[..32]); + assert_eq!(bytes[32..apart], alloc::vec![0xee; apart - 32][..]); + assert_eq!(bytes[apart..], written[32..]); + // The memory copied out of is freed by the next turn. + GateService::disconnect(&shared, connection); + let freed = shared + .try_turn() + .unwrap() + .device() + .backend() + .destroyed + .iter() + .filter(|object| matches!(object, Object::Buffer(_))) + .count(); + assert_eq!(freed, 2, "both bands' host memory"); +}