Skip to content
43 changes: 41 additions & 2 deletions drivers/gpu/drm/asahi/m3/m3_batch_policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,10 @@ pub(crate) fn urgent_waiting(urgencies: impl Iterator<Item=u8>, active:u8) -> bo
urgencies.into_iter().any(|p|p>active)
}

pub(crate) const fn may_join(render:bool, next:usize, same_vm:bool, same_urgency:bool) -> bool {
render && next==0 && same_vm && same_urgency
/// A later pending packet may extend a batch of either engine from its first command, for the
/// batch's VM and at its urgency. The batch limit and GPU-time budget still bound the batch.
pub(crate) const fn may_join(next:usize, same_vm:bool, same_urgency:bool) -> bool {
next==0 && same_vm && same_urgency
}

pub(crate) const fn default_depth(t8122:bool) -> usize {if t8122 {2} else {1}}
Expand All @@ -68,6 +70,37 @@ pub(crate) fn pipeline_room(depth: usize, batches: usize, passes: usize,
Some(((last_base + last_count) % SLOTS, SLOTS - passes))
}

/// Whether the next command may extend the batch. Render passes always need the budget. A compute
/// batch always takes one command; further commands need a budget and the VM's measured compute
/// cost, so that without a budget every compute batch is one command, as before. Only an
/// explicit `m3_compute_batch_override` lets the front packet's own commands go unbudgeted.
pub(crate) fn admits(render:bool, joined:bool, explicit:bool, cost:Option<u64>, budget:Option<u64>,
passes:usize) -> bool {
if render || passes == 0 { return within_budget(cost, budget, passes); }
if explicit && !joined { return true; }
budget.is_some() && within_budget(cost, budget, passes)
}

/// The compute batch limit. `size` is `m3_compute_batch_override` when set, else
/// `m3_compute_batch_size`; 0 means the user set neither. The default joins compute commands
/// only on the Legacy firmware interface, where it was measured: on the Extended interface (J613)
/// the default stays one command per batch until a J613 row covers it. A user-set size applies
/// on both interfaces.
pub(crate) fn compute_batch_limit(size:u64, extended:bool, slots:usize) -> usize {
let size = match size {
0 if extended => 1,
0 => slots,
size => usize::try_from(size).unwrap_or(slots),
};
size.clamp(1, slots)
}

/// Seconds a published batch may run before it is failed: each command keeps the two seconds it
/// had when it was published alone, so batching never shortens a command's deadline.
pub(crate) const fn batch_deadline_secs(commands:usize) -> i64 {
2 * (if commands == 0 { 1 } else { commands }) as i64
}

/// Always admit one pass; subsequent passes must fit the measured budget.
/// Unknown cost permits one pass until a measurement is available.
pub(crate) fn within_budget(cost: Option<u64>, budget: Option<u64>, passes: usize) -> bool {
Expand All @@ -89,6 +122,12 @@ pub(crate) const fn release_unpublished(may_be_published: bool) -> bool {
!may_be_published
}

/// A batch entry that is its packet's first command: no earlier batch included the packet, so if
/// this batch fails before anything reached the firmware, the packet is unpublished again.
pub(crate) const fn first_publication(command: usize) -> bool {
command == 0
}

pub(crate) const fn retain_runtime(stop_failed: bool, gpu_pending: bool) -> bool {
stop_failed || gpu_pending
}
Expand Down
38 changes: 25 additions & 13 deletions drivers/gpu/drm/asahi/m3/m3_params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,8 +208,12 @@ pub(crate) fn render_internal_timestamps()->bool {
/// `aurora.m3_render_batch_size`: bounded ordered render batch size (1..16, default 2).
static M3_RENDER_BATCH_SIZE: AtomicU64 = AtomicU64::new(2);
m3_param!("m3_render_batch_size", M3_RENDER_BATCH_SIZE, parse_u64);
/// `aurora.m3_compute_batch_size`: bounded ordered compute batch size (1..16).
static M3_COMPUTE_BATCH_SIZE: AtomicU64 = AtomicU64::new(1);
/// `aurora.m3_compute_batch_size`: bounded ordered compute batch size (1..16). 0 (the default)
/// selects the firmware profile's default: the compute storage's slot count on the Legacy
/// interface, and 1 on the Extended interface (J613), whose compute batching has no row yet.
/// A compute batch grows past one command only under the GPU-time budget
/// (`m3_render_batch_budget_us`); without a budget each compute batch is one command.
static M3_COMPUTE_BATCH_SIZE: AtomicU64 = AtomicU64::new(0);
m3_param!("m3_compute_batch_size", M3_COMPUTE_BATCH_SIZE, parse_u64);
/// `aurora.m3_early_tiling`: opt-in fragment-only stage dependencies.
static M3_EARLY_TILING: AtomicU64 = AtomicU64::new(0);
Expand Down Expand Up @@ -263,15 +267,22 @@ static M3_COMPUTE_BATCH_OVERRIDE: AtomicU64 = AtomicU64::new(0);
m3_param!("m3_compute_batch_override", M3_COMPUTE_BATCH_OVERRIDE,
parse_compute_batch_override, 0o644, Some(get_atomic_param));

/// Snapshot once per packet, so a live write never changes an in-flight batch.
pub(crate) fn compute_batch_size() -> usize {
/// Whether `m3_compute_batch_override` is set (it then bounds a packet's own commands alone).
pub(crate) fn compute_batch_overridden() -> bool {
M3_COMPUTE_BATCH_OVERRIDE.load(Ordering::Relaxed) != 0
}

/// Snapshot once per packet, so a live write never changes an in-flight batch. Without a
/// user-set size or override the loaded firmware profile picks the default.
pub(crate) fn compute_batch_size(profile: crate::m3::m3_profile::Profile) -> usize {
let override_size = M3_COMPUTE_BATCH_OVERRIDE.load(Ordering::Relaxed);
let size = if override_size == 0 {
M3_COMPUTE_BATCH_SIZE.load(Ordering::Relaxed) as usize
M3_COMPUTE_BATCH_SIZE.load(Ordering::Relaxed)
} else {
override_size as usize
override_size
};
size.clamp(1, crate::m3::m3_compute_storage::SLOTS)
crate::m3::m3_runtime::policy::compute_batch_limit(size,
profile == crate::m3::m3_profile::Profile::Extended, crate::m3::m3_compute_storage::SLOTS)
}

/// `aurora.g15_debug`: G15 bring-up bits, see [`G15Debug`].
Expand Down Expand Up @@ -483,12 +494,13 @@ pub(crate) fn pipeline_depth(soc: &crate::m3::m3_soc::Soc) -> usize {
}
}

/// `aurora.m3_render_batch_budget_us`: writable at runtime. A render batch takes in later packets
/// of its VM only while the VM's measured GPU time per pass, times the passes already in the
/// batch, stays below this budget (4000 µs on experimental T8122, disabled on Pro).
/// Coalescing a client's heavy frames
/// otherwise makes every other client's work, the compositor's included, wait for all of them.
/// 0 disables the budget; u64::MAX restores the SoC default.
/// `aurora.m3_render_batch_budget_us`: writable at runtime. A render or compute batch takes in
/// later packets of its VM only while the VM's measured GPU time per pass (or per compute
/// command), times the passes already in the batch, stays below this budget (4000 µs by
/// default). Each batched command keeps its own completion deadline. Coalescing a client's heavy
/// frames or dispatches otherwise makes every other client's work, the compositor's included,
/// wait for all of them. 0 disables the budget, and every compute batch is then one command;
/// u64::MAX restores the default.
static M3_RENDER_BATCH_BUDGET_US: AtomicU64 = AtomicU64::new(u64::MAX);
m3_param!("m3_render_batch_budget_us", M3_RENDER_BATCH_BUDGET_US, parse_u64, 0o644, Some(get_atomic_param));

Expand Down
77 changes: 52 additions & 25 deletions drivers/gpu/drm/asahi/m3/m3_runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,9 @@ struct Inner {
/// Whether a T8122 job verdict line was already emitted for the current job, so the
/// execute-path fallback does not add a second one. T8122 only.
t8122_verdict: bool,
/// Publish the front packet alone once: a batch that joined later packets failed before
/// anything reached the firmware, and the front packet must not take the blame for them.
solo_next: bool,
/// The step the firmware boot sequence has reached, for the T8122 boot verdict. T8122 only.
boot_step: crate::m3::t8122_start::BootStep,
/// Packets that joined a batch started by an earlier packet (debug summary).
Expand All @@ -96,6 +99,8 @@ struct Inner {
/// Recent measured render GPU time per pass by VM. Smoothed over batches;
/// replacing the least recently measured VM does not retain its mappings.
pass_cost: policy::PassCosts,
/// Measured GPU time per compute command, per VM (the compute twin of `pass_cost`).
compute_cost: policy::PassCosts,
/// Latched only after the isolated InitBM draw fully retired.
render_initialized: bool,
/// Blocks new publication while a system sleep is preparing or active.
Expand Down Expand Up @@ -520,6 +525,7 @@ impl Inner {
self.packets.retain(|p| self.active.iter().any(|b|b.entries.iter().any(|(q,_)|Arc::ptr_eq(p,q))));
}
fn fail_front(&mut self,error:Error) {
self.solo_next=false;
if let Ok((packet,_))=self.pending.remove(0) {
if !self.packet_active(&packet) && !self.fault_captured {packet.release_guard();}
packet.fail_packet(error);
Expand All @@ -530,8 +536,8 @@ impl Inner {
for (packet,_) in entries {packet.finish(result);}
}
/// Choose the next batch from the front of `pending`: the front packet's next commands of
/// one engine, and for render also the leading render commands of following packets of the
/// same VM, up to the ordered-batch limit.
/// one engine, and the leading commands of that engine of following packets of the same VM,
/// up to the ordered-batch limit and the batch's GPU-time budget.
fn next_batch(&self,max:usize)->Result<KVec<(Arc<crate::m3::m3_submit::Packet>,usize)>> {
let mut entries=KVec::new();
let Some((packet,next))=self.pending.first() else {return Ok(entries);};
Expand All @@ -551,21 +557,21 @@ impl Inner {
let started=self.jobs.iter().any(|job| matches!(job,NativeJob::Render(j) if j.started()));
if started {crate::m3::m3_params::render_batch_size().min(max).max(1)} else {1}
} else {
crate::m3::m3_params::compute_batch_size()
.clamp(1,crate::m3::m3_compute_storage::SLOTS)
crate::m3::m3_params::compute_batch_size(self.device.firmware().profile())
};
let same_engine=|c:&crate::m3::m3_submit::Command| render==matches!(c,crate::m3::m3_submit::Command::Render{..});
let per_pass=self.pass_cost.get(packet.vm.id());
let per_pass=if render {self.pass_cost.get(packet.vm.id())} else {self.compute_cost.get(packet.vm.id())};
let budget=crate::m3::m3_params::render_batch_budget_ns(self.device.soc());
let explicit=crate::m3::m3_params::compute_batch_overridden();
let in_flight:usize=self.active.iter().map(|b|b.entries.len()).sum();
for (position,(candidate,start)) in self.pending.iter().enumerate() {
// Later packets join only render batches, only from their first command, and only
// for the VM the batch is bound to, while the batch's expected GPU time is within
// the budget.
if position>0 && !policy::may_join(render,*start,candidate.vm.same(&packet.vm),candidate.urgency==packet.urgency) {break;}
// Later packets join only from their first command, only for the VM the batch is
// bound to and at its urgency, while the batch's expected GPU time is within the
// budget. Each queued submission otherwise pays a full firmware round trip.
if position>0 && (self.solo_next || !policy::may_join(*start,candidate.vm.same(&packet.vm),candidate.urgency==packet.urgency)) {break;}
let mut index=*start;
while index<candidate.commands.len() && entries.len()<limit && same_engine(&candidate.commands[index]) {
if render && !policy::within_budget(per_pass,budget,in_flight+entries.len()) {return Ok(entries);}
if !policy::admits(render,position>0,explicit,per_pass,budget,in_flight+entries.len()) {return Ok(entries);}
entries.push((candidate.clone(),index),GFP_KERNEL)?;
index+=1;
}
Expand Down Expand Up @@ -644,6 +650,7 @@ impl Inner {
};
match self.publish(&entries,base,overlap) {
Ok(batch)=>{
self.solo_next=false;
// Consume the published commands from `pending`.
let Some((last,last_index))=entries.last().map(|(p,i)|(p.clone(),*i)) else {break;};
while let Some((packet,_))=self.pending.first() {
Expand All @@ -668,21 +675,35 @@ impl Inner {
self.t8122_verdict=true;
}
// A live ring WRITE or doorbell may have been published: keep packets
// retained (self.packets) and fail them and everything in flight.
// retained (self.packets) and fail them and everything in flight. The
// error may come from before the batch's packets were marked.
for (p,_) in entries.iter() {p.mark_published();}
self.capture_fault(error);
Self::finish_all(&entries,Err(error));
self.fail_active(error);
self.fail_pending(error);
return true;
} else if overlap && error==EBUSY {
// Not publishable behind the running batch (new VM binding or storage
// growth): wait for it to retire.
break;
} else {
// Nothing reached the firmware: fail only the front packet, as a failed
// execute() did before publication.
self.fail_front(error);
progress=true;
// Nothing reached the firmware. A packet whose first command is in this
// batch was never published before, so it is unpublished again if the
// batch marked it: a later failure then releases its VM job guard.
for (p,i) in entries.iter() {if policy::first_publication(*i) {p.clear_published();}}
if overlap && error==EBUSY {
// Not publishable behind the running batch (new VM binding or
// storage growth): wait for it to retire.
break;
} else if !self.solo_next && entries.iter().any(|(p,_)|!Arc::ptr_eq(p,&entries[0].0)) {
// Later packets joined, and the error may be theirs: retry the front
// packet alone. If it publishes, the next packet is tried as the
// front in turn, so only a packet that fails alone is failed.
self.solo_next=true;
progress=true;
} else {
// Fail only the front packet, as a failed execute() did before
// publication.
self.fail_front(error);
progress=true;
}
}
}
}
Expand Down Expand Up @@ -712,9 +733,11 @@ impl Inner {
for (p,_) in entries {
if !self.packets.iter().any(|q| Arc::ptr_eq(q,p)) {self.packets.push(p.clone(),GFP_KERNEL).map_err(|_|early(ENOMEM))?;}
}
// Before any producer state changes: an append the overlapping firmware consumes, or a
// partial publication, makes these packets visible to it.
for (p,_) in entries {p.mark_published();}
// Behind a running batch the firmware can consume an append without a new doorbell, so
// the packets count as published before any producer state changes. With nothing in
// flight they are marked only once every command is encoded (below): an encoding
// failure then leaves them unpublished.
if overlap {for (p,_) in entries {p.mark_published();}}
let found=self.jobs.iter().position(|job| matches!((job,control),
(NativeJob::Compute(_),crate::m3::m3_submit::Command::Compute(_)) |
(NativeJob::Render(_),crate::m3::m3_submit::Command::Render{..})));
Expand Down Expand Up @@ -806,6 +829,8 @@ impl Inner {
packet.vm.mark_binding_published().map_err(early)?;
}
let publication_tick=if crate::debug::debug_enabled(crate::debug::DebugFlags::M3PassTiming) {physical_counter()} else {0};
// Every command is encoded and the next step tells the firmware about the batch.
for (p,_) in entries {p.mark_published();}
self.state.health.set_gpu_pending(true);
self.gpu_pending = true;
let late=|e:Error|(e,true);
Expand Down Expand Up @@ -1044,7 +1069,7 @@ impl Inner {
return Ok(true);
}
Ok(false)=>{
let (expired,previous)=self.active.first().map(|b|(b.start.elapsed()>=Delta::from_secs(2),b.previous_events)).ok_or(EIO)?;
let (expired,previous)=self.active.first().map(|b|(b.start.elapsed()>=Delta::from_secs(policy::batch_deadline_secs(b.entries.len())),b.previous_events)).ok_or(EIO)?;
if expired {
dev_err!(self.drm.as_ref(),"M3 pipelined completion events={} previous={}\n",self.config.completed_events,previous);
if self.config.recovery_phase() == Ok(1) {
Expand Down Expand Up @@ -1126,7 +1151,7 @@ impl Inner {
if evented && batch.events_ns<0 {batch.events_ns=at;}
}
if let Some(t)=poll_start {batch.polling_ns+=t.elapsed().as_nanos();batch.polls+=1;}
(evented,batch.start.elapsed()>=Delta::from_secs(2),batch.previous_events)
(evented,batch.start.elapsed()>=Delta::from_secs(policy::batch_deadline_secs(batch.entries.len())),batch.previous_events)
};
if stamped && evented {
let retire_mmio=crate::m3::m3_params::retire_mmio(self.device.soc());
Expand Down Expand Up @@ -1230,6 +1255,8 @@ impl Inner {
let vm=batch.entries[0].0.vm.id();
self.pass_cost.record(vm,gpu_ns/batch_count as u64);
self.render_initialized=true;
} else {
self.compute_cost.record(batch.entries[0].0.vm.id(),gpu_ns/batch_count as u64);
}
if crate::debug::debug_enabled(crate::debug::DebugFlags::M3PassTiming) {
let observed_tick=physical_counter();
Expand Down Expand Up @@ -1447,7 +1474,7 @@ impl Runtime {
quarantined_packets:KVec::new(),quarantine_budget:crate::m3::m3_recovery::QuarantineBudget::new(crate::m3::m3_recovery::QUARANTINE_LIMIT),
recovery_window_ns:0,recovery_window_count:0,recoveries:0,
gpu_pending:false,active_power_last:None,active_power_samples:0,fault_captured:false,timing:[[0;7];2],render_batches:[0;crate::m3::m3_pass_layout::SLOTS],
geometry:[GeometryTiming::default();32],geometry_overflow:0,coalesced_packets:0,coalesced_render_stamps:0,mixed_batches:0,pass_cost:policy::PassCosts::default(),render_initialized:false,asleep:false,sleep_held:false,t8122_verdict:false,
geometry:[GeometryTiming::default();32],geometry_overflow:0,coalesced_packets:0,coalesced_render_stamps:0,mixed_batches:0,pass_cost:policy::PassCosts::default(),compute_cost:policy::PassCosts::default(),render_initialized:false,asleep:false,sleep_held:false,t8122_verdict:false,solo_next:false,
boot_step:crate::m3::t8122_start::BootStep::Publish })) })
}
pub(crate) fn drm(&self) -> driver::AsahiDevRef { self.inner.drm.clone() }
Expand Down
Loading
Loading