Skip to content
Open
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
6 changes: 5 additions & 1 deletion drivers/gpu/drm/asahi/g16/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1861,6 +1861,7 @@ impl Firmware {
|| c.is_rt()
|| head_order.wait_through != [None, None]
|| !head.fw_waits.is_empty()
|| self.engine.flights.iter().any(|fl| fl.renders != 0)
|| self.compute_queue_is_heavy(&head.queue, now)
{
return false;
Expand Down Expand Up @@ -1936,7 +1937,10 @@ impl Firmware {
cap > 1 && pending_cmds < cap
}
Some(Command::Render(_)) => {
if head.resources.render_scs() || !head.fw_waits.is_empty() {
if head.resources.render_scs()
|| !head.fw_waits.is_empty()
|| self.engine.flights.iter().any(|fl| fl.computes != 0)
{
return false;
}
let queue_active: usize = self
Expand Down
16 changes: 10 additions & 6 deletions drivers/gpu/drm/asahi/g16/job.rs
Original file line number Diff line number Diff line change
Expand Up @@ -794,12 +794,16 @@ pub(crate) struct Scheduler {

impl Scheduler {
pub(crate) fn new(dev: &device::Device) -> Result<Self> {
// Keep drm_sched run/free work in the creating CPU's cluster (matching g17/job.rs).
// Completion work still follows the per-submit submitter_cpu, not queue creation, and
// an unbound workqueue restricted via apply_workqueue_attrs() falls back to
// wq_unbound_cpumask if the cluster goes offline (failing soft if restrict() errors).
let submit = workqueue::OwnedQueue::new_ordered_reclaim(c_str!("aurora_g16"))?;
let _ = submit.restrict(Cpumask::cluster_of(CpuId::current()));
// Run drm_sched's submit worker at WQ_HIGHPRI in the creating CPU's cluster (matching
// g17/job.rs) to raise worker priority for host-signalled and dependency-waited jobs
// (scheduler latency remains possible). Completion work still follows submitter_cpu,
// not queue creation, and without a multi-CPU cluster topology the queue stays
// unrestricted rather than pinned to a single CPU.
let submit = workqueue::OwnedQueue::new_ordered_highpri_reclaim(c_str!("aurora_g16"))?;
let cluster = Cpumask::cluster_of(CpuId::current());
if cluster.weight() > 1 {
let _ = submit.restrict(cluster);
}
let scheduler = sched::Scheduler::new_with_queues(
dev,
1,
Expand Down
9 changes: 8 additions & 1 deletion drivers/gpu/drm/asahi/g16/poll.rs
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ impl Shared {
} else {
HOUSEKEEPING_NS
};
let housekeeping_due =
let mut housekeeping_due =
now.wrapping_sub(firmware.last_housekeeping_ns) >= housekeeping_interval;
let was_evented = had_flights && self.evented.swap(false, Ordering::AcqRel);
let recovery_pending = firmware.recovery_pending().unwrap_or(true);
Expand Down Expand Up @@ -329,6 +329,13 @@ impl Shared {
firmware.fail_stop(error, done);
self.fail_stop(error);
}
if !had_flights && !firmware.engine.flights.is_empty() {
// On an idle-to-active transition, let the upcoming EP 0x20 completion (or the
// already-armed `resnap` hrtimer for long flights) drive deferred housekeeping
// after waking userspace instead of kicking an immediate `FAST_POLL_WORK` onto the
// submitter CPU that contends on `Shared::state` while the single flight runs.
housekeeping_due = false;
}
if !firmware.engine.flights.is_empty() || firmware.engine.chan_wait {
// If an EP 0x20 event retired an older flight while later flights remain active,
// or arrived before the oldest receipt became visible, arm a short repoll so
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ def function(text, name):
queue_methods = '\n'.join(function(queue_source, name) for name in ['cancel', 'check', 'cancelled_through', 'is_compute_retired'])
methods = '\n'.join(function(source, name) for name in ['latch_failure', 'complete', 'finish', 'is_started', 'try_start_inline', 'start', 'check_command_dependencies', 'command_retired', 'note_full_retirement', 'mark_terminal_retired', 'waits_on_queue'])
push_method = function_from(source, 'pub(crate) fn push(&mut self, job: Arc<Job>')
sched_new_method = function_from(source, 'pub(crate) fn new(dev: &device::Device)')
fence_methods = '\n'.join(function(fence_source, name) for name in ['dependency_status', 'check_dependencies', 'wait_dependencies'])
harness = r'''
#![allow(dead_code)]
Expand Down Expand Up @@ -638,7 +639,99 @@ def function(text, name):
q1.cancel(&p_orders,0);
assert_eq!(cons.check_command_dependencies(0),Err(ECANCELED));
}
'''.replace('QUEUE_METHODS', queue_methods).replace('ORDER_SOURCE', order_source).replace('FENCE_METHODS', fence_methods).replace('METHODS', methods.replace('super::fence::','fence::').replace('super::command::','command::')).replace('PUSH_METHOD', push_method)
mod scheduler_new_check {
use core::sync::atomic::{AtomicUsize, Ordering};
use std::cell::Cell;
use std::sync::{Arc, Mutex};
type Result<T = ()> = core::result::Result<T, super::Error>;
const GFP_KERNEL: u32 = 0;
macro_rules! c_str { ($s:expr) => { $s }; }
thread_local! {
static CLUSTER_WEIGHT: Cell<u32> = const { Cell::new(4) };
static HIGHPRI_CALLS: Cell<u32> = const { Cell::new(0) };
static RESTRICT_CALLS: Cell<u32> = const { Cell::new(0) };
}
mod device { pub struct Device; }
mod hw {
pub mod sizes { pub const SCHEDULER_CREDITS: u32 = 64; }
pub mod tuning { pub const SCHED_TIMEOUT_MS: u32 = 1000; }
}
struct CpuId;
impl CpuId { fn current() -> Self { Self } }
struct Cpumask(u32);
impl Cpumask {
fn cluster_of(_cpu: CpuId) -> Self { Self(CLUSTER_WEIGHT.with(Cell::get)) }
fn weight(&self) -> u32 { self.0 }
}
mod workqueue {
use super::*;
pub struct OwnedQueue;
impl OwnedQueue {
pub fn new_ordered_highpri_reclaim(_name: &str) -> Result<Self> {
HIGHPRI_CALLS.with(|c| c.set(c.get() + 1));
Ok(Self)
}
pub fn restrict(&self, _mask: Cpumask) -> Result {
RESTRICT_CALLS.with(|c| c.set(c.get() + 1));
Ok(())
}
}
}
mod sched {
use super::*;
pub enum Priority { Kernel }
pub struct Scheduler<T>(core::marker::PhantomData<T>);
impl<T> Scheduler<T> {
pub fn new_with_queues(
_dev: &device::Device,
_rqs: u32,
_credits: u32,
_hang: u32,
_timeout: u32,
_name: &str,
submit: Option<workqueue::OwnedQueue>,
_timeout_wq: Option<workqueue::OwnedQueue>,
) -> Result<Self> {
assert!(submit.is_some());
Ok(Self(core::marker::PhantomData))
}
}
pub struct Entity<T>(core::marker::PhantomData<T>);
impl<T> Entity<T> {
pub fn new(_s: &Scheduler<T>, _p: Priority) -> Result<Self> {
Ok(Self(core::marker::PhantomData))
}
}
}
struct SchedJob;
struct Scheduler {
entity: sched::Entity<SchedJob>,
_scheduler: sched::Scheduler<SchedJob>,
pending_sched: Arc<AtomicUsize>,
}
struct ArcNew;
trait ArcExt<T> { fn new_gfp(v: T, _gfp: u32) -> Result<Arc<T>>; }
impl<T> ArcExt<T> for Arc<T> { fn new_gfp(v: T, _gfp: u32) -> Result<Arc<T>> { Ok(Arc::new(v)) } }
impl Scheduler {
SCHED_NEW_METHOD
}
#[test]
fn scheduler_new_uses_highpri_ordered_wq_and_restricts_only_multicpu_clusters() {
HIGHPRI_CALLS.with(|c| c.set(0));
RESTRICT_CALLS.with(|c| c.set(0));
CLUSTER_WEIGHT.with(|c| c.set(4));
let _s = Scheduler::new(&device::Device).unwrap();
assert_eq!(HIGHPRI_CALLS.with(Cell::get), 1);
assert_eq!(RESTRICT_CALLS.with(Cell::get), 1);

CLUSTER_WEIGHT.with(|c| c.set(1));
let _s2 = Scheduler::new(&device::Device).unwrap();
assert_eq!(HIGHPRI_CALLS.with(Cell::get), 2);
assert_eq!(RESTRICT_CALLS.with(Cell::get), 1, "single-CPU cluster stays unrestricted");
let _ = (Mutex::new(()), ArcNew, Ordering::Relaxed);
}
}
'''.replace('QUEUE_METHODS', queue_methods).replace('ORDER_SOURCE', order_source).replace('FENCE_METHODS', fence_methods).replace('METHODS', methods.replace('super::fence::','fence::').replace('super::command::','command::')).replace('PUSH_METHOD', push_method).replace('SCHED_NEW_METHOD', sched_new_method.replace('Arc::new(', 'Arc::new_gfp(').replace('core::sync::atomic::AtomicUsize', 'AtomicUsize'))

with tempfile.TemporaryDirectory(prefix='m4-rust-job-') as directory:
directory=pathlib.Path(directory); test=directory/'test.rs'; test.write_text(harness)
Expand All @@ -649,6 +742,6 @@ def function(text, name):
(OUT/'job-failure-host.log').write_text(result.stdout+result.stderr)
(OUT/'job-failure-host.json').write_text(json.dumps({
'source':str(SOURCE),'sha256':hashlib.sha256(SOURCE.read_bytes()).hexdigest(),
'result':'pass','test_groups':25,
'result':'pass','test_groups':26,
'limitations':'Production Job methods with host VM/fence mocks; actual DRM scheduler and firmware publication gates require kernel and execution integration validation.'
},indent=2)+'\n')
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,7 @@ def item(declaration, text=source):
drain_compute_delta: u32,
coalesce_us: Option<u32>,
publish_waits: Option<(bool, bool)>,
publish_adds_flight: bool,
retire_calls: u32,
publish_full_calls: u32,
publish_checked_calls: u32,
Expand Down Expand Up @@ -383,6 +384,7 @@ def item(declaration, text=source):
drain_compute_delta: 0,
coalesce_us: None,
publish_waits: None,
publish_adds_flight: false,
retire_calls: 0,
publish_full_calls: 0,
publish_checked_calls: 0,
Expand Down Expand Up @@ -454,6 +456,16 @@ def item(declaration, text=source):
self.engine.slot_wait = slot_wait;
self.engine.held_wait = held_wait;
}
if self.publish_adds_flight {
self.engine.flights.push(Flight {
computes: 1,
compute_pipe: 0,
renders: 0,
render_pair: 0,
target: 0x100,
fs_target: 0,
});
}
self.publish_checked_calls += 1;
Ok(())
}
Expand Down Expand Up @@ -705,6 +717,36 @@ def item(declaration, text=source):
assert_eq!(shared.rearm_soon.get(), 1);
}

#[test]
fn submit_locked_skips_eager_housekeeping_poll_on_idle_to_active_transition() {
// Idle GPU past HOUSEKEEPING_NS (1 ms): publishing a fresh single flight arms resnap
// instead of immediately kicking poll_now() onto the submitter CPU while the flight runs.
CLOCK.with(|c| c.set(3_000_000));
let shared = Shared::new();
let mut fw = Firmware::new();
fw.last_housekeeping_ns = 1_000_000;
fw.publish_adds_flight = true;

let mut done = vec![];
shared
.submit_locked(&mut fw, Arc::new(Job { id: 10 }), &mut done)
.unwrap();
assert_eq!(fw.publish_checked_calls, 1);
assert_eq!(fw.engine.flights.len(), 1);
assert_eq!(shared.rearmed.get(), 1);
assert_eq!(shared.poll_now_calls.get(), 0);

// If an idle submit publishes no flight while housekeeping is due, poll_now() still runs.
let shared_idle = Shared::new();
let mut fw_idle = Firmware::new();
fw_idle.last_housekeeping_ns = 1_000_000;
shared_idle
.submit_locked(&mut fw_idle, Arc::new(Job { id: 11 }), &mut done)
.unwrap();
assert_eq!(fw_idle.engine.flights.len(), 0);
assert_eq!(shared_idle.poll_now_calls.get(), 1);
}

#[test]
fn poll_step_defers_active_housekeeping_until_five_ms_and_off_hot_lock() {
let mut fw = Firmware::new();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3179,11 +3179,22 @@ def item(declaration):
assert_eq!(h.defer_busy_coalesce(425_000), None);
h.engine.flights.pop();

// Same-queue interleaved render active alongside computes bypasses compute coalescing.
let r_same = mk_job(&vm1, &q1, true, 1, [None, None]);
h.engine.flights.push(Flight { job: r_same, computes: 0, renders: 1, compute_pipe: 0, published_ns: 415_000, doomed: false, recovery_suspect: false, initbm: false });
assert_eq!(h.defer_busy_coalesce(430_000), None);
h.engine.flights.pop();

// A render with queue_active == 2 coalesces up to K=6 passes before flushing.
let r1 = mk_job(&vm1, &q1, true, 1, [None, None]);
h.engine.flights = vec![Flight { job: r1, computes: 0, renders: 2, compute_pipe: 0, published_ns: 490_000, doomed: false, recovery_suspect: false, initbm: false }];
h.engine.pending = vec![mk_job(&vm1, &q1, true, 3, [Some(2), None])];
assert_eq!(h.defer_busy_coalesce(500_000), Some(18));
// Same-queue interleaved compute active alongside renders bypasses render coalescing.
h.engine.flights.push(Flight { job: c1.clone(), computes: 1, renders: 0, compute_pipe: 0, published_ns: 495_000, doomed: false, recovery_suspect: false, initbm: false });
assert_eq!(h.defer_busy_coalesce(501_000), None);
h.engine.flights.pop();
assert_eq!(h.defer_busy_coalesce(500_000), Some(18));
for seq in 4..=7 {
h.engine.pending.push(mk_job(&vm1, &q1, true, seq, [Some(seq - 1), None]));
assert_eq!(h.defer_busy_coalesce(502_000), Some(16));
Expand Down
Loading