🐎 Walk a queue's command buffers at once, committed in turn
One process's busy queue was bound to its service thread: the thread walked and committed each command buffer before it took the next, so a single app drawing 10k draws a buffer topped out near 460k draws/s, and a buffer that asks for its CB_SUBMITTED was taken, and answered, only once the buffer before it on its queue was walked (WindowServer's composite, 2-4 ms a frame). The service thread now begins each buffer, posts its CB_SUBMITTED where it gets it at its take, and hands the walk and the commit to the queue's lane, whose threads walk several buffers at once. What the guest sees keeps the order it had when one buffer was carried out after another: - each buffer takes a turn in its lane at its begin, and its commit, its stand-in's and a failure posted at once for it wait for the turns before it, so they come in the order the buffers were taken; - a buffer that waits for an event holds its queue from its begin, not its commit, so a later buffer is still answered at its scheduling; - a buffer with a video encoder is walked in its turn, as its session's work starts at the walk; - a buffer's signal of its queue's surface timeline, and the release of one that does not run, are decided in its turn, so the surface order still sees a queue's buffers taken in their ring's order: a waiter that read a later buffer taken would otherwise skip its wait for an earlier one still walking. Threads stay bounded: a busy lane keeps one thread of its own, and gets up to three more only from a device-wide budget of twice the host's cores, which it never waits for (2048 busy queues hold one thread each and the budget's). The contract argument is in design.md, "A queue's own order".
This commit is contained in:
1 parent
725fd5d42c
commit
e9e2b69241
7 files changed
+972
-71
No files matched your search
@@ -28,7 +28,8 @@ use std::os::fd::RawFd;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
use parking_lot::RwLock;
|
||||
use parking_lot::lock_api::ArcRwLockReadGuard;
|
||||
use parking_lot::{RawRwLock, RwLock};
|
||||
use reims_graphics::ops::RgfxCommandBuffer;
|
||||
use reims_graphics::region::Region;
|
||||
use reims_graphics::wire::{
|
||||
@@ -73,7 +74,7 @@ use crate::graphics::compile::{CompileKind, CompileOf, CompilePool, Pending};
|
||||
use crate::graphics::completion::cb_failed;
|
||||
use crate::graphics::decode::worker::{Unsettled, Worker};
|
||||
use crate::graphics::decode::{
|
||||
CompletionSink, DecodeError, Decoders, FailedContexts, GraphicsDecoder, LibraryJob,
|
||||
Begun, CompletionSink, DecodeError, Decoders, FailedContexts, GraphicsDecoder, LibraryJob,
|
||||
LibraryStart, MadeLibrary, PipelineJob, ReflectionSink, ScheduledSink, SignalSink, Sinks,
|
||||
SubmittedSink, compile_refusing, complete, make_library, refused_reply, refusing,
|
||||
};
|
||||
@@ -706,9 +707,11 @@ impl<P: ApiPlatform> GraphicsControl<P> {
|
||||
///
|
||||
/// A pipeline or library create is made on the compile pool instead
|
||||
/// ([`Self::start_pipeline`], [`Self::start_library`]), and a command buffer that names a
|
||||
/// pipeline still compiling waits for it first (`compile`). An indirect command buffer's
|
||||
/// create is made on the ICB thread ([`Self::start_icb`]), and the destroy of one still being
|
||||
/// made waits for it. A library lookup is answered here ([`Self::lookup_library`]).
|
||||
/// pipeline still compiling waits for it first (`compile`), and is then begun here and walked
|
||||
/// and committed on its queue's lane ([`Self::begin_command_buffer`]). An indirect command
|
||||
/// buffer's create is made on the ICB thread ([`Self::start_icb`]), and the destroy of one
|
||||
/// still being made waits for it. A library lookup is answered here
|
||||
/// ([`Self::lookup_library`]).
|
||||
fn handle_stage3(self: &Arc<Self>, poster: &CompletionPoster, message: &[u8]) {
|
||||
let r#type = RgfxMsgHeader::read_from_prefix(message).map_or(0, |(h, _)| h.r#type);
|
||||
match r#type {
|
||||
@@ -740,7 +743,13 @@ impl<P: ApiPlatform> GraphicsControl<P> {
|
||||
self.start_icb(poster, message);
|
||||
return;
|
||||
}
|
||||
RGFX_CMD_COMMAND_BUFFER => self.pending.wait_for_command_buffer(message),
|
||||
RGFX_CMD_COMMAND_BUFFER => {
|
||||
self.pending.wait_for_command_buffer(message);
|
||||
if !foreign_queue(poster, message) {
|
||||
self.begin_command_buffer(poster, message);
|
||||
return;
|
||||
}
|
||||
}
|
||||
RGFX_CMD_ICB_WRITE => self.pending.wait_for_icb_write(message),
|
||||
// The destroy of an indirect command buffer still being made (the kext destroys
|
||||
// behind a create it stopped waiting for, after a minute, or one made for a context
|
||||
@@ -892,19 +901,90 @@ impl<P: ApiPlatform> GraphicsControl<P> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A `COMMAND_BUFFER` `message` of the process's own queue, which `poster` posts onto, on the
|
||||
/// queue's service thread ([`Self::handle_stage3`]): begun here, its turn in its queue's lane
|
||||
/// taken first and its `CB_SUBMITTED` posted where it gets it at its take
|
||||
/// ([`GraphicsDecoder::begin_taken`]), then walked and committed on the lane, in its turn
|
||||
/// ([`Self::carry_out`]), so the thread goes on to the queue's next buffer meanwhile.
|
||||
fn begin_command_buffer(self: &Arc<Self>, poster: &CompletionPoster, message: &[u8]) {
|
||||
entry::run(|_| {
|
||||
// Held to the end of the buffer's work, on its lane ([`Self::reset_gate`]).
|
||||
let carried = self.reset_gate.read_arc();
|
||||
// Of a queue the device's reset ended, which the decoder's reset dropped, or is to
|
||||
// drop: nothing of it is carried out, and nothing is owed.
|
||||
if poster.stale() {
|
||||
return;
|
||||
}
|
||||
let mut decoder =
|
||||
(self.decoders).sender(Some(sender_context(poster, message)), self.sinks(poster));
|
||||
let begun =
|
||||
refusing(|| decoder.begin_taken(&self.device, message, poster.queue_obj_id()));
|
||||
self.carry_out(decoder, begun, carried, poster.clone(), message.to_vec());
|
||||
});
|
||||
}
|
||||
|
||||
/// The rest of the `COMMAND_BUFFER` `message`'s work once it is begun (`begun`, on `decoder`),
|
||||
/// on its queue's lane where it took a turn there ([`GraphicsDecoder::lane`]), else here: it
|
||||
/// is walked and committed in its turn ([`GraphicsDecoder::finish_command_buffer`]), stood in
|
||||
/// for where it was not carried out, and reported through `poster` as
|
||||
/// [`Self::handle_stage3`] reports a message, its failure posted in its turn too. The decoder
|
||||
/// lets go of what the message holds, and `carried` of the reset gate, before the report,
|
||||
/// which may wait for room on the ring.
|
||||
fn carry_out(
|
||||
self: &Arc<Self>,
|
||||
decoder: GraphicsDecoder<P>,
|
||||
begun: RaiseResult<Result<Begun<P>, DecodeError>>,
|
||||
carried: ArcRwLockReadGuard<RawRwLock, ()>,
|
||||
poster: CompletionPoster,
|
||||
message: Vec<u8>,
|
||||
) {
|
||||
let lane = decoder.lane();
|
||||
let control = Arc::clone(self);
|
||||
let job = move || {
|
||||
entry::run(|_| {
|
||||
let mut decoder = decoder;
|
||||
let outcome = match begun {
|
||||
Ok(Ok(begun)) => {
|
||||
refusing(|| decoder.finish_command_buffer(&control.device, &message, begun))
|
||||
}
|
||||
Ok(Err(e)) => Ok(Err(e)),
|
||||
Err(raise) => Err(raise),
|
||||
};
|
||||
let stood_in = !matches!(outcome, Ok(Ok(())))
|
||||
&& matches!(
|
||||
refusing(|| decoder.stand_in_for_failed(&control.device, &message)),
|
||||
Ok(true)
|
||||
);
|
||||
// A failure posted below comes after the commits of the buffers before it.
|
||||
if !matches!(outcome, Ok(Ok(()))) && !stood_in {
|
||||
decoder.wait_turn();
|
||||
}
|
||||
let turn = decoder.take_turn();
|
||||
drop(decoder);
|
||||
drop(carried);
|
||||
control.report(&poster, &message, outcome, stood_in);
|
||||
drop(turn);
|
||||
});
|
||||
};
|
||||
match lane {
|
||||
Some(lane) => lane.run(Box::new(job)),
|
||||
None => job(),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Host::take_command_buffer`]: takes the `COMMAND_BUFFER` `message` of the queue `poster`
|
||||
/// posts onto, on a doorbell's thread, where it gets its `CB_SUBMITTED` at its take
|
||||
/// ([`GraphicsDecoder::submits_at_take`]) and nothing need be waited for: it runs on that
|
||||
/// queue, every lock of the decoder's it takes is free, each tried, and no pipeline it names is
|
||||
/// still compiling. It is begun here, its command buffer made and its sinks pointed at the
|
||||
/// queue's ring, as [`Self::handle_stage3`] begins it, and its decoder is carried to the
|
||||
/// queue's service thread with the rest of its work, which walks and commits it, then reports
|
||||
/// a failure as `handle_stage3` does. Its `CB_SUBMITTED` is posted here, waiting for nothing,
|
||||
/// once its ticket in the commit order is issued, which the guest's later buffers are
|
||||
/// committed after (`decode`'s `sequencer`); else by the service thread before the walk. A
|
||||
/// buffer the platform refused at its make gets none, and its failure on the service thread.
|
||||
/// A take that is not made lets go of what it took, under locks each held for a short section
|
||||
/// only.
|
||||
/// still compiling. It is begun here, its turn in its queue's lane taken, its command buffer
|
||||
/// made and its sinks pointed at the queue's ring, as [`Self::begin_command_buffer`] begins
|
||||
/// it, and its decoder is carried to the queue's service thread with the rest of its work,
|
||||
/// which the thread hands to the lane ([`Self::carry_out`]). Its `CB_SUBMITTED` is posted
|
||||
/// here, waiting for nothing, once its ticket in the commit order is issued, which the guest's
|
||||
/// later buffers are committed after (`decode`'s `sequencer`); else by the service thread
|
||||
/// before it hands the rest over. A buffer the platform refused at its make gets none, and its
|
||||
/// failure in its turn. A take that is not made lets go of what it took, its turn among them,
|
||||
/// under locks each held for a short section only.
|
||||
fn take_command_buffer(
|
||||
self: &Arc<Self>,
|
||||
poster: &CompletionPoster,
|
||||
@@ -949,21 +1029,7 @@ impl<P: ApiPlatform> GraphicsControl<P> {
|
||||
decoder.issue_ticket(false);
|
||||
submitted.post();
|
||||
}
|
||||
let outcome = match begun {
|
||||
Ok(Ok(begun)) => {
|
||||
refusing(|| decoder.finish_command_buffer(&control.device, &message, begun))
|
||||
}
|
||||
Ok(Err(e)) => Ok(Err(e)),
|
||||
Err(raise) => Err(raise),
|
||||
};
|
||||
let stood_in = !matches!(outcome, Ok(Ok(())))
|
||||
&& matches!(
|
||||
refusing(|| decoder.stand_in_for_failed(&control.device, &message)),
|
||||
Ok(true)
|
||||
);
|
||||
drop(decoder);
|
||||
drop(carried);
|
||||
control.report(&poster, &message, outcome, stood_in);
|
||||
control.carry_out(decoder, begun, carried, poster, message);
|
||||
});
|
||||
});
|
||||
Some(Taken { post, rest })
|
||||
|
||||
@@ -41,13 +41,15 @@
|
||||
//! **A take on the doorbell's thread.** A buffer that gets its `CB_SUBMITTED` at its take may be
|
||||
//! taken on the thread of the guest's doorbell write instead (`reims_graphics`'s
|
||||
//! `Device::mmio_write_taking`), where nothing need be waited for there
|
||||
//! ([`GraphicsDecoder::submits_at_take`]): it is begun there ([`GraphicsDecoder::begin_command_buffer`],
|
||||
//! which makes its command buffer and fills no device cache, trying each lock it takes), its
|
||||
//! `CB_SUBMITTED` posted there once its ticket in the commit order is issued, and its decoder
|
||||
//! carried to its queue's service thread, which walks and commits it
|
||||
//! ([`GraphicsDecoder::finish_command_buffer`]). A queue's command buffers made
|
||||
//! and not completed are counted ([`InFlight`]), so the platform's `commandBuffer`, which waits
|
||||
//! while a queue holds 64, does not wait on that thread.
|
||||
//! ([`GraphicsDecoder::submits_at_take`], which tries its turn in its queue's lane too): it is
|
||||
//! begun there ([`GraphicsDecoder::begin_command_buffer`], which makes its command buffer and
|
||||
//! fills no device cache, trying each lock it takes), its `CB_SUBMITTED` posted there once its
|
||||
//! ticket in the commit order is issued, and its decoder carried to its queue's service thread,
|
||||
//! which hands its walk and commit to the queue's lane ([`GraphicsDecoder::finish_command_buffer`],
|
||||
//! [`super::lane`]) as it hands those of every buffer it begins itself
|
||||
//! ([`GraphicsDecoder::begin_taken`]). A queue's command buffers made and not completed are
|
||||
//! counted ([`InFlight`]), so the platform's `commandBuffer`, which waits while a queue holds 64,
|
||||
//! does not wait on that thread.
|
||||
//!
|
||||
//! **Two kinds of failure.** A message or op that will not parse structurally — a
|
||||
//! short message, a bad `len`, an op body too short for a header — is a protocol
|
||||
@@ -99,6 +101,7 @@ use reims_vgpu_core::sync::Mutex;
|
||||
use zerocopy::FromBytes;
|
||||
|
||||
use super::super::completion::{cb_complete, cb_failed};
|
||||
use super::lane::{Lane, Turn};
|
||||
use super::surface_cache::Uses;
|
||||
use super::surface_order::{Marks, Signalled};
|
||||
use super::tables::QueueCounts;
|
||||
@@ -256,6 +259,9 @@ pub(crate) struct Begun<P: Platform> {
|
||||
behind: bool,
|
||||
/// Its context's drain.
|
||||
drain: Option<Arc<Drain>>,
|
||||
/// It holds a video encoder, so it is walked in its turn: its session's work starts as it is
|
||||
/// walked, and so in its queue's order.
|
||||
ordered: bool,
|
||||
}
|
||||
|
||||
impl<P: Platform> Begun<P> {
|
||||
@@ -267,14 +273,12 @@ impl<P: Platform> Begun<P> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Commits `cb`, counted in its queue's hold first where it is `held`.
|
||||
/// Commits `cb`, which holds its queue where it is `held` (counted since its begin), letting the
|
||||
/// queue go where the commit fails.
|
||||
fn commit_holding<C: CommandBuffer<P>, P: Platform>(
|
||||
cb: &C,
|
||||
held: Option<&Held>,
|
||||
) -> RaiseResult<()> {
|
||||
if let Some(held) = held {
|
||||
held.queue.fetch_add(1, Ordering::AcqRel);
|
||||
}
|
||||
let committed = cb.commit(ON);
|
||||
if committed.is_err()
|
||||
&& let Some(held) = held
|
||||
@@ -284,8 +288,8 @@ fn commit_holding<C: CommandBuffer<P>, P: Platform>(
|
||||
committed
|
||||
}
|
||||
|
||||
/// A committed command buffer that waits for an event, counted in its queue's hold
|
||||
/// ([`GraphicsDecoder`]'s `held_queues`) until it is scheduled, or else finishes.
|
||||
/// A command buffer that waits for an event, counted in its queue's hold ([`QueueCounts`]'s
|
||||
/// `held`) from its begin until it is scheduled, or else finishes, or goes uncommitted.
|
||||
struct Held {
|
||||
/// Its queue's count of such buffers not yet scheduled.
|
||||
queue: Arc<AtomicUsize>,
|
||||
@@ -302,6 +306,13 @@ impl Held {
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Held {
|
||||
/// A buffer never committed, or whose handlers went unrun, lets its queue go.
|
||||
fn drop(&mut self) {
|
||||
self.release();
|
||||
}
|
||||
}
|
||||
|
||||
/// The submission handler of a command buffer: once the platform has taken its work for the GPU,
|
||||
/// it lets the buffer's queue go where the buffer `held` it, posts its `submitted` where not yet
|
||||
/// posted, and then its `scheduled`, so the guest's command buffer becomes `Scheduled` and its
|
||||
@@ -328,13 +339,17 @@ fn submission_handler(
|
||||
}))
|
||||
}
|
||||
|
||||
/// Whether the queue whose counts are `counts` is held, a buffer of it that waits for an event not
|
||||
/// yet scheduled; and, where the buffer to commit `waits` for an event (the host's fill of a device
|
||||
/// cache among them), its own hold of the queue, which keeps it and the queue's later buffers from
|
||||
/// being submitted before it is scheduled, as Metal submits a queue's buffers in order.
|
||||
/// Whether the queue whose counts are `counts` is held, a buffer of it begun before that waits for
|
||||
/// an event and is not yet scheduled; and, where the buffer begun now `waits` for an event (the
|
||||
/// host's fill of a device cache among them), its own hold of the queue, counted from now, which
|
||||
/// keeps it and the queue's later buffers from being submitted before it is scheduled, as Metal
|
||||
/// submits a queue's buffers in order. It is counted at the buffer's begin, not its commit, so a
|
||||
/// buffer of the queue begun before this one commits (its lane walks several at once,
|
||||
/// [`super::lane`]) is behind it, as one begun after its commit is.
|
||||
fn hold(counts: &QueueCounts, waits: bool) -> (bool, Option<Arc<Held>>) {
|
||||
let behind = counts.held.load(Ordering::Acquire) > 0;
|
||||
let held = waits.then(|| {
|
||||
counts.held.fetch_add(1, Ordering::AcqRel);
|
||||
Arc::new(Held {
|
||||
queue: Arc::clone(&counts.held),
|
||||
released: AtomicBool::new(false),
|
||||
@@ -377,6 +392,8 @@ struct Take {
|
||||
asks: bool,
|
||||
/// The buffers of other queues its first `SURFACE_ORDER` names, where it holds one.
|
||||
order: Option<Vec<RgfxSurfaceOrderWait>>,
|
||||
/// The stream holds a video encoder, whose session's work starts as it is walked.
|
||||
video: bool,
|
||||
}
|
||||
|
||||
/// What the host takes of the op stream `ops` ([`Take`]). The scan stops at an op it cannot step
|
||||
@@ -406,6 +423,7 @@ fn take(mut ops: &[u8]) -> Take {
|
||||
.collect();
|
||||
out.order = Some(waits);
|
||||
}
|
||||
RGFX_OP_ENCODER_BEGIN_VIDEO => out.video = true,
|
||||
_ => {}
|
||||
}
|
||||
ops = &ops[len..];
|
||||
@@ -549,13 +567,87 @@ impl<P: Platform> GraphicsDecoder<P> {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
// Its turn in its queue's lane, tried here, so its begin takes no lock it need wait for; a
|
||||
// take not made lets the turn go at once.
|
||||
let Some(turn) = self.turn_on(counts) else {
|
||||
return false;
|
||||
};
|
||||
let Some(held) = self.surface_caches.hold_ready(&take.uses) else {
|
||||
return false;
|
||||
};
|
||||
*self.turn.borrow_mut() = turn;
|
||||
*self.held_caches.borrow_mut() = Some(held);
|
||||
true
|
||||
}
|
||||
|
||||
/// The command buffer's turn in the lane of the queue whose counts are `counts`
|
||||
/// ([`super::lane`]): `Some(None)` where the queue has no lane, `None` where only tried and
|
||||
/// the lane is busy.
|
||||
fn turn_on(&self, counts: &QueueCounts) -> Option<Option<Turn>> {
|
||||
match &counts.lane {
|
||||
Some(lane) => lane.turn(self.try_only).map(Some),
|
||||
None => Some(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Begins the `COMMAND_BUFFER` `message` a queue's service thread takes off the ring of the
|
||||
/// queue `queue`, as [`Self::decode_command_buffer`] carries it out up to its walk, which
|
||||
/// [`Self::finish_command_buffer`] does on the queue's lane ([`super::lane`]). Its turn in the
|
||||
/// lane is taken first, after its drain and before anything of it can fail, so its commit,
|
||||
/// its stand-in's or the failure posted for it comes in the order the queue's buffers were
|
||||
/// taken; a context whose work is refused gets [`DecodeError::ContextFailed`], as `decode`
|
||||
/// answers it; and where it gets its `CB_SUBMITTED` at its take, that is posted here, once its
|
||||
/// ticket in the commit order is issued.
|
||||
pub(crate) fn begin_taken(
|
||||
&mut self,
|
||||
device: &P::Device,
|
||||
message: &[u8],
|
||||
queue: Option<u64>,
|
||||
) -> RaiseResult<Result<Begun<P>, DecodeError>> {
|
||||
self.end_message();
|
||||
let drain = self.command_buffer_drain();
|
||||
if let Some(counts) = queue.and_then(|queue| self.queue_counts(queue))
|
||||
&& let Some(turn) = self.turn_on(counts)
|
||||
{
|
||||
*self.turn.borrow_mut() = turn;
|
||||
}
|
||||
if self.context_failed() {
|
||||
return Ok(Err(DecodeError::ContextFailed));
|
||||
}
|
||||
let begun = match self.begin_command_buffer(device, message, drain, true)? {
|
||||
Ok(begun) => begun,
|
||||
Err(e) => return Ok(Err(e)),
|
||||
};
|
||||
if let Some(submitted) = begun.submitted_at_take() {
|
||||
self.issue_ticket(false);
|
||||
submitted.post();
|
||||
}
|
||||
Ok(Ok(begun))
|
||||
}
|
||||
|
||||
/// Waits, with no lock held, for the turns in its queue's lane before the command buffer's
|
||||
/// (one taken before it), where it has one ([`super::lane`]).
|
||||
pub(crate) fn wait_turn(&self) {
|
||||
if let Some(turn) = self.turn.borrow().as_ref() {
|
||||
turn.wait();
|
||||
}
|
||||
}
|
||||
|
||||
/// The lane of the command buffer's queue, where it was given a turn there.
|
||||
pub(crate) fn lane(&self) -> Option<Arc<Lane>> {
|
||||
self.turn
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.map(|turn| Arc::clone(turn.lane()))
|
||||
}
|
||||
|
||||
/// The command buffer's turn in its queue's lane, taken out of the handle, so the caller lets
|
||||
/// go of the rest of what the message holds and keeps its place in its queue's order (a
|
||||
/// failure it posts after).
|
||||
pub(crate) fn take_turn(&mut self) -> Option<Turn> {
|
||||
self.turn.get_mut().take()
|
||||
}
|
||||
|
||||
/// Begins the `COMMAND_BUFFER` `message`, whose completion handler will hold `drain`: opens a
|
||||
/// command buffer on the named queue, readies the device caches its `SURFACE_USE` ops use
|
||||
/// (filling each that holds an older generation, where `may_fill`; a doorbell's thread, which
|
||||
@@ -583,18 +675,15 @@ impl<P: Platform> GraphicsDecoder<P> {
|
||||
};
|
||||
// The queue the buffer runs on; a missing or wrong-kind queue is a
|
||||
// message-level bad reference (the op stream has not started).
|
||||
let cb = {
|
||||
let Some(ObjHandle::CommandQueue(queue)) = self.named(m.queue_obj_id) else {
|
||||
return Ok(Err(DecodeError::BadReference));
|
||||
};
|
||||
match queue.command_buffer(ON)? {
|
||||
Some(cb) => cb,
|
||||
None => return Ok(Err(DecodeError::Refused)),
|
||||
}
|
||||
let Some(ObjHandle::CommandQueue(queue)) = self.named(m.queue_obj_id) else {
|
||||
return Ok(Err(DecodeError::BadReference));
|
||||
};
|
||||
let Some(counts) = self.queue_counts(m.queue_obj_id) else {
|
||||
return Ok(Err(DecodeError::BadReference));
|
||||
};
|
||||
let Some(cb) = queue.command_buffer(ON)? else {
|
||||
return Ok(Err(DecodeError::Refused));
|
||||
};
|
||||
let in_flight = InFlight::new(&counts.in_flight);
|
||||
let take = take(ops);
|
||||
let held_caches = self.held_caches.borrow_mut().take();
|
||||
@@ -630,6 +719,7 @@ impl<P: Platform> GraphicsDecoder<P> {
|
||||
held,
|
||||
behind,
|
||||
drain,
|
||||
ordered: take.video,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -656,6 +746,7 @@ impl<P: Platform> GraphicsDecoder<P> {
|
||||
submitted,
|
||||
held,
|
||||
drain,
|
||||
ordered,
|
||||
..
|
||||
} = begun;
|
||||
let Some(ops) = read::<RgfxCommandBuffer>(message).and_then(|m| ops_of(message, &m)) else {
|
||||
@@ -664,9 +755,15 @@ impl<P: Platform> GraphicsDecoder<P> {
|
||||
// A structural malformation in the stream stops the walk and is reported;
|
||||
// everything else faults the exec and propagates.
|
||||
let mut events = EventOps::default();
|
||||
if ordered {
|
||||
self.wait_turn();
|
||||
}
|
||||
if let Err(e) = self.walk_ops(ops, &cb, &mut events)? {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
// After the buffers of its queue taken before it ([`super::lane`]): its signal of its
|
||||
// queue's surface timeline is decided in its ring's order ([`Self::order_signal`]).
|
||||
self.wait_turn();
|
||||
let signalled = self.order_signal(device, queue_obj_id, &marks, seqno, order, &cb)?;
|
||||
// Register the submission and completion paths and commit: no scheduled or completed
|
||||
// handler, so the platform posts the buffer's records from the threads that submit it
|
||||
@@ -761,6 +858,7 @@ impl<P: Platform> GraphicsDecoder<P> {
|
||||
.queue_counts(queue_obj_id)
|
||||
.map(|c| Arc::clone(&c.order));
|
||||
let queue = queue.as_ref();
|
||||
self.wait_turn();
|
||||
self.order_release(device, queue_obj_id, marks.as_deref(), seqno, names, queue)?;
|
||||
return Ok(false);
|
||||
}
|
||||
@@ -774,6 +872,7 @@ impl<P: Platform> GraphicsDecoder<P> {
|
||||
};
|
||||
let Some(cb) = queue.command_buffer(ON)? else {
|
||||
let marks = Some(&*counts.order);
|
||||
self.wait_turn();
|
||||
self.order_release(device, queue_obj_id, marks, seqno, names, Some(queue))?;
|
||||
return Ok(false);
|
||||
};
|
||||
@@ -801,6 +900,8 @@ impl<P: Platform> GraphicsDecoder<P> {
|
||||
let held = Arc::clone(held);
|
||||
cb.add_submission_handler(ON, Box::new(move || held.release()))?;
|
||||
}
|
||||
// In its queue's order ([`super::lane`]): its signal, and its commit.
|
||||
self.wait_turn();
|
||||
let signalled =
|
||||
self.order_signal(device, queue_obj_id, &counts.order, seqno, names, &cb)?;
|
||||
let handler = self.completed_handler(
|
||||
@@ -825,7 +926,10 @@ impl<P: Platform> GraphicsDecoder<P> {
|
||||
/// surface timeline as it ends where it `names` the op or a buffer of another queue waits
|
||||
/// past what the queue signalled ([`super::surface_order::SurfaceOrder::signal`]); what its
|
||||
/// completed handler then calls. One that holds no op and is waited for by none takes no lock
|
||||
/// ([`Marks::quiet`]).
|
||||
/// ([`Marks::quiet`]). Called in the buffer's turn in its queue's lane ([`super::lane`]), as
|
||||
/// [`Self::order_release`] is, so a queue's buffers note themselves taken in their ring's
|
||||
/// order whatever order their walks end in: the order reads a buffer taken past a seqno as
|
||||
/// every buffer up to it taken ([`super::surface_order`]).
|
||||
fn order_signal(
|
||||
&self,
|
||||
device: &P::Device,
|
||||
|
||||
@@ -0,0 +1,456 @@
|
||||
//! A command queue's lane: the walks and commits of the queue's command buffers, on threads of the
|
||||
//! lane's, several at once where there are several to do, each committed in its turn
|
||||
//! (docs/graphics-kext/design.md, "What a walk sees").
|
||||
//!
|
||||
//! - **Jobs.** The queue's service thread (or a doorbell's) takes and begins each command buffer,
|
||||
//! in the order the guest published them, and hands the rest of its work to the lane
|
||||
//! ([`Lane::run`]): its walk, its commit, its stand-in or the failure posted for it. The lane's
|
||||
//! threads take the jobs in the order they came.
|
||||
//! - **Threads.** A lane with work has one thread of its own, made as a job comes and none is
|
||||
//! running, which goes once it has had no job for [`IDLE`]. A job that comes while every thread
|
||||
//! of the lane is busy may get the lane another, up to [`LANE_THREADS`] in all, where the
|
||||
//! device's budget of such threads ([`Budget`]) has one to spare; a lane never waits for the
|
||||
//! budget, so those threads add speed and nothing else, and a device of many busy queues holds
|
||||
//! one thread a busy lane and the budget's at most.
|
||||
//! - **Turns.** Each command buffer is given a turn as it is begun, in the order they are taken
|
||||
//! ([`Lane::turn`]). Its commit (or its stand-in's, or the failure posted at once for it) waits
|
||||
//! for its turn ([`Turn::wait`]), which comes once every turn before it has passed, and its turn
|
||||
//! passes as its job ends ([`Turn`]'s drop): the queue's command buffers are committed in the
|
||||
//! order the guest sent them, as one after another, whatever order their walks end in. Metal
|
||||
//! allows a queue's command buffers to be encoded at once and committed in order.
|
||||
//! - **Why a thread of the lane's own.** Every wait of a job (its turn, its ticket in the commit
|
||||
//! order, a fill of a device cache) is for a command buffer begun before it, and a lane's
|
||||
//! threads take its jobs in the order they were begun, so the lane's own thread is always at
|
||||
//! or past its first unfinished job, and the device's first unfinished one always runs: the
|
||||
//! waits end. Threads only shared between queues could all be held by later jobs waiting for
|
||||
//! an earlier one not yet started.
|
||||
|
||||
use std::collections::{BTreeSet, VecDeque};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use reims_vgpu_core::sync::{Condvar, Mutex};
|
||||
|
||||
/// The most threads a lane runs its jobs on at once: its own and the budget's.
|
||||
pub(crate) const LANE_THREADS: usize = 4;
|
||||
|
||||
/// How long a lane's thread stays with no job before it goes.
|
||||
const IDLE: Duration = Duration::from_secs(1);
|
||||
|
||||
/// The rest of a command buffer's work, for a lane's thread.
|
||||
pub(crate) type Job = Box<dyn FnOnce() + Send>;
|
||||
|
||||
/// The device's budget of lanes' extra threads (the module doc): at most `limit` at once, across
|
||||
/// every lane.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Budget {
|
||||
limit: usize,
|
||||
taken: AtomicUsize,
|
||||
}
|
||||
|
||||
impl Budget {
|
||||
/// A budget of twice the host's cores, as many as can run a walk each with as many waiting.
|
||||
pub(crate) fn of_host() -> Arc<Budget> {
|
||||
let cores = std::thread::available_parallelism().map_or(4, std::num::NonZero::get);
|
||||
Budget::new(2 * cores)
|
||||
}
|
||||
|
||||
/// A budget of `limit` threads.
|
||||
pub(crate) fn new(limit: usize) -> Arc<Budget> {
|
||||
Arc::new(Budget {
|
||||
limit,
|
||||
taken: AtomicUsize::new(0),
|
||||
})
|
||||
}
|
||||
|
||||
/// One thread of the budget, where it has one to spare; waits for nothing.
|
||||
fn take(&self) -> bool {
|
||||
(self.taken)
|
||||
.fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| {
|
||||
(n < self.limit).then_some(n + 1)
|
||||
})
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
/// A thread of the budget went.
|
||||
fn give_back(&self) {
|
||||
self.taken.fetch_sub(1, Ordering::AcqRel);
|
||||
}
|
||||
|
||||
/// The budget's threads running now (for the tests).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn taken(&self) -> usize {
|
||||
self.taken.load(Ordering::Acquire)
|
||||
}
|
||||
}
|
||||
|
||||
/// What a lane's lock guards.
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
/// The jobs not yet started, in the order they came.
|
||||
jobs: VecDeque<Job>,
|
||||
/// The lane has its own thread.
|
||||
own: bool,
|
||||
/// The budget's threads the lane has.
|
||||
extra: usize,
|
||||
/// How many of the lane's threads wait for a job.
|
||||
idle: usize,
|
||||
/// The queue went: its threads go once its jobs are done.
|
||||
closed: bool,
|
||||
/// The turns given so far, and every turn below `passed` has passed.
|
||||
issued: u64,
|
||||
passed: u64,
|
||||
/// The turns past `passed` that passed before it.
|
||||
early: BTreeSet<u64>,
|
||||
}
|
||||
|
||||
/// A command queue's lane (the module doc).
|
||||
pub(crate) struct Lane {
|
||||
/// The queue's id, for its threads' names.
|
||||
queue: u64,
|
||||
/// The device's budget of extra threads.
|
||||
budget: Arc<Budget>,
|
||||
state: Mutex<State>,
|
||||
/// A job came, or the lane closed.
|
||||
work: Condvar,
|
||||
/// A turn passed.
|
||||
turned: Condvar,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Lane {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Lane").field("queue", &self.queue).finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Lane {
|
||||
/// The lane of queue `queue`, with no thread yet, its extra threads from `budget`.
|
||||
pub(crate) fn new(queue: u64, budget: Arc<Budget>) -> Arc<Lane> {
|
||||
Arc::new(Lane {
|
||||
queue,
|
||||
budget,
|
||||
state: Mutex::default(),
|
||||
work: Condvar::new(),
|
||||
turned: Condvar::new(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The next turn, for a command buffer begun now; `None` where only tried and the lane's lock
|
||||
/// is busy.
|
||||
pub(crate) fn turn(self: &Arc<Self>, try_only: bool) -> Option<Turn> {
|
||||
let mut state = if try_only {
|
||||
self.state.try_lock()?
|
||||
} else {
|
||||
self.state.lock()
|
||||
};
|
||||
let number = state.issued;
|
||||
state.issued += 1;
|
||||
Some(Turn {
|
||||
lane: Arc::clone(self),
|
||||
number,
|
||||
})
|
||||
}
|
||||
|
||||
/// Runs `job` on one of the lane's threads, after the jobs that came before it have started:
|
||||
/// an idle one, else the lane's own where it has none, else one of the budget's where every
|
||||
/// thread of the lane is busy and the budget has one to spare, else the next of the lane's
|
||||
/// to be free. On the calling thread where the lane has no thread and none can be made.
|
||||
pub(crate) fn run(self: &Arc<Self>, job: Job) {
|
||||
let mut state = self.state.lock();
|
||||
state.jobs.push_back(job);
|
||||
// An idle thread for each job not yet started: one woken before takes the one before.
|
||||
if state.idle >= state.jobs.len() {
|
||||
drop(state);
|
||||
self.work.notify_one();
|
||||
return;
|
||||
}
|
||||
let own = !state.own;
|
||||
if own {
|
||||
state.own = true;
|
||||
} else if 1 + state.extra < LANE_THREADS && self.budget.take() {
|
||||
state.extra += 1;
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
drop(state);
|
||||
let lane = Arc::clone(self);
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name(format!("reims-vgpu.graphics-lane-{:#x}", self.queue))
|
||||
.spawn(move || lane.serve(own));
|
||||
if spawned.is_err() {
|
||||
let mut state = self.state.lock();
|
||||
if !own {
|
||||
state.extra -= 1;
|
||||
self.budget.give_back();
|
||||
return;
|
||||
}
|
||||
state.own = false;
|
||||
log::warn!(
|
||||
target: "reims_vgpu::graphics",
|
||||
"queue {:#x}: no lane thread could be started: its command buffers' work is \
|
||||
carried out where it is taken",
|
||||
self.queue
|
||||
);
|
||||
let jobs = std::mem::take(&mut state.jobs);
|
||||
drop(state);
|
||||
for job in jobs {
|
||||
job();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A lane thread, the lane's `own` or one of the budget's: the jobs, in the order they came,
|
||||
/// until the lane closes with none left or none comes for [`IDLE`].
|
||||
fn serve(&self, own: bool) {
|
||||
let mut state = self.state.lock();
|
||||
loop {
|
||||
if let Some(job) = state.jobs.pop_front() {
|
||||
drop(state);
|
||||
job();
|
||||
state = self.state.lock();
|
||||
continue;
|
||||
}
|
||||
if state.closed {
|
||||
break;
|
||||
}
|
||||
state.idle += 1;
|
||||
let waited = self.work.wait_for(&mut state, IDLE);
|
||||
state.idle -= 1;
|
||||
if waited.timed_out() && state.jobs.is_empty() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if own {
|
||||
state.own = false;
|
||||
} else {
|
||||
state.extra -= 1;
|
||||
self.budget.give_back();
|
||||
}
|
||||
}
|
||||
|
||||
/// The queue went: the lane's threads go once the jobs it has are done.
|
||||
pub(crate) fn close(&self) {
|
||||
self.state.lock().closed = true;
|
||||
self.work.notify_all();
|
||||
}
|
||||
|
||||
/// How many threads the lane has (for the tests).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn threads(&self) -> usize {
|
||||
let state = self.state.lock();
|
||||
usize::from(state.own) + state.extra
|
||||
}
|
||||
}
|
||||
|
||||
/// A command buffer's turn in its queue's lane ([`Lane::turn`]): it passes as it drops, once every
|
||||
/// turn before it has, so the turns after it go on.
|
||||
pub(crate) struct Turn {
|
||||
lane: Arc<Lane>,
|
||||
number: u64,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Turn {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_tuple("Turn").field(&self.number).finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Turn {
|
||||
/// The lane it is a turn of.
|
||||
pub(crate) fn lane(&self) -> &Arc<Lane> {
|
||||
&self.lane
|
||||
}
|
||||
|
||||
/// Waits, with no lock of the caller's held, for every turn before this one to pass.
|
||||
pub(crate) fn wait(&self) {
|
||||
let mut state = self.lane.state.lock();
|
||||
while state.passed < self.number {
|
||||
self.lane.turned.wait(&mut state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Turn {
|
||||
fn drop(&mut self) {
|
||||
let mut guard = self.lane.state.lock();
|
||||
let state = &mut *guard;
|
||||
if state.passed == self.number {
|
||||
state.passed += 1;
|
||||
while state.early.remove(&state.passed) {
|
||||
state.passed += 1;
|
||||
}
|
||||
} else {
|
||||
state.early.insert(self.number);
|
||||
}
|
||||
drop(guard);
|
||||
self.lane.turned.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A turn waits for every turn before it, whichever order they pass in.
|
||||
#[test]
|
||||
fn a_turn_waits_for_every_turn_before_it() {
|
||||
let lane = Lane::new(1, Budget::new(0));
|
||||
let first = lane.turn(false).unwrap();
|
||||
let second = lane.turn(false).unwrap();
|
||||
let third = lane.turn(false).unwrap();
|
||||
let order = Mutex::new(Vec::new());
|
||||
std::thread::scope(|scope| {
|
||||
scope.spawn(|| {
|
||||
third.wait();
|
||||
order.lock().push(3);
|
||||
});
|
||||
std::thread::sleep(Duration::from_millis(30));
|
||||
// The second passes before the first: the third still waits.
|
||||
drop(second);
|
||||
std::thread::sleep(Duration::from_millis(30));
|
||||
assert!(
|
||||
order.lock().is_empty(),
|
||||
"the third went before the first passed"
|
||||
);
|
||||
order.lock().push(1);
|
||||
drop(first);
|
||||
});
|
||||
assert_eq!(*order.lock(), [1, 3]);
|
||||
drop(third);
|
||||
// Every turn has passed: the next waits for nothing.
|
||||
lane.turn(false).unwrap().wait();
|
||||
}
|
||||
|
||||
/// A gate jobs wait at until it opens.
|
||||
#[derive(Default)]
|
||||
struct Gate {
|
||||
open: Mutex<bool>,
|
||||
moved: Condvar,
|
||||
}
|
||||
|
||||
impl Gate {
|
||||
fn pass(&self) {
|
||||
let mut open = self.open.lock();
|
||||
while !*open {
|
||||
self.moved.wait(&mut open);
|
||||
}
|
||||
}
|
||||
|
||||
fn open(&self) {
|
||||
*self.open.lock() = true;
|
||||
self.moved.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits about 2 s for `done`; whether it came.
|
||||
fn until(done: impl Fn() -> bool) -> bool {
|
||||
for _ in 0..2000 {
|
||||
if done() {
|
||||
return true;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// A lane runs its jobs at once on up to [`LANE_THREADS`] threads, its own and the budget's,
|
||||
/// and its threads go once it closes.
|
||||
#[test]
|
||||
fn a_lane_runs_its_jobs_at_once_on_the_budget_s_threads() {
|
||||
let budget = Budget::new(LANE_THREADS);
|
||||
let lane = Lane::new(2, Arc::clone(&budget));
|
||||
let started = Arc::new(Mutex::new(Vec::new()));
|
||||
let running = Arc::new(AtomicUsize::new(0));
|
||||
let gate = Arc::new(Gate::default());
|
||||
for n in 0..LANE_THREADS {
|
||||
let (started, running, gate) = (
|
||||
Arc::clone(&started),
|
||||
Arc::clone(&running),
|
||||
Arc::clone(&gate),
|
||||
);
|
||||
lane.run(Box::new(move || {
|
||||
started.lock().push(n);
|
||||
running.fetch_add(1, Ordering::AcqRel);
|
||||
gate.pass();
|
||||
}));
|
||||
}
|
||||
assert!(
|
||||
until(|| running.load(Ordering::Acquire) == LANE_THREADS),
|
||||
"not all at once"
|
||||
);
|
||||
let mut order = started.lock().clone();
|
||||
order.sort_unstable();
|
||||
assert_eq!(order, (0..LANE_THREADS).collect::<Vec<_>>());
|
||||
assert_eq!(
|
||||
budget.taken(),
|
||||
LANE_THREADS - 1,
|
||||
"the lane's own thread and the budget's"
|
||||
);
|
||||
gate.open();
|
||||
lane.close();
|
||||
assert!(
|
||||
until(|| lane.threads() == 0),
|
||||
"the closed lane's threads stayed"
|
||||
);
|
||||
assert_eq!(budget.taken(), 0);
|
||||
}
|
||||
|
||||
/// A lane whose budget is spent runs its jobs on its own thread alone, one after another in
|
||||
/// the order they came, and never waits for the budget.
|
||||
#[test]
|
||||
fn a_lane_with_no_budget_left_runs_its_jobs_on_its_own_thread_in_order() {
|
||||
let lane = Lane::new(3, Budget::new(0));
|
||||
let done = Arc::new(Mutex::new(Vec::new()));
|
||||
for n in 0..8 {
|
||||
let done = Arc::clone(&done);
|
||||
lane.run(Box::new(move || done.lock().push(n)));
|
||||
}
|
||||
assert!(until(|| done.lock().len() == 8));
|
||||
assert_eq!(*done.lock(), (0..8).collect::<Vec<_>>());
|
||||
assert_eq!(lane.threads(), 1);
|
||||
lane.close();
|
||||
assert!(until(|| lane.threads() == 0));
|
||||
}
|
||||
|
||||
/// 2048 busy queues, the most a process may make, hold one thread each and the budget's, at
|
||||
/// most: the threads a device makes are bounded whatever its processes do.
|
||||
#[test]
|
||||
fn busy_lanes_hold_one_thread_each_and_the_budget_s() {
|
||||
const QUEUES: u64 = 2048;
|
||||
const BUDGET: usize = 16;
|
||||
let budget = Budget::new(BUDGET);
|
||||
let gate = Arc::new(Gate::default());
|
||||
let running = Arc::new(AtomicUsize::new(0));
|
||||
let lanes: Vec<Arc<Lane>> = (0..QUEUES)
|
||||
.map(|queue| Lane::new(queue, Arc::clone(&budget)))
|
||||
.collect();
|
||||
for lane in &lanes {
|
||||
for _ in 0..3 {
|
||||
let (gate, running) = (Arc::clone(&gate), Arc::clone(&running));
|
||||
lane.run(Box::new(move || {
|
||||
running.fetch_add(1, Ordering::AcqRel);
|
||||
gate.pass();
|
||||
}));
|
||||
}
|
||||
}
|
||||
// Every lane runs its first job on its own thread; the budget's threads run a few more.
|
||||
assert!(until(
|
||||
|| running.load(Ordering::Acquire) >= QUEUES as usize + BUDGET
|
||||
));
|
||||
let threads: usize = lanes.iter().map(|lane| lane.threads()).sum();
|
||||
assert!(
|
||||
threads <= QUEUES as usize + BUDGET,
|
||||
"{threads} threads for {QUEUES} lanes and a budget of {BUDGET}"
|
||||
);
|
||||
assert_eq!(budget.taken(), BUDGET);
|
||||
gate.open();
|
||||
for lane in &lanes {
|
||||
lane.close();
|
||||
}
|
||||
assert!(until(|| lanes.iter().all(|lane| lane.threads() == 0)));
|
||||
assert_eq!(running.load(Ordering::Acquire), 3 * QUEUES as usize);
|
||||
}
|
||||
}
|
||||
@@ -140,6 +140,7 @@ mod compute;
|
||||
#[cfg(test)]
|
||||
mod fuzz;
|
||||
mod icb;
|
||||
mod lane;
|
||||
mod library;
|
||||
mod managed;
|
||||
mod render;
|
||||
@@ -158,6 +159,8 @@ pub(crate) mod worker;
|
||||
|
||||
pub use video::{GraphicsVideo, GraphicsVideoSession, VideoDecode, VideoPlane};
|
||||
|
||||
pub(crate) use cmdbuf::Begun;
|
||||
use lane::{Lane, Turn};
|
||||
#[cfg(test)]
|
||||
pub(crate) use library::tests::{metallib as test_metallib, sha as test_sha};
|
||||
#[cfg(test)]
|
||||
@@ -467,6 +470,8 @@ pub(crate) struct Shared<P: Platform> {
|
||||
/// The queues' surface timelines, which order command buffers of different queues over the
|
||||
/// IOSurfaces they share ([`surface_order`]).
|
||||
surface_order: Mutex<surface_order::SurfaceOrder<P>>,
|
||||
/// The budget of the queues' lanes' extra threads ([`lane`]).
|
||||
lanes: Arc<lane::Budget>,
|
||||
/// Called after each op of every command buffer's walk (the tests' look inside a walk).
|
||||
#[cfg(test)]
|
||||
walk_hook: Mutex<Option<WalkHook>>,
|
||||
@@ -533,6 +538,9 @@ pub struct GraphicsDecoder<P: Platform> {
|
||||
/// The command buffer's ticket in the commit order, where it was answered at its take; given
|
||||
/// back with the handle, after its commit or its stand-in's.
|
||||
ticket: RefCell<Option<Ticket>>,
|
||||
/// The command buffer's turn in its queue's lane ([`lane`]), from its begin; it passes with
|
||||
/// the handle, once the buffer's commit, stand-in or failure is done.
|
||||
turn: RefCell<Option<Turn>>,
|
||||
/// The device caches a doorbell's take found ready and counted the buffer among the users of
|
||||
/// ([`Caches::hold_ready`]), for its begin.
|
||||
held_caches: RefCell<Option<surface_cache::Held<P>>>,
|
||||
@@ -567,6 +575,7 @@ impl<P: Platform> GraphicsDecoder<P> {
|
||||
surface_caches: Arc::new(Caches::new(true)),
|
||||
sequencer: Arc::default(),
|
||||
surface_order: Mutex::new(surface_order::SurfaceOrder::new()),
|
||||
lanes: lane::Budget::of_host(),
|
||||
#[cfg(test)]
|
||||
walk_hook: Mutex::new(None),
|
||||
region,
|
||||
@@ -587,6 +596,7 @@ impl<P: Platform> GraphicsDecoder<P> {
|
||||
try_only: false,
|
||||
mark: Cell::new(None),
|
||||
ticket: RefCell::new(None),
|
||||
turn: RefCell::new(None),
|
||||
held_caches: RefCell::new(None),
|
||||
drain: RefCell::new(None),
|
||||
order_waits: RefCell::new(Vec::new()),
|
||||
@@ -616,6 +626,7 @@ impl<P: Platform> GraphicsDecoder<P> {
|
||||
self.views.get_mut().clear();
|
||||
self.mark.set(None);
|
||||
self.ticket.get_mut().take();
|
||||
self.turn.get_mut().take();
|
||||
self.held_caches.get_mut().take();
|
||||
self.drain.get_mut().take();
|
||||
self.order_waits.get_mut().clear();
|
||||
@@ -1450,10 +1461,8 @@ impl<P: Platform> GraphicsDecoder<P> {
|
||||
Some(queue) => {
|
||||
let mut entry = Entry::of(ObjHandle::CommandQueue(queue));
|
||||
let order = self.shared.surface_order.lock().marks(m.obj_id);
|
||||
entry.queue = Some(QueueCounts {
|
||||
order,
|
||||
..QueueCounts::default()
|
||||
});
|
||||
let lane = Lane::new(m.obj_id, Arc::clone(&self.shared.lanes));
|
||||
entry.queue = Some(QueueCounts::on(lane, order));
|
||||
self.store(m.obj_id, entry);
|
||||
Ok(Ok(()))
|
||||
}
|
||||
|
||||
@@ -38,15 +38,17 @@ use reims_vgpu_core::collections::hasher::KeyBuild;
|
||||
use reims_vgpu_core::platform::Platform;
|
||||
use reims_vgpu_core::sync::Mutex;
|
||||
|
||||
use super::lane::Lane;
|
||||
use super::managed::ManagedCopy;
|
||||
use super::video::PlanePlace;
|
||||
use super::{Drain, ObjHandle, drop_refused};
|
||||
|
||||
/// A command queue's counts of the host's command buffers made on it ([`super::cmdbuf`]).
|
||||
#[derive(Clone, Default)]
|
||||
/// A command queue's counts of the host's command buffers made on it ([`super::cmdbuf`]), and its
|
||||
/// lane ([`super::lane`]), which closes as the queue's entry goes.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct QueueCounts {
|
||||
/// How many of its command buffers that wait for an event are not yet scheduled. A buffer
|
||||
/// committed behind one is not submitted until it is, as Metal's is not.
|
||||
/// How many of its command buffers that wait for an event are begun and not yet scheduled. A
|
||||
/// buffer committed behind one is not submitted until it is, as Metal's is not.
|
||||
pub(crate) held: Arc<AtomicUsize>,
|
||||
/// How many command buffers the host made on it have not completed (a take on a doorbell's
|
||||
/// thread).
|
||||
@@ -54,6 +56,30 @@ pub(crate) struct QueueCounts {
|
||||
/// Its marks in the surface order, which a command buffer that holds no op reads and writes
|
||||
/// with no lock ([`super::surface_order::Marks`]).
|
||||
pub(crate) order: Arc<super::surface_order::Marks>,
|
||||
/// Where its command buffers' walks and commits run, each in its turn; `None` for a queue
|
||||
/// whose buffers are carried out whole where they are taken (the decoder's own tests).
|
||||
pub(crate) lane: Option<Arc<Lane>>,
|
||||
}
|
||||
|
||||
impl QueueCounts {
|
||||
/// A queue's counts, its command buffers carried out on `lane`, its marks in the surface order
|
||||
/// `order`.
|
||||
pub(crate) fn on(lane: Arc<Lane>, order: Arc<super::surface_order::Marks>) -> QueueCounts {
|
||||
QueueCounts {
|
||||
held: Arc::default(),
|
||||
in_flight: Arc::default(),
|
||||
order,
|
||||
lane: Some(lane),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for QueueCounts {
|
||||
fn drop(&mut self) {
|
||||
if let Some(lane) = &self.lane {
|
||||
lane.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One object of a context's, as made. Its fields drop in their order: a `Managed` object's CPU
|
||||
|
||||
@@ -1765,6 +1765,8 @@ type GateState = Arc<(
|
||||
|
||||
struct WalkGate {
|
||||
state: GateState,
|
||||
/// The ops walked past the gate once a walk took it: other walks' while it is shut.
|
||||
passed: Arc<AtomicU32>,
|
||||
}
|
||||
|
||||
impl WalkGate {
|
||||
@@ -1774,7 +1776,8 @@ impl WalkGate {
|
||||
reims_vgpu_core::sync::Mutex::new((false, false, false)),
|
||||
reims_vgpu_core::sync::Condvar::new(),
|
||||
));
|
||||
let hook = Arc::clone(&state);
|
||||
let passed = Arc::new(AtomicU32::new(0));
|
||||
let (hook, past) = (Arc::clone(&state), Arc::clone(&passed));
|
||||
device
|
||||
.control
|
||||
.decoder()
|
||||
@@ -1782,7 +1785,11 @@ impl WalkGate {
|
||||
let (lock, moved) = &*hook;
|
||||
let mut s = lock.lock();
|
||||
// (taken by a walk, the walk stopped at it, open)
|
||||
if index != 0 || s.0 {
|
||||
if s.0 {
|
||||
past.fetch_add(1, Ordering::SeqCst);
|
||||
return;
|
||||
}
|
||||
if index != 0 {
|
||||
return;
|
||||
}
|
||||
s.0 = true;
|
||||
@@ -1792,7 +1799,19 @@ impl WalkGate {
|
||||
moved.wait(&mut s);
|
||||
}
|
||||
})));
|
||||
WalkGate { state }
|
||||
WalkGate { state, passed }
|
||||
}
|
||||
|
||||
/// Waits, about 3 s at most, for `n` ops to be walked past the gate once a walk took it;
|
||||
/// whether they were.
|
||||
fn passed(&self, n: u32) -> bool {
|
||||
for _ in 0..3000 {
|
||||
if self.passed.load(Ordering::SeqCst) >= n {
|
||||
return true;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Waits, about 3 s at most, for a walk to stop at the gate; whether one did.
|
||||
@@ -2177,6 +2196,177 @@ fn a_queue_s_buffer_runs_beside_another_queue_s_walk() {
|
||||
assert_eq!((done.cb_obj_id, done.status), (100, RGFX_CB_OK));
|
||||
}
|
||||
|
||||
/// A command buffer with the ops `ops`, each a tag and its body, on queue `queue_obj_id`.
|
||||
fn command_buffer_of(queue_obj_id: u64, cb_obj_id: u64, ops: &[(u16, &[u8])]) -> Vec<u8> {
|
||||
use reims_graphics::ops::RgfxOpHeader;
|
||||
|
||||
let mut stream = Vec::new();
|
||||
for &(tag, body) in ops {
|
||||
let header = RgfxOpHeader {
|
||||
tag,
|
||||
flags: 0,
|
||||
len: (8 + body.len()) as u32,
|
||||
};
|
||||
stream.extend_from_slice(header.as_bytes());
|
||||
stream.extend_from_slice(body);
|
||||
}
|
||||
let mut bytes = RgfxCommandBuffer {
|
||||
header: RgfxMsgHeader {
|
||||
r#type: RGFX_CMD_COMMAND_BUFFER,
|
||||
size: 0,
|
||||
seqno: 0,
|
||||
},
|
||||
queue_obj_id,
|
||||
cb_obj_id,
|
||||
op_bytes: stream.len() as u64,
|
||||
}
|
||||
.as_bytes()
|
||||
.to_vec();
|
||||
bytes.extend(stream);
|
||||
bytes
|
||||
}
|
||||
|
||||
/// A headless device with queue 1 of process 1 made, its ring, and the process's sampler 4.
|
||||
fn one_queue(
|
||||
raised: &Arc<AtomicU32>,
|
||||
) -> (
|
||||
GraphicsDevice<FakePlatform>,
|
||||
Arc<FakePlatform>,
|
||||
Guest,
|
||||
QueueRing,
|
||||
) {
|
||||
const RING_DATA: u32 = 0x1_0000;
|
||||
const SUBMIT_OFF: u64 = RGFX_CONTEXT_ALLOCATIONS_OFFSET;
|
||||
const COMPLETE_OFF: u64 = RGFX_CONTEXT_ALLOCATIONS_OFFSET + 0x2_0000;
|
||||
let (device, platform) = headless_on(raised);
|
||||
device.mmio_write(RGFX_REG_STATUS.into(), RGFX_STATUS_DRIVER_READY);
|
||||
let mut guest = Guest::new(&device);
|
||||
let rings = (SUBMIT_OFF, COMPLETE_OFF);
|
||||
assert_eq!(
|
||||
create_queue(&device, &mut guest, 1, 1, rings, RING_DATA, 0),
|
||||
RGFX_STATUS_OK
|
||||
);
|
||||
assert_eq!(
|
||||
sampler_answered(&device, &mut guest, obj(1, 4)),
|
||||
RGFX_STATUS_OK
|
||||
);
|
||||
let ring = QueueRing::new(&device, SUBMIT_OFF, COMPLETE_OFF, u64::from(RING_DATA));
|
||||
(device, platform, guest, ring)
|
||||
}
|
||||
|
||||
/// Two command buffers of one queue are walked at once, and committed in the order they came
|
||||
/// (`decode`'s `lane`): the second, sent while the first's walk is stopped at the gate, is walked
|
||||
/// whole beside it, and committed only once the first is. They complete in that order
|
||||
#[test]
|
||||
fn a_queue_s_buffers_are_walked_at_once_and_committed_in_order() {
|
||||
let raised = Arc::new(AtomicU32::new(0));
|
||||
let (device, platform, _guest, mut ring) = one_queue(&raised);
|
||||
let gate = WalkGate::on(&device);
|
||||
ring.send(&device, sampler_command_buffer(obj(1, 1), 100, obj(1, 4)));
|
||||
assert!(gate.reached(), "the first walk did not start");
|
||||
ring.send(&device, sampler_command_buffer(obj(1, 1), 101, obj(1, 4)));
|
||||
assert!(
|
||||
gate.passed(3),
|
||||
"the second buffer was not walked beside the first"
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
assert!(
|
||||
platform.world().committed().is_empty(),
|
||||
"the second was committed before the first"
|
||||
);
|
||||
gate.open();
|
||||
committed(&platform, 2);
|
||||
for cb in [100, 101] {
|
||||
assert!(complete_until_event(&platform, &mut ring), "no completion");
|
||||
let done = RgfxCbComplete::read_from_bytes(&ring.event().unwrap()).unwrap();
|
||||
assert_eq!((done.cb_obj_id, done.status), (cb, RGFX_CB_OK));
|
||||
}
|
||||
}
|
||||
|
||||
/// A command buffer that asks for its `CB_SUBMITTED`, sent behind one of its queue that waits for
|
||||
/// an event and is still being walked, is answered at its scheduling, after that one's, not at its
|
||||
/// take: the waiting one holds its queue from its begin, as it would from its commit had it been
|
||||
/// carried out whole first (the fake platform schedules each buffer at its commit)
|
||||
#[test]
|
||||
fn a_buffer_behind_one_that_waits_and_is_still_walked_is_answered_at_its_scheduling() {
|
||||
use reims_graphics::ops::{RGFX_OP_WAIT_EVENT, RgfxOpEvent};
|
||||
|
||||
let raised = Arc::new(AtomicU32::new(0));
|
||||
let (device, platform, mut guest, mut ring) = one_queue(&raised);
|
||||
guest.send(&device, shared_event_create(obj(1, 7), 0));
|
||||
let wait = RgfxOpEvent {
|
||||
event_obj_id: obj(1, 7),
|
||||
value: 1,
|
||||
};
|
||||
let gate = WalkGate::on(&device);
|
||||
let waits = command_buffer_of(obj(1, 1), 100, &[(RGFX_OP_WAIT_EVENT, wait.as_bytes())]);
|
||||
ring.send(&device, waits);
|
||||
assert!(gate.reached(), "the first walk did not start");
|
||||
ring.send(&device, asking(obj(1, 1), 101));
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
assert!(
|
||||
!ring.has_event(),
|
||||
"answered while the buffer before it is walked"
|
||||
);
|
||||
gate.open();
|
||||
committed(&platform, 2);
|
||||
let bytes = ring.event().expect("a CB_SUBMITTED");
|
||||
let posted = RgfxCbSubmitted::read_from_bytes(&bytes).unwrap();
|
||||
assert_eq!(
|
||||
(posted.header.r#type, posted.cb_obj_id),
|
||||
(RGFX_EVT_CB_SUBMITTED, 101)
|
||||
);
|
||||
assert_eq!(
|
||||
ring.scheduled.first().map(|&(_, cb)| cb),
|
||||
Some(100),
|
||||
"the one before it was scheduled first"
|
||||
);
|
||||
}
|
||||
|
||||
/// A command buffer that holds a video encoder is walked in its turn, after the buffers of its
|
||||
/// queue before it, not beside them: its session's work starts as it is walked. Here its walk
|
||||
/// waits for the stopped first buffer, then faults at the encoder (its process holds no session),
|
||||
/// and its failure comes after the first's completion
|
||||
#[test]
|
||||
fn a_video_buffer_is_walked_in_its_turn() {
|
||||
use reims_graphics::ops::{
|
||||
RGFX_OP_ENCODER_BEGIN_BLIT, RGFX_OP_ENCODER_BEGIN_VIDEO, RGFX_OP_ENCODER_END,
|
||||
RgfxOpVideoPass,
|
||||
};
|
||||
|
||||
let raised = Arc::new(AtomicU32::new(0));
|
||||
let (device, platform, _guest, mut ring) = one_queue(&raised);
|
||||
let gate = WalkGate::on(&device);
|
||||
ring.send(&device, sampler_command_buffer(obj(1, 1), 100, obj(1, 4)));
|
||||
assert!(gate.reached(), "the first walk did not start");
|
||||
let pass = RgfxOpVideoPass {
|
||||
session_obj_id: obj(1, 9),
|
||||
};
|
||||
let video = command_buffer_of(
|
||||
obj(1, 1),
|
||||
101,
|
||||
&[
|
||||
(RGFX_OP_ENCODER_BEGIN_BLIT, &[]),
|
||||
(RGFX_OP_ENCODER_END, &[]),
|
||||
(RGFX_OP_ENCODER_BEGIN_VIDEO, pass.as_bytes()),
|
||||
],
|
||||
);
|
||||
ring.send(&device, video);
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
assert_eq!(
|
||||
gate.passed.load(Ordering::SeqCst),
|
||||
0,
|
||||
"the video buffer was walked beside the first"
|
||||
);
|
||||
gate.open();
|
||||
assert!(gate.passed(2), "the video buffer was not walked");
|
||||
for (cb, ok) in [(100, true), (101, false)] {
|
||||
assert!(complete_until_event(&platform, &mut ring), "no completion");
|
||||
let done = RgfxCbComplete::read_from_bytes(&ring.event().unwrap()).unwrap();
|
||||
assert_eq!((done.cb_obj_id, done.status == RGFX_CB_OK), (cb, ok));
|
||||
}
|
||||
}
|
||||
|
||||
/// An argument layout query on ring 0 writes the platform's layout into the sender's block and is
|
||||
/// answered by a `COMPLETE` at its seqno, making no object; one whose block is another process's
|
||||
/// is refused, with nothing written
|
||||
|
||||
@@ -1687,10 +1687,11 @@ structs and `Platform` calls). The reims-graphics crate stays the transport
|
||||
walk and commit. Each context's objects are in a table of their own, each
|
||||
message is carried out on a decoder of its own, and every lock is held for a
|
||||
short section (the list is in `crates/reims-vgpu/src/graphics/decode/mod.rs`).
|
||||
Ring 0 goes on while a queue walks, and so does every other queue. Under the
|
||||
single lock this replaces, the decoder's lock was held from a command buffer's
|
||||
take to its commit, so each other message came wholly before the take or wholly
|
||||
after the commit. Each outcome the new design allows is one of those two:
|
||||
Ring 0 goes on while a queue walks, and so does every other queue, and the
|
||||
queue's own later buffers are walked beside it. Under the single lock this
|
||||
replaces, the decoder's lock was held from a command buffer's take to its
|
||||
commit, so each other message came wholly before the take or wholly after the
|
||||
commit. Each outcome the new design allows is one of those two:
|
||||
- **Objects.** A command buffer names objects as its context's table was when
|
||||
its first lookup (its queue, at its begin) took its view of the table. A
|
||||
create, destroy or close carried out on another thread after that is not
|
||||
@@ -1760,6 +1761,55 @@ after the commit. Each outcome the new design allows is one of those two:
|
||||
wait for a walk, as the lock did. Tested by `a_reset_during_a_walk_comes_after_it`
|
||||
and `a_reset_drops_every_object_the_guest_made` (`graphics/tests.rs`), and
|
||||
by the decoder's fuzz (`decode/fuzz.rs`).
|
||||
- **A queue's own order.** A queue's service thread (or a doorbell's) begins
|
||||
each of its command buffers in the order the guest published them and hands
|
||||
the walk and the commit to the queue's lane (`decode/lane.rs`), whose threads
|
||||
walk several at once, so one process's busy queue is not bound to one
|
||||
thread. Under the lock a queue's next buffer was taken after the commit of
|
||||
the one before it. Here each buffer gets its turn in its queue's lane at its
|
||||
begin, before anything of it can fail, and its commit, its stand-in's commit
|
||||
and the failure posted at once for it wait for every turn before its own, so
|
||||
they come in the order the buffers were taken, as under the lock. A walk
|
||||
encodes into its own command buffer, which the platform runs in commit order:
|
||||
Apple's Metal guide lets a queue's buffers be encoded on several threads and
|
||||
run in the order they are committed, and metal2vulkan resolves barriers,
|
||||
layouts and fences at submit, in commit order. Four things a buffer does
|
||||
before its commit are seen beyond it, and each keeps the lock's order:
|
||||
- its hold of its queue: a buffer that waits for an event, or for the
|
||||
host's fill of a device cache, holds its queue from its begin, not its
|
||||
commit, so a buffer after it that asks for its `CB_SUBMITTED` is answered
|
||||
at its scheduling, as behind one already committed;
|
||||
- a video encoder's work, which its session starts as it is walked: a buffer
|
||||
that holds one is walked only in its turn;
|
||||
- its signal of its queue's surface timeline ("Surface order"), and the
|
||||
release that stands in for one of a buffer that does not run: each is
|
||||
decided in the buffer's turn, after its walk, since the order reads a
|
||||
queue's buffer taken past a seqno as every buffer up to it taken, and a
|
||||
waiter that saw a later buffer taken while an earlier one still walked
|
||||
would wait for nothing;
|
||||
- its answer at its take, posted at its begin, before the buffers before it
|
||||
on its queue commit: everything the guest sends after the answer is
|
||||
committed after the buffer (its ticket), which commits after them, so
|
||||
nothing sent later sees the difference, and those buffers are `Committed`
|
||||
or `Scheduled` at the answer by a race, as Metal's are.
|
||||
|
||||
A turn passes as its buffer's work ends, and a buffer waits only for turns
|
||||
and tickets of buffers begun before it. A lane's threads take its jobs in
|
||||
the order they came, and every lane with work has a thread of its own, so
|
||||
the oldest unfinished buffer of each lane is on a thread, and so is the
|
||||
oldest of the device: the waits end, by induction on the begin order. A
|
||||
lane's own thread goes after a second with no job; a job that comes while
|
||||
every thread of the lane is busy gets another, up to four a lane, only where
|
||||
the device-wide budget of twice the host's cores has one free, which a lane
|
||||
never waits for. So 2048 busy queues hold one thread each and the budget's
|
||||
at most. Tested through the device by
|
||||
`a_queue_s_buffers_are_walked_at_once_and_committed_in_order`,
|
||||
`a_buffer_behind_one_that_waits_and_is_still_walked_is_answered_at_its_scheduling`
|
||||
and `a_video_buffer_is_walked_in_its_turn` (`graphics/tests.rs`), and by the
|
||||
lane's `a_turn_waits_for_every_turn_before_it`,
|
||||
`a_lane_runs_its_jobs_at_once_on_the_budget_s_threads`,
|
||||
`a_lane_with_no_budget_left_runs_its_jobs_on_its_own_thread_in_order` and
|
||||
`busy_lanes_hold_one_thread_each_and_the_budget_s`.
|
||||
- **What still waits on ring 0's thread:** a range message, for its own
|
||||
context's answered buffers; a download, a release or a block named again, for
|
||||
that block's writers; a present's fill, for that block's users; and the
|
||||
|
||||
Reference in new issue
Block a user