diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs index bd3fb28fc..d61b49019 100644 --- a/crates/metal2vulkan-runtime/src/device/mod.rs +++ b/crates/metal2vulkan-runtime/src/device/mod.rs @@ -208,8 +208,9 @@ pub(super) struct DeviceShared { /// reserved queue this modulo their number. presenting_made: AtomicU64, /// Whether its command queues share `VkQueue`s, and its check's verdict - /// (`queue_share.rs`). - pub(crate) queue_switch: crate::queue_share::QueueSwitch, + /// (`queue_share.rs`). Shared with the check's thread, which holds no device handle + /// (`queue_switch_check.rs`). + pub(crate) queue_switch: Arc, /// The compile-and-plan device: the description restricted to what is enabled. compile: metal2vulkan::device::Device, /// What `compile`'s profile takes of viewport depth ranges past `[0, 1]`, which draws read @@ -308,12 +309,16 @@ pub(super) struct DeviceShared { nudge: vk::Semaphore, pub(super) completion: Completion, /// The idle fences the batches that end command buffers signal (`command_buffer/fences.rs`). - pub(super) fences: Fences, + /// Shared with the queue-switch check's thread, whose uses of a queue take them where its + /// failures are relayed (`queue_switch_check.rs`). + pub(super) fences: Arc, /// The queues' serial contexts: every command buffer's transitions and handlers run there, /// and the releases handed off a thread that may run none of the program's code /// ([`Device::let_go_elsewhere`]). pub(super) contexts: Contexts, - loader_word: LoaderWord, + /// Shared with the queue-switch check's thread, which allocates command buffers + /// (`queue_switch_check.rs`). + pub(super) loader_word: Arc, /// The runtime created the `VkDevice` and destroys it. owned: bool, /// The device was lost: no further submission. Shared with the relay (`relay.rs`), which @@ -522,8 +527,9 @@ pub(super) struct DeviceShared { /// The rooms of the draws its render encoders kept for instances recorded inline after a /// split, which the next such instances take (`render/inline_splits.rs`). pub(super) kept_rooms: crate::render::SpareKept, - /// Counts of its commit path's work, for the lanes (`work_counts.rs`). - pub(super) counts: super::work_counts::Counters, + /// Counts of its commit path's work, for the lanes (`work_counts.rs`). Shared with the + /// queue-switch check's thread (`queue_switch_check.rs`). + pub(super) counts: Arc, /// Where the driver fails pending work as memory a device-address buffer lay in is freed, /// the record of its batches the memory's blocks that go wait by (`freed_memory.rs`). pub(crate) parking: OnceLock>, @@ -737,6 +743,9 @@ impl Drop for DeviceShared { let Some(_busy) = exit_guard::enter() else { return; }; + // The queue-switch check holds nothing of the device either: it stops at its next step, + // and its objects go before the wait returns (`queue_switch_check.rs`). + self.queue_switch.stop(); // The watch of the program's marks and the releases of freed memory, posted to the // handler threads, hold nothing of the device: those that begin from here on call // nothing, and the threads' stop below waits for those running (`freed_memory.rs`). @@ -1898,7 +1907,9 @@ impl Device { queue_families, round_robin_made: AtomicU64::new(0), presenting_made: AtomicU64::new(0), - queue_switch: crate::queue_share::QueueSwitch::new(compile.policy().queue_sharing), + queue_switch: Arc::new(crate::queue_share::QueueSwitch::new( + compile.policy().queue_sharing, + )), compile, depth_ranges, enabled, @@ -1943,9 +1954,9 @@ impl Device { scheduler, nudge, completion, - fences: Fences::default(), + fences: Arc::default(), contexts, - loader_word, + loader_word: Arc::new(loader_word), owned, lost, textures, diff --git a/crates/metal2vulkan-runtime/src/device/relay.rs b/crates/metal2vulkan-runtime/src/device/relay.rs index 174026986..e333f0a44 100644 --- a/crates/metal2vulkan-runtime/src/device/relay.rs +++ b/crates/metal2vulkan-runtime/src/device/relay.rs @@ -437,6 +437,42 @@ impl super::DeviceShared { /// program's); once the process is exiting no mark is made. A use of `uses` /// [`Uses::OneSignalling`] is counted in the queue's place in its driver's period of stalls /// (`submit_stalls.rs`); any other, or one with a mark, forgets the place. + pub(crate) fn use_queue( + &self, + queue: usize, + by: By, + uses: Uses, + f: impl FnOnce(vk::Queue) -> R, + ) -> R { + self.queue_uses().use_queue(queue, by, uses, f) + } + + /// What its uses of a queue outside a batch reach ([`QueueUses`]), borrowed from it. + pub(crate) fn queue_uses(&self) -> QueueUses<'_> { + QueueUses { + queues: &self.queues, + parking: self.parking.get().map(|parking| &**parking), + counts: &self.counts, + fences: &self.fences, + functions: &self.functions, + } + } +} + +/// What a use of a device's `VkQueue` outside a batch reaches ([`QueueUses::use_queue`]): its +/// queues, its parking, its counts, its fences and its functions. Borrowed from the device +/// ([`DeviceShared::queue_uses`](super::DeviceShared::queue_uses)), or from the shares of them +/// the queue-switch check holds, which hold no device (`queue_switch_check.rs`). +pub(crate) struct QueueUses<'a> { + pub(crate) queues: &'a [super::QueueSlot], + pub(crate) parking: Option<&'a crate::freed_memory::Parking>, + pub(crate) counts: &'a crate::work_counts::Counters, + pub(crate) fences: &'a crate::command_buffer::fences::Fences, + pub(crate) functions: &'a Functions, +} + +impl QueueUses<'_> { + /// [`DeviceShared::use_queue`](super::DeviceShared::use_queue), over what it reaches. pub(crate) fn use_queue( &self, queue: usize, @@ -446,7 +482,7 @@ impl super::DeviceShared { ) -> R { let slot = &self.queues[queue]; let flights = slot.flights.get(); - let parking = (self.parking.get()).filter(|_| matches!(by, By::Program)); + let parking = self.parking.filter(|_| matches!(by, By::Program)); if flights.is_none() && parking.is_none() { return match uses { Uses::Unknown => slot.with(f), @@ -469,7 +505,7 @@ impl super::DeviceShared { } let fence = flights.and_then(|flights| { exit_guard::enter().and_then(|_busy| { - let raw = self.vk(); + let raw = self.functions.get(); let mut done = flights.done_marks(); if !done.is_empty() { // SAFETY: each is signaled, its submission completed, and out of the log. @@ -492,13 +528,13 @@ impl super::DeviceShared { // Taken before `f` submits: a block that goes meanwhile waits for the mark. let mark = parking.and_then(|parking| { let _busy = exit_guard::enter()?; - parking.program_use(queue, self.vk()) + parking.program_use(queue, self.functions.get()) }); let used = f(vk_queue); let Some(_busy) = exit_guard::enter() else { return used; }; - let raw = self.vk(); + let raw = self.functions.get(); let logged = fence.zip(flights); if let Some((fence, flights)) = logged { flights.push(fence, by); diff --git a/crates/metal2vulkan-runtime/src/freed_memory.rs b/crates/metal2vulkan-runtime/src/freed_memory.rs index 8622dc90b..5f56bee2e 100644 --- a/crates/metal2vulkan-runtime/src/freed_memory.rs +++ b/crates/metal2vulkan-runtime/src/freed_memory.rs @@ -569,7 +569,7 @@ pub(crate) mod held { } /// Let them go once `closed` is set, or once they were let go already. - pub(super) fn release_once(&self, closed: &AtomicBool) { + pub(crate) fn release_once(&self, closed: &AtomicBool) { while !closed.load(Ordering::SeqCst) && lock(&self.state).0 { std::thread::sleep(Duration::from_millis(1)); } diff --git a/crates/metal2vulkan-runtime/src/queue_share.rs b/crates/metal2vulkan-runtime/src/queue_share.rs index 8a1628784..370b6328d 100644 --- a/crates/metal2vulkan-runtime/src/queue_share.rs +++ b/crates/metal2vulkan-runtime/src/queue_share.rs @@ -321,7 +321,8 @@ impl Verdict { } /// A device's sharing (`DeviceShared::queue_switch`): its policy, its check's verdict and the switch -/// cost it measured, and whether the check started and settled. +/// cost it measured, whether the check started and settled, and whether its thread runs, which +/// the device's teardown stops and waits for (`queue_switch_check.rs`). pub(crate) struct QueueSwitch { /// The device's policy is `Adaptive`. adaptive: bool, @@ -334,6 +335,20 @@ pub(crate) struct QueueSwitch { wake: Condvar, /// The check's run in this process, in nanoseconds; 0 where none ended. took: AtomicU64, + /// The check's thread runs: from before it is spawned until it let go of its objects and of + /// its shares of the device's parts ([`began`](Self::began), [`ended`](Self::ended)). + running: Mutex, + /// Signalled as the check's thread ends. + ending: Condvar, + /// The device's teardown began: the check stops at its next step ([`stop`](Self::stop)). + stopping: AtomicBool, + /// How long the teardown waited for the check's thread to end, in nanoseconds: 0 where it + /// waited for none. + stop_waited: AtomicU64, + /// The crate's device tests' hold of the check between its rounds + /// (`tests/teardown_threads.rs`). + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + pub(crate) held: crate::freed_memory::held::Held, } impl QueueSwitch { @@ -347,6 +362,12 @@ impl QueueSwitch { settled: Mutex::new(false), wake: Condvar::new(), took: AtomicU64::new(0), + running: Mutex::new(false), + ending: Condvar::new(), + stopping: AtomicBool::new(false), + stop_waited: AtomicU64::new(0), + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + held: Default::default(), } } @@ -366,6 +387,74 @@ impl QueueSwitch { !self.started.swap(true, Ordering::AcqRel) } + /// Settle the verdict as [`settle`](Self::settle) does, where it shares now with `slots`, the + /// round robin's `VkQueue`s, keeping their times from here on ([`SlotShare::watched`]). + pub(crate) fn settle_over( + &self, + slots: &[QueueSlot], + verdict: Verdict, + cost: i64, + took: Option, + ) { + if self.adaptive && verdict == Verdict::Idles { + for slot in slots { + slot.share.watched.store(true, Ordering::Relaxed); + } + } + self.settle(verdict, cost, took); + } + + /// The check's thread is about to be spawned: it runs until [`ended`](Self::ended). + pub(crate) fn began(&self) { + *lock(&self.running) = true; + } + + /// The check's thread let go of its objects and of its shares of the device's parts (or was + /// never spawned). + pub(crate) fn ended(&self) { + *lock(&self.running) = false; + self.ending.notify_all(); + } + + /// Whether the device's teardown began, so the check stops at its next step. + pub(crate) fn stopping(&self) -> bool { + self.stopping.load(Ordering::SeqCst) + } + + /// The device's teardown: the check stops at its next step, and this waits until its thread + /// ended, which holds no device handle, so never runs this teardown (`queue_switch_check.rs`). + pub(crate) fn stop(&self) { + self.stopping.store(true, Ordering::SeqCst); + let mut running = lock(&self.running); + if !*running { + return; + } + let waiting = Instant::now(); + while *running { + running = + (self.ending.wait(running)).unwrap_or_else(std::sync::PoisonError::into_inner); + } + let nanos = u64::try_from(waiting.elapsed().as_nanos()).unwrap_or(u64::MAX); + self.stop_waited.store(nanos.max(1), Ordering::Release); + } + + /// How long the device's teardown waited for the check's thread to end; `None` where it + /// waited for none. + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + pub(crate) fn stop_waited(&self) -> Option { + match self.stop_waited.load(Ordering::Acquire) { + 0 => None, + nanos => Some(Duration::from_nanos(nanos)), + } + } + + /// Let the tests' hold of the check go once the device's teardown began, or once it was let + /// go already. + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + pub(crate) fn release_once_stopping(&self) { + self.held.release_once(&self.stopping); + } + /// Settle the verdict, with the cost measured (or 0) and the check's run where it ran. fn settle(&self, verdict: Verdict, cost: i64, took: Option) { self.cost.store(cost, Ordering::Release); @@ -622,12 +711,8 @@ impl Device { /// times from here on ([`SlotShare::watched`]). pub(crate) fn settle_queue_switch(&self, verdict: Verdict, cost: i64, took: Option) { let shared = self.shared(); - if shared.queue_switch.adaptive && verdict == Verdict::Idles { - for slot in &shared.queues[..shared.round_robin()] { - slot.share.watched.store(true, Ordering::Relaxed); - } - } - shared.queue_switch.settle(verdict, cost, took); + let slots = &shared.queues[..shared.round_robin()]; + shared.queue_switch.settle_over(slots, verdict, cost, took); } /// Start the device's check where its verdict is pending and none started, and wait until the diff --git a/crates/metal2vulkan-runtime/src/queue_switch_check.rs b/crates/metal2vulkan-runtime/src/queue_switch_check.rs index 0fae6ee68..3c4e285e7 100644 --- a/crates/metal2vulkan-runtime/src/queue_switch_check.rs +++ b/crates/metal2vulkan-runtime/src/queue_switch_check.rs @@ -33,19 +33,39 @@ //! it is made and runs no check. A failed run is kept nowhere. //! - **Its thread.** Each reach of the device runs inside a section of the exit guard //! (`exit_guard.rs`), as every runtime thread's does: the objects' making, the submissions, each -//! wait of at most [`WAIT_SLICE`], and the releases. The check holds its device for its run, a -//! few milliseconds, so its objects never outlive it; once the process is exiting it ends, -//! unrecorded, and leaves them to the process's end. A submission refused still opens its +//! wait of at most [`WAIT_SLICE`], and the releases. Once the process is exiting it ends, +//! unrecorded, and leaves its objects to the process's end. A submission refused still opens its //! round's gate, so no batch submitted waits for good. +//! - **Holding nothing of the device.** The check holds only the parts of the device it works +//! with ([`Parts`]), never a handle: a check that held one for its run would hold the device's +//! last once the program dropped its own while the check ran (the first moments of a device +//! that makes a command queue and goes), and the device would go on the check's thread after +//! the program's last drop returned, where a consumer that adopted its `VkDevice` destroys it +//! then ("Host access to `device` must be externally synchronized", and every object made from +//! it is destroyed before it: VUID-vkDestroyDevice-device-05137). So the program's last drop +//! tears the device down before it returns. The teardown first stops the check +//! (`QueueSwitch::stop`): the check reads that between its steps, before its objects' making, +//! before each round and before it reads the timestamps, so the teardown waits for at most one +//! step (a round's two batches, which complete as soon as the GPU reaches them, or the making), +//! then for the check to let its objects go, unrecorded and its verdict `Unchecked`, before the +//! check's thread drops its shares of the device's parts and ends. -use crate::device::relay::By; +use crate::command_buffer::fences::Fences; +use crate::device::functions::{Functions, Vk}; +use crate::device::relay::{By, QueueUses}; use crate::device::submit_stalls::Uses; -use crate::device::Device; +use crate::device::{Device, QueueSlot}; use crate::error::{vulkan, Error}; use crate::exit_guard::{self, Call}; -use crate::queue_share::{encode, record_name, Verdict, SWITCH_IDLES}; +use crate::freed_memory::Parking; +use crate::in_place::DriverIdentity; +use crate::loader_word::LoaderWord; +use crate::queue_share::{encode, record_name, QueueSwitch, Verdict, SWITCH_IDLES}; use crate::release; +use crate::shader_cache::store::Store; +use crate::work_counts::Counters; use ash::vk; +use std::sync::Arc; use std::time::{Duration, Instant}; /// The rounds of each kind, the two `VkQueue`s' and the one's. @@ -78,28 +98,108 @@ pub(crate) fn timed(device: &Device) -> bool { .is_some_and(|clock| clock.calibration.is_some()) } -/// Start the check on a thread of its own: whether it started. +/// Start the check on a thread of its own: whether it started. The thread holds `device`'s +/// [`Parts`], never a handle (the module docs). pub(crate) fn start(device: &Device) -> bool { - let weak = device.downgrade(); + let parts = Parts::of(device); + let switch = Arc::clone(&parts.switch); + switch.began(); let builder = std::thread::Builder::new().name("m2v-queue-switch-check".to_owned()); - exit_guard::spawn(builder, move || run(weak)).is_ok() + let spawned = exit_guard::spawn(builder, move || { + let switch = Arc::clone(&parts.switch); + run(&parts); + // Its shares go before the teardown that waits for it goes on. + drop(parts); + switch.ended(); + }); + if spawned.is_err() { + switch.ended(); + } + spawned.is_ok() } -/// The check's thread: the measurement, the verdict, the record. -fn run(weak: crate::device::WeakDevice) { +/// The parts of a device its check works with, none of which holds the device (the module docs): +/// shares of its functions, its `VkQueue`s, its parking, its counts, its fences, its loader word, +/// its sharing and its shader cache's store, and what it reads of the device as the check +/// starts. +struct Parts { + functions: Arc, + queues: Arc<[QueueSlot]>, + parking: Option>, + counts: Arc, + fences: Arc, + loader_word: Arc, + switch: Arc, + store: Arc, + /// The primary family, its pool's. + family: u32, + /// How many of the device's `VkQueue`s, the first, the round robin lends. + round_robin: usize, + /// The two `VkQueue`s it measures ([`pair`]), where it measures. + pair: Option<(usize, usize)>, + /// Nanoseconds per timestamp tick, and the bits a timestamp holds. + clock: (f64, u32), + identity: DriverIdentity, +} + +impl Parts { + /// `device`'s. + fn of(device: &Device) -> Parts { + let shared = device.shared(); + let clock = shared.timing.clock(); + Parts { + functions: shared.functions(), + queues: Arc::clone(&shared.queues), + parking: shared.parking.get().cloned(), + counts: Arc::clone(&shared.counts), + fences: Arc::clone(&shared.fences), + loader_word: Arc::clone(&shared.loader_word), + switch: Arc::clone(&shared.queue_switch), + store: shared.shader_cache.content_store_share(), + family: shared.queue_family, + round_robin: shared.round_robin(), + pair: pair(device).filter(|_| timed(device)), + clock: clock.map_or((0.0, 64), |clock| (clock.period, clock.valid_bits)), + identity: device.driver_identity(), + } + } + + /// The device's functions. + fn vk(&self) -> &Vk { + self.functions.get() + } + + /// What a use of one of the device's `VkQueue`s reaches. + fn queue_uses(&self) -> QueueUses<'_> { + QueueUses { + queues: &self.queues, + parking: self.parking.as_deref(), + counts: &self.counts, + fences: &self.fences, + functions: &self.functions, + } + } + + /// Settle the device's verdict (`Device::settle_queue_switch`). + fn settle(&self, verdict: Verdict, cost: i64, took: Option) { + let slots = &self.queues[..self.round_robin]; + self.switch.settle_over(slots, verdict, cost, took); + } +} + +/// The check's thread: the measurement, the verdict, the record. Stopped by the device's +/// teardown, it settles `Unchecked` and records nothing. +fn run(parts: &Parts) { let started = Instant::now(); - let Some(device) = weak.upgrade() else { + let Some(pair) = parts.pair else { + parts.settle(Verdict::Unchecked, 0, None); return; }; - let Some(pair) = pair(&device).filter(|_| timed(&device)) else { - device.settle_queue_switch(Verdict::Unchecked, 0, None); - return; - }; - let measured = measure(&device, pair); - device.shared().counts.queue_switch_check_ran(); + let measured = measure(parts, pair); + parts.counts.queue_switch_check_ran(); let took = Some(started.elapsed()); let Ok(Some((alternated, alone))) = measured else { - device.settle_queue_switch(Verdict::Unchecked, 0, took); + parts.settle(Verdict::Unchecked, 0, took); return; }; let cost = alternated - alone; @@ -107,27 +207,30 @@ fn run(weak: crate::device::WeakDevice) { true => Verdict::Idles, false => Verdict::DoesNotIdle, }; - let identity = device.driver_identity(); + let identity = &parts.identity; // A failed write leaves the verdict to the device's life alone. - let _ = (device.shared().shader_cache.content_store()) - .write_record_soon(&record_name(&identity), encode(&identity, verdict, cost)); - device.settle_queue_switch(verdict, cost, took); + let _ = + (parts.store).write_record_soon(&record_name(identity), encode(identity, verdict, cost)); + parts.settle(verdict, cost, took); } /// The median gap, in nanoseconds, between batches on the two `VkQueue`s of `pair` and between -/// batches on one: `Ok(None)` where too few rounds' timestamps were written or the process is -/// exiting, `Err` where a Vulkan call refused. -fn measure(device: &Device, pair: (usize, usize)) -> Result, Error> { - let Some(mut objects) = Objects::make(device, 4 * ROUNDS)? else { +/// batches on one: `Ok(None)` where too few rounds' timestamps were written, the process is +/// exiting or the device's teardown stopped the check, `Err` where a Vulkan call refused. +fn measure(parts: &Parts, pair: (usize, usize)) -> Result, Error> { + if parts.switch.stopping() { + return Ok(None); + } + let Some(mut objects) = Objects::make(parts, 4 * ROUNDS)? else { return Ok(None); }; - let ran = objects.run(device, pair); + let ran = objects.run(parts, pair); let gaps = match ran { - Ok(true) => objects.gaps(device), - Ok(false) => Ok(None), + Ok(true) if !parts.switch.stopping() => objects.gaps(parts), + Ok(_) => Ok(None), Err(error) => Err(error), }; - objects.release(device); + objects.release(parts); gaps } @@ -149,15 +252,14 @@ impl Objects { /// The objects for `batches` batches, each command buffer recorded: its two queries reset, /// then a timestamp at the top of the pipe and one at the bottom. `Ok(None)` where the process /// is exiting. - fn make(device: &Device, batches: usize) -> Result, Error> { + fn make(parts: &Parts, batches: usize) -> Result, Error> { let Some(_busy) = exit_guard::enter() else { return Ok(None); }; - let shared = device.shared(); - let raw = shared.vk(); + let raw = parts.vk(); let pool_info = vk::CommandPoolCreateInfo::default() .flags(vk::CommandPoolCreateFlags::TRANSIENT) - .queue_family_index(shared.queue_family); + .queue_family_index(parts.family); // SAFETY: the device is live, inside a section. let pool = unsafe { raw.create_command_pool(&pool_info, None) }.map_err(vulkan)?; exit_guard::called(Call::CreateCommandPool); @@ -169,12 +271,12 @@ impl Objects { done: [vk::Semaphore::null(); 2], settled: true, }; - let made = objects.fill(device, batches); + let made = objects.fill(parts, batches); drop(_busy); match made { Ok(()) => Ok(Some(objects)), Err(error) => { - objects.release(device); + objects.release(parts); Err(error) } } @@ -182,13 +284,21 @@ impl Objects { /// Make the pool's command buffers, the query pool and the timelines, and record the command /// buffers, inside the caller's section. - fn fill(&mut self, device: &Device, batches: usize) -> Result<(), Error> { - let raw = device.shared().vk(); + fn fill(&mut self, parts: &Parts, batches: usize) -> Result<(), Error> { + let raw = parts.vk(); let allocate = vk::CommandBufferAllocateInfo::default() .command_pool(self.pool) .level(vk::CommandBufferLevel::PRIMARY) .command_buffer_count(batches as u32); - self.buffers = device.allocate_command_buffers(&allocate)?; + // SAFETY: the device is live (its teardown waits for the check), and the pool is the + // check's, which this thread alone uses; its loader word is put back first + // (`loader_word.rs`). + let allocated = unsafe { + parts.loader_word.restore(); + raw.allocate_command_buffers(&allocate) + }; + exit_guard::called(Call::AllocateCommandBuffers); + self.buffers = allocated.map_err(vulkan)?; let info = vk::QueryPoolCreateInfo::default() .query_type(vk::QueryType::TIMESTAMP) .query_count(2 * batches as u32); @@ -229,10 +339,16 @@ impl Objects { } /// Submit every round's batches on `pair`, and wait for each round's: whether every batch - /// completed (false once the process is exiting, the objects then left to its end). - fn run(&mut self, device: &Device, pair: (usize, usize)) -> Result { + /// completed (false once the process is exiting, the objects then left to its end, and once + /// the device's teardown stopped the check before a round, every batch submitted completed). + fn run(&mut self, parts: &Parts, pair: (usize, usize)) -> Result { let mut done = [0u64; 2]; for round in 0..2 * ROUNDS { + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + parts.switch.held.pass(); + if parts.switch.stopping() { + return Ok(false); + } let queues = match round % 2 { 0 => [pair.0, pair.1], _ => [pair.0, pair.0], @@ -249,7 +365,7 @@ impl Objects { signal: (self.done[lane], done[lane]), }); } - if !self.round(device, &batches, gate, done)? { + if !self.round(parts, &batches, gate, done)? { return Ok(false); } } @@ -262,13 +378,13 @@ impl Objects { /// where they could not be. fn round( &mut self, - device: &Device, + parts: &Parts, batches: &[Batch], gate: u64, done: [u64; 2], ) -> Result { self.settled = false; - let (submitted, refused) = match self.submit(device, batches, gate) { + let (submitted, refused) = match self.submit(parts, batches, gate) { Some(answer) => answer, None => return Ok(false), }; @@ -277,7 +393,7 @@ impl Objects { let lane = usize::from(batch.signal.0 != self.done[0]); reached[lane] = reached[lane].min(batch.signal.1 - 1); } - if !self.wait(device, reached)? { + if !self.wait(parts, reached)? { return Ok(false); } self.settled = true; @@ -292,13 +408,13 @@ impl Objects { /// refusal; `None` where the process is exiting. fn submit( &self, - device: &Device, + parts: &Parts, batches: &[Batch], gate: u64, ) -> Option<(usize, Option)> { let _busy = exit_guard::enter()?; - let shared = device.shared(); - let raw = shared.vk(); + let raw = parts.vk(); + let uses = parts.queue_uses(); let mut submitted = 0; let mut refused = None; for batch in batches { @@ -321,12 +437,12 @@ impl Objects { // recorded, ended and in no other submission; each timeline's signals rise in the order // they run (each lane's batches run in its queue's order); the gate's wait is // signalled below. - let made = shared.use_queue( + let made = uses.use_queue( batch.queue, By::Runtime, Uses::OneSignalling, |queue| unsafe { - shared.counts.queue_submitted(1, 1); + parts.counts.queue_submitted(1, 1); raw.queue_submit(queue, &[submit], vk::Fence::null()) }, ); @@ -348,7 +464,7 @@ impl Objects { /// Wait for each `VkQueue`'s timeline to reach its value of `done`, a slice at a time, each a /// section: whether they did (false once the process is exiting). - fn wait(&self, device: &Device, done: [u64; 2]) -> Result { + fn wait(&self, parts: &Parts, done: [u64; 2]) -> Result { let (semaphores, values): (Vec, Vec) = (self.done.iter()) .zip(done) .filter(|&(_, value)| value > 0) @@ -367,8 +483,7 @@ impl Objects { // SAFETY: the timelines are the check's, each signalled to its value by a submission // made. let waited = unsafe { - device - .shared() + parts .vk() .wait_semaphores(&info, WAIT_SLICE.as_nanos() as u64) }; @@ -383,20 +498,17 @@ impl Objects { /// The median gap between batches on the two `VkQueue`s and on one, in nanoseconds, from the /// timestamps (`Ok(None)` where fewer than [`FEWEST`] of either kind were written). - fn gaps(&self, device: &Device) -> Result, Error> { + fn gaps(&self, parts: &Parts) -> Result, Error> { let Some(_busy) = exit_guard::enter() else { return Ok(None); }; - let shared = device.shared(); - let Some(clock) = shared.timing.clock() else { - return Ok(None); - }; + let (period, valid_bits) = parts.clock; let count = 2 * self.buffers.len(); let mut stamps = vec![[0u64; 2]; count]; // SAFETY: the pool's queries, each written by a batch that completed; 64-bit values each // with its availability. let read = unsafe { - shared.vk().get_query_pool_results( + parts.vk().get_query_pool_results( self.queries, 0, &mut stamps, @@ -408,7 +520,7 @@ impl Objects { Ok(()) | Err(vk::Result::NOT_READY) => {} Err(error) => return Err(vulkan(error)), } - let mask = match clock.valid_bits { + let mask = match valid_bits { 64.. => u64::MAX, bits => (1u64 << bits) - 1, }; @@ -422,7 +534,7 @@ impl Objects { true => (to - from) as f64, false => -((from - to) as f64), }; - (ticks * clock.period) as i64 + (ticks * period) as i64 }; // The batch of query pair `batch`: its start and end. let batch = |batch: usize| Some((at(2 * batch)?, at(2 * batch + 1)?)); @@ -450,14 +562,14 @@ impl Objects { /// Let the objects go, inside a section, where every batch submitted completed; else leave /// them to the device's end. - fn release(&self, device: &Device) { + fn release(&self, parts: &Parts) { if !self.settled { return; } let Some(_busy) = exit_guard::enter() else { return; }; - let raw = device.shared().vk(); + let raw = parts.vk(); // SAFETY: no submission that names them is pending (each completed, or none was made), // inside a section; a null handle is skipped. unsafe { diff --git a/crates/metal2vulkan-runtime/src/shader_cache/mod.rs b/crates/metal2vulkan-runtime/src/shader_cache/mod.rs index 3e2a6ef45..351160abc 100644 --- a/crates/metal2vulkan-runtime/src/shader_cache/mod.rs +++ b/crates/metal2vulkan-runtime/src/shader_cache/mod.rs @@ -454,6 +454,12 @@ impl ShaderCache { &self.store } + /// A share of [`content_store`](Self::content_store), for a thread that holds no device + /// (`queue_switch_check.rs`). + pub(crate) fn content_store_share(&self) -> Arc { + Arc::clone(&self.store) + } + /// Destroy the `VkPipelineCache` of every record the device holds, then stop the cache /// thread, which writes what is queued first: the device is going. /// diff --git a/crates/metal2vulkan-runtime/src/tests/teardown_threads.rs b/crates/metal2vulkan-runtime/src/tests/teardown_threads.rs index ad9cf5a36..f6ebcb478 100644 --- a/crates/metal2vulkan-runtime/src/tests/teardown_threads.rs +++ b/crates/metal2vulkan-runtime/src/tests/teardown_threads.rs @@ -42,6 +42,13 @@ //! block waiting for that mark and the release of freed memory that a later command buffer's //! completion posted, held too, as the program's wait for that command buffer returns. The //! teardown frees the block and runs its deallocator, before the last drop returns. +//! - **Not the queue-switch check's thread**: a device whose first command queue starts its check +//! of the GPU's idling between `VkQueue`s (`queue_switch_check.rs`), held between two of its +//! rounds, holds nothing of the device: the program's drops tear the device down on its own +//! thread before the last drop returns, the teardown stopping the check and waiting for it at +//! most one step and its release of its objects, within the 16 ms the owner allows a wait. A +//! device that runs no check (one family of one `VkQueue`, or no calibrated timestamps) skips +//! it, saying so. //! //! The teardown's end is seen through the device's message sink, whose last share the instance //! drops after `vkDestroyInstance`, the teardown's last step: the sink owns a value that, dropped, @@ -555,3 +562,55 @@ fn a_release_of_freed_memory_leaves_the_device_to_the_program_s_thread() { .layer_reported_nothing("the teardown that freed the block left no object and used none"); drop(host); } + +/// A device whose check of its GPU's idling between `VkQueue`s runs, held between two of its rounds +/// (`queue_switch_check.rs`): the check holds no device handle, so the program's last drop tears +/// the device down on its own thread before it returns, and the teardown's wait for the check (it +/// stops at its next step and lets its objects go) is within [`RELEASE`]. Without the hold the +/// check runs some milliseconds after the first command queue, the window in which a check that +/// held its device took the last drop's teardown to its own thread. +#[test] +fn a_running_queue_switch_check_leaves_the_device_to_the_program_s_thread() { + let scratch = Scratch::new("switch"); + let (device, ending) = watched(&scratch.0); + let switch = Arc::clone(&device.shared().queue_switch); + if crate::queue_switch_check::pair(&device).is_none() + || !crate::queue_switch_check::timed(&device) + { + println!( + "SKIPPED {}: the device runs no queue-switch check", + device.name() + ); + return; + } + switch.held.hold(); + let queue = device.new_command_queue().unwrap(); + switch.held.until_waiting(1, WAIT); + let releasing = std::thread::spawn({ + let switch = Arc::clone(&switch); + move || switch.release_once_stopping() + }); + let dropping = Instant::now(); + drop(queue); + drop(device); + let dropped = dropping.elapsed(); + let torn_down = ending.thread.try_recv(); + switch.held.release(); + releasing.join().unwrap(); + assert_eq!( + torn_down, + Ok(program_thread()), + "the device was not torn down on this thread before its last drop returned" + ); + let waited = switch + .stop_waited() + .expect("the teardown waited for the running check"); + println!("the last drop took {dropped:?}, of which the wait for the check {waited:?}"); + assert!( + waited < RELEASE, + "the teardown waited {waited:?} for the check" + ); + ending + .watched + .layer_reported_nothing("the teardown that stopped the check left no object and used none"); +}