Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 87 additions & 6 deletions crates/xcl/src/hle/d3d12x/build_queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@ impl Priority {
}
}

fn queue_stall_kind(priority: Priority) -> crate::stall::StallKind {
match priority {
Priority::Speculative | Priority::Preload => crate::stall::StallKind::PipelineQueueSpeculative,
Priority::BoundSoon | Priority::Foreground => crate::stall::StallKind::PipelineQueueDemand,
}
}

#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub(super) struct JobId(u64);

Expand Down Expand Up @@ -156,10 +163,32 @@ struct Job {
priority: Priority,
preload_rank: Option<usize>,
generation: u64,
previous_queue_wait: Option<crate::stall::DeferredDuration>,
queue_wait: Option<crate::stall::DeferredSpan>,
work: Work,
completion: Arc<Completion>,
}

struct ReadyJob {
priority: Priority,
previous_queue_wait: Option<crate::stall::DeferredDuration>,
queue_wait: Option<crate::stall::DeferredDuration>,
work: Work,
completion: Arc<Completion>,
}

impl ReadyJob {
fn publish_queue_wait(self) -> (Work, Arc<Completion>) {
if let Some(wait) = self.previous_queue_wait {
wait.finish(crate::stall::StallKind::PipelineQueueSpeculative);
}
if let Some(wait) = self.queue_wait {
wait.finish(queue_stall_kind(self.priority));
}
(self.work, self.completion)
}
}

struct State {
next_id: u64,
next_sequence: u64,
Expand Down Expand Up @@ -228,6 +257,10 @@ impl Inner {
return true;
}
let ranked_preload = job.priority == Priority::Preload && job.preload_rank.is_some();
if queue_stall_kind(job.priority) != queue_stall_kind(priority) {
job.previous_queue_wait = job.queue_wait.take().map(crate::stall::DeferredSpan::stop);
job.queue_wait = crate::stall::deferred_span();
}
job.priority = priority;
job.generation += 1;
let ticket = Ticket { id, generation: job.generation };
Expand All @@ -250,7 +283,7 @@ impl Inner {
}
}

fn take_ready(&self, state: &mut State, low: Priority, high: Priority) -> Option<(Work, Arc<Completion>)> {
fn take_ready(&self, state: &mut State, low: Priority, high: Priority) -> Option<ReadyJob> {
for priority in (low.index()..=high.index()).rev() {
let priority = match priority {
0 => Priority::Speculative,
Expand All @@ -263,12 +296,21 @@ impl Inner {
job.priority == priority && job.generation == ticket.generation
});
if current {
let job = state.jobs.remove(&ticket.id).unwrap();
let mut job = state.jobs.remove(&ticket.id).unwrap();
if priority == Priority::Preload && job.preload_rank.is_some() {
self.ranked_preloads.started.fetch_add(1, Ordering::Relaxed);
}
// Dequeue acceptance is the end of priority-band residence. Stop the clock
// while the queue state is authoritative, but publish only after unlocking.
let queue_wait = job.queue_wait.take().map(crate::stall::DeferredSpan::stop);
job.completion.set(JobStatus::Running);
return Some((job.work, job.completion));
return Some(ReadyJob {
priority,
previous_queue_wait: job.previous_queue_wait.take(),
queue_wait,
work: job.work,
completion: job.completion,
});
}
}
}
Expand All @@ -280,7 +322,8 @@ impl Inner {
let changed = self.changed(low, high);
loop {
if let Some(job) = self.take_ready(&mut state, low, high) {
return Some(job);
drop(state);
return Some(job.publish_queue_wait());
}
if state.stopped || !wait {
return None;
Expand All @@ -297,7 +340,8 @@ impl Inner {
return None;
}
if let Some(job) = self.take_ready(&mut state, low, high) {
return Some(job);
drop(state);
return Some(job.publish_queue_wait());
}
state = changed.wait_timeout(state, std::time::Duration::from_millis(250)).unwrap_or_else(|e| e.into_inner()).0;
}
Expand Down Expand Up @@ -355,6 +399,10 @@ impl BuildQueue {
}

/// Add work, optionally ordered by an earlier-run rank within the Preload band only.
///
/// Queue latency measures accepted priority-band residence: it starts at insertion after the
/// state mutex is acquired, so admission mutex wait is excluded. A cross-band promotion ends
/// the speculative interval when that promotion is accepted while holding the same mutex.
pub(super) fn submit_ranked(&self, priority: Priority, preload_rank: Option<usize>, work: Work) -> Option<JobHandle> {
let completion = Arc::new(Completion::new());
let mut state = self.inner.state.lock().unwrap_or_else(|e| e.into_inner());
Expand All @@ -365,7 +413,15 @@ impl BuildQueue {
let id = JobId(state.next_id);
let generation = 0;
let preload_rank = if priority == Priority::Preload { preload_rank } else { None };
state.jobs.insert(id, Job { priority, preload_rank, generation, work, completion: completion.clone() });
state.jobs.insert(id, Job {
priority,
preload_rank,
generation,
previous_queue_wait: None,
queue_wait: crate::stall::deferred_span(),
work,
completion: completion.clone(),
});
state.push(priority, Ticket { id, generation }, preload_rank);
if preload_rank.is_some() {
self.inner.ranked_preloads.submissions.fetch_add(1, Ordering::Relaxed);
Expand Down Expand Up @@ -446,6 +502,14 @@ mod tests {
Box::new(move || out.lock().unwrap().push(value))
}

#[test]
fn queue_latency_bands_match_worker_priorities() {
assert_eq!(queue_stall_kind(Priority::Speculative), crate::stall::StallKind::PipelineQueueSpeculative);
assert_eq!(queue_stall_kind(Priority::Preload), crate::stall::StallKind::PipelineQueueSpeculative);
assert_eq!(queue_stall_kind(Priority::BoundSoon), crate::stall::StallKind::PipelineQueueDemand);
assert_eq!(queue_stall_kind(Priority::Foreground), crate::stall::StallKind::PipelineQueueDemand);
}

#[test]
fn highest_priority_runs_first_and_each_priority_is_fifo() {
let q = BuildQueue::new();
Expand Down Expand Up @@ -505,6 +569,23 @@ mod tests {
);
}

#[test]
fn promoted_timing_is_abandoned_for_cancel_shutdown_and_refusal() {
let q = BuildQueue::new();
let cancelled = q.submit(Priority::Speculative, Box::new(|| panic!("must not run"))).unwrap();
assert!(cancelled.promote(Priority::Foreground));
assert_eq!(cancelled.status(), JobStatus::Queued);
assert!(cancelled.cancel());
assert_eq!(cancelled.wait(), JobStatus::Cancelled);

let shutdown = q.submit(Priority::Preload, Box::new(|| panic!("must not run"))).unwrap();
assert!(shutdown.promote(Priority::BoundSoon));
assert_eq!(shutdown.status(), JobStatus::Queued);
q.shutdown();
assert_eq!(shutdown.wait(), JobStatus::Cancelled);
assert!(q.submit(Priority::Foreground, Box::new(|| {})).is_none());
}

#[test]
fn promotion_is_monotonic_and_joins_the_new_priority_fifo() {
let q = BuildQueue::new();
Expand Down
8 changes: 8 additions & 0 deletions crates/xcl/src/report.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ fn stall_kind_name(kind: crate::stall::StallKind) -> &'static str {
StallKind::ShaderTranslation => "shader_translation",
StallKind::DxcQueue => "dxc_queue",
StallKind::DxcCompile => "dxc_compile",
StallKind::PipelineQueueSpeculative => "pipeline_queue_speculative",
StallKind::PipelineQueueDemand => "pipeline_queue_demand",
StallKind::PipelineWait => "pipeline_wait",
StallKind::DriverCompileGate => "driver_compile_gate",
StallKind::DriverCompile => "driver_compile",
Expand Down Expand Up @@ -418,6 +420,12 @@ mod tests {
assert_eq!(json["slow_events"][0]["duration_ns"], 50_000_000);
}

#[test]
fn pipeline_queue_stall_names_are_stable() {
assert_eq!(stall_kind_name(crate::stall::StallKind::PipelineQueueSpeculative), "pipeline_queue_speculative");
assert_eq!(stall_kind_name(crate::stall::StallKind::PipelineQueueDemand), "pipeline_queue_demand");
}

#[test]
fn missing_fields_in_a_stall_summary_take_safe_defaults() {
let summary: StallSummary = serde_json::from_str(r#"{"version":1}"#).unwrap();
Expand Down
88 changes: 87 additions & 1 deletion crates/xcl/src/stall.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ pub enum StallKind {
ShaderTranslation,
DxcQueue,
DxcCompile,
PipelineQueueSpeculative,
PipelineQueueDemand,
PipelineWait,
DriverCompileGate,
DriverCompile,
Expand All @@ -40,10 +42,12 @@ pub enum StallKind {
}

impl StallKind {
pub const ALL: [Self; 21] = [
pub const ALL: [Self; 23] = [
Self::ShaderTranslation,
Self::DxcQueue,
Self::DxcCompile,
Self::PipelineQueueSpeculative,
Self::PipelineQueueDemand,
Self::PipelineWait,
Self::DriverCompileGate,
Self::DriverCompile,
Expand Down Expand Up @@ -190,6 +194,14 @@ impl Recorder {
Some(Span { recorder: self, kind, started_ns: clock.now_ns(), clock, finished: false })
}

#[inline]
fn defer_with(&self, clock: &dyn Clock) -> Option<DeferredSpan> {
if !self.enabled.load(Ordering::Relaxed) {
return None;
}
Some(DeferredSpan { started_ns: clock.now_ns() })
}

fn record(&self, kind: StallKind, started_ns: u64, duration_ns: u64) {
self.aggregates[kind.index()].record(duration_ns);
if duration_ns < SLOW_SPAN_NS {
Expand Down Expand Up @@ -224,6 +236,45 @@ pub struct Span<'a> {
finished: bool,
}

/// A duration whose kind is chosen when it finishes. Dropping it records nothing, so work refused
/// or cancelled before it starts does not look like completed queue latency.
pub struct DeferredSpan {
started_ns: u64,
}

impl DeferredSpan {
fn stop_with(self, clock: &dyn Clock) -> DeferredDuration {
DeferredDuration {
started_ns: self.started_ns,
duration_ns: clock.now_ns().saturating_sub(self.started_ns),
}
}

pub fn stop(self) -> DeferredDuration {
self.stop_with(&CLOCK)
}

pub fn finish(self, kind: StallKind) {
self.stop().finish(kind);
}
}

/// A stopped deferred duration. Dropping it records nothing.
pub struct DeferredDuration {
started_ns: u64,
duration_ns: u64,
}

impl DeferredDuration {
fn finish_with(self, recorder: &Recorder, kind: StallKind) {
recorder.record(kind, self.started_ns, self.duration_ns);
}

pub fn finish(self, kind: StallKind) {
self.finish_with(&RECORDER, kind);
}
}

impl Drop for Span<'_> {
fn drop(&mut self) {
if !self.finished {
Expand Down Expand Up @@ -254,6 +305,12 @@ pub fn span(kind: StallKind) -> Option<Span<'static>> {
RECORDER.start_with(kind, &CLOCK)
}

/// Begin an opt-in duration which records only when [`DeferredSpan::finish`] is called.
#[inline]
pub fn deferred_span() -> Option<DeferredSpan> {
RECORDER.defer_with(&CLOCK)
}

/// A high-frequency command-recording span, enabled only by `XCL_STALL_TRACE_DETAIL`.
#[inline]
pub fn detail_span(kind: StallKind) -> Option<Span<'static>> {
Expand Down Expand Up @@ -314,10 +371,39 @@ mod tests {
let recorder = Recorder::new();
let clock = TestClock::new(10);
assert!(recorder.start_with(StallKind::DxcCompile, &clock).is_none());
assert!(recorder.defer_with(&clock).is_none());
assert_eq!(clock.calls.load(Ordering::Relaxed), 0);
assert_eq!(recorder.snapshot().aggregates[StallKind::DxcCompile.index()].count, 0);
}

#[test]
fn deferred_spans_split_queue_bands_and_abandoned_work_records_nothing() {
let recorder = Recorder::new();
recorder.enable();
let clock = TestClock::new(10);

let speculative = recorder.defer_with(&clock).unwrap();
clock.now.store(30, Ordering::Relaxed);
let speculative = speculative.stop_with(&clock);
let demand = recorder.defer_with(&clock).unwrap();
clock.now.store(75, Ordering::Relaxed);
speculative.finish_with(&recorder, StallKind::PipelineQueueSpeculative);
demand.stop_with(&clock).finish_with(&recorder, StallKind::PipelineQueueDemand);
let abandoned_previous = recorder.defer_with(&clock).unwrap();
clock.now.store(100, Ordering::Relaxed);
let abandoned_previous = abandoned_previous.stop_with(&clock);
let abandoned_active = recorder.defer_with(&clock).unwrap();
clock.now.store(1_000, Ordering::Relaxed);
drop((abandoned_previous, abandoned_active));

let snapshot = recorder.snapshot();
let speculative = &snapshot.aggregates[StallKind::PipelineQueueSpeculative.index()];
let demand = &snapshot.aggregates[StallKind::PipelineQueueDemand.index()];
assert_eq!((speculative.count, speculative.total_ns), (1, 20));
assert_eq!((demand.count, demand.total_ns), (1, 45));
assert_eq!(clock.calls.load(Ordering::Relaxed), 7, "abandoning deferred work must not read the clock again");
}

#[test]
fn coarse_tracing_does_not_enable_detail_spans() {
let recorder = Recorder::new();
Expand Down
Loading