🐎 Take a take's own block off the pool's thread

A take that fits no piece waited for its own piece on the pool's one thread,
which served every ask in turn: the headroom's 16 MiB blocks from rt (each up
to 72 ms where rt's maker makes one), then the take's own block, and a piece
going back blocked the thread until its holds and the host's remove were done.
On the 2080's gate walk, context 39's take of 560320 KiB waited 271.54 ms for
its piece, of which 139.5 ms was rt's allocation of its block; the rest was
the wait behind that thread's other work and the add.

Now the take's worker takes the block of its own length from the source, with
the pool's lock let go of, so only that take waits for its allocation. A new
thread, reims-vgpu.graphics-pool-ahead, takes the blocks of the pool's own
asks (the headroom and the host's pool_grow). The pool's thread places the
takes' blocks before the taker's, and gives a piece back a step at a time: it
asks the host's remove once no hold is left and gives the block back once the
host removed it, waiting for neither, with the 1 s warning kept.

For the host: pool_add and pool_remove stay on reims-vgpu.graphics-pool, one
at a time, in the order the pieces are placed, each add before its remove.
A take's block may now be placed ahead of headroom blocks asked before it,
so the order of the adds, and the pool offsets the guest's takes get, can
differ under a race from before. The new tests fail on the code before this
(job m3-max-58851): another context's take, the headroom and a give-back now
go on while a take's own block is being made.
This commit is contained in:
Anees Iqbal committed 2026-11-20 07:43:48 -08:00
1 parent 7f74e7c7ec
commit a299f41355
6 files changed
+545 -207

No files matched your search

+1 -1
View File
@@ -1050,7 +1050,7 @@ impl<P: ApiPlatform> GraphicsDevice<P> {
}
/// Asks for at least `length` more bytes of the guest's Shared pool now, as the guest's own
/// ask does: the pool's thread takes a block and asks the host to map it
/// ask does: the pool's taker takes a block, and the pool's thread asks the host to map it
/// ([`GraphicsCallbacks::pool_add`]). Waits for nothing and calls back never.
/// [`Error::InvalidArgument`] without a pool, or for a `length` of 0.
pub fn pool_grow(&self, length: u64) -> Result<(), Error> {
+323 -166
View File
@@ -5,14 +5,19 @@
//! # Growth
//!
//! An ask for more pool ([`Pool::grow`]: the host's `rvg_graphics_device_pool_grow`, and the
//! headroom rule below) wakes the pool's thread, `reims-vgpu.graphics-pool`. It takes a Shared
//! block from the source ([`BlockSource::take_block`], which waits only when no block is ready),
//! places it at the lowest free address of the range that holds it, 2 MiB aligned, so pieces go
//! out in ascending addresses, and asks the host to map it there ([`PoolHost::add`]) with no lock
//! of the pool's held. The host maps it (QEMU: a RAM region of its own over the block, added on
//! its main loop) and says so ([`Pool::added`], the C API's "range added"); only then does
//! [`Pool::find`] find it. A block the source hands out again after the pool gave it back is
//! placed and mapped anew, as any block is: its piece went before it went back.
//! headroom rule below) wakes the pool's taker, `reims-vgpu.graphics-pool-ahead`, which takes a
//! Shared block from the source ([`BlockSource::take_block`], which waits only when no block is
//! ready) for each such ask in turn, oldest first. A take that fits no piece takes a block of its
//! own length on its context's worker (`takes`), so only that take waits for the source's
//! allocation. The pool's thread, `reims-vgpu.graphics-pool`, places each block taken, the takes'
//! before the taker's, at the lowest free address of the range that holds it, 2 MiB aligned, so
//! pieces go out in ascending addresses, and asks the host to map it there ([`PoolHost::add`])
//! with no lock of the pool's held: it waits for no source, so neither another context's take nor
//! the headroom waits behind a take's allocation, nor a take behind the headroom's. The host maps
//! it (QEMU: a RAM region of its own over the block, added on its main loop) and says so
//! ([`Pool::added`], the C API's "range added"); only then does [`Pool::find`] find it. A block
//! the source hands out again after the pool gave it back is placed and mapped anew, as any block
//! is: its piece went before it went back.
//!
//! # Headroom and giving blocks back
//!
@@ -33,11 +38,13 @@
//! # Release
//!
//! The pool gives a block back to the source only once the guest's mapping of its piece is gone.
//! It takes the piece out of the lookups, waits for every hold on it ([`PieceHold`]) to go, asks
//! It takes the piece out of the lookups, and once every hold on it ([`PieceHold`]) has gone, asks
//! the host to unmap it ([`PoolHost::remove`]), and gives the block back once the host says it is
//! out of the guest's address space and no host thread of its own touches it ([`Pool::removed`]).
//! So the source may free a block the moment it gets it back: no guest access, no thread of the
//! host's and no thread of the library's touches it.
//! The pool's thread takes each step as it comes due, waiting for none of them, so a piece on its
//! way back holds up no other piece's place or add. So the source may free a block the moment it
//! gets it back: no guest access, no thread of the host's and no thread of the library's touches
//! it.
//!
//! At the device's release the host has removed every piece it added (QEMU does so as it tears
//! the device down, before the release): from then on ([`Pool::close`]) the pool waits only for
@@ -73,7 +80,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::thread::JoinHandle;
use std::time::Duration;
use parking_lot::{Condvar, Mutex};
use parking_lot::{Condvar, Mutex, MutexGuard};
use reims_vgpu_vulkan::answer::count_kind;
use reims_vgpu_vulkan::core::num::ToU64 as _;
use reims_vgpu_vulkan::core::platform::os::clock::MonoTime;
@@ -370,6 +377,15 @@ enum Mapped {
Removed,
}
/// A piece on its way back to the source (the module doc's "Release").
#[derive(Clone, Copy, Debug)]
struct Going {
/// Since when.
since: MonoTime,
/// Whether the pool's thread warned that it still waits.
warned: bool,
}
/// One block in the range, which the pool holds until its piece is out of the guest.
#[derive(Debug)]
struct Piece {
@@ -387,6 +403,9 @@ struct Piece {
/// Whether some of its bytes may be neither carved nor in `zeros`: set at its place and at
/// each carve's free, and cleared once the zeroer finds none (`takes`, "Zeros ahead").
zero_pending: bool,
/// Since when it is on its way back to the source, where it is: only a piece the pool gives
/// back, never one the host removed of its own.
going: Option<Going>,
}
impl Piece {
@@ -403,14 +422,23 @@ struct State {
pieces: BTreeMap<u64, Piece>,
/// Each piece's address, by its block.
by_block: HashMap<BlockId, u64>,
/// Asks for more pool, oldest first.
/// Asks for more pool no take waits on, the headroom's and the host's, oldest first: the
/// pool's taker takes a block for each ([`Shared::take_ahead`]).
asks: VecDeque<Ask>,
/// The length of the ask no take waits on that the pool's thread serves, from its take off
/// [`Self::asks`] to its piece's place or its end with no piece; 0 while it serves none.
/// The length of the ask the pool's taker serves, from its take off [`Self::asks`] until its
/// block is in [`Self::ahead`] or no block came of it; 0 while it serves none.
serving: u64,
/// The asks a take waits on, by number, with where each one's piece went once it was served:
/// `Some(None)` where no piece came of it (`takes`).
/// The blocks the pool's taker took, oldest first, for the pool's thread to place after
/// [`Self::own`]'s.
ahead: VecDeque<BlockInfo>,
/// The blocks the take workers took for takes that fit no piece, oldest first, for the pool's
/// thread to place before any of [`Self::ahead`]'s (`takes`).
own: VecDeque<Own>,
/// The takes waiting for their own blocks' places, by number, with where each one's piece
/// went once it was placed: `Some(None)` where no piece came of it (`takes`).
waits: HashMap<u64, Option<Option<u64>>>,
/// The source, for the take workers' own blocks: let go of at the device's release.
source: Option<Arc<dyn BlockSource>>,
/// The contexts' blocks of the pool, by guest physical address (`takes`).
carves: BTreeMap<u64, takes::Carve>,
/// The contexts with a take in flight or a worker, by context (`takes`).
@@ -449,11 +477,18 @@ struct State {
full_logged: bool,
}
/// An ask for at least `length` more bytes of pool, and the number of the take's wait on it.
/// An ask for at least `length` more bytes of pool that no take waits on.
#[derive(Clone, Copy, Debug)]
struct Ask {
length: u64,
wait: Option<u64>,
}
/// A block a take worker took for its take (`takes`), and the number of the take's wait on its
/// place.
#[derive(Clone, Copy, Debug)]
struct Own {
block: BlockInfo,
wait: u64,
}
impl State {
@@ -473,21 +508,19 @@ impl State {
self.keep_headroom();
}
/// Where the empty pieces the guest may use and the asks for more pool no take waits on, the
/// one the pool's thread serves among them, hold fewer than [`HEADROOM`] bytes, asks for a
/// block of [`BLOCK_LEN`] for each piece short, so they hold that many: whether it asked.
/// Where the empty pieces the guest may use, the asks for more pool no take waits on, the one
/// the pool's taker serves among them, and the blocks it took that wait for their places,
/// hold fewer than [`HEADROOM`] bytes, asks for a block of [`BLOCK_LEN`] for each piece short,
/// so they hold that many: whether it asked.
fn keep_headroom(&mut self) -> bool {
let empty = (self.empties()).fold(0, |all: u64, (_, p, _)| all.saturating_add(p.block.len));
let asked = (self.asks.iter())
.filter(|a| a.wait.is_none())
.fold(self.serving, |all: u64, a| all.saturating_add(a.length));
let mut held = empty.saturating_add(asked);
let asked =
(self.asks.iter()).fold(self.serving, |all: u64, a| all.saturating_add(a.length));
let taken = (self.ahead.iter()).fold(asked, |all: u64, b| all.saturating_add(b.len));
let mut held = empty.saturating_add(taken);
let ask = held < HEADROOM;
while held < HEADROOM {
self.asks.push_back(Ask {
length: BLOCK_LEN,
wait: None,
});
self.asks.push_back(Ask { length: BLOCK_LEN });
held = held.saturating_add(BLOCK_LEN);
}
ask
@@ -515,6 +548,85 @@ impl State {
p.empty_since = Some(now);
}
}
/// Sets the piece at `at` on its way back to the source, at `now`: out of the lookups, its
/// remove asked once no hold is left on it ([`Self::next_remove`]), and its block given back
/// once the host removed it ([`Self::next_back`]).
fn send_back(&mut self, at: u64, now: MonoTime) {
if let Some(p) = self.pieces.get_mut(&at) {
p.mapped = Mapped::Removing { asked: false };
p.going = Some(Going {
since: now,
warned: false,
});
}
}
/// A piece on its way back that no hold is on and whose remove the host was not asked yet,
/// marked asked: its address and length.
fn next_remove(&mut self) -> Option<(u64, u64)> {
let (&at, p) = (self.pieces.iter_mut()).find(|(_, p)| {
p.going.is_some() && p.holds == 0 && p.mapped == Mapped::Removing { asked: false }
})?;
p.mapped = Mapped::Removing { asked: true };
Some((at, p.block.len))
}
/// The block of a piece on its way back that the host removed and no hold is on, the piece
/// taken out of the pool.
fn next_back(&mut self) -> Option<BlockId> {
let at = (self.pieces.iter())
.find(|(_, p)| p.going.is_some() && p.holds == 0 && p.mapped == Mapped::Removed)
.map(|(&at, _)| at)?;
self.take_piece(at)
}
/// At the device's release, once the host removed every piece: the blocks of the pieces on
/// their way back that no hold is on, the pieces taken out of the pool. The rest wait for
/// their holds at the release's end ([`Shared::take_all_out`]).
fn take_out_going(&mut self) -> Vec<BlockId> {
let going: Vec<u64> = (self.pieces.iter())
.filter(|(_, p)| p.going.is_some() && p.holds == 0)
.map(|(&at, _)| at)
.collect();
(going.into_iter())
.filter_map(|at| self.take_piece(at))
.collect()
}
/// Takes the piece at `at` out of the pool: its block.
fn take_piece(&mut self, at: u64) -> Option<BlockId> {
let p = self.pieces.remove(&at)?;
self.by_block.remove(&p.block.id);
Some(p.block.id)
}
/// Warns once of each piece on its way back that still waits 1 s after it set out, saying
/// what for, at `now`: how long until the next of them is due its warning.
fn warn_going(&mut self, now: MonoTime) -> Option<Duration> {
let mut next: Option<Duration> = None;
for (&at, p) in &mut self.pieces {
let Some(going) = p.going.as_mut().filter(|g| !g.warned) else {
continue;
};
let when = going.since.saturating_add(Duration::from_secs(1));
if when > now {
let after = when.saturating_duration_since(now);
next = Some(next.map_or(after, |n| n.min(after)));
continue;
}
going.warned = true;
log::warn!(
"pool: the piece at {at:#x} still waits to go back after 1 s: {}",
if p.holds > 0 {
"a thread of the device's holds it"
} else {
"the host has not removed it"
}
);
}
next
}
}
/// The pool's shared part: what the thread, the device and the holds hold.
@@ -621,10 +733,14 @@ impl Drop for PieceHold {
/// The guest's Shared pool of one device.
pub struct Pool {
shared: Arc<Shared>,
/// The source. Let go of once the thread that takes from it has ended and every block went
/// The source. Let go of once the threads that take from it have ended and every block went
/// back to it ([`Pool::close`]); it frees its blocks once nothing else holds it.
source: Option<Arc<dyn BlockSource>>,
/// The pool's thread, which places pieces and gives them back ([`Shared::serve`]).
thread: Option<JoinHandle<()>>,
/// The pool's taker, which takes the blocks of the asks no take waits on
/// ([`Shared::take_ahead`]).
ahead: Option<JoinHandle<()>>,
}
impl std::fmt::Debug for Pool {
@@ -636,9 +752,9 @@ impl std::fmt::Debug for Pool {
}
impl Pool {
/// A pool over `range`, timed by `now`, its blocks from `source`, and its thread started.
/// [`Error::InvalidArgument`] for a range [`PoolConfig::is_valid`] refuses,
/// [`Error::HostResources`] where the thread is refused.
/// A pool over `range`, timed by `now`, its blocks from `source`, and its thread and taker
/// started. [`Error::InvalidArgument`] for a range [`PoolConfig::is_valid`] refuses,
/// [`Error::HostResources`] where a thread is refused.
pub(crate) fn new(
range: PoolConfig,
host: PoolHost,
@@ -664,23 +780,34 @@ impl Pool {
host,
release_delay,
now,
state: Mutex::new(State::default()),
state: Mutex::new(State {
source: Some(Arc::clone(&source)),
..State::default()
}),
changed: Condvar::new(),
threads: Arc::default(),
});
let thread = {
let spawn = |name: &str, f: fn(&Arc<Shared>, &dyn BlockSource)| {
let shared = Arc::clone(&shared);
let source = Arc::clone(&source);
std::thread::Builder::new()
.name("reims-vgpu.graphics-pool".into())
.spawn(move || shared.serve(source.as_ref()))
.map_err(|_| Error::HostResources)?
(std::thread::Builder::new().name(name.into()))
.spawn(move || f(&shared, source.as_ref()))
.ok()
};
Ok(Pool {
let thread = spawn("reims-vgpu.graphics-pool", Shared::serve);
let ahead = spawn("reims-vgpu.graphics-pool-ahead", Shared::take_ahead);
let mut pool = Pool {
shared,
source: Some(source),
thread: Some(thread),
})
thread,
ahead,
};
if pool.thread.is_none() || pool.ahead.is_none() {
// The release ends the one made.
pool.close();
return Err(Error::HostResources);
}
Ok(pool)
}
/// The range of guest physical addresses the pool takes.
@@ -688,10 +815,10 @@ impl Pool {
self.shared.range
}
/// Asks for at least `length` more bytes of pool: the pool's thread takes a block and has the
/// host map it. Waits for nothing.
/// Asks for at least `length` more bytes of pool: the pool's taker takes a block, and the
/// pool's thread has the host map it. Waits for nothing.
pub fn grow(&self, length: u64) {
let ask = Ask { length, wait: None };
let ask = Ask { length };
self.shared.state.lock().asks.push_back(ask);
self.shared.changed.notify_all();
}
@@ -819,17 +946,23 @@ impl Pool {
.collect()
}
/// The device's release: the host removed every piece it added. Ends the pool's thread (a
/// piece it is giving back waits only for its holds from now on), its take workers (a take
/// in flight is answered never) and its zeroer, and waits until their threads let go of the
/// pool ([`Threads`]), then, where no ledger lives, waits for every hold on the
/// pieces left, gives each one's block back and lets go of the source. Where a ledger lives
/// (the decoder's, whose heaps over the contexts' blocks may outlive the device), the last
/// one's drop does that.
/// The device's release: the host removed every piece it added. Ends the pool's thread (which
/// gives back the pieces on their way back that no hold is on), its taker, its take workers
/// (a take in flight is answered never) and its zeroer, and waits until their threads let go
/// of the pool ([`Threads`]); gives back the blocks taken and not placed, with no word to the
/// host; then, where no ledger lives, waits for every hold on the pieces left, gives each
/// one's block back and lets go of the source. Where a ledger lives (the decoder's, whose
/// heaps over the contexts' blocks may outlive the device), the last one's drop does that.
pub(crate) fn close(&mut self) {
self.shared.state.lock().closed = true;
let mut st = self.shared.state.lock();
st.closed = true;
st.source = None;
drop(st);
self.shared.changed.notify_all();
if let Some(t) = self.thread.take() {
for t in [self.thread.take(), self.ahead.take()]
.into_iter()
.flatten()
{
let _ = t.join();
}
self.shared.wait_for_workers();
@@ -838,6 +971,16 @@ impl Pool {
return;
};
let mut st = self.shared.state.lock();
let own = std::mem::take(&mut st.own);
let ahead = std::mem::take(&mut st.ahead);
drop(st);
let unplaced = (own.into_iter().map(|o| o.block)).chain(ahead);
for block in unplaced {
if let Err(e) = source.release_block(block.id) {
log::warn!(kind:? = e; "pool: the source refused a block back: {e:?}");
}
}
let mut st = self.shared.state.lock();
if st.keepers > 0 {
st.left = Some(source);
return;
@@ -860,52 +1003,57 @@ impl Drop for Pool {
}
impl Shared {
/// The pool's thread: takes a block for each ask and has the host map it, making the zeroer
/// where none runs (`takes`, "Zeros ahead"), and gives back the pieces that stayed empty past
/// their delay, until the pool closes.
/// The pool's thread: places each block taken, the take workers' first, and has the host map
/// it, making the zeroer where none runs (`takes`, "Zeros ahead"); and gives back the pieces
/// that stayed empty past their delay, a step at a time as each comes due, waiting for no
/// hold and no remove; until the pool closes, where it gives back those on their way back
/// that no hold is on.
fn serve(self: &Arc<Self>, source: &dyn BlockSource) {
let mut st = self.state.lock();
loop {
let mut st = self.state.lock();
if st.closed {
let back = st.take_out_going();
drop(st);
for block in back {
if let Err(e) = source.release_block(block) {
log::warn!(kind:? = e; "pool: the source refused a block back: {e:?}");
}
}
return;
}
if let Some(Ask { length, wait }) = st.asks.pop_front() {
st.serving = if wait.is_none() { length } else { 0 };
drop(st);
let placed = match source.take_block(MemoryClass::Shared, length) {
Ok(block) => self.place(source, block),
Err(e) => {
log::warn!(kind:? = e; "pool: no block of {length} bytes: {e:?}");
None
let next = match st.own.pop_front() {
Some(own) => Some((own.block, Some(own.wait))),
None => st.ahead.pop_front().map(|block| (block, None)),
};
if let Some((block, wait)) = next {
self.place(&mut st, source, block, wait);
continue;
}
if let Some((at, len)) = st.next_remove() {
MutexGuard::unlocked(&mut st, || (self.host.remove)(at, len));
continue;
}
if let Some(block) = st.next_back() {
MutexGuard::unlocked(&mut st, || {
if let Err(e) = source.release_block(block) {
log::warn!(kind:? = e; "pool: the source refused a block back: {e:?}");
}
};
let mut st = self.state.lock();
st.serving = 0;
let start = placed.is_some() && st.start_zeroer();
drop(st);
if start {
takes::spawn_zeroer(self);
}
// The take waiting on it, where it still does, looks where the piece went.
if let Some(wait) = wait
&& let Some(outcome) = self.state.lock().waits.get_mut(&wait)
{
*outcome = Some(placed);
}
self.changed.notify_all();
});
continue;
}
let now = (self.now)();
let (due, next) = self.due(&st, now);
if let Some((at, block)) = due {
drop(st);
log::info!("pool: the empty piece at {at:#x} goes back to the source");
self.take_out(block);
if let Err(e) = source.release_block(block) {
log::warn!(kind:? = e; "pool: the source refused a block back: {e:?}");
}
if let Some(at) = due {
st.send_back(at, now);
MutexGuard::unlocked(&mut st, || {
log::info!("pool: the empty piece at {at:#x} goes back to the source");
});
continue;
}
let next = match (next, st.warn_going(now)) {
(Some(a), Some(b)) => Some(a.min(b)),
(a, b) => a.or(b),
};
match next {
Some(after) => {
let _ = self.changed.wait_for(&mut st, after);
@@ -915,18 +1063,51 @@ impl Shared {
}
}
/// The pool's taker: takes a Shared block for each ask no take waits on ([`State::asks`]),
/// oldest first, with the pool's lock let go of, and hands it to the pool's thread to place
/// ([`State::ahead`]), until the pool closes. A block it takes once the device's release began
/// goes back with no word to the host, which removed its pieces before the release.
fn take_ahead(self: &Arc<Self>, source: &dyn BlockSource) {
let mut st = self.state.lock();
loop {
if st.closed {
return;
}
let Some(Ask { length }) = st.asks.pop_front() else {
self.changed.wait(&mut st);
continue;
};
st.serving = length;
let block =
MutexGuard::unlocked(&mut st, || source.take_block(MemoryClass::Shared, length));
st.serving = 0;
match block {
Ok(block) if !st.closed => {
st.ahead.push_back(block);
self.changed.notify_all();
}
Ok(block) => MutexGuard::unlocked(&mut st, || {
let _ = source.release_block(block.id);
}),
Err(e) => MutexGuard::unlocked(&mut st, || {
log::warn!(kind:? = e; "pool: no block of {length} bytes: {e:?}");
}),
}
}
}
/// The piece whose block goes back now, if any, and how long until the next may: of the
/// empty pieces the guest may use, every one above the headroom ([`State::empties`]), once
/// empty for the delay.
fn due(&self, st: &State, now: MonoTime) -> (Option<(u64, BlockId)>, Option<Duration>) {
fn due(&self, st: &State, now: MonoTime) -> (Option<u64>, Option<Duration>) {
let empty = (st.empties()).filter_map(|(at, p, headroom)| {
let since = p.empty_since.filter(|_| !headroom)?;
Some((at, p.block.id, since.saturating_add(self.release_delay)))
Some((at, since.saturating_add(self.release_delay)))
});
let mut next: Option<Duration> = None;
for (at, block, when) in empty {
for (at, when) in empty {
if when <= now {
return (Some((at, block)), None);
return (Some(at), None);
}
let after = when.saturating_duration_since(now);
next = Some(next.map_or(after, |n| n.min(after)));
@@ -934,12 +1115,52 @@ impl Shared {
(None, next)
}
/// Places `block` at the lowest free address that holds it and asks the host to map it: the
/// address, or `None` where the block went back, the range full, the pool closed or the
/// block not whole host pages ([`UNALIGNED_CODE`]).
fn place(&self, source: &dyn BlockSource, block: BlockInfo) -> Option<u64> {
/// Places `block` at the lowest free address that holds it, where a take waits on it
/// (`wait`) says where it went, and asks the host to map it, with the lock `st` holds let go
/// of for the add. No piece comes of it, and it goes back, where the range is full or the
/// block is not whole host pages ([`UNALIGNED_CODE`]).
fn place(
self: &Arc<Self>,
st: &mut MutexGuard<'_, State>,
source: &dyn BlockSource,
block: BlockInfo,
wait: Option<u64>,
) {
let placed = self.fit_piece(st, source, block);
if let Some(wait) = wait
&& let Some(outcome) = st.waits.get_mut(&wait)
{
*outcome = Some(placed.map(|(at, _)| at));
}
let start = placed.is_some() && st.start_zeroer();
MutexGuard::unlocked(st, || {
if start {
takes::spawn_zeroer(self);
}
// The take waiting on it, where it still does, looks where the piece went.
self.changed.notify_all();
if let Some((at, contents)) = placed {
(self.host.add)(at, contents.as_ptr(), block.len);
}
});
}
/// [`Self::place`]'s piece: `block`'s, at the lowest free address that holds it, its address
/// and host mapping, or `None` where the block went back, the range full or the block not
/// whole host pages. The pool's lock `st` holds is let go of where the block goes back.
fn fit_piece(
&self,
st: &mut MutexGuard<'_, State>,
source: &dyn BlockSource,
block: BlockInfo,
) -> Option<(u64, NonNull<u8>)> {
let back = |st: &mut MutexGuard<'_, State>| {
MutexGuard::unlocked(st, || {
let _ = source.release_block(block.id);
});
};
let Some(contents) = block.contents else {
let _ = source.release_block(block.id);
back(st);
return None;
};
let page = OsVm::new().page_size().max(1);
@@ -956,15 +1177,7 @@ impl Shared {
);
}
count_kind(UNALIGNED_CODE);
let _ = source.release_block(block.id);
return None;
}
let mut st = self.state.lock();
// A block made while the device was released goes back with no word to the host, which
// removed its pieces before the release.
if st.closed {
drop(st);
let _ = source.release_block(block.id);
back(st);
return None;
}
let Some(at) = first_fit(self.range, &st.pieces, block.len) else {
@@ -976,8 +1189,7 @@ impl Shared {
block.len >> 20
);
}
drop(st);
let _ = source.release_block(block.id);
back(st);
return None;
};
st.pieces.insert(
@@ -990,66 +1202,11 @@ impl Shared {
carves: 0,
zeros: takes::Ranges::new(),
zero_pending: true,
going: None,
},
);
st.by_block.insert(block.id, at);
// Its ask is served: the piece counts from here on.
st.serving = 0;
drop(st);
(self.host.add)(at, contents.as_ptr(), block.len);
Some(at)
}
/// Takes `block`'s piece out before the block goes back: out of the lookups, then, once no
/// hold is left, out of the guest (the module doc's "Release"). Returns once the host said it
/// is out, or, after the device's release, once no hold is left.
fn take_out(&self, block: BlockId) {
let mut st = self.state.lock();
if !st.by_block.contains_key(&block) {
return;
}
let mut warned = false;
let started = (self.now)();
loop {
let closed = st.closed;
let Some(&at) = st.by_block.get(&block) else {
return;
};
let Some(p) = st.pieces.get_mut(&at) else {
return;
};
match p.mapped {
Mapped::Adding | Mapped::Live => p.mapped = Mapped::Removing { asked: false },
Mapped::Removing { asked: false } if p.holds == 0 && !closed => {
p.mapped = Mapped::Removing { asked: true };
let len = p.block.len;
drop(st);
(self.host.remove)(at, len);
st = self.state.lock();
}
Mapped::Removing { .. } if p.holds == 0 && closed => p.mapped = Mapped::Removed,
Mapped::Removed if p.holds == 0 => {
st.pieces.remove(&at);
st.by_block.remove(&block);
return;
}
_ => {
let waited = (self.now)().saturating_duration_since(started);
if !warned && waited > Duration::from_secs(1) {
warned = true;
log::warn!(
"pool: the piece at {at:#x} still waits to go back after 1 s: {}",
if p.holds > 0 {
"a thread of the device's holds it"
} else {
"the host has not removed it"
}
);
}
let _ = self.changed.wait_for(&mut st, Duration::from_millis(250));
}
}
}
Some((at, contents))
}
/// [`Pool::close`]'s part, once the pool's thread has ended: waits for every hold on the
+39 -17
View File
@@ -10,10 +10,13 @@
//! that fits, first fit), on the thread that carries the take out, with the pool's lock held and
//! nothing else done: it never allocates and never zeroes. The take then goes to its context's
//! worker (`reims-vgpu.graphics-pool-take`), which zeroes the block through the piece's host
//! mapping and answers. Where nothing fits, the worker asks for a piece of the take's length, waits
//! for the pool's thread to place it and the host to map it, and carves again. A context's takes
//! are answered in its own order, one worker a context with a take in flight, so a take waits only
//! behind its own context's earlier ones, never behind another's growth or zeroing. A worker goes
//! mapping and answers. Where nothing fits, the worker takes a block of the take's length from the
//! source with the pool's lock let go of, so only this take waits for its allocation, and hands it
//! to the pool's thread, which places it ahead of the headroom's blocks; once the host mapped the
//! piece, the worker carves again. A context's takes are answered in its own order, one worker a
//! context with a take in flight, so a take waits only behind its own context's earlier ones,
//! never behind another's growth or zeroing, nor behind the headroom's blocks or the pieces going
//! back. A worker goes
//! after [`WORKER_IDLE`] with no take. Every block reads zero at its answer: its worker zeroes
//! it at its take, off the thread that carried the take out, its bytes counted
//! ([`super::TAKE_ZEROED_BYTES_CODE`]), but for those the pool's zeroer zeroed ahead of it
@@ -103,11 +106,12 @@ use parking_lot::MutexGuard;
use reims_vgpu_vulkan::answer::count_kind_by;
use super::{
Ask, Error, Live, Mapped, MonoTime, Piece, Shared, State, TAKE_CLAIM_WAIT_MAX_NS_CODE,
TAKE_CLAIM_WAIT_NS_CODE, TAKE_CLAIM_WAITS_CODE, TAKE_WAIT_CODES, TAKE_WAITS_CODE,
TAKE_ZERO_PREZEROED_BYTES_CODE, TAKE_ZEROED_BYTES_CODE, ZERO_HOLD_LONG, ZERO_HOLD_MAX_NS_CODE,
ZERO_HOLD_PART_MAX_NS_CODES, ZERO_HOLDS_LONG_CODE, ZERO_LONG_HOLD_PART_NS_CODES,
ZERO_WRITE_MAX_NS_CODE, ZERO_WRITE_NS_CODE, ZEROED_AHEAD_BYTES_CODE,
Error, Live, Mapped, MemoryClass, MonoTime, Own, Piece, Shared, State,
TAKE_CLAIM_WAIT_MAX_NS_CODE, TAKE_CLAIM_WAIT_NS_CODE, TAKE_CLAIM_WAITS_CODE, TAKE_WAIT_CODES,
TAKE_WAITS_CODE, TAKE_ZERO_PREZEROED_BYTES_CODE, TAKE_ZEROED_BYTES_CODE, ZERO_HOLD_LONG,
ZERO_HOLD_MAX_NS_CODE, ZERO_HOLD_PART_MAX_NS_CODES, ZERO_HOLDS_LONG_CODE,
ZERO_LONG_HOLD_PART_NS_CODES, ZERO_WRITE_MAX_NS_CODE, ZERO_WRITE_NS_CODE,
ZEROED_AHEAD_BYTES_CODE,
};
/// A block's alignment and its length's granule: 64 KiB, the wire's `RGFX_POOL_BLOCK_ALIGN`.
@@ -1038,10 +1042,11 @@ impl Shared {
}
/// A carve of `len` bytes for the take of `context` numbered `life`, which none fitted at its
/// take: asks the pool for a piece of `len`, waits for its thread to place it and the host to
/// map it, and carves again, until a carve fits, no piece comes, or the take is stale. Where
/// the zeroer's claimed chunk alone keeps it out, it waits for the chunk's write instead of
/// asking, counted (the module doc's "Zeros ahead").
/// take: takes a block of `len` from the source with the pool's lock let go of, so only this
/// take waits for its allocation, hands it to the pool's thread to place, waits for its place
/// and the host's map, and carves again, until a carve fits, no piece comes, or the take is
/// stale. Where the zeroer's claimed chunk alone keeps it out, it waits for the chunk's write
/// instead, counted (the module doc's "Zeros ahead").
fn carve_grown(
&self,
st: &mut MutexGuard<'_, State>,
@@ -1073,12 +1078,29 @@ impl Shared {
continue;
}
asked = asked.or_else(|| Some((self.now)()));
let Some(source) = st.source.clone() else {
return Grown::Stale;
};
let block = MutexGuard::unlocked(st, || source.take_block(MemoryClass::Shared, len));
let block = match block {
Ok(block) => block,
Err(e) => {
MutexGuard::unlocked(st, || {
log::warn!(kind:? = e; "pool: no block of {len} bytes: {e:?}");
});
return Grown::NoRoom;
}
};
if !st.stands(context, life) {
// Its take ended, or the device was released, meanwhile: it goes back unplaced.
MutexGuard::unlocked(st, || {
let _ = source.release_block(block.id);
});
return Grown::Stale;
}
let wait = st.next_serial();
st.waits.insert(wait, None);
st.asks.push_back(Ask {
length: len,
wait: Some(wait),
});
st.own.push_back(Own { block, wait });
self.changed.notify_all();
let placed = loop {
if !st.stands(context, life) {
+151
View File
@@ -1280,6 +1280,157 @@ impl BlockSource for Gated {
}
}
/// A source whose takes of the lengths `gated` names wait until the test opens its gate, counted
/// as they wait; the rest are [`HostBlocks`]'.
struct Held {
blocks: HostBlocks,
gated: fn(u64) -> bool,
open: Mutex<bool>,
waiting: Mutex<usize>,
changed: Condvar,
}
impl Held {
fn new(gated: fn(u64) -> bool) -> Arc<Held> {
Arc::new(Held {
blocks: HostBlocks::new(),
gated,
open: Mutex::new(false),
waiting: Mutex::new(0),
changed: Condvar::new(),
})
}
/// The pool over `range(64)` on `host` and `clock`, its blocks from `self`.
fn pool(self: &Arc<Self>, host: &Arc<Host>, delay: Duration, clock: PoolNow) -> Pool {
let source: Arc<dyn BlockSource> = Arc::clone(self) as _;
Pool::with_delay(range(64), host.pool_host(), delay, clock, source).unwrap()
}
/// Waits until `n` takes wait at the gate, or the test fails after 10 s.
fn wait_waiting(&self, n: usize) {
let deadline = Instant::now() + Duration::from_secs(10);
let mut waiting = self.waiting.lock();
while *waiting < n {
assert!(
!self.changed.wait_until(&mut waiting, deadline).timed_out(),
"{} takes wait at the gate, not {n}",
*waiting
);
}
}
/// Opens the gate.
fn open(&self) {
*self.open.lock() = true;
self.changed.notify_all();
}
/// A guard that opens the gate at its drop: made after the pool, it drops first, so a test
/// that fails with a take at the gate still closes its pool.
fn opener(self: &Arc<Self>) -> Opener {
Opener(Arc::clone(self))
}
}
/// [`Held::opener`].
struct Opener(Arc<Held>);
impl Drop for Opener {
fn drop(&mut self) {
self.0.open();
}
}
impl BlockSource for Held {
fn take_block(&self, class: MemoryClass, len: u64) -> Result<BlockInfo, BlockError> {
if (self.gated)(len) {
*self.waiting.lock() += 1;
self.changed.notify_all();
let mut open = self.open.lock();
while !*open {
self.changed.wait(&mut open);
}
}
self.blocks.take_block(class, len)
}
fn release_block(&self, block: BlockId) -> Result<(), BlockError> {
self.blocks.release_block(block)
}
}
/// A take that fits no piece takes a block of its own length on its context's worker, and the
/// pool's thread places and maps it ahead of the headroom's: it waits behind none of the blocks
/// the pool's taker takes, which here wait at the source
#[test]
fn a_take_of_a_piece_of_its_own_waits_behind_no_headroom_block() {
let host = Arc::new(Host::default());
let source = Held::new(|len| len <= BLOCK_LEN);
let pool = source.pool(&host, LONG, now());
let _open = source.opener();
let ledger = pool.ledger();
assert!(ledger.keep_headroom());
source.wait_waiting(1);
let long = BLOCK_LEN + TAKE_ALIGN;
let rx = take(&ledger, 1, long);
// [`HostBlocks`] rounds a block longer than a unit up to 2 MiB.
let own = BLOCK_LEN + 2 * MIB;
assert_eq!(host.wait_for(1), [Call::Add(BASE, own)]);
pool.added(BASE).unwrap();
assert_eq!(answer(&rx), Some((0, long)));
// The headroom's blocks come once the source gives them, placed past the take's.
source.open();
let adds: Vec<_> = (0..KEPT)
.map(|i| Call::Add(BASE + own + i * BLOCK_LEN, BLOCK_LEN))
.collect();
assert_eq!(host.wait_for(1 + KEPT_CALLS)[1..], adds[..]);
}
/// While a take's own block is being made (here: it waits at the source), the rest of the pool
/// goes on: a piece empty past its delay is asked out of the guest, its remove left unanswered by
/// the host; another context's take is carved and answered; and the next headroom piece its take
/// asked is taken, placed past the piece going back, and mapped. The take's block, once it comes,
/// is placed past them and answered, and the piece going back goes once the host removed it
#[test]
fn a_takes_own_block_holds_up_no_other_take_headroom_or_give_back() {
let delay = Duration::from_millis(50);
let (host, hand) = (Arc::new(Host::default()), Hand::default());
let source = Held::new(|len| len > BLOCK_LEN);
let pool = source.pool(&host, delay, hand.clock());
let _open = source.opener();
for _ in 0..=KEPT {
pool.grow(BLOCK_LEN);
}
let n = KEPT_CALLS + 1;
host.wait_for(n);
for i in 0..=KEPT {
pool.added(BASE + i * BLOCK_LEN).unwrap();
}
let ledger = pool.ledger();
let long = BLOCK_LEN + TAKE_ALIGN;
let rx = take(&ledger, 1, long);
source.wait_waiting(1);
hand.on(delay);
assert_eq!(host.wait_for(n + 1)[n], Call::Remove(PAST, BLOCK_LEN));
assert_eq!(answer(&take(&ledger, 2, TAKE_ALIGN)), Some((0, TAKE_ALIGN)));
let next = PAST + BLOCK_LEN;
assert_eq!(host.wait_for(n + 2)[n + 1], Call::Add(next, BLOCK_LEN));
pool.added(next).unwrap();
assert!(rx.try_recv().is_err(), "answered before its block came");
source.open();
let at = next + BLOCK_LEN;
assert_eq!(
host.wait_for(n + 3)[n + 2],
Call::Add(at, BLOCK_LEN + 2 * MIB)
);
pool.added(at).unwrap();
assert_eq!(answer(&rx), Some((at - BASE, long)));
pool.removed(PAST).unwrap();
wait_counts(&source.blocks, n + 1, 1);
assert_eq!(host.calls().len(), n + 3);
}
/// A block the source hands out once the device's release began goes back to it, and the host
/// is asked to map nothing: it removed its pieces before the release
#[test]
+23 -19
View File
@@ -498,8 +498,9 @@ so a block that takes a recursive lock its caller holds would re-enter it.
ahead on Windows (`reims-vgpu.graphics-drawn-spares-<i>`), video
(`reims-vgpu.graphics-video-<i>`) and event waits (`reims-vgpu.graphics-event-waits`). How
long a pool keeps an idle thread is `reims-vgpu-graphics`'s `keep`. The guest's Shared pool
has a thread of its own (`reims-vgpu.graphics-pool`, 15.1), which takes blocks and gives them
back.
has two threads of its own (15.1): its taker (`reims-vgpu.graphics-pool-ahead`), which takes
the blocks of its own asks for more pool, and its thread (`reims-vgpu.graphics-pool`), which
places the blocks, has the host map them and gives them back.
- A worker per serial queue while it has work (it ends after 5 s idle), the process's display
thread among them.
- Metal's completion threads, and the host's own threads inside a call that may call back (both
@@ -945,23 +946,26 @@ The guest's Shared pool (`pool.rs`, api.md "The guest's Shared pool") is a range
addresses with no RAM under it. The host names the addresses it can give in the config, and the
device takes as many as its GPU device's memory heaps hold, every heap summed (`pool_range` in
`graphics.rs`, `PoolConfig::sized`, the sum from `GpuDevice::memory_heaps_total`), which the host
then reserves (`rvg_graphics_device_pool_range`). The pool's thread takes Shared blocks from its
block source, places each at the range's lowest free 2 MiB-aligned address, and has the host map it
there (`pool_add`); a piece is found only once the host says it is in (`pool_added`). The source is
rt's blocks (`pool::RtBlocks`, the platform's `ApiPlatform::block_source`), each known to its device
while handed out; where a platform gives none (the testkit's), it is `HostBlocks`, the process's own
memory, in the same shape (`take_block`, `release_block`). A piece the pool asks for itself is one
of metal2vulkan-rt's units, 16 MiB (`BLOCK_LEN`, read from rt), and a take longer than a unit has a
piece of its own length. The pool keeps 64 MiB of empty pieces as headroom (`HEADROOM`), from the
guest driver's take of `POOL` on (`Host::pool_taken`), so the guest's first takes find them, and
gives a piece above them that stays empty past `RELEASE_DELAY` back to the source, which keeps it
ready or frees it. Before a block goes back the pool takes its piece out of the lookups, waits for
the device's holds on it, asks the host to remove it (`pool_remove`), and gives the block back once
the host says it is out (`pool_removed`), so the source may free any block it gets back at once: no
guest access and no thread touches it. A block taken again is placed and mapped anew. The device's
drop closes the pool after its windows: the pool's thread ends, the pool waits for every hold, gives
every block back and lets go of the source, which frees them; the host has removed every piece
before the release (QEMU at its teardown), so the pool asks it nothing then.
then reserves (`rvg_graphics_device_pool_range`). The pool's taker takes Shared blocks from its
block source for the pool's own asks, and a take that fits no piece takes a block of its own length
on its context's take worker, so only that take waits for the source's allocation. The pool's thread
places each block, the takes' first, at the range's lowest free 2 MiB-aligned address, and has the
host map it there (`pool_add`); a piece is found only once the host says it is in (`pool_added`).
The source is rt's blocks (`pool::RtBlocks`, the platform's `ApiPlatform::block_source`), each known
to its device while handed out; where a platform gives none (the testkit's), it is `HostBlocks`, the
process's own memory, in the same shape (`take_block`, `release_block`). A piece the pool asks for
itself is one of metal2vulkan-rt's units, 16 MiB (`BLOCK_LEN`, read from rt), and a take longer than
a unit has a piece of its own length. The pool keeps 64 MiB of empty pieces as headroom
(`HEADROOM`), from the guest driver's take of `POOL` on (`Host::pool_taken`), so the guest's first
takes find them, and gives a piece above them that stays empty past `RELEASE_DELAY` back to the
source, which keeps it ready or frees it. Before a block goes back the pool takes its piece out of
the lookups, asks the host to remove it (`pool_remove`) once the device's holds on it are gone, and
gives the block back once the host says it is out (`pool_removed`), its thread waiting for neither
meanwhile, so the source may free any block it gets back at once: no guest access and no thread
touches it. A block taken again is placed and mapped anew. The device's drop closes the pool after
its windows: the pool's threads end, the pool waits for every hold, gives every block back and lets
go of the source, which frees them; the host has removed every piece before the release (QEMU at its
teardown), so the pool asks it nothing then.
### 15.3 Drop order is explicit
+8 -4
View File
@@ -4858,9 +4858,12 @@ reads it once.
piece with room, first fit at a multiple of 64 KiB, on the thread that
carries the take out, neither allocating nor zeroing there; the context's
own worker (`reims-vgpu.graphics-pool-take`) zeroes the block through the
host's mapping and answers, first growing the pool by a piece of the take's
length where nothing fit; rt says nothing of a block's bytes as it hands
it out, so bytes no block of the piece held before are zeroed too. Ahead
host's mapping and answers. Where nothing fit, the worker first takes a
block of the take's length from rt itself, so only that take waits for
rt's allocation, and the pool's thread places it ahead of the headroom's
blocks; the worker carves the take once the host has mapped it. rt says
nothing of a block's bytes as it hands it out, so bytes no block of the
piece held before are zeroed too. Ahead
of the takes, the pool's zeroer (`reims-vgpu.graphics-pool-zero`) zeroes,
off every take's path, the bytes no block holds in each piece a block
lies in and in the headroom's pieces (below), a new piece's from its place
@@ -4873,7 +4876,8 @@ reads it once.
lies where it would with no zeroer. No other empty piece is zeroed: it goes back
whole. The device's release waits for the zeroer and the take workers to
let go of the pool. So a context's takes are answered in its order, and
never wait behind another context's growth or zeroing. The host keeps
never wait behind another context's growth or zeroing, nor behind the
headroom's blocks or the pieces going back. The host keeps
64 MiB of empty pieces ahead of the takes from the kext's take of `POOL`
on (`Host::pool_taken`), each 16 MiB, metal2vulkan-rt's unit, so a take
grows the pool only where those pieces have no room for it, as a take longer