diff --git a/crates/metal2vulkan-runtime/src/memory.rs b/crates/metal2vulkan-runtime/src/memory.rs index 27efa8480..fe77da921 100644 --- a/crates/metal2vulkan-runtime/src/memory.rs +++ b/crates/metal2vulkan-runtime/src/memory.rs @@ -804,9 +804,12 @@ struct State { /// Per class, when the block-maker thread's last free of an idle allocation of it ended, in /// nanoseconds of [`host_time`](crate::host_time); 0 before one. freed_at: [u64; 2], - /// The internals asked of the block-maker thread and not yet made, by [`Internal::index`]: - /// the zero source, the ring's first block and the staging region from the device's making. + /// The internals asked of the block-maker thread and not yet taken up, by [`Internal::index`]: + /// the zero source, the ring's first block and the staging region from the device's making, + /// and each later ring block a take asks for. asked: [bool; INTERNALS], + /// The internal the block-maker thread took up and is making ([`run`]). + making: Option, stop: bool, next_id: u32, next_allocation: u32, @@ -929,6 +932,7 @@ impl Pool { freed_at: [0, 0], // The device's fixed-size internals: the block-maker thread's first work. asked: [true; INTERNALS], + making: None, stop: false, next_id: 1, next_allocation: 1, @@ -1425,15 +1429,16 @@ impl Pool { true } - /// Waits while `internal` is asked of the block-maker thread: until it has made it, its make - /// failed, or it stopped. A wait is counted in [`Metrics::maker_waits`] and its time in - /// [`Metrics::maker_wait_max_nanos`]; where it is not asked, the call returns at once. + /// Waits while `internal` is asked of the block-maker thread or being made there: until it has + /// made it, its make failed, or it stopped. A wait is counted in [`Metrics::maker_waits`] and + /// its time in [`Metrics::maker_wait_max_nanos`]; where it is neither, the call returns at + /// once. /// /// [`Metrics::maker_waits`]: crate::Metrics::maker_waits /// [`Metrics::maker_wait_max_nanos`]: crate::Metrics::maker_wait_max_nanos pub(crate) fn await_made(&self, internal: Internal) { let mut state = self.lock(); - if !state.asked[internal.index()] { + if !state.pending(internal) { return; } let since = crate::host_time(); @@ -1441,7 +1446,7 @@ impl Pool { { state.waiting += 1; } - while state.asked[internal.index()] { + while state.pending(internal) { state = self.wait(state); } #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] @@ -1466,17 +1471,29 @@ impl Pool { } /// For the device tests: waits until the block-maker thread has made, or failed to make, - /// every internal asked of it. + /// every internal asked of it; fails where it has not within the tests' patience. #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] pub(crate) fn await_internals(&self) { + let patience = crate::tests::command::on_device::PATIENCE; + let deadline = std::time::Instant::now() + patience; let mut state = self.lock(); - while state.asked.contains(&true) { - state = self.wait(state); + while state.asked.contains(&true) || state.making.is_some() { + let left = deadline.saturating_duration_since(std::time::Instant::now()); + assert!( + !left.is_zero(), + "timed out waiting for the block-maker thread's internals" + ); + state = self.wait_for(state, left); } } } impl State { + /// Whether `internal` is asked of the block-maker thread or being made there. + fn pending(&self, internal: Internal) -> bool { + self.asked[internal.index()] || self.making == Some(internal) + } + /// Whether the class holds a wholly free unit: a unit allocation of [`ALLOCATION_LEN`], not /// retiring, that no block holds, so a take of up to a whole unit has a free range with no /// Vulkan call. The block-maker thread makes the class's next allocation while it holds none @@ -1673,13 +1690,14 @@ pub(crate) fn stock(core: &Core) { } /// The block-maker thread, until the device's teardown or a quiesce stops it. Off every caller's -/// path, in order: it makes each internal asked of it ([`Internal`]), the device's fixed-size -/// ones first of all; it frees each imported or exported block given back, then runs an import's -/// release; it makes an allocation of a class that holds no wholly free unit ([`State::whole`]), -/// having the consumer map it before it joins the pool; and it frees each allocation idle for -/// [`IDLE_AGE_NANOS`], after the consumer's unmap of it, one at a time. Each of its allocations -/// and frees starts once the submit calls inside the driver as its previous one returned have -/// returned ([`maker_call`]), and what it made is handed on as its call returns. It sleeps until +/// path, in order: it takes up each internal asked of it and makes it ([`Internal`]), the +/// device's fixed-size ones first of all, so an ask made during a make is made after it; it +/// frees each imported or exported block given back, then runs an import's release; it makes an +/// allocation of a class that holds no wholly free unit ([`State::whole`]), having the consumer +/// map it before it joins the pool; and it frees each allocation idle for [`IDLE_AGE_NANOS`], +/// after the consumer's unmap of it, one at a time. Each of its allocations and frees starts once +/// the submit calls inside the driver as its previous one returned have returned +/// ([`maker_call`]), and what it made is handed on as its call returns. It sleeps until /// the next change, or until the oldest idle allocation reaches the idle age. Stopped, it makes /// nothing more: what is asked of it and not made, the calls that need it make. pub(crate) fn run(core: Arc) { @@ -1706,10 +1724,14 @@ pub(crate) fn run(core: Arc) { return; } if let Some(internal) = (Internal::ALL.into_iter()).find(|i| state.asked[i.index()]) { + // Taken up before the make: an ask made while it runs (the ring asks again once it has + // this make's block) is a new one, made next. + state.asked[internal.index()] = false; + state.making = Some(internal); drop(state); make_internal(&core, internal); state = pool.lock(); - state.asked[internal.index()] = false; + state.making = None; pool.changed.notify_all(); continue; } @@ -1860,6 +1882,7 @@ fn make_internal(core: &Arc, internal: Internal) { if let MakerTest::Fail = core.maker_test { if internal == Internal::RingBlock { core.ring.unasked(); + core.ring.meet_park(); } return; } diff --git a/crates/metal2vulkan-runtime/src/ring.rs b/crates/metal2vulkan-runtime/src/ring.rs index 002f6d0be..b95dfd78f 100644 --- a/crates/metal2vulkan-runtime/src/ring.rs +++ b/crates/metal2vulkan-runtime/src/ring.rs @@ -11,8 +11,10 @@ //! leaves fewer chunks free than a block holds, so a block's chunks are free ahead of the takes //! and the ring holds at most one block more than the most chunks in use at once need. It makes //! one block at a time, without the ring's lock: a take or a give-back never waits for the -//! driver's allocation. A take that finds no chunk free while the block-maker thread makes the -//! next waits for it, or for a chunk given back, counted in +//! driver's allocation. It takes an ask up before it makes the block, so a take that asks again +//! once the ring has that block, before the thread is done with it, asks anew, and the thread +//! makes the next block after it: no ask goes unanswered. A take that finds no chunk free while +//! the block-maker thread makes the next waits for it, or for a chunk given back, counted in //! [`Metrics::maker_waits`](crate::Metrics::maker_waits). Where it made none (its make failed, or //! it had stopped), a take that finds no chunk free makes the block on its own thread, without //! the ring's lock, counted in @@ -67,7 +69,8 @@ pub(crate) struct Ring { changed: Condvar, /// For the device tests: where set, the making of a block, the block-maker thread's or a /// take's, meets the test at the barrier twice before it allocates, once parked and once - /// released. + /// released; so does the block-maker thread's answer that it makes none + /// (`crate::memory::MakerTest::Fail`), once the ring has it. #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] pub(crate) park: Mutex>>, } @@ -262,6 +265,23 @@ impl Ring { (self.state.try_lock().ok()).map(|state| (state.blocks.len(), state.free.len())) } + /// For the device tests: whether the ring's next block waits on an ask of the block-maker + /// thread. + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + pub(crate) fn asked(&self) -> bool { + lock(&self.state).next == Next::Maker + } + + /// For the device tests: meets the test at [`park`](Self::park) twice where it is set. + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + pub(crate) fn meet_park(&self) { + let park = lock(&self.park).clone(); + if let Some(park) = park { + park.wait(); + park.wait(); + } + } + /// Frees every block, returning how many it freed. /// /// # Safety @@ -317,13 +337,7 @@ fn waited(core: &Core, since: Option) { /// counted at [`Site::RingBlock`] on a consumer's thread. fn make(core: &Core) -> Result<(RingBlock, u64, Mapping), Error> { #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - { - let park = lock(&core.ring.park).clone(); - if let Some(park) = park { - park.wait(); - park.wait(); - } - } + core.ring.meet_park(); let device = &core.device; let info = vk::BufferCreateInfo::default() .size(BLOCK) diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 29638f0f6..92e08030f 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -14,7 +14,7 @@ mod border; mod buffer_accesses; mod cache; mod choice; -mod command; +pub(crate) mod command; mod compute; mod copy_out; mod copy_over; diff --git a/crates/metal2vulkan-runtime/src/tests/ring.rs b/crates/metal2vulkan-runtime/src/tests/ring.rs index d4807fdda..6ac0ec132 100644 --- a/crates/metal2vulkan-runtime/src/tests/ring.rs +++ b/crates/metal2vulkan-runtime/src/tests/ring.rs @@ -4,16 +4,21 @@ //! the block waits for it, or for a chunk given back, counted as a wait for the block-maker //! thread; no block is made on a caller's thread; and chunks given back are taken again before //! any further block. Where the block-maker thread makes none, a take that makes a block makes it -//! without the ring's lock, and takes that meet while it is made make one block between them. +//! without the ring's lock, and takes that meet while it is made make one block between them. An +//! ask made once the ring has the block-maker thread's answer to the last, before the thread is +//! done with it, is answered too. Every wait of these tests is bounded: a lost step fails with +//! its message. #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod on_device { use crate::device::{lock, Core}; use crate::memory::MakerTest; use crate::ring::{Writes, CHUNK, SPARE}; - use crate::tests::command::on_device::{each_device, each_device_with, Release}; + use crate::tests::command::on_device::{ + each_device, each_device_with, within, Release, PATIENCE, + }; use crate::DeviceOptions; - use std::sync::{Arc, Barrier}; + use std::sync::{mpsc, Arc, Barrier}; use std::thread; use std::time::Duration; @@ -36,6 +41,27 @@ mod on_device { thread::spawn(move || taken(&core, 1)) } + /// What `thread` returned, once it has within the tests' patience. + fn joined(what: &str, thread: thread::JoinHandle) -> Writes { + within(what, || thread.is_finished()); + thread.join().unwrap_or_else(|_| panic!("{what} panicked")) + } + + /// The test's first meeting with the thread parked at `park`, which comes within the tests' + /// patience, and the release of that thread. The meeting waits on a thread of its own, so a + /// thread that never parks fails the test rather than hanging it. + fn met(what: &str, park: &Arc) -> Release { + let (done, meeting) = mpsc::channel(); + let at = Arc::clone(park); + thread::spawn(move || { + at.wait(); + let _ = done.send(()); + }); + let meeting = meeting.recv_timeout(PATIENCE); + meeting.unwrap_or_else(|_| panic!("timed out waiting for {what}")); + Release::of(park) + } + /// The ring's blocks and free chunks, its lock free. fn chunks(core: &Core) -> (usize, usize) { core.ring.chunks().expect("the ring's lock is free") @@ -50,6 +76,14 @@ mod on_device { chunks(core) } + /// The options of a device whose block-maker thread makes no internal. + fn making_none() -> DeviceOptions { + DeviceOptions { + maker: MakerTest::Fail, + ..DeviceOptions::default() + } + } + #[test] fn the_block_maker_thread_makes_the_ring_s_next_block_ahead_of_the_takes() { each_device("ring_ahead", |name, _, device| { @@ -66,8 +100,7 @@ mod on_device { let park = Arc::new(Barrier::new(2)); *lock(&ring.park) = Some(Arc::clone(&park)); let first = taken(core, 1); - park.wait(); - let mut release = Release::of(&park); + let mut release = met("the block-maker thread's make", &park); *lock(&ring.park) = None; assert_eq!( ring.chunks(), @@ -87,7 +120,7 @@ mod on_device { ); // A give-back on this thread goes on while the block is made, and serves the take. spare.give_back(core); - let waited = waiter.join().expect("the waiter"); + let waited = joined("the take served by the give-back", waiter); assert_eq!( counters.metrics().maker_waits, waits + 1, @@ -117,11 +150,7 @@ mod on_device { #[test] fn where_the_block_maker_thread_makes_none_a_take_makes_the_block_off_the_lock() { - let options = || DeviceOptions { - maker: MakerTest::Fail, - ..DeviceOptions::default() - }; - each_device_with("ring_off_the_lock", options, |name, _, device| { + each_device_with("ring_off_the_lock", making_none, |name, _, device| { let core = device.core(); let ring = &core.ring; if settled(core).1 == 0 { @@ -136,8 +165,7 @@ mod on_device { *lock(&ring.park) = Some(Arc::clone(&park)); let maker = take_one(core); // The take is parked where it makes the block. - park.wait(); - let mut release = Release::of(&park); + let mut release = met("the take that makes the block", &park); *lock(&ring.park) = None; assert_eq!( ring.chunks(), @@ -148,8 +176,8 @@ mod on_device { // A give-back on this thread goes on while the block is made. spare.give_back(core); release.now(); - let made = maker.join().expect("the maker"); - let waited = waiter.join().expect("the waiter"); + let made = joined("the take that made the block", maker); + let waited = joined("the take that met it", waiter); assert_eq!( settled(core).0, before + 1, @@ -160,9 +188,14 @@ mod on_device { } // A fill past the ring's chunks makes one block; chunks given back are taken again. let (blocks, free) = settled(core); - let past = taken(core, free + 1); + let past = [ + taken(core, free), + joined("a take past the ring's chunks", take_one(core)), + ]; assert_eq!(settled(core).0, blocks + 1, "{name}: one block past"); - past.give_back(core); + for writes in past { + writes.give_back(core); + } let again = taken(core, settled(core).1); assert_eq!( settled(core), @@ -178,4 +211,41 @@ mod on_device { ); }); } + + #[test] + fn an_ask_made_once_the_ring_has_the_block_maker_thread_s_answer_is_answered() { + each_device_with("ring_ask_in_answer", making_none, |name, _, device| { + let core = device.core(); + let ring = &core.ring; + if settled(core).1 == 0 { + taken(core, 1).give_back(core); + } + let blocks = settled(core).0; + assert!(!ring.asked(), "{name}: no ask waits"); + // The take that leaves fewer than a block's chunks free asks; the block-maker + // thread's answer, that it makes none, is parked once the ring has it. + let park = Arc::new(Barrier::new(2)); + *lock(&ring.park) = Some(Arc::clone(&park)); + let first = taken(core, 1); + let mut release = met("the block-maker thread's answer", &park); + *lock(&ring.park) = None; + // The ring has the answer: the next take asks again, before the thread is done. + let second = taken(core, 1); + assert!(ring.asked(), "{name}: the second take asked"); + release.now(); + let free = settled(core).1; + assert!( + !ring.asked(), + "{name}: the ask made while the block-maker thread answered the last went \ + unanswered: a take that finds no chunk free waits for it with nothing coming" + ); + // A take past the ring's chunks makes the block, on its own thread. + let rest = taken(core, free); + let past = joined("a take past the ring's chunks", take_one(core)); + assert_eq!(settled(core).0, blocks + 1, "{name}: one block past"); + for writes in [first, second, rest, past] { + writes.give_back(core); + } + }); + } }