From a700462ffa129c54018dcd7798bed7ccb056faa1 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 04:59:02 +1100 Subject: [PATCH 1/4] drm/asahi: m3: let queued compute submissions share a firmware batch The M3 runtime publishes one compute batch at a time and publishes the next one only after the previous one fully retired. Later pending packets could join render batches only, so every queued compute submission paid its own firmware round trip. On a J615 (M3, 27.2 firmware) that round trip is about 260 us for a 182 ns shader, so a light compute job costs ~390 us per vkQueueSubmit even at queue depth 8. Let later packets of the same VM and urgency join a compute batch from their first command, as render batches already do, and bound compute batches by the same GPU-time budget as render batches, using a per-VM measured GPU time per compute command. The compute batch size now defaults to the compute storage's slot count; the budget and the pending queue bound the batch in practice. The runtime knob m3_compute_batch_override still wins when set. On the J615 (one-shot kernel, in-boot ABAB of the batch size 1/8/1/8): compute.light at depth 8 goes from 394 to 174 us per submit, a light render clear from 363 to 173 us, heavy ALU compute from 1180 to 857 us, with 0 firmware error events. gpubench-stress-vk passes every test that does not inject a GPU fault. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/m3/m3_batch_policy.rs | 6 ++++-- drivers/gpu/drm/asahi/m3/m3_params.rs | 13 ++++++------ drivers/gpu/drm/asahi/m3/m3_runtime.rs | 22 ++++++++++++--------- tools/asahi/m3-batching-tests.rs | 9 ++++----- 4 files changed, 28 insertions(+), 22 deletions(-) diff --git a/drivers/gpu/drm/asahi/m3/m3_batch_policy.rs b/drivers/gpu/drm/asahi/m3/m3_batch_policy.rs index 27295660640ae..cb0c877edf667 100644 --- a/drivers/gpu/drm/asahi/m3/m3_batch_policy.rs +++ b/drivers/gpu/drm/asahi/m3/m3_batch_policy.rs @@ -48,8 +48,10 @@ pub(crate) fn urgent_waiting(urgencies: impl Iterator, 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}} diff --git a/drivers/gpu/drm/asahi/m3/m3_params.rs b/drivers/gpu/drm/asahi/m3/m3_params.rs index 85033c88e4192..6a2e1c74d7d70 100644 --- a/drivers/gpu/drm/asahi/m3/m3_params.rs +++ b/drivers/gpu/drm/asahi/m3/m3_params.rs @@ -208,8 +208,9 @@ pub(crate) fn render_internal_timestamps()->bool { /// `asahi.m3_render_batch_size`: bounded ordered render batch size (1..16). static M3_RENDER_BATCH_SIZE: AtomicU64 = AtomicU64::new(1); m3_param!("m3_render_batch_size", M3_RENDER_BATCH_SIZE, parse_u64); -/// `asahi.m3_compute_batch_size`: bounded ordered compute batch size (1..16). -static M3_COMPUTE_BATCH_SIZE: AtomicU64 = AtomicU64::new(1); +/// `asahi.m3_compute_batch_size`: bounded ordered compute batch size (1..16). The default is the +/// compute storage's slot count; the batch's GPU-time budget and the pending queue bound it. +static M3_COMPUTE_BATCH_SIZE: AtomicU64 = AtomicU64::new(crate::m3::m3_compute_storage::SLOTS as u64); m3_param!("m3_compute_batch_size", M3_COMPUTE_BATCH_SIZE, parse_u64); /// `asahi.m3_early_tiling`: opt-in fragment-only stage dependencies. static M3_EARLY_TILING: AtomicU64 = AtomicU64::new(0); @@ -483,10 +484,10 @@ pub(crate) fn pipeline_depth(soc: &crate::m3::m3_soc::Soc) -> usize { } } -/// `asahi.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 +/// `asahi.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 on +/// experimental T8122, disabled on Pro). 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; u64::MAX restores the SoC default. static M3_RENDER_BATCH_BUDGET_US: AtomicU64 = AtomicU64::new(u64::MAX); diff --git a/drivers/gpu/drm/asahi/m3/m3_runtime.rs b/drivers/gpu/drm/asahi/m3/m3_runtime.rs index 8bd242a483432..65bcae740a709 100644 --- a/drivers/gpu/drm/asahi/m3/m3_runtime.rs +++ b/drivers/gpu/drm/asahi/m3/m3_runtime.rs @@ -72,6 +72,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, config: Config, @@ -231,8 +233,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,usize)>> { let mut entries=KVec::new(); let Some((packet,next))=self.pending.first() else {return Ok(entries);}; @@ -256,17 +258,17 @@ impl Inner { .clamp(1,crate::m3::m3_compute_storage::SLOTS) }; 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 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 && !policy::may_join(*start,candidate.vm.same(&packet.vm),candidate.urgency==packet.urgency) {break;} let mut index=*start; while index driver::AsahiDevRef { self.inner.drm.clone() } diff --git a/tools/asahi/m3-batching-tests.rs b/tools/asahi/m3-batching-tests.rs index d9a0a35c04dd0..18b7775e0aa37 100644 --- a/tools/asahi/m3-batching-tests.rs +++ b/tools/asahi/m3-batching-tests.rs @@ -21,11 +21,10 @@ fn priority_fifo_and_partial_packet_yields() { // An unfinished low-priority packet gets a high-priority predecessor next batch. let low_continuation=vec![0,0]; assert_eq!(pending_position(low_continuation.into_iter(),3),0); - assert!(!may_join(true,0,true,false)); - assert!(!may_join(true,1,true,true)); - assert!(!may_join(true,0,false,true)); - assert!(!may_join(false,0,true,true)); - assert!(may_join(true,0,true,true)); + assert!(!may_join(0,true,false)); + assert!(!may_join(1,true,true)); + assert!(!may_join(0,false,true)); + assert!(may_join(0,true,true)); // A sorted pending head cannot detect its own urgency advantage. Compare // with the active batch so same-VM urgent work also stops extending it. assert!(urgent_waiting([3,0].into_iter(),0)); From 8eaf76139b6b55af3b869565ea1ded41b1ebbf23 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 05:38:54 +1100 Subject: [PATCH 2/4] drm/asahi: m3: bound joined compute batches by budget and deadline Review follow-up for the compute batching change: - Each batched command keeps the 2 s completion deadline it had when it was published alone: the batch deadline is now 2 s per command. Before, a batch of several long dispatches could exceed one 2 s deadline and fail the GPU although every command was in time. - A compute batch grows past one command only under a GPU-time budget and once the VM's compute cost is measured, whether the commands come from the front packet or from later packets. Without a budget every compute batch is one command, as before. An explicit m3_compute_batch_override still bounds the front packet's own commands alone, as before; it never lets other packets join without the budget. - If a batch that joined later packets fails before anything reached the firmware, the joined packets are marked unpublished again and the front packet is retried alone before it is failed, so it does not take the blame for a joined packet. Host tests cover the admission rule and the deadline. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/m3/m3_batch_policy.rs | 17 ++++++++++ drivers/gpu/drm/asahi/m3/m3_params.rs | 11 ++++-- drivers/gpu/drm/asahi/m3/m3_runtime.rs | 23 ++++++++++--- drivers/gpu/drm/asahi/m3/m3_submit.rs | 3 ++ tools/asahi/m3-batching-tests.rs | 37 +++++++++++++++++++++ 5 files changed, 84 insertions(+), 7 deletions(-) diff --git a/drivers/gpu/drm/asahi/m3/m3_batch_policy.rs b/drivers/gpu/drm/asahi/m3/m3_batch_policy.rs index cb0c877edf667..2558ea6ae6ab2 100644 --- a/drivers/gpu/drm/asahi/m3/m3_batch_policy.rs +++ b/drivers/gpu/drm/asahi/m3/m3_batch_policy.rs @@ -70,6 +70,23 @@ 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, budget:Option, + 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) +} + +/// 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, budget: Option, passes: usize) -> bool { diff --git a/drivers/gpu/drm/asahi/m3/m3_params.rs b/drivers/gpu/drm/asahi/m3/m3_params.rs index 6a2e1c74d7d70..628e927bc42a1 100644 --- a/drivers/gpu/drm/asahi/m3/m3_params.rs +++ b/drivers/gpu/drm/asahi/m3/m3_params.rs @@ -209,7 +209,8 @@ pub(crate) fn render_internal_timestamps()->bool { static M3_RENDER_BATCH_SIZE: AtomicU64 = AtomicU64::new(1); m3_param!("m3_render_batch_size", M3_RENDER_BATCH_SIZE, parse_u64); /// `asahi.m3_compute_batch_size`: bounded ordered compute batch size (1..16). The default is the -/// compute storage's slot count; the batch's GPU-time budget and the pending queue bound it. +/// compute storage's slot count. 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(crate::m3::m3_compute_storage::SLOTS as u64); m3_param!("m3_compute_batch_size", M3_COMPUTE_BATCH_SIZE, parse_u64); /// `asahi.m3_early_tiling`: opt-in fragment-only stage dependencies. @@ -264,6 +265,11 @@ 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)); +/// 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. pub(crate) fn compute_batch_size() -> usize { let override_size = M3_COMPUTE_BATCH_OVERRIDE.load(Ordering::Relaxed); @@ -487,7 +493,8 @@ pub(crate) fn pipeline_depth(soc: &crate::m3::m3_soc::Soc) -> usize { /// `asahi.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 on -/// experimental T8122, disabled on Pro). Coalescing a client's heavy frames or dispatches +/// experimental T8122, disabled on Pro, where compute packets then never join). 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; u64::MAX restores the SoC default. static M3_RENDER_BATCH_BUDGET_US: AtomicU64 = AtomicU64::new(u64::MAX); diff --git a/drivers/gpu/drm/asahi/m3/m3_runtime.rs b/drivers/gpu/drm/asahi/m3/m3_runtime.rs index 65bcae740a709..81cdd4dbdac8b 100644 --- a/drivers/gpu/drm/asahi/m3/m3_runtime.rs +++ b/drivers/gpu/drm/asahi/m3/m3_runtime.rs @@ -63,6 +63,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). @@ -223,6 +226,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.finish(Err(error)); @@ -260,15 +264,16 @@ impl Inner { let same_engine=|c:&crate::m3::m3_submit::Command| render==matches!(c,crate::m3::m3_submit::Command::Render{..}); 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 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 && !policy::may_join(*start,candidate.vm.same(&packet.vm),candidate.urgency==packet.urgency) {break;} + 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 index0,explicit,per_pass,budget,in_flight+entries.len()) {return Ok(entries);} entries.push((candidate.clone(),index),GFP_KERNEL)?; index+=1; } @@ -340,6 +345,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() { @@ -374,6 +380,13 @@ impl Inner { // 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)) { + // Nothing reached the firmware, but later packets joined: they joined from + // their first command and were never published before, so they are + // unpublished again. Retry the front packet alone before failing it. + for (p,_) in entries.iter().filter(|(p,_)|!Arc::ptr_eq(p,&entries[0].0)) {p.clear_published();} + self.solo_next=true; + progress=true; } else { // Nothing reached the firmware: fail only the front packet, as a failed // execute() did before publication. @@ -734,7 +747,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); self.fail_active(ETIMEDOUT);return Err(ETIMEDOUT); @@ -810,7 +823,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()); @@ -1124,7 +1137,7 @@ impl Runtime { }; Ok(Self { inner: ManuallyDrop::new(owner.write(Inner { transport, state, config, uat, window, drm, device, jobs:KVec::new(),packets:KVec::new(),pending:KVec::new(),active:KVec::new(),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(),compute_cost:policy::PassCosts::default(),render_initialized: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,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() } diff --git a/drivers/gpu/drm/asahi/m3/m3_submit.rs b/drivers/gpu/drm/asahi/m3/m3_submit.rs index 155bda714e9d9..4c9dffdd7891a 100644 --- a/drivers/gpu/drm/asahi/m3/m3_submit.rs +++ b/drivers/gpu/drm/asahi/m3/m3_submit.rs @@ -85,6 +85,9 @@ impl Packet { pub(crate) fn release_guard(&self) {drop(self.vm_job.lock().take());} /// Called before the first firmware-visible change of a batch that includes this packet. pub(crate) fn mark_published(&self) {self.published.store(true,Ordering::Relaxed);} + /// Undo `mark_published` for a packet that joined a batch from its first command when that + /// batch failed before any firmware-visible change. + pub(crate) fn clear_published(&self) {self.published.store(false,Ordering::Relaxed);} /// Whether the firmware may have seen any of this packet's commands. pub(crate) fn may_be_published(&self)->bool {self.published.load(Ordering::Relaxed)} pub(crate) fn retired(&self) {self.release_guard();self.finish(Ok(()));} diff --git a/tools/asahi/m3-batching-tests.rs b/tools/asahi/m3-batching-tests.rs index 18b7775e0aa37..591389c5c9ea1 100644 --- a/tools/asahi/m3-batching-tests.rs +++ b/tools/asahi/m3-batching-tests.rs @@ -32,6 +32,43 @@ fn priority_fifo_and_partial_packet_yields() { assert!(!urgent_waiting([0,0].into_iter(),0)); } +#[test] +fn compute_batches_grow_only_under_a_budget() { + let budget=Some(4_000_000); + for joined in [false,true] { for explicit in [false,true] { + // One command always goes. + assert!(admits(false,joined,explicit,None,None,0)); + // A measured cost that fits the budget lets the batch grow. + assert!(admits(false,joined,explicit,Some(1_000_000),budget,3)); + assert!(admits(false,joined,explicit,Some(10_000),budget,1)); + }} + // Without an override: no budget or no measurement keeps one command per batch. + for joined in [false,true] { + assert!(!admits(false,joined,false,Some(10_000),None,1)); + assert!(!admits(false,joined,false,None,budget,1)); + assert!(!admits(false,joined,false,Some(1_000_000),budget,4)); + } + // An explicit override bounds the front packet's own commands alone, never joined ones. + assert!(admits(false,false,true,None,None,15)); + assert!(admits(false,false,true,Some(10_000_000),budget,15)); + assert!(!admits(false,true,true,None,None,1)); + assert!(!admits(false,true,true,Some(1_000_000),budget,4)); + // Render keeps its budget rule. + for joined in [false,true] { + assert!(admits(true,joined,false,None,budget,0)); + assert!(!admits(true,joined,false,None,budget,1)); + assert!(admits(true,joined,false,None,None,7)); + } +} + +#[test] +fn batched_commands_keep_their_deadline() { + assert_eq!(batch_deadline_secs(0),2); + assert_eq!(batch_deadline_secs(1),2); + assert_eq!(batch_deadline_secs(8),16); + assert_eq!(batch_deadline_secs(16),32); +} + #[test] fn initbm_vm_engine_and_notification_gates() { for bits in 0..32 { From 9f4e653b1b3887aec68619b4cf603c03d56f62dc Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:52:33 +1100 Subject: [PATCH 3/4] drm/asahi: m3: mark a batch's packets published once it is encoded publish() marked every packet of a batch published before it encoded any command. When the encoding of a joined packet failed, nothing had reached the firmware, but the packet stayed pending and marked. A later failure of the pending queue then kept its VM job guard, and its VM stayed quarantined for work the firmware never saw. The previous commit unmarked joined packets on that path. Do it at the source instead: - With nothing in flight, the batch's packets are marked only once every command is encoded, just before the firmware is told about the batch. Behind a running batch the firmware can consume an append without a doorbell, so there they are still marked first. - If a batch fails before anything reached the firmware, every packet whose first command was in it is unmarked again, also when a batch behind a running one has to wait (EBUSY). A continuation keeps its mark. - An error that may have been published marks the batch's packets in publish_next(), because it can now come from before the marking. A failure of a batch with joined packets still retries the front packet alone, so a packet is failed only when it fails as a batch of its own: the front packet no longer takes the blame for a joined one, and a joined one is tried as the front before it is failed. Also drop "disabled on Pro" from the m3_render_batch_budget_us text: this runtime only probes on T8122. The first commit of this series quotes an earlier development kernel (batch size 1/8/1/8, a light render clear from 363 us). Measured with that commit itself on the J615, default command line, with m3_compute_batch_override flipped 0/1/0/1 in one boot (0 is the new default, 1 the old behaviour), in us per submit at depth 8: compute.light 178.2/394.9/173.6/396.8, the light render clear 174.8/396.8/173.6/397.5, heavy ALU compute 856.2/1207.7/844.6/1184.8. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/m3/m3_batch_policy.rs | 6 +++ drivers/gpu/drm/asahi/m3/m3_params.rs | 10 ++--- drivers/gpu/drm/asahi/m3/m3_runtime.rs | 49 +++++++++++++-------- drivers/gpu/drm/asahi/m3/m3_submit.rs | 7 +-- 4 files changed, 45 insertions(+), 27 deletions(-) diff --git a/drivers/gpu/drm/asahi/m3/m3_batch_policy.rs b/drivers/gpu/drm/asahi/m3/m3_batch_policy.rs index 2558ea6ae6ab2..0749916ab8f69 100644 --- a/drivers/gpu/drm/asahi/m3/m3_batch_policy.rs +++ b/drivers/gpu/drm/asahi/m3/m3_batch_policy.rs @@ -108,6 +108,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 } diff --git a/drivers/gpu/drm/asahi/m3/m3_params.rs b/drivers/gpu/drm/asahi/m3/m3_params.rs index 628e927bc42a1..eb0a3156b088b 100644 --- a/drivers/gpu/drm/asahi/m3/m3_params.rs +++ b/drivers/gpu/drm/asahi/m3/m3_params.rs @@ -492,11 +492,11 @@ pub(crate) fn pipeline_depth(soc: &crate::m3::m3_soc::Soc) -> usize { /// `asahi.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 on -/// experimental T8122, disabled on Pro, where compute packets then never join). 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; u64::MAX restores the SoC default. +/// 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)); diff --git a/drivers/gpu/drm/asahi/m3/m3_runtime.rs b/drivers/gpu/drm/asahi/m3/m3_runtime.rs index 81cdd4dbdac8b..3de08e7f85199 100644 --- a/drivers/gpu/drm/asahi/m3/m3_runtime.rs +++ b/drivers/gpu/drm/asahi/m3/m3_runtime.rs @@ -370,28 +370,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 if !self.solo_next && entries.iter().any(|(p,_)|!Arc::ptr_eq(p,&entries[0].0)) { - // Nothing reached the firmware, but later packets joined: they joined from - // their first command and were never published before, so they are - // unpublished again. Retry the front packet alone before failing it. - for (p,_) in entries.iter().filter(|(p,_)|!Arc::ptr_eq(p,&entries[0].0)) {p.clear_published();} - self.solo_next=true; - progress=true; } 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; + } } } } @@ -421,9 +428,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{..}))); @@ -515,6 +524,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); diff --git a/drivers/gpu/drm/asahi/m3/m3_submit.rs b/drivers/gpu/drm/asahi/m3/m3_submit.rs index 4c9dffdd7891a..f8967532331a6 100644 --- a/drivers/gpu/drm/asahi/m3/m3_submit.rs +++ b/drivers/gpu/drm/asahi/m3/m3_submit.rs @@ -83,10 +83,11 @@ impl Packet { } /// Called only after all published commands retired or before any publication. pub(crate) fn release_guard(&self) {drop(self.vm_job.lock().take());} - /// Called before the first firmware-visible change of a batch that includes this packet. + /// Called before the first firmware-visible change of a batch that includes this packet: once + /// the batch's commands are encoded, or before encoding behind a batch that is still running. pub(crate) fn mark_published(&self) {self.published.store(true,Ordering::Relaxed);} - /// Undo `mark_published` for a packet that joined a batch from its first command when that - /// batch failed before any firmware-visible change. + /// Undo `mark_published` for a packet whose first command was in a batch that failed before + /// any firmware-visible change. pub(crate) fn clear_published(&self) {self.published.store(false,Ordering::Relaxed);} /// Whether the firmware may have seen any of this packet's commands. pub(crate) fn may_be_published(&self)->bool {self.published.load(Ordering::Relaxed)} From 79d1535a7a5452c531506050f3ec6cba8cb51b97 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:52:33 +1100 Subject: [PATCH 4/4] tools/asahi: test the M3 compute batch selection and its budget m3-batch-select-tests.py runs the production next_batch() and batch policy on queues of host packets: a VM without a measured compute cost gets one command per batch, a measured cost caps the count at the GPU-time budget, without a budget every batch is one command, and only packets of the batch's VM and urgency join, from their first command. It also covers the override, the solo retry and a stale cost: the batch that a too low estimate admits stays within its deadline, and its retirement corrects the estimate. A mutation that drops the admission check must fail. m3-batching-tests.rs gains the same budget cases on the policy alone, and the rule that a batch which fails before publication leaves its new packets unpublished. Signed-off-by: Ryan Murray --- tools/asahi/m3-batch-select-tests.py | 220 +++++++++++++++++++++++++++ tools/asahi/m3-batching-tests.rs | 73 +++++++++ tools/asahi/run-host-tests.py | 2 + 3 files changed, 295 insertions(+) create mode 100644 tools/asahi/m3-batch-select-tests.py diff --git a/tools/asahi/m3-batch-select-tests.py b/tools/asahi/m3-batch-select-tests.py new file mode 100644 index 0000000000000..18d5cdc1bc5d5 --- /dev/null +++ b/tools/asahi/m3-batch-select-tests.py @@ -0,0 +1,220 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Run the production M3 batch selection (`next_batch`) on queues of host packets. + +The extracted Runtime method and the production batch policy choose the commands of one firmware +batch. The packets, parameters and measured costs are host models: this covers which commands +share a batch, not their encoding or retirement. +""" +import argparse +from pathlib import Path +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +M3 = ROOT / 'drivers/gpu/drm/asahi/m3' + + +def method(text, marker): + start = text.index(marker) + end = text.index('{', start) + 1 + depth = 1 + while depth: + depth += (text[end] == '{') - (text[end] == '}') + end += 1 + return text[start:end] + + +PREFIX = r''' +#![allow(dead_code)] +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +type Result = std::result::Result; +#[path = "POLICY"] +mod policy; +struct Flags; +const GFP_KERNEL: Flags = Flags; +struct KVec(Vec); +impl KVec { + fn new() -> Self { Self(Vec::new()) } + fn push(&mut self, value: T, _flags: Flags) -> Result { self.0.push(value); Ok(()) } +} +impl std::ops::Deref for KVec { + type Target = [T]; + fn deref(&self) -> &[T] { &self.0 } +} +static COMPUTE_BATCH: AtomicUsize = AtomicUsize::new(16); +static RENDER_BATCH: AtomicUsize = AtomicUsize::new(1); +static OVERRIDDEN: AtomicBool = AtomicBool::new(false); +mod m3 { + pub mod m3_compute_storage { pub const SLOTS: usize = 16; } + pub mod m3_submit { + #[derive(Clone, Copy)] + pub enum Command { Render { command: u32, usc: u32 }, Compute(u32) } + pub struct Vm(pub u64); + impl Vm { + pub fn id(&self) -> u64 { self.0 } + pub fn same(&self, other: &Vm) -> bool { self.0 == other.0 } + } + pub struct Packet { pub vm: Vm, pub urgency: u8, pub commands: Vec } + } + pub mod m3_params { + use std::sync::atomic::Ordering; + pub fn mixed_batch() -> bool { false } + pub fn render_batch_size() -> usize { crate::RENDER_BATCH.load(Ordering::Relaxed) } + pub fn compute_batch_size() -> usize { crate::COMPUTE_BATCH.load(Ordering::Relaxed) } + pub fn compute_batch_overridden() -> bool { crate::OVERRIDDEN.load(Ordering::Relaxed) } + pub fn render_batch_budget_ns(soc: &crate::Soc) -> Option { soc.budget } + } +} +use m3::m3_submit::{Command, Packet, Vm}; +struct Soc { chip_id: u32, budget: Option } +struct Device(Soc); +impl Device { fn soc(&self) -> &Soc { &self.0 } } +struct Job(bool); +impl Job { fn started(&self) -> bool { self.0 } } +enum NativeJob { Render(Job), Compute(Job) } +struct Batch { entries: Vec<(Arc, usize)> } +struct Inner { + pending: Vec<(Arc, usize)>, active: Vec, jobs: Vec, device: Device, + render_initialized: bool, solo_next: bool, + pass_cost: policy::PassCosts, compute_cost: policy::PassCosts, +} +impl Inner { +''' +TESTS = r''' +} +const BUDGET: Option = Some(policy::default_budget_us(true) * 1000); +const SLOTS: usize = m3::m3_compute_storage::SLOTS; +fn compute(vm: u64, urgency: u8, commands: usize) -> (Arc, usize) { + (Arc::new(Packet { vm: Vm(vm), urgency, commands: vec![Command::Compute(0); commands] }), 0) +} +fn runtime(pending: Vec<(Arc, usize)>, budget: Option) -> Inner { + Inner { pending, active: Vec::new(), jobs: vec![NativeJob::Render(Job(true))], + device: Device(Soc { chip_id: 0x8122, budget }), render_initialized: true, solo_next: false, + pass_cost: policy::PassCosts::default(), compute_cost: policy::PassCosts::default() } +} +/// The batch as (pending position, command index) pairs. +fn batch(inner: &Inner) -> Vec<(usize, usize)> { + inner.next_batch(SLOTS).unwrap().iter().map(|(packet, index)| { + (inner.pending.iter().position(|(p, _)| Arc::ptr_eq(p, packet)).unwrap(), *index) + }).collect() +} +fn count(inner: &Inner) -> usize { batch(inner).len() } +fn queued(packets: usize, commands: usize) -> Vec<(Arc, usize)> { + (0..packets).map(|_| compute(1, 0, commands)).collect() +} +fn main() { + // No measured compute cost for the VM: one command per batch, whether the commands come from + // queued packets or from one packet. + assert_eq!(count(&runtime(queued(8, 1), BUDGET)), 1); + assert_eq!(count(&runtime(queued(1, SLOTS), BUDGET)), 1); + // A measurement of another VM, or of the VM's render passes, doesn't count. + let mut inner = runtime(queued(8, 1), BUDGET); + inner.compute_cost.record(2, 182); + inner.pass_cost.record(1, 182); + assert_eq!(count(&inner), 1); + // A light dispatch (182 ns): every queued packet joins, up to the storage's slots. + inner.compute_cost.record(1, 182); + assert_eq!(batch(&inner), (0..8).map(|p| (p, 0)).collect::>()); + let mut inner = runtime(queued(3, SLOTS), BUDGET); + inner.compute_cost.record(1, 182); + assert_eq!(batch(&inner), (0..SLOTS).map(|i| (0, i)).collect::>()); + // The measured cost caps the count: cost times commands stays within the 4 ms budget. + for (ns, commands) in [(250_000, 16), (500_000, 8), (1_000_000, 4), (1_500_000, 2), + (2_000_000, 2), (2_000_001, 1), (4_000_000, 1), (200_000_000, 1)] { + for pending in [queued(SLOTS, 1), queued(1, SLOTS), queued(6, 3)] { + let mut inner = runtime(pending, BUDGET); + inner.compute_cost.record(1, ns); + assert_eq!(count(&inner), commands, "{} ns", ns); + } + } + // A batch cut inside a joined packet leaves that packet's remaining commands for later. + let mut inner = runtime(queued(6, 3), BUDGET); + inner.compute_cost.record(1, 1_000_000); + assert_eq!(batch(&inner), [(0, 0), (0, 1), (0, 2), (1, 0)]); + // Without a budget every compute batch is one command, measured or not. + let mut inner = runtime(queued(8, 1), None); + inner.compute_cost.record(1, 182); + assert_eq!(count(&inner), 1); + // The batch size parameter still bounds a budgeted batch. + COMPUTE_BATCH.store(3, Ordering::Relaxed); + let mut inner = runtime(queued(8, 1), BUDGET); + inner.compute_cost.record(1, 182); + assert_eq!(count(&inner), 3); + COMPUTE_BATCH.store(SLOTS, Ordering::Relaxed); + // Only packets of the batch's VM and urgency join, in queue order, from their first command. + for (other, joins) in [(compute(1, 0, 1), true), (compute(2, 0, 1), false), + (compute(1, 1, 1), false), ((compute(1, 0, 2).0, 1), false)] { + let mut inner = runtime(vec![compute(1, 0, 1), other, compute(1, 0, 1)], BUDGET); + inner.compute_cost.record(1, 182); + assert_eq!(count(&inner), if joins { 3 } else { 1 }); + } + // A packet that goes on with a render pass ends the batch after its compute commands. + let mixed = Arc::new(Packet { vm: Vm(1), urgency: 0, + commands: vec![Command::Compute(0), Command::Render { command: 0, usc: 0 }] }); + let mut inner = runtime(vec![compute(1, 0, 1), (mixed, 0), compute(1, 0, 1)], BUDGET); + inner.compute_cost.record(1, 182); + assert_eq!(batch(&inner), [(0, 0), (1, 0)]); + // After a batch with joined packets failed before publication the front packet goes alone. + let mut inner = runtime(queued(4, 2), BUDGET); + inner.compute_cost.record(1, 182); + assert_eq!(count(&inner), 8); + inner.solo_next = true; + assert_eq!(batch(&inner), [(0, 0), (0, 1)]); + // An explicit override bounds the front packet's own commands without the budget; joined + // packets still need it. + OVERRIDDEN.store(true, Ordering::Relaxed); + let mut inner = runtime(queued(2, 4), BUDGET); + assert_eq!(count(&inner), 4); + inner.compute_cost.record(1, 1_000_000); + assert_eq!(count(&inner), 4); + let mut inner = runtime(queued(2, 4), BUDGET); + inner.compute_cost.record(1, 182); + assert_eq!(count(&inner), 8); + assert_eq!(count(&runtime(queued(2, 4), None)), 4); + OVERRIDDEN.store(false, Ordering::Relaxed); + // A stale cost: a VM measured at 100 us per command queues 200 ms dispatches. The estimate + // still admits a full batch. Its deadline is the sum of the deadlines the commands had + // alone, so the batch (3.2 s) is in time; its retirement then corrects the estimate. + let mut inner = runtime(queued(1, SLOTS), BUDGET); + inner.compute_cost.record(1, 100_000); + let commands = count(&inner); + assert_eq!(commands, SLOTS); + let alone = policy::batch_deadline_secs(1); + assert_eq!(policy::batch_deadline_secs(commands), alone * commands as i64); + assert!(commands as i64 * 200 < policy::batch_deadline_secs(commands) * 1000); + inner.compute_cost.record(1, 200_000_000); + assert_eq!(count(&inner), 1); + println!("PASS: production compute batch selection under the GPU-time budget"); +} +''' + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--out', type=Path) + parser.add_argument('--mutation', choices=['unbudgeted']) + args = parser.parse_args() + runtime = (M3 / 'm3_runtime.rs').read_text() + body = method(runtime, 'fn next_batch(') + if args.mutation: + gate = body[body.index('if !policy::admits('):] + gate = gate[:gate.index('}') + 1] + assert 'return Ok(entries);' in gate + body = body.replace(gate, '') + out = args.out or Path(tempfile.mkdtemp(prefix='m3-batch-select-')) + out.mkdir(parents=True, exist_ok=True) + source = out / 'select.rs' + source.write_text(PREFIX.replace('POLICY', str(M3 / 'm3_batch_policy.rs')) + body + TESTS) + binary = out / 'select' + subprocess.run(['rustc', '--edition=2021', str(source), '-o', str(binary)], check=True) + result = subprocess.run([str(binary)]) + if result.returncode: + # Preserve the Rust assertion's exit and diagnostic. A Python traceback + # means a broken harness to run-host-tests, not a killed mutation. + raise SystemExit(result.returncode) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/m3-batching-tests.rs b/tools/asahi/m3-batching-tests.rs index 591389c5c9ea1..af5ed97c2f6ce 100644 --- a/tools/asahi/m3-batching-tests.rs +++ b/tools/asahi/m3-batching-tests.rs @@ -69,6 +69,79 @@ fn batched_commands_keep_their_deadline() { assert_eq!(batch_deadline_secs(16),32); } +/// Commands a compute batch admits for a cost and budget, with no override (`next_batch()` asks +/// `admits` once per command; m3-batch-select-tests.py runs that selection itself). +fn compute_commands(joined:bool,cost:Option,budget:Option) -> usize { + (0..SLOTS).take_while(|n|admits(false,joined,false,cost,budget,*n)).count() +} + +#[test] +fn the_measured_compute_cost_sizes_the_batch() { + let budget=Some(default_budget_us(true)*1000); + for joined in [false,true] { + let mut costs=PassCosts::default(); + // No measurement for the VM yet: one command. + assert_eq!(compute_commands(joined,costs.get(1),budget),1); + // A light dispatch (182 ns): only the slots bound the batch. + costs.record(1,182); + assert_eq!(compute_commands(joined,costs.get(1),budget),SLOTS); + // Another VM's measurement doesn't count. + assert_eq!(compute_commands(joined,costs.get(2),budget),1); + // The measured cost caps the count: cost * commands stays within the 4 ms budget. + for (ns,commands) in [(250_000,16),(500_000,8),(1_000_000,4),(1_500_000,2),(2_000_000,2), + (2_000_001,1),(4_000_000,1),(200_000_000,1)] { + let mut costs=PassCosts::default(); + costs.record(1,ns); + assert_eq!(compute_commands(joined,costs.get(1),budget),commands,"{ns} ns"); + } + // Without a budget every batch is one command, measured or not. + assert_eq!(compute_commands(joined,Some(182),None),1); + assert_eq!(compute_commands(joined,None,None),1); + } +} + +#[test] +fn a_stale_compute_cost_cannot_time_out_a_batch_of_valid_commands() { + let budget=Some(default_budget_us(true)*1000); + // A VM measured at 100 us per command then queues 200 ms dispatches: the stale cost still + // admits a full batch. + let mut costs=PassCosts::default(); + costs.record(1,100_000); + let commands=compute_commands(true,costs.get(1),budget); + assert_eq!(commands,SLOTS); + // Its deadline is the sum of the deadlines the commands had alone, so the batch (3.2 s) + // is in time, and so is any batch whose commands each fit their own deadline. + let alone=batch_deadline_secs(1); + for n in 1..=SLOTS {assert_eq!(batch_deadline_secs(n),alone*n as i64);} + assert!(commands as i64*200