diff --git a/drivers/gpu/drm/asahi/m3/m3_batch_policy.rs b/drivers/gpu/drm/asahi/m3/m3_batch_policy.rs index 27295660640ae..0749916ab8f69 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}} @@ -68,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 { @@ -89,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 85033c88e4192..eb0a3156b088b 100644 --- a/drivers/gpu/drm/asahi/m3/m3_params.rs +++ b/drivers/gpu/drm/asahi/m3/m3_params.rs @@ -208,8 +208,10 @@ 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. 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. static M3_EARLY_TILING: AtomicU64 = AtomicU64::new(0); @@ -263,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); @@ -483,12 +490,13 @@ 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 -/// 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. +/// `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 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 8bd242a483432..3de08e7f85199 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). @@ -72,6 +75,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, @@ -221,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)); @@ -231,8 +237,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 +262,18 @@ 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 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 index0,explicit,per_pass,budget,in_flight+entries.len()) {return Ok(entries);} entries.push((candidate.clone(),index),GFP_KERNEL)?; index+=1; } @@ -338,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() { @@ -362,21 +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 { - // 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; + } } } } @@ -406,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{..}))); @@ -500,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); @@ -732,7 +758,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); @@ -808,7 +834,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()); @@ -906,6 +932,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(); @@ -1120,7 +1148,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(),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..f8967532331a6 100644 --- a/drivers/gpu/drm/asahi/m3/m3_submit.rs +++ b/drivers/gpu/drm/asahi/m3/m3_submit.rs @@ -83,8 +83,12 @@ 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 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)} pub(crate) fn retired(&self) {self.release_guard();self.finish(Ok(()));} 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 d9a0a35c04dd0..af5ed97c2f6ce 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)); @@ -33,6 +32,116 @@ 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); +} + +/// 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