diff --git a/drivers/gpu/drm/asahi/g16/command.rs b/drivers/gpu/drm/asahi/g16/command.rs index c45d53bc86eab..b21c9eb1f9b53 100644 --- a/drivers/gpu/drm/asahi/g16/command.rs +++ b/drivers/gpu/drm/asahi/g16/command.rs @@ -181,6 +181,15 @@ pub(crate) struct RenderCommand { /// Explicit hardware attachments in effect for each render engine. pub(crate) vertex_attachments: KVec, pub(crate) fragment_attachments: KVec, + /// Whether this pass exceeds the light-TA wave threshold (multi-layer or large tilemap). + pub(crate) heavy_ta: bool, +} + +impl RenderCommand { + /// Whether this render pass requires the conservative `TA_WAVE_PASSES` wave window. + pub(crate) fn is_heavy_ta(&self) -> bool { + self.heavy_ta + } } /// A validated compute command. @@ -1517,6 +1526,9 @@ pub(crate) fn parse_stream(bytes: &[u8], early_tiling: bool) -> Result 1 + || super::encode::Geometry::new(&packet, 0).tilemap_bytes + > hw::sizes::TA_LIGHT_TILEMAP_BYTES; commands.push(Command::Render(KBox::new( RenderCommand { cmd: packet, @@ -1525,6 +1537,7 @@ pub(crate) fn parse_stream(bytes: &[u8], early_tiling: bool) -> Result; 4], @@ -651,6 +657,7 @@ impl Engine { slot_wait: false, ta_wave_wait: false, short_repoll: false, + coalesce_deadline_ns: 0, progress_flight: [0; 3], progress: [None; 4], stats: KBox::zeroed(GFP_KERNEL)?, @@ -999,6 +1006,7 @@ impl Firmware { self.engine.chan_wait = false; self.engine.slot_wait = false; self.engine.ta_wave_wait = false; + self.engine.coalesce_deadline_ns = 0; while self.recovery.failed().is_none() && !self.engine.frozen && !self.engine.pending.is_empty() @@ -1015,15 +1023,36 @@ impl Firmware { // while preserving per-queue FIFO, unless the head job itself requires // `flights` to drain to empty first (unprimed cold InitBM render, failed // VM, or recovery/InitBM in flight). - if !self.engine.flights.is_empty() && !self.can_queue_behind(&job) { + let mut ta_pending: Option = None; + if !self.engine.flights.is_empty() + && !self.can_queue_behind_with_ta(&job, &mut ta_pending) + { if self.needs_engine_drain(&job) { self.engine.stats.hold[0] += 1; break; } - let ta_wave_paused = self.ta_pending_passes() >= super::hw::sizes::TA_WAVE_PASSES; + let ta_val = *ta_pending.get_or_insert_with(|| self.ta_pending_passes()); + let ta_wave_paused = ta_val >= self.active_ta_wave_cap(); let mut alt: Option = None; for (i, cand) in self.engine.pending.iter().enumerate() { - if i == index || !self.can_queue_behind(cand) { + if i == index { + continue; + } + // Fast O(1) skip for blocked head-queue followers: `Engine::pick` chose the + // earliest pending job of `job.queue`, so later jobs of the same queue are + // FIFO-blocked unless an independent non-query compute may bypass TA-wave + // paused renders. + if i > index + && Arc::ptr_eq(&cand.queue, &job.queue) + && !(ta_wave_paused + && matches!( + command(cand, cand.progress.sent()), + Some(Command::Compute(c)) if !c.query_access + )) + { + continue; + } + if !self.can_queue_behind_with_ta(cand, &mut ta_pending) { continue; } // Preserve per-queue FIFO: never jump a later job of a queue ahead @@ -1042,7 +1071,8 @@ impl Firmware { ) && matches!( command(earlier, earlier.progress.sent()), - Some(Command::Render(_)) + Some(Command::Render(r)) + if ta_val >= self.ta_wave_cap_for(r.is_heavy_ta()) ) && !self.needs_engine_drain(earlier) && earlier @@ -1075,17 +1105,16 @@ impl Firmware { .pending .iter() .any(|cand| self.blocked_on_slot_headroom(cand)); - self.engine.ta_wave_wait = self.ta_pending_passes() - >= super::hw::sizes::TA_WAVE_PASSES - && self.engine.pending.iter().any(|cand| { - matches!( - command(cand, cand.progress.sent()), - Some(Command::Render(_)) - ) && !self.needs_engine_drain(cand) - && cand - .check_command_dependencies(cand.progress.sent()) - .is_ok() - }); + self.engine.ta_wave_wait = self.engine.pending.iter().any(|cand| { + matches!( + command(cand, cand.progress.sent()), + Some(Command::Render(r)) + if ta_val >= self.ta_wave_cap_for(r.is_heavy_ta()) + ) && !self.needs_engine_drain(cand) + && cand + .check_command_dependencies(cand.progress.sent()) + .is_ok() + }); self.engine.stats.hold[0] += 1; break; } @@ -1185,12 +1214,12 @@ impl Firmware { if job.progress.sent() == job.progress.count() { self.engine.unpend(&job); // fully published } - // Ring TA/FS immediately once a render wave fills TA_WAVE_PASSES so the GPU - // starts tiling right away instead of waiting behind another loop iteration - // or an alt-class compute publication. + // Ring TA/FS immediately once a render wave fills the active TA wave window so + // the GPU starts tiling right away instead of waiting behind another loop + // iteration or an alt-class compute publication. if pending_rings & ((1u8 << (Channel::Fs as u8)) | (1u8 << (Channel::Ta as u8))) != 0 - && self.ta_pending_passes() >= super::hw::sizes::TA_WAVE_PASSES + && self.ta_pending_passes() >= self.active_ta_wave_cap() { if let Err(e) = self.flush_doorbells(&mut pending_rings) { dev_err!( @@ -1408,6 +1437,45 @@ impl Firmware { pending } + /// Adaptive TA wave window for a candidate render pass: conservative `TA_WAVE_PASSES` (4) + /// when either the candidate or any active render flight is heavy (multi-layer or tilemap + /// above `TA_LIGHT_TILEMAP_BYTES`), and `TA_WAVE_PASSES_LIGHT` (8) for light single-layer + /// render bursts. + fn ta_wave_cap_for(&self, cand_heavy: bool) -> usize { + if cand_heavy + || self + .engine + .flights + .iter() + .any(|fl| fl.renders != 0 && fl.heavy_render) + { + super::hw::sizes::TA_WAVE_PASSES + } else { + super::hw::sizes::TA_WAVE_PASSES_LIGHT + } + } + + /// Active TA wave window across in-flight renders and pending render heads, used for + /// immediate wave doorbell flushes and `ta_wave_ready()` hysteresis. + pub(crate) fn active_ta_wave_cap(&self) -> usize { + if self + .engine + .flights + .iter() + .any(|fl| fl.renders != 0 && fl.heavy_render) + || self.engine.pending.iter().any(|cand| { + matches!( + command(cand, cand.progress.sent()), + Some(Command::Render(r)) if r.is_heavy_ta() + ) + }) + { + super::hw::sizes::TA_WAVE_PASSES + } else { + super::hw::sizes::TA_WAVE_PASSES_LIGHT + } + } + /// Whether `job`'s next command may be published behind the flights in flight: /// /// - Compute queues behind healthy non-InitBM compute flights of any VM or same-VM @@ -1428,6 +1496,14 @@ impl Firmware { /// firmware DM1 timeout. Cold InitBM priming renders and every failure or recovery path /// still drain the engine first. fn can_queue_behind(&self, job: &Arc) -> bool { + let mut ta_pending = None; + self.can_queue_behind_with_ta(job, &mut ta_pending) + } + + /// [`Self::can_queue_behind`] with an optional caller-hoisted cache of + /// [`Self::ta_pending_passes`] so scanning many pending jobs performs at most one WC stamp + /// read per pass. + fn can_queue_behind_with_ta(&self, job: &Arc, ta_pending: &mut Option) -> bool { let e = &self.engine; let sent = job.progress.sent(); if job.vm.status.get() != 0 @@ -1506,15 +1582,16 @@ impl Firmware { .compute_slot_mask() .is_ok_and(|mask| self.slots.compute_available_in_mask(mask)) } - Some(Command::Render(_)) => { + Some(Command::Render(r)) => { let cross_vm_compute = e .flights .iter() .any(|f| f.computes != 0 && !Arc::ptr_eq(&f.job.vm, &job.vm)); let render_count: usize = e.flights.iter().map(|f| f.renders as usize).sum(); + let ta_cap = self.ta_wave_cap_for(r.is_heavy_ta()); !cross_vm_compute && render_count < params::render_flights() - && self.ta_pending_passes() < super::hw::sizes::TA_WAVE_PASSES + && *ta_pending.get_or_insert_with(|| self.ta_pending_passes()) < ta_cap && !self.slots.render_exhausted() && !self.pools.exhausted() && super::recovery::logic::next_ordinal(e.draw).is_some() @@ -1540,6 +1617,209 @@ impl Firmware { } } + /// Whether `self.engine.pending` is an eligible single-queue, single-VM busy horizon + /// batch that can accumulate more same-queue commands before publishing. + fn can_defer_busy_coalesce(&self, now: u64) -> bool { + if self.recovery.failed().is_some() + || self.engine.frozen + || self.engine.flights.is_empty() + || self.engine.pending.is_empty() + || self.engine.flights.len() >= super::hw::sizes::FLIGHTS + || self.engine.chan_wait + || self.engine.slot_wait + || self.engine.ta_wave_wait + || self + .engine + .flights + .iter() + .any(|f| f.doomed || f.recovery_suspect || f.initbm) + { + return false; + } + let head = &self.engine.pending[0]; + let head_sent = head.progress.sent(); + if head.vm.status.get() != 0 + || head.long() + || !self.can_queue_behind(head) + || self + .engine + .flights + .iter() + .any(|fl| !Arc::ptr_eq(&fl.job.queue, &head.queue)) + || self + .engine + .pending + .iter() + .any(|j| !Arc::ptr_eq(&j.queue, &head.queue) || !Arc::ptr_eq(&j.vm, &head.vm)) + { + return false; + } + let Some(head_order) = head.command_order(head_sent) else { + return false; + }; + match command(head, head_sent) { + Some(Command::Compute(c)) => { + if head.resources.compute_scs() + || c.is_rt() + || head_order.wait_through != [None, None] + || !head.fw_waits.is_empty() + || self.compute_queue_is_heavy(&head.queue, now) + { + return false; + } + let queue_active: usize = self + .engine + .flights + .iter() + .filter(|fl| fl.computes != 0 && Arc::ptr_eq(&fl.job.queue, &head.queue)) + .map(|fl| fl.computes as usize) + .sum(); + if queue_active < 2 { + return false; + } + let Some(mut next_seq) = head_order.sequence.checked_add(1) else { + return false; + }; + let mut pending_cmds = 1usize; + for k in (head_sent + 1)..head.progress.count() { + let Some(Command::Compute(c2)) = command(head, k) else { + return false; + }; + if c2.is_rt() || !head.can_fold_horizon_cmd(k, next_seq) { + return false; + } + let Some(s) = next_seq.checked_add(1) else { + return false; + }; + next_seq = s; + pending_cmds += 1; + } + for j in &self.engine.pending[1..] { + let n = j.progress.count(); + if j.long() + || j.resources.compute_scs() + || !j.can_fold_horizon_job(next_seq) + || (0..n).any(|k| { + matches!(command(j, k), Some(Command::Compute(c2)) if c2.is_rt()) + }) + { + return false; + } + let Some(s) = next_seq.checked_add(u64::from(n)) else { + return false; + }; + next_seq = s; + pending_cmds += n as usize; + } + let active_computes: usize = self + .engine + .flights + .iter() + .map(|fl| fl.computes as usize) + .sum(); + let Ok(slot_mask) = head.resources.compute_slot_mask() else { + return false; + }; + let pipe = + self.choose_compute_pipe(&head.queue, [None, None], slot_mask, false, false); + let free_c = self.slots.free_compute_in_mask_for_pipe(slot_mask, pipe) as usize; + let cap = super::hw::sizes::COALESCE_MAX_CMDS + .min(free_c) + .min(params::compute_flights().saturating_sub(active_computes)) + .min(super::hw::sizes::COMPUTE_SLOTS); + cap > 1 && pending_cmds < cap + } + Some(Command::Render(r)) => { + if head.resources.render_scs() || !head.fw_waits.is_empty() { + return false; + } + let queue_active: usize = self + .engine + .flights + .iter() + .filter(|fl| fl.renders != 0 && Arc::ptr_eq(&fl.job.queue, &head.queue)) + .map(|fl| fl.renders as usize) + .sum(); + if queue_active < 2 { + return false; + } + let Some(mut next_seq) = head_order.sequence.checked_add(1) else { + return false; + }; + let mut wave_heavy = r.is_heavy_ta(); + let mut pending_cmds = 1usize; + for k in (head_sent + 1)..head.progress.count() { + if !head.can_fold_render_cmd(k, next_seq) { + return false; + } + if matches!(command(head, k), Some(Command::Render(r2)) if r2.is_heavy_ta()) { + wave_heavy = true; + } + let Some(s) = next_seq.checked_add(1) else { + return false; + }; + next_seq = s; + pending_cmds += 1; + } + for j in &self.engine.pending[1..] { + let n = j.progress.count(); + if j.long() + || j.resources.render_scs() + || !j.can_fold_render_horizon_job(next_seq) + { + return false; + } + if (0..n).any(|k| { + matches!(command(j, k), Some(Command::Render(r2)) if r2.is_heavy_ta()) + }) { + wave_heavy = true; + } + let Some(s) = next_seq.checked_add(u64::from(n)) else { + return false; + }; + next_seq = s; + pending_cmds += n as usize; + } + let active_renders: usize = self + .engine + .flights + .iter() + .map(|fl| fl.renders as usize) + .sum(); + let wave_cap = self.ta_wave_cap_for(wave_heavy); + let ta_room = wave_cap.saturating_sub(self.ta_pending_passes()); + let cap = super::hw::sizes::COALESCE_MAX_CMDS + .min(params::render_flights().saturating_sub(active_renders)) + .min(ta_room) + .min(super::hw::sizes::RENDER_SLOTS); + cap > 1 && pending_cmds < cap + } + None => false, + } + } + + /// Defers immediate publication for up to `COALESCE_WINDOW_US` while a single queue already + /// has `>= 2` active commands in flight so consecutive same-queue `SUBMIT` ioctls accumulate + /// into one multi-command flight (up to `COALESCE_MAX_CMDS`), cutting `SubmitRecord`s, WC + /// producer updates, and doorbells without delaying `d=1`/`d=2`, barriered streams, RT/SCS + /// work, or multi-queue/cross-VM handoffs. + pub(crate) fn defer_busy_coalesce(&mut self, now: u64) -> Option { + if !self.can_defer_busy_coalesce(now) { + self.engine.coalesce_deadline_ns = 0; + return None; + } + if self.engine.coalesce_deadline_ns == 0 { + self.engine.coalesce_deadline_ns = + now.saturating_add(super::hw::sizes::COALESCE_WINDOW_NS); + } + if now >= self.engine.coalesce_deadline_ns { + self.engine.coalesce_deadline_ns = 0; + return None; + } + let rem_ns = self.engine.coalesce_deadline_ns.saturating_sub(now); + Some((rem_ns.div_ceil(1000) as u32).clamp(1, super::hw::sizes::COALESCE_WINDOW_US)) + } + /// Resolves the newest in-flight target stamp and producer `InitBM` state for `class` /// (`RENDER` -> `r_fs_stamp`, `COMPUTE` -> `cstamp`) across `job`'s same-queue `target_seq` /// and any cross-queue `job.fw_waits` (plus an earlier member of an in-progress render batch @@ -1808,19 +2088,54 @@ impl Firmware { Ok(waits) } + /// Whether `queue`'s recent or active compute work is heavy enough to benefit from 2-pipe + /// CDM fanout rather than 1-pipe affinity and horizon folding: + /// - per-queue retired CDM GPU duration EWMA `>= COMPUTE_HEAVY_EMA_US`, or + /// - a sole active single-command compute flight of `queue` on its pipe has already been + /// executing for `>= COMPUTE_HEAVY_INFLIGHT_NS` without completing (instant detection + /// before retirement updates the EWMA, while queued multi-flight light bursts never false- + /// trigger from queueing age). + fn compute_queue_is_heavy(&self, queue: &Arc, now: u64) -> bool { + if queue.compute_ewma_us.load(Ordering::Relaxed) >= super::hw::sizes::COMPUTE_HEAVY_EMA_US { + return true; + } + let mut pipe_flights = [0usize; super::hw::sizes::COMPUTE_PIPES]; + for fl in &self.engine.flights { + if fl.computes != 0 { + let p = (fl.compute_pipe as usize).min(super::hw::sizes::COMPUTE_PIPES - 1); + pipe_flights[p] += 1; + } + } + self.engine.flights.iter().any(|fl| { + let p = (fl.compute_pipe as usize).min(super::hw::sizes::COMPUTE_PIPES - 1); + fl.computes == 1 + && pipe_flights[p] == 1 + && Arc::ptr_eq(&fl.job.queue, queue) + && fl.published_ns != 0 + && now.saturating_sub(fl.published_ns) + >= super::hw::sizes::COMPUTE_HEAVY_INFLIGHT_NS + }) + } + /// Chooses which compute pipe (`0..COMPUTE_PIPES`) executes the next compute command: /// - Base-only/SCS VMs (bits strictly in `0..PIPE1_COMPUTE_START`) or states where pipe 1 /// has no available unit in `slot_mask` stay on pipe 0 so `0..PIPE1_COMPUTE_START` never /// split across two pipes. /// - If the command waits only on one pipe, reuse that pipe (in-order ring, zero `c2c` /// barrier). - /// - If barrier-free (`[None, None]`) or waiting on both pipes (`[Some, Some]`), pick the - /// pipe with fewer active compute commands, breaking ties by `next_compute_pipe`. + /// - If barrier-free (`[None, None]`), `!heavy_compute`, and `queue` already has an active + /// compute flight on a single pipe with free units, keep that light queue pipe-affine so + /// consecutive horizon submits fold onto one workqueue without splitting across pipes. + /// - Otherwise (heavy compute streams, other queues, cross-VM compute, or waiting on both + /// pipes `[Some, Some]`), pick the pipe with fewer active compute commands, breaking ties + /// by `next_compute_pipe`. fn choose_compute_pipe( &self, + queue: &Arc, waits: [Option; sizes::COMPUTE_PIPES], slot_mask: u32, rt_compute: bool, + heavy_compute: bool, ) -> usize { if rt_compute || self @@ -1833,27 +2148,47 @@ impl Firmware { return 0; } match waits { - [Some(_), None] => 0, - [None, Some(_)] => 1, - _ => { - if !self.slots.compute_available_in_mask_for_pipe(slot_mask, 0) { - return 1; - } - let mut active = [0usize; sizes::COMPUTE_PIPES]; + [Some(_), None] => return 0, + [None, Some(_)] => return 1, + [None, None] if !heavy_compute => { + let mut q_pipe: Option = None; for fl in &self.engine.flights { - if fl.computes != 0 { + if fl.computes != 0 && Arc::ptr_eq(&fl.job.queue, queue) { let p = (fl.compute_pipe as usize).min(sizes::COMPUTE_PIPES - 1); - active[p] += fl.computes as usize; + match q_pipe { + None => q_pipe = Some(p), + Some(prev) if prev == p => {} + Some(_) => { + q_pipe = None; + break; + } + } } } - if active[0] < active[1] { - 0 - } else if active[1] < active[0] { - 1 - } else { - (self.engine.next_compute_pipe as usize) % sizes::COMPUTE_PIPES + if let Some(p) = q_pipe { + if self.slots.compute_available_in_mask_for_pipe(slot_mask, p) { + return p; + } } } + [None, None] | [Some(_), Some(_)] => {} + } + if !self.slots.compute_available_in_mask_for_pipe(slot_mask, 0) { + return 1; + } + let mut active = [0usize; sizes::COMPUTE_PIPES]; + for fl in &self.engine.flights { + if fl.computes != 0 { + let p = (fl.compute_pipe as usize).min(sizes::COMPUTE_PIPES - 1); + active[p] += fl.computes as usize; + } + } + if active[0] < active[1] { + 0 + } else if active[1] < active[0] { + 1 + } else { + (self.engine.next_compute_pipe as usize) % sizes::COMPUTE_PIPES } } @@ -2069,8 +2404,8 @@ impl Firmware { } else { &[Channel::Compute] }; - let (compute_pipe, c_waits) = if render { - (0usize, [None; sizes::COMPUTE_PIPES]) + let (compute_pipe, c_waits, heavy_compute) = if render { + (0usize, [None; sizes::COMPUTE_PIPES], false) } else { let slot_mask = job.resources.compute_slot_mask()?; let rt_compute = job.resources.compute_scs() @@ -2080,7 +2415,12 @@ impl Firmware { job.command_order(index) .and_then(|o| o.wait_through[super::command::COMPUTE]), )?; - (self.choose_compute_pipe(waits, slot_mask, rt_compute), waits) + let heavy = self.compute_queue_is_heavy(&job.queue, now_ns()); + ( + self.choose_compute_pipe(&job.queue, waits, slot_mask, rt_compute, heavy), + waits, + heavy, + ) }; let pipe_behind = !render && self @@ -2198,11 +2538,13 @@ impl Firmware { } } let active_computes = active_pipe[0] + active_pipe[1]; - // Keep barrier-free work balanced across both compute pipes: fold extra commands - // into this pipe only when the alternate pipe already has deeper queued work, so - // independent submits distribute across pipes 0 and 1 in the same doorbell batch. - let pipe_fold_cap = - active_pipe[1 - compute_pipe].saturating_sub(active_pipe[compute_pipe] + 1); + // Keep heavy barrier-free compute balanced across both CDM pipes while light + // single-queue compute streams stay pipe-affine and fold freely into one batch. + let pipe_fold_cap = if heavy_compute && c_waits == [None; sizes::COMPUTE_PIPES] { + active_pipe[1 - compute_pipe].saturating_sub(active_pipe[compute_pipe] + 1) + } else { + usize::MAX + }; let used = prefix.c_head.wrapping_sub(c_read) % sizes::QUEUE_CAP; let ring_more = (sizes::QUEUE_CAP.saturating_sub(4)).saturating_sub(used) as usize; let mut more_slots = free_c @@ -2370,10 +2712,18 @@ impl Firmware { .iter() .map(|fl| fl.renders as usize) .sum(); + let ta_pending_before = self.ta_pending_passes(); + let mut wave_heavy = + self.ta_wave_cap_for(r.is_heavy_ta()) == sizes::TA_WAVE_PASSES; + let wave_cap = if wave_heavy { + sizes::TA_WAVE_PASSES + } else { + sizes::TA_WAVE_PASSES_LIGHT + }; let mut more_renders = params::render_flights() .saturating_sub(active_renders + 1) .min(sizes::RENDER_SLOTS.saturating_sub(1)) - .min(sizes::TA_WAVE_PASSES.saturating_sub(self.ta_pending_passes() + 1)); + .min(wave_cap.saturating_sub(ta_pending_before + 1)); while more_renders > 0 && end < job.progress.count() { let Some(next_seq) = last_seq.and_then(|s| s.checked_add(1)) else { break; @@ -2386,6 +2736,18 @@ impl Firmware { let Some(Command::Render(r2)) = command(job, end) else { break; }; + if r2.is_heavy_ta() && !wave_heavy { + if ta_pending_before + prefix.renders as usize + 1 + > sizes::TA_WAVE_PASSES + { + break; + } + wave_heavy = true; + more_renders = more_renders.min( + sizes::TA_WAVE_PASSES + .saturating_sub(ta_pending_before + prefix.renders as usize), + ); + } let Some(o2) = job.command_order(end) else { break; }; @@ -2461,7 +2823,7 @@ impl Firmware { more_renders -= 1; } // Cross-job render horizon: fold subsequent ready render-only jobs of - // the same queue and VM into the same <= TA_WAVE_PASSES flight, sharing + // the same queue and VM into the same adaptive TA wave flight, sharing // one TA/FS producer advance, one UMA submitted update, and one doorbell. // Any non-qualifying job of this queue ends the scan so no later job // overtakes it. @@ -2514,14 +2876,18 @@ impl Firmware { { break; } - let mut picked = [0usize; sizes::TA_WAVE_PASSES]; + let mut picked = [0usize; sizes::TA_WAVE_PASSES_LIGHT]; let mut picked_mask = f.claims.pass_mask; let mut precheck_ok = true; + let mut job_heavy = false; for k in 0..n2 { let Some(Command::Render(r2)) = command(&j2, k) else { precheck_ok = false; break; }; + if r2.is_heavy_ta() { + job_heavy = true; + } let Some(o2) = j2.command_order(k) else { precheck_ok = false; break; @@ -2578,7 +2944,13 @@ impl Firmware { picked[k as usize] = slot; picked_mask |= 1u64 << slot; } - if !precheck_ok || f.group.reserve(1, GFP_NOWAIT).is_err() { + if !precheck_ok + || (job_heavy + && !wave_heavy + && ta_pending_before + prefix.renders as usize + n2_usize + > sizes::TA_WAVE_PASSES) + || f.group.reserve(1, GFP_NOWAIT).is_err() + { break; } let _ = f.group.push_within_capacity(j2.clone()); @@ -2607,6 +2979,12 @@ impl Firmware { } last_seq = Some(first_seq + u64::from(n2 - 1)); more_renders -= n2_usize; + if job_heavy && !wave_heavy { + wave_heavy = true; + let ta_in_wave = ta_pending_before + prefix.renders as usize; + more_renders = more_renders + .min(sizes::TA_WAVE_PASSES.saturating_sub(ta_in_wave)); + } } } } @@ -2856,8 +3234,8 @@ impl Firmware { fw_stamp: g.fw_stamp.va, work: s.work.va, work_gva: s.work.lower_gva.ok_or(EINVAL)?, - // Exact embedded sequence: every self-reference then matches the qualified layout. - seq: s.work.va + 0x900, + // Separate device-lifetime firmware-cached microsequence record for this unit index. + seq: s.seq.va, preempt_gva: s.preempt.gva.ok_or(EINVAL)?, its: s.its.va, stats_fw: self.init.compute_activity.va, @@ -2886,6 +3264,7 @@ impl Firmware { let rt = compute_rt(&cmd.ray, s.seeds); let scratch = self.engine.scratch.as_deref_mut().ok_or(ENOMEM)?; let w = image(&mut scratch.cw)?; + let q = image(&mut scratch.cq)?; // User results are published coherently after the complete retirement receipt. // The firmware's internal timestamp pair remains enabled. encode::encode_compute_rt( @@ -2899,9 +3278,10 @@ impl Firmware { 1, &rt, w, - image(&mut scratch.cq)?, + q, ) .map_err(|_| EINVAL)?; + s.seq.write(0, q)?; let full_work = self.slots.compute_needs_full_work(index) || before == 0; if full_work { if before != 0 { @@ -2921,14 +3301,14 @@ impl Firmware { s.work.write(0, w)?; } else { // Clean same-VM reuse: DESCRIPTOR (0xe00..0xea0) was already authenticated on - // retirement for this exact unit and VM, and static NOTIFIER (0xc00..0xd18) and - // tail (0xee0..0xf08) remain intact in place. Skip the 160-byte WC read-back and - // write only the active head and encoded body through the microsequence end. - let body_end = work::compute::SEQ_EMBEDDED + work::compute::SEQ_SIZE; + // retirement for this exact unit and VM, static NOTIFIER (0xc00..0xd18) and tail + // (0xee0..0xf08) remain intact in place, and the live microsequence lives in + // firmware-cached `s.seq`. Skip the 160-byte WC read-back and embedded sequence copy, + // writing only the active head and body before `SEQ_EMBEDDED`. s.work.write(0, &w[..work::compute::HEAD_ACTIVE_SIZE])?; s.work.write( work::compute::BODY_ACTIVE_START, - &w[work::compute::BODY_ACTIVE_START..body_end], + &w[work::compute::BODY_ACTIVE_START..work::compute::SEQ_EMBEDDED], )?; } let wait_render = self.cross_engine_wait(job, cmd_index, super::command::RENDER)?; @@ -3150,6 +3530,7 @@ impl Firmware { (refs, false) }; f.has_timestamps |= !cmd.timestamp_outputs.is_empty(); + f.heavy_render |= cmd.is_heavy_ta(); let p = resources.render_pass(k)?; let pass = p.refs(); let heap_bytes = if cmd.cmd.layers > 1 { 0x1000 } else { 0x200 }; diff --git a/drivers/gpu/drm/asahi/g16/graph.rs b/drivers/gpu/drm/asahi/g16/graph.rs index f23f4936ab3aa..f5c3e8debcab1 100644 --- a/drivers/gpu/drm/asahi/g16/graph.rs +++ b/drivers/gpu/drm/asahi/g16/graph.rs @@ -14,7 +14,7 @@ use kernel::{ use super::channel::Channel; use super::fw::graph::{self, job_list, notifier_page, qinfo, qstate, sched_ctx}; use super::hw::{pte, sizes, tuning, FwAbi}; -use super::object::{Class, FwObject, Objects, Placement, Request}; +use super::object::{Class, Factory, FwObject, Objects, Placement, Request}; use super::Firmware; use crate::driver::AsahiDrmDevice; @@ -126,23 +126,55 @@ pub(crate) struct ComputeGraph { pub(crate) fw_stamp: Arc, } -struct QueueObjects { +struct QueueSession { qinfo: Arc, qstate: Arc, - ring: Arc, user_stamp: Arc, fw_stamp: Arc, } -impl QueueObjects { +impl QueueSession { fn new(o: &mut Objects) -> Result { Ok(Self { qinfo: alloc(o, qinfo::SIZE, graph_fw(), None, 0, false)?, qstate: alloc(o, qstate::SIZE, Class::Fw, None, 0, false)?, - ring: alloc(o, sizes::QUEUE_CAP as usize * 8, cmd_fw(), None, 0, false)?, user_stamp: alloc(o, 8, Class::Shared, None, 0, false)?, fw_stamp: alloc(o, 8, Class::Shared, None, 0, false)?, }) } + /// Completes the queue with its firmware-cached work ring from a device-lifetime + /// [`Factory::persistent_objects`] allocator. The host only writes 64-bit work/barrier VAs + /// into the ring before advancing the uncached `qstate::WRITE` producer and never reads + /// back firmware writes, matching macOS 26B123's `0x443` command-ring mapping. + fn finish(self, rings: &mut Objects) -> Result { + Ok(QueueObjects { + qinfo: self.qinfo, + qstate: self.qstate, + ring: alloc( + rings, + sizes::QUEUE_CAP as usize * 8, + Class::FwCoherent, + None, + 0, + false, + )?, + user_stamp: self.user_stamp, + fw_stamp: self.fw_stamp, + }) + } +} + +struct QueueObjects { + qinfo: Arc, + qstate: Arc, + ring: Arc, + user_stamp: Arc, + fw_stamp: Arc, +} +impl QueueObjects { + #[allow(dead_code)] + fn new(o: &mut Objects, rings: &mut Objects) -> Result { + QueueSession::new(o)?.finish(rings) + } } fn init_queue( @@ -173,14 +205,30 @@ fn init_notifier(page: &FwObject, threshold: &FwObject) -> Result { Ok(()) } -impl ComputeGraph { +struct ComputeGraphSession { + sched_ctx: Arc, + notifier: Arc, + threshold: Arc, + job_list: Arc, + q: QueueSession, +} +impl ComputeGraphSession { fn new(o: &mut Objects, sched_ctx: Arc) -> Result { - let q = QueueObjects::new(o)?; Ok(Self { sched_ctx, notifier: alloc(o, 0x1000, Class::Fw, None, 0, false)?, threshold: alloc(o, 24, Class::Fw, None, 0, false)?, job_list: alloc(o, job_list::SIZE, graph_fw(), None, 0, false)?, + q: QueueSession::new(o)?, + }) + } + fn finish(self, rings: &mut Objects) -> Result { + let q = self.q.finish(rings)?; + Ok(ComputeGraph { + sched_ctx: self.sched_ctx, + notifier: self.notifier, + threshold: self.threshold, + job_list: self.job_list, qscratch: q.qinfo.clone(), qinfo: q.qinfo, qstate: q.qstate, @@ -189,6 +237,13 @@ impl ComputeGraph { fw_stamp: q.fw_stamp, }) } +} + +impl ComputeGraph { + #[allow(dead_code)] + fn new(o: &mut Objects, rings: &mut Objects, sched_ctx: Arc) -> Result { + ComputeGraphSession::new(o, sched_ctx)?.finish(rings) + } fn init(&self, abi: FwAbi, init_ctx: bool) -> Result { if init_ctx { self.sched_ctx.write(0, &graph::context_image())?; @@ -226,16 +281,21 @@ pub(crate) struct RenderGraph { pub(crate) legacy_empty: Arc, pub(crate) registration_barrier: Arc, } -impl RenderGraph { +struct RenderGraphSession { + ta: QueueSession, + fs: QueueSession, + sched_ctx: Arc, + notifier: Arc, + threshold: Arc, + job_list: [Arc; 2], + legacy_empty: Arc, + registration_barrier: Arc, +} +impl RenderGraphSession { fn new(o: &mut Objects, context: Arc) -> Result { - let [ta, fs] = [QueueObjects::new(o)?, QueueObjects::new(o)?]; Ok(Self { - qscratch: [ta.qinfo.clone(), fs.qinfo.clone()], - qinfo: [ta.qinfo, fs.qinfo], - qstate: [ta.qstate, fs.qstate], - ring: [ta.ring, fs.ring], - user_stamp: [ta.user_stamp, fs.user_stamp], - fw_stamp: [ta.fw_stamp, fs.fw_stamp], + ta: QueueSession::new(o)?, + fs: QueueSession::new(o)?, sched_ctx: context, notifier: alloc(o, 0x1000, Class::Fw, None, 0, false)?, threshold: alloc(o, 24, Class::Fw, None, 0, false)?, @@ -254,6 +314,30 @@ impl RenderGraph { )?, }) } + fn finish(self, rings: &mut Objects) -> Result { + let [ta, fs] = [self.ta.finish(rings)?, self.fs.finish(rings)?]; + Ok(RenderGraph { + qscratch: [ta.qinfo.clone(), fs.qinfo.clone()], + qinfo: [ta.qinfo, fs.qinfo], + qstate: [ta.qstate, fs.qstate], + ring: [ta.ring, fs.ring], + user_stamp: [ta.user_stamp, fs.user_stamp], + fw_stamp: [ta.fw_stamp, fs.fw_stamp], + sched_ctx: self.sched_ctx, + notifier: self.notifier, + threshold: self.threshold, + job_list: self.job_list, + legacy_empty: self.legacy_empty, + registration_barrier: self.registration_barrier, + }) + } +} + +impl RenderGraph { + #[allow(dead_code)] + fn new(o: &mut Objects, rings: &mut Objects, context: Arc) -> Result { + RenderGraphSession::new(o, context)?.finish(rings) + } fn init(&self, abi: FwAbi) -> Result { init_notifier(&self.notifier, &self.threshold)?; for e in 0..2 { @@ -272,26 +356,52 @@ impl RenderGraph { } } +/// Session-side queue graph allocations before sealing the session allocator and attaching +/// the firmware-cached work rings from a probe-time device-lifetime +/// [`Factory::persistent_objects_probe`] pool. +pub(crate) struct GraphSession { + compute: [ComputeGraphSession; sizes::COMPUTE_PIPES], + render: RenderGraphSession, +} + pub(crate) struct Graphs { pub(crate) dev: ARef, pub(crate) compute: [ComputeGraph; sizes::COMPUTE_PIPES], pub(crate) render: RenderGraph, + /// Owns the firmware-cached work rings for the device lifetime (never dropped). + _ring_objects: core::mem::ManuallyDrop, } impl Graphs { #[inline(never)] - pub(crate) fn new(dev: &AsahiDrmDevice, o: &mut Objects) -> Result { + pub(crate) fn prepare(o: &mut Objects) -> Result { // Host polls sched_ctx from WC during register_context(); keep uncached and share one // scheduling context across all compute pipes and the render graph. let sched_ctx = alloc(o, sched_ctx::SIZE, Class::Fw, None, 0, false)?; let compute = [ - ComputeGraph::new(o, sched_ctx.clone())?, - ComputeGraph::new(o, sched_ctx.clone())?, + ComputeGraphSession::new(o, sched_ctx.clone())?, + ComputeGraphSession::new(o, sched_ctx.clone())?, ]; - let render = RenderGraph::new(o, sched_ctx)?; + let render = RenderGraphSession::new(o, sched_ctx)?; + Ok(GraphSession { compute, render }) + } + + #[inline(never)] + pub(crate) fn finish( + dev: &AsahiDrmDevice, + session: GraphSession, + factory: &Factory, + ) -> Result { + // Never dropped even on partial failure: ASC-cached mappings have no qualified teardown. + let mut ring_objects = core::mem::ManuallyDrop::new(factory.persistent_objects_probe()); + let [c0, c1] = session.compute; + let compute = [c0.finish(&mut ring_objects)?, c1.finish(&mut ring_objects)?]; + let render = session.render.finish(&mut ring_objects)?; + ring_objects.finish_private()?; Ok(Self { dev: dev.as_ref().as_ref().into(), compute, render, + _ring_objects: ring_objects, }) } } diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index d556b290062e5..3d9cf3793dc03 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -782,13 +782,19 @@ pub(crate) mod sizes { /// Worst-case firmware work-ring entries per compute command (`fs2c` barrier + cross-pipe /// `c2c` barrier + `work`). pub(crate) const MAX_COMPUTE_RING_ENTRIES: usize = 3; - /// Maximum unfinished TA passes kept in flight at once so multi-pass render bursts stay - /// inside M4 firmware's `<= 4`-pass TA/scene pipeline without throttling single-pass - /// pipelining (where TA finishes well ahead of FS). + /// Maximum unfinished TA passes kept in flight at once for heavy multi-layer or large-tilemap + /// renders so heavy bursts stay inside M4 firmware's `<= 4`-pass TA/scene pipeline. pub(crate) const TA_WAVE_PASSES: usize = 4; - /// Unfinished TA pass count at or below which a TA-wave-paused render queue wakes to + /// Maximum unfinished TA passes kept in flight at once for light single-layer renders + /// (`tilemap_bytes <= TA_LIGHT_TILEMAP_BYTES`), doubling the wave window for light render + /// bursts and deeper micro-coalesced batches. + pub(crate) const TA_WAVE_PASSES_LIGHT: usize = 8; + /// Tilemap byte threshold at or below which a single-layer render qualifies for + /// `TA_WAVE_PASSES_LIGHT`. + pub(crate) const TA_LIGHT_TILEMAP_BYTES: u64 = 64 * 1024; + /// Headroom below the active TA wave cap at which a TA-wave-paused render queue wakes to /// launch the next wave, avoiding 1-pass stub drips. - pub(crate) const TA_WAVE_REFILL: usize = TA_WAVE_PASSES / 2; + pub(crate) const TA_WAVE_REFILL_HEADROOM: usize = 2; /// Base render pass slots allocated on first render (full TPC/tilemap capacity). pub(crate) const BASE_RENDER_SLOTS: usize = 2; /// Retained render pass slots per VM at most. A slot is reused only after a later render @@ -896,10 +902,22 @@ pub(crate) mod sizes { ); /// Maximum jobs folded into one barrier-free compute horizon prefix. pub(crate) const HORIZON_JOBS: u32 = COMPUTE_UNITS as u32; - /// Jobs admitted to the engine per logical queue: enough to keep a queue's commands - /// in flight back to back without scheduler backpressure stalls; exact prior-command + /// Maximum commands accumulated in a busy-state horizon micro-coalescing batch before + /// immediate publication, and maximum hold window (18 us) while a queue already has >= 2 + /// active commands in flight. + pub(crate) const COALESCE_MAX_CMDS: usize = 6; + pub(crate) const COALESCE_WINDOW_US: u32 = 18; + pub(crate) const COALESCE_WINDOW_NS: u64 = (COALESCE_WINDOW_US as u64) * 1000; + /// Per-queue retired CDM execution EWMA threshold (microseconds) at or above which + /// barrier-free compute fans out across both CDM pipes instead of staying 1-pipe affine. + pub(crate) const COMPUTE_HEAVY_EMA_US: u32 = 200; + /// Elapsed wall-clock time (nanoseconds) on a sole active single-command compute flight + /// that immediately classifies the queue as heavy before its first retirement updates EWMA. + pub(crate) const COMPUTE_HEAVY_INFLIGHT_NS: u64 = 180_000; + /// Jobs admitted to the engine per logical queue: enough to keep deep queues (`d=64`) + /// queued back to back without scheduler backpressure stalls; exact prior-command /// dependencies still gate each one. - pub(crate) const SCHEDULER_CREDITS: u32 = 32; + pub(crate) const SCHEDULER_CREDITS: u32 = 64; /// Unconsumed records per 256-entry channel ring a prefix may be posted behind. pub(crate) const AHEAD_RECORDS: u32 = 128; /// Policy bound on logical queues reported in QUEUE_LIMITS (not a firmware limit). diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 2dedd2d48c3b6..7c7851ee6068a 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -749,16 +749,19 @@ impl Firmware { ); power.set_table(booted.init.rows); let backend = (|| -> Result<_> { - let graph = graph::Graphs::new(dev, &mut booted.objects)?; + let graph_session = graph::Graphs::prepare(&mut booted.objects)?; let slots = slots::Slots::new()?; let pools = pools::Pools::new_boxed(dev)?; let vms = vm::Registry::new()?; let engine = engine::Engine::new()?; let render_cmds = resources::RenderCmds::new()?; + let compute_cmds = resources::ComputeCmds::new()?; + let private_factory = booted.objects.private_factory(render_cmds, compute_cmds); + let graph = graph::Graphs::finish(dev, graph_session, &private_factory)?; let slot = KBox::::new_uninit(GFP_KERNEL)?; - Ok((graph, slots, pools, vms, engine, render_cmds, slot)) + Ok((graph, private_factory, slots, pools, vms, engine, slot)) })(); - let (graph, slots, pools, vms, engine, render_cmds, slot) = match backend { + let (graph, private_factory, slots, pools, vms, engine, slot) = match backend { Ok(backend) => backend, Err(error) => { dev_err!( @@ -773,12 +776,11 @@ impl Firmware { let boot::Booted { session, init, - mut objects, + objects, channels, events, .. } = KBox::into_inner(booted); - let private_factory = objects.private_factory(render_cmds); let mut firmware = slot .write_init(init!(Firmware { session, diff --git a/drivers/gpu/drm/asahi/g16/object.rs b/drivers/gpu/drm/asahi/g16/object.rs index c4c42d1dd1290..080d21522921b 100644 --- a/drivers/gpu/drm/asahi/g16/object.rs +++ b/drivers/gpu/drm/asahi/g16/object.rs @@ -272,6 +272,30 @@ impl FwObject { // SAFETY: ptr() bounds this naturally aligned 64-bit volatile receipt. return Ok(u64::from_le(unsafe { (p as *const u64).read_volatile() })); } + if p as usize % 4 == 0 { + // Packed 64-bit firmware fields such as compute::DESCRIPTOR_COUNTER (0xe4c) and + // DESCRIPTOR_COMPLETED (0xe54) are 4-byte aligned. Read aligned 32-bit word pairs + // rather than falling through to 16 single-byte WC loads in self.read(). + let pair = |words: *const u32| -> (u32, u32) { + rmb(); + // SAFETY: ptr() bounds 8 bytes and `words` is 4-byte aligned. + let lo = u32::from_le(unsafe { words.read_volatile() }); + // SAFETY: `words.add(1)` stays within the 8-byte range and is 4-byte aligned. + let hi = u32::from_le(unsafe { words.add(1).read_volatile() }); + (lo, hi) + }; + let words = p.cast::(); + let mut first = pair(words); + for _ in 0..3 { + let next = pair(words); + if first == next { + rmb(); + return Ok(u64::from(next.0) | (u64::from(next.1) << 32)); + } + first = next; + } + return Err(EAGAIN); + } let mut first = [0u8; 8]; let mut next = [0u8; 8]; self.read(offset, &mut first)?; @@ -352,6 +376,7 @@ pub(crate) struct Factory { window: Arc>, firmware: core::ops::Range, render_cmds: Arc, + compute_cmds: Arc, } impl Factory { @@ -367,6 +392,7 @@ impl Factory { }), sealed: false, persistent: false, + probe: false, fw_next: self.firmware.start, retained: KVec::new(), clients: KVec::new(), @@ -389,6 +415,7 @@ impl Factory { }), sealed: false, persistent: false, + probe: false, fw_next: self.firmware.start, retained: KVec::new(), clients: KVec::new(), @@ -413,6 +440,7 @@ impl Factory { }), sealed: false, persistent: true, + probe: false, fw_next: self.firmware.start, retained: KVec::new(), clients: KVec::new(), @@ -422,11 +450,26 @@ impl Factory { } } + /// Probe-time variant of [`Self::persistent_objects`], called only from + /// [`super::graph::Graphs::finish`] during platform `probe()` before `drm_dev_register()` + /// makes `registration_guard()` available. + pub(crate) fn persistent_objects_probe(&self) -> Objects { + let mut objects = self.persistent_objects(); + objects.probe = true; + objects + } + /// The device-lifetime render command records of pass slot `k`, shared by every VM's /// [`super::slots::PassSlot`] `k`. pub(crate) fn pass_cmds(&self, k: usize) -> Result { self.render_cmds.get(self, k) } + + /// The device-lifetime compute command records of hardware compute unit `k`, shared by every + /// VM's [`super::slots::ComputeSlot`] bound to hardware unit `k`. + pub(crate) fn compute_cmds(&self, k: usize) -> Result { + self.compute_cmds.get(self, k) + } } /// The firmware object allocator and the set of retained objects. @@ -439,6 +482,8 @@ pub(crate) struct Objects { sealed: bool, /// A device-lifetime allocator that may map [`Class::FwCoherent`] records. persistent: bool, + /// Runs during platform `probe()` before `drm_dev_register()` provides `registration_guard()`. + probe: bool, /// Next free VA of the firmware allocator window. fw_next: u64, /// Every object owned by this session or private arena. @@ -468,6 +513,7 @@ impl Objects { private: None, sealed: false, persistent: false, + probe: false, fw_next: hw::va::FW_ALLOC.start, retained: KVec::new(), clients: KVec::new(), @@ -481,6 +527,7 @@ impl Objects { pub(crate) fn private_factory( &mut self, render_cmds: Arc, + compute_cmds: Arc, ) -> Factory { self.sealed = true; Factory { @@ -489,6 +536,7 @@ impl Objects { window: self.window.clone(), firmware: self.fw_next..hw::va::FW_ALLOC.end, render_cmds, + compute_cmds, } } @@ -546,9 +594,17 @@ impl Objects { } else { gem::new_kernel_object_wc(&self.dev, bytes)? }; - let registered = self.dev.registration_guard().ok_or(ENODEV)?; - let parent: &kernel::platform::Device = registered.as_ref(); - gem::prepare_new_object(&backing.gem, parent.as_ref())?; + if self.probe { + // SAFETY: `Factory::persistent_objects_probe()` is called only from + // `Graphs::finish()` during platform `probe()`, while the platform device is + // bound and before `drm_dev_register()` makes `registration_guard()` available. + let bound = unsafe { self.dev.as_ref().as_ref().as_bound() }; + gem::prepare_new_object(&backing.gem, bound)?; + } else { + let registered = self.dev.registration_guard().ok_or(ENODEV)?; + let parent: &kernel::platform::Device = registered.as_ref(); + gem::prepare_new_object(&backing.gem, parent.as_ref())?; + } let clean = req.class == Class::FwCoherent && req.lower.is_some(); let cpu = if req.cpu { let vmap = backing.vmap()?; diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 2fca6c71513e6..e11cfd22168f2 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -141,7 +141,18 @@ impl Shared { ) { Ok(true) if retry_tail => {} Ok(true) => { - self.rearm(firmware.engine.chan_wait || firmware.engine.short_repoll) + let soon = firmware.engine.chan_wait || firmware.engine.short_repoll; + if firmware.engine.coalesce_deadline_ns != 0 && !soon { + let rem_us = (firmware + .engine + .coalesce_deadline_ns + .saturating_sub(now_ns()) + .div_ceil(1000) as u32) + .clamp(1, super::hw::sizes::COALESCE_WINDOW_US); + self.rearm_after(rem_us.min(self.rearm_us(false))); + } else { + self.rearm(soon); + } } // Idle: arm a delayed poll while DVFS utilization is decaying or a CLPC // floor hold is still pending so both expire cleanly to idle power. @@ -271,20 +282,26 @@ impl Shared { Ok(()) }); } + let mut coalesce_us = None; if pub_res.is_ok() { if retired_any || !had_flights { firmware.reclaim_closed_vm_slots(); } - pub_res = if recovery_pending { - let r = firmware.publish(done); - if r.is_ok() { - firmware.last_housekeeping_ns = now; - firmware.last_aux_drain_ns = now; - } - r - } else { - firmware.publish_checked(done) - }; + if !recovery_pending && !retired_any && !restored_event && had_flights { + coalesce_us = firmware.defer_busy_coalesce(now); + } + if coalesce_us.is_none() { + pub_res = if recovery_pending { + let r = firmware.publish(done); + if r.is_ok() { + firmware.last_housekeeping_ns = now; + firmware.last_aux_drain_ns = now; + } + r + } else { + firmware.publish_checked(done) + }; + } } if pub_res.is_ok() && !firmware.engine.flights.is_empty() @@ -300,11 +317,15 @@ impl Shared { // If an EP 0x20 event retired an older flight while later flights remain active, // or arrived before the oldest receipt became visible, arm a short repoll so // trailing completions never fall back to `resnap_us`. - self.rearm( - firmware.engine.chan_wait - || restored_event - || (was_evented && retired_any && !firmware.engine.flights.is_empty()), - ); + if let Some(us) = coalesce_us { + self.rearm_after(us.min(self.rearm_us(false))); + } else { + self.rearm( + firmware.engine.chan_wait + || restored_event + || (was_evented && retired_any && !firmware.engine.flights.is_empty()), + ); + } } else { firmware.power.report_work(false); self.arm_idle_power_poll(firmware); @@ -527,10 +548,15 @@ impl Shared { /// Re-checks a published command soon: hrtimer, with a throttled 1-jiffy backup; sooner while /// a ready prefix waits for record consumption or a post-event receipt tail is settling. pub(crate) fn rearm(self: &Arc, soon: bool) { + self.rearm_after(self.rearm_us(soon)); + } + + /// Arms the poll hrtimer for `us` microseconds (coalescing with an already-armed deadline + /// within 5 us) plus the throttled 1-jiffy backup poll. + pub(crate) fn rearm_after(self: &Arc, us: u32) { if self.sleeping.load(Ordering::Acquire) { return; } - let us = self.rearm_us(soon); let now = now_ns(); let target_ns = now.saturating_add(u64::from(us) * 1000); let armed_ns = self.resnap_deadline_ns.load(Ordering::Acquire); @@ -683,6 +709,8 @@ impl Firmware { // while `publish_woke` covers external state changes (VM close, unstarted queue // cancellation) and `ta_wave_ready()` wakes TA-wave-paced renders when a `0x70` TA // pass finishes while FS is still running. + let coalesce_due = self.engine.coalesce_deadline_ns != 0 + && (!evented || now >= self.engine.coalesce_deadline_ns); let should_publish = !self.engine.pending.is_empty() && (retired_any || !had_flights @@ -692,6 +720,7 @@ impl Firmware { || scrub_woke || publish_woke || self.ta_wave_ready() + || coalesce_due || housekeeping_due); let published = if should_publish { self.publish_checked(done) @@ -816,10 +845,13 @@ impl Firmware { Some((compute, render)) } - /// Whether a render job paused by `TA_WAVE_PASSES` pacing has enough TA headroom to publish + /// Whether a render job paused by TA wave pacing has enough TA headroom to publish /// the next wave without dribbling 1-pass stub flights. fn ta_wave_ready(&self) -> bool { - self.engine.ta_wave_wait && self.ta_pending_passes() <= super::hw::sizes::TA_WAVE_REFILL + let cap = self.active_ta_wave_cap(); + self.engine.ta_wave_wait + && self.ta_pending_passes() + <= cap.saturating_sub(super::hw::sizes::TA_WAVE_REFILL_HEADROOM) } /// Cheap single-stage stamp check for the oldest compute pipe 0/1 and oldest render flights' @@ -917,8 +949,9 @@ impl Firmware { } /// A compute unit's GPU start and end ticks. 25G83 writes them into the unit's ITS pair; - /// ABIs with `work_ticks` leave ITS 0/0 and write them into the work object. The ITS pair - /// is used whenever it holds an interval. + /// ABIs with `work_ticks` leave ITS 0/0 and write them into the work object. Check + /// `work_ticks` first when the ABI defines them so 26B123 skips two always-zero WC reads + /// per command, falling back to ITS if `work_ticks` holds no interval. fn compute_ticks(&self, unit: &super::slots::ComputeSlot) -> Result<(u64, u64)> { Self::compute_ticks_with(self.init.abi.compute().work_ticks, unit) } @@ -927,27 +960,26 @@ impl Firmware { work_ticks: Option<(usize, usize)>, unit: &super::slots::ComputeSlot, ) -> Result<(u64, u64)> { - let (start, end) = (unit.its.r64(0)?, unit.its.r64(8)?); - if start != 0 && end >= start { - return Ok((start, end)); - } - let Some((start_off, end_off)) = work_ticks else { - return Ok((start, end)); - }; - let w = &unit.work; - // Work tick offsets are 4-byte aligned (not 8-byte), so read hi/lo/hi to avoid tearing. - let at = |o: usize| -> Result { - for _ in 0..4 { - let hi1 = w.r32(o + 4)?; - let lo = w.r32(o)?; - let hi2 = w.r32(o + 4)?; - if hi1 == hi2 { - return Ok(u64::from(lo) | (u64::from(hi1) << 32)); + if let Some((start_off, end_off)) = work_ticks { + let w = &unit.work; + // Work tick offsets are 4-byte aligned (not 8-byte), so read hi/lo/hi to avoid tearing. + let at = |o: usize| -> Result { + for _ in 0..4 { + let hi1 = w.r32(o + 4)?; + let lo = w.r32(o)?; + let hi2 = w.r32(o + 4)?; + if hi1 == hi2 { + return Ok(u64::from(lo) | (u64::from(hi1) << 32)); + } } + Err(EIO) + }; + let (start, end) = (at(start_off)?, at(end_off)?); + if start != 0 && end >= start { + return Ok((start, end)); } - Err(EIO) - }; - Ok((at(start_off)?, at(end_off)?)) + } + Ok((unit.its.r64(0)?, unit.its.r64(8)?)) } /// Exact queue-ring proof for one serialized publication on its workqueue pipe. @@ -1836,6 +1868,8 @@ impl Firmware { }; let (mut lo, mut hi) = (u64::MAX, 0u64); let (mut first, mut last) = (u64::MAX, 0u64); + let mut cdm_flight_ticks = 0u64; + let mut cdm_counted = 0u32; let work_ticks = self.init.abi.compute().work_ticks; let s = &mut self.engine.stats; @@ -1872,6 +1906,10 @@ impl Firmware { &mut s.cdm_ticks, crate::usage::Engine::Compute, ); + if ticks[1] >= ticks[0] { + cdm_flight_ticks = ticks[1] - ticks[0]; + cdm_counted = 1; + } } else { // Multi-command prefix fallback: read each member's internal timestamp cells. let mut stage = |o: &super::object::FwObject, @@ -1910,9 +1948,20 @@ impl Firmware { }; if let Ok((start, end)) = Self::compute_ticks_with(work_ticks, c) { add_interval(start, end, &mut s.cdm_ticks, crate::usage::Engine::Compute); + if start != 0 && end >= start { + cdm_flight_ticks = cdm_flight_ticks.saturating_add(end - start); + cdm_counted += 1; + } } } } + if cdm_counted != 0 { + let per_cmd_ticks = cdm_flight_ticks / u64::from(cdm_counted); + let per_cmd_us = (per_cmd_ticks.saturating_mul(1_000_000) + / super::hw::COMMAND_TIMESTAMP_HZ) + .clamp(1, 100_000) as u32; + f.job.queue.note_compute_us(per_cmd_us); + } if hi > lo { s.span_ticks = s.span_ticks.saturating_add(hi - lo); } diff --git a/drivers/gpu/drm/asahi/g16/queue.rs b/drivers/gpu/drm/asahi/g16/queue.rs index 319232fd46334..28332f8de5e74 100644 --- a/drivers/gpu/drm/asahi/g16/queue.rs +++ b/drivers/gpu/drm/asahi/g16/queue.rs @@ -76,6 +76,9 @@ pub(crate) struct QueueState { /// engine when a job arrives. pub(crate) owned: [AtomicU32; 32], pub(crate) owned_index: AtomicU32, + /// EWMA of retired per-command CDM GPU execution duration (microseconds) for adaptive + /// 1-pipe affinity vs 2-pipe heavy compute fanout. + pub(crate) compute_ewma_us: AtomicU32, } impl QueueState { @@ -124,6 +127,20 @@ impl QueueState { let shift = seq.wrapping_sub(completed).wrapping_sub(2); shift < 64 && (self.compute_ooo.load(Ordering::Acquire) & (1u64 << shift)) != 0 } + + /// Updates the lock-free EWMA of recent retired per-command CDM GPU execution duration + /// (microseconds) for this queue using a symmetric 50% step so transitions between light + /// and heavy compute streams adapt within 2-3 completions. + pub(crate) fn note_compute_us(&self, us: u32) { + let us = us.clamp(1, 100_000); + let prev = self.compute_ewma_us.load(Ordering::Relaxed); + let next = if prev == 0 { + us + } else { + prev.saturating_add(us) / 2 + }; + self.compute_ewma_us.store(next, Ordering::Relaxed); + } } /// One per-file logical-queue credit, released after the queue scheduler drains. @@ -212,6 +229,7 @@ impl Queue { published: [const { AtomicU64::new(0) }; 2], owned: [const { AtomicU32::new(0) }; 32], owned_index: AtomicU32::new(0), + compute_ewma_us: AtomicU32::new(0), }, GFP_KERNEL, )?; diff --git a/drivers/gpu/drm/asahi/g16/recovery.rs b/drivers/gpu/drm/asahi/g16/recovery.rs index e641735511142..f0d082eea46d4 100644 --- a/drivers/gpu/drm/asahi/g16/recovery.rs +++ b/drivers/gpu/drm/asahi/g16/recovery.rs @@ -290,6 +290,7 @@ impl Firmware { self.floor_power(error); } self.engine.frozen = true; + self.engine.coalesce_deadline_ns = 0; self.events.grow.clear(); self.fail_flights(error, done); self.fail_all_vms(EIO); diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index 25b0d609a3d2a..0961b97b38903 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -9,7 +9,7 @@ use super::{ command::Command, object::{Factory, Objects}, pools::{PbEpoch, PoolSet}, - slots::{ComputeSlot, PassCmds, PassSlot, Placement}, + slots::{ComputeSlot, PassCmds, PassSlot, Placement, UnitCmds}, vm::VmState, }; use crate::mmu; @@ -75,6 +75,60 @@ impl RenderCmds { } } +/// One hardware compute unit's device-lifetime command records and the allocator that maps +/// them. The allocator is never dropped for the same reason as [`PersistentPassCmds`]. +struct PersistentUnitCmds { + objects: core::mem::ManuallyDrop, + cmds: Option, +} + +/// The firmware-cached compute command records (microsequence and barrier records) of every +/// hardware compute unit (`0..COMPUTE_UNITS`), created on first use and kept until reboot. A +/// hardware compute unit is device-global and claimed by one flight at a time, so every VM's +/// [`ComputeSlot`] bound to hardware unit `k` shares its records, and closing a VM drops no +/// firmware-cached mapping. +#[pin_data] +pub(crate) struct ComputeCmds { + #[pin] + sets: Mutex<[Option>; super::hw::sizes::COMPUTE_UNITS]>, +} + +impl ComputeCmds { + pub(crate) fn new() -> Result> { + Arc::pin_init( + pin_init!(Self { + sets <- new_mutex!( + [const { None }; super::hw::sizes::COMPUTE_UNITS], + "g16::compute_cmds" + ), + }), + GFP_KERNEL, + ) + } + + /// The records of hardware compute unit `k`, allocated from `factory` on first use. + pub(crate) fn get(&self, factory: &Factory, k: usize) -> Result { + let mut sets = self.sets.lock(); + let entry = sets.get_mut(k).ok_or(EINVAL)?; + if let Some(cmds) = entry.as_ref().and_then(|set| set.cmds.as_ref()) { + return Ok(cmds.clone()); + } + let mut set = KBox::new( + PersistentUnitCmds { + objects: core::mem::ManuallyDrop::new(factory.persistent_objects()), + cmds: None, + }, + GFP_KERNEL, + )?; + // From here on a failure leaks the allocator with whatever it mapped. + let cmds = UnitCmds::new(&mut set.objects)?; + set.objects.finish_private()?; + set.cmds = Some(cmds.clone()); + *entry = Some(set); + Ok(cmds) + } +} + /// Never-exposed PB epochs an open VM keeps on standby after bursts drain. /// /// With PB epoch reuse most renders never expose a fresh epoch; keeping a @@ -114,18 +168,21 @@ impl ComputeArena { pub(crate) fn seeds(&self) -> u32 { self.unit.seeds } - /// Allocates one self-contained compute unit `k` (its index and `placement` fix its client - /// addresses; the index fixes its hardware UMA slot). + /// Allocates one self-contained compute unit at local VA index `local` bound to device-wide + /// hardware ledger slot `hw_slot` (`local` and `placement` fix its client addresses; `hw_slot` + /// selects its shared device-lifetime command records). fn new( factory: &Factory, bind: &mmu::VmBind, vm: &mmu::Vm, live: &Arc, - k: usize, + local: usize, + hw_slot: usize, placement: Placement, ) -> Result> { + let cmds = factory.compute_cmds(hw_slot)?; let mut objects = factory.objects(vm); - let unit = ComputeSlot::new_in(&mut objects, factory, k as u64, placement)?; + let unit = ComputeSlot::new_in(&mut objects, factory, local as u64, placement, &cmds)?; objects.finish_private()?; Ok(Arc::new( Self(crate::cleanup::Deferred::new(ComputeInner { @@ -164,7 +221,7 @@ impl ComputeUnitSet { let mut units = KVec::with_capacity(range.len(), GFP_KERNEL)?; for k in range { units.push( - ComputeArena::new(factory, bind, vm, live, k, placement)?, + ComputeArena::new(factory, bind, vm, live, k, k, placement)?, GFP_KERNEL, )?; } @@ -187,9 +244,17 @@ impl ComputeUnitSet { seeds: u32, ) -> Result> { let mut units = KVec::with_capacity(super::hw::sizes::SCS_COMPUTE_UNITS, GFP_KERNEL)?; - for local in 0..super::hw::sizes::SCS_COMPUTE_UNITS { + for (local, &hw_slot) in hw_slots.iter().enumerate() { units.push( - ComputeArena::new(factory, bind, vm, live, local, Placement::Scs { seeds })?, + ComputeArena::new( + factory, + bind, + vm, + live, + local, + hw_slot, + Placement::Scs { seeds }, + )?, GFP_KERNEL, )?; } diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index f6952828e1eca..1d48b4cd996d4 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -12,12 +12,44 @@ use core::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use kernel::{prelude::*, sync::Arc}; use super::encode::{Geometry, PassRefs}; -use super::fw::work::{barrier, fs, ta}; -use super::graph::{alloc, alloc_work, cmd_fw, Client}; +use super::fw::work::{barrier, compute, fs, ta}; +use super::graph::{alloc, alloc_work, Client}; use super::hw::{client, sizes}; use super::object::{Class, Factory, FwLease, FwObject, Objects}; use super::pools::lifetime::Lifetime; +/// The compute command records of one hardware compute unit index (microsequence and barrier +/// records), shared by every VM's [`ComputeSlot`] bound to that hardware unit: the unit index +/// is device-global and claimed by one flight at a time. The host writes them before +/// publication and never reads back what the firmware writes, so they take the firmware-cached +/// [`Class::FwCoherent`] view macOS 26B123 gives its per-queue command objects, with no client +/// or lower alias. +#[derive(Clone)] +pub(crate) struct UnitCmds { + pub(crate) seq: Arc, + pub(crate) barrier: Arc, +} + +impl UnitCmds { + /// Allocates one compute unit index's command records from a device-lifetime allocator + /// ([`Factory::persistent_objects`]), which the caller never drops. + pub(crate) fn new(o: &mut Objects) -> Result { + let coherent = Class::FwCoherent; + Ok(Self { + seq: alloc(o, compute::SEQ_SIZE, coherent, None, 0, false)?, + // Holds fs2c (+0x00) and cross-pipe c2c (+0x40) barriers within one page. + barrier: alloc( + o, + barrier::SIZE * sizes::COMPUTE_PIPES, + coherent, + None, + 0, + false, + )?, + }) + } +} + /// One immutable allocation set. Mutable firmware pool cursors survive successful reuse. pub(crate) struct ComputeSlot { pub(crate) its: Arc, @@ -149,16 +181,23 @@ pub(crate) fn init_uma_pool(state: &FwObject, list: &FwObject, pool: u64, seeds: impl ComputeSlot { #[allow(dead_code)] - pub(crate) fn new(o: &mut Objects, fw_factory: &Factory, k: u64) -> Result { - Self::new_in(o, fw_factory, k, Placement::Base) + pub(crate) fn new( + o: &mut Objects, + fw_factory: &Factory, + k: u64, + cmds: &UnitCmds, + ) -> Result { + Self::new_in(o, fw_factory, k, Placement::Base, cmds) } - /// Unit `k` at `placement`. + /// Unit `k` at `placement`, around the device-lifetime command records `cmds` of its + /// hardware ledger slot. pub(crate) fn new_in( o: &mut Objects, fw_factory: &Factory, k: u64, placement: Placement, + cmds: &UnitCmds, ) -> Result { placement.check()?; let sh = Class::Shared; @@ -178,16 +217,8 @@ impl ComputeSlot { false, )?, work, - seq: alloc(o, 0x300, cmd_fw(), None, 0, false)?, - // Holds fs2c (+0x00) and cross-pipe c2c (+0x40) barriers within one page. - barrier: alloc( - o, - barrier::SIZE * sizes::COMPUTE_PIPES, - cmd_fw(), - None, - 0, - false, - )?, + seq: cmds.seq.clone(), + barrier: cmds.barrier.clone(), pool: o.alloc(super::object::Request { size: placement.pool_bytes(), class: sh, @@ -249,9 +280,9 @@ impl ComputeSlot { /// Resets command-local state before reuse. Pool/list/counter/descriptor state is preserved. /// /// Clean same-VM reuse only zeroes the 16-byte internal timestamp pair so retirement - /// checks cannot observe stale ticks; `work` (including its embedded sequence) is - /// overwritten completely by `prefix_compute`. First use, cross-VM retarget, cancelled - /// preparation, or post-recovery/error reuse runs the full scrub of all scratch areas. + /// checks cannot observe stale ticks; `work` and `seq` are overwritten by `prefix_compute`. + /// First use, cross-VM retarget, cancelled preparation, or post-recovery/error reuse runs + /// the full scrub of all scratch areas. fn scrub(&self, full: bool) -> Result { self.its.fill(0, 0, 16)?; if !full { @@ -1107,12 +1138,15 @@ impl Slots { pub(crate) fn note_render_retired(&mut self) { self.render.scrub_pending = true; } - /// Stages any newly displaced, cleanly retired render pass slots for off-lock pre-scrubbing. - /// Never touches `Published` or undisplaced `Retired` slots. + /// Stages any newly displaced, cleanly retired render pass slots for off-lock pre-scrubbing, + /// scanning cursor-ordered from `pass_cursor` so the slots `pick_pass_in_for` will reach next + /// are scrubbed first. Never touches `Published` or undisplaced `Retired` slots. pub(crate) fn stage_displaced_pass_scrubs(&mut self) { self.render.scrub_pending = false; self.fold_scrub_stats(); - for k in 0..sizes::RENDER_SLOTS { + let start = self.pass_cursor as usize % sizes::RENDER_SLOTS; + for i in 0..sizes::RENDER_SLOTS { + let k = (start + i) % sizes::RENDER_SLOTS; let bit = 1u64 << k; if self.pass_busy & bit != 0 || !self.render.lifetime.available(k) diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-command-stream.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-command-stream.py index 27093fdfdf1e7..0a779b3fb7d3d 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-command-stream.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-command-stream.py @@ -124,7 +124,7 @@ mod file { pub const MAX_COMMANDS_PER_SUBMISSION: u32 = 64; } mod hw { pub const USER_RANGE: core::ops::Range = 0x4000..((1u64 << 42) - 0x8000); - pub mod sizes { pub const MAX_ATTACHMENTS: usize = 16; } + pub mod sizes { pub const MAX_ATTACHMENTS: usize = 16; pub const TA_LIGHT_TILEMAP_BYTES: u64 = 64 * 1024; } pub mod client { pub const PB_HEAP_SIZE:u64=0x10000000; CAPACITIES } } mod fw { diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py index 03099634f7b6c..df5d84c420362 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py @@ -66,8 +66,10 @@ def item(declaration, text=source): mod hw { pub mod sizes { pub const TA_WAVE_PASSES: usize = 4; - pub const TA_WAVE_REFILL: usize = TA_WAVE_PASSES / 2; + pub const TA_WAVE_PASSES_LIGHT: usize = 8; + pub const TA_WAVE_REFILL_HEADROOM: usize = 2; pub const COMPUTE_PIPES: usize = 2; + pub const COALESCE_WINDOW_US: u32 = 18; } } @@ -161,6 +163,7 @@ def item(declaration, text=source): slot_wait: bool, ta_wave_wait: bool, short_repoll: bool, + coalesce_deadline_ns: u64, frozen: bool, stats: Stats, prof: Prof, @@ -217,6 +220,8 @@ def item(declaration, text=source): rearmed: Cell, idle_power_polls: Cell, rearm_soon: Cell, + rearm_after_calls: Cell, + last_rearm_us: Cell, poll_now_calls: Cell, } impl Shared { @@ -229,9 +234,18 @@ def item(declaration, text=source): rearmed: Cell::new(0), idle_power_polls: Cell::new(0), rearm_soon: Cell::new(0), + rearm_after_calls: Cell::new(0), + last_rearm_us: Cell::new(0), poll_now_calls: Cell::new(0), }) } + fn rearm_us(&self, soon: bool) -> u32 { + if soon { 25 } else { 100 } + } + fn rearm_after(&self, us: u32) { + self.rearm_after_calls.set(self.rearm_after_calls.get() + 1); + self.last_rearm_us.set(us); + } fn rearm(&self, soon: bool) { self.rearmed.set(self.rearmed.get() + 1); if soon { @@ -311,6 +325,8 @@ def item(declaration, text=source): drain_fs_delta: u32, drain_compute_delta: u32, ta_pending: usize, + ta_wave_cap: usize, + coalesce_us: Option, retire_calls: u32, publish_full_calls: u32, publish_checked_calls: u32, @@ -347,6 +363,7 @@ def item(declaration, text=source): slot_wait: false, ta_wave_wait: false, short_repoll: false, + coalesce_deadline_ns: 0, frozen: false, stats: Stats::default(), prof: Prof::default(), @@ -364,6 +381,8 @@ def item(declaration, text=source): drain_fs_delta: 0, drain_compute_delta: 0, ta_pending: 0, + ta_wave_cap: hw::sizes::TA_WAVE_PASSES, + coalesce_us: None, retire_calls: 0, publish_full_calls: 0, publish_checked_calls: 0, @@ -425,12 +444,19 @@ def item(declaration, text=source): Ok(()) } fn publish_checked(&mut self, _done: &mut Completions) -> Result { + self.engine.coalesce_deadline_ns = 0; self.publish_checked_calls += 1; Ok(()) } + fn defer_busy_coalesce(&mut self, _now: u64) -> Option { + self.coalesce_us + } fn ta_pending_passes(&self) -> usize { self.ta_pending } + fn active_ta_wave_cap(&self) -> usize { + self.ta_wave_cap + } __RECLAIM_CLOSED_VM_SLOTS__ __POLL_STEP__ @@ -998,8 +1024,7 @@ def item(declaration, text=source): assert!(!retry_tail); assert!(fw.engine.short_repoll); - // TA drains to 2 (<= TA_WAVE_REFILL): immediately wakes publish_checked() to launch the - // next wave cleanly. + // TA drains to 2 (<= cap - TA_WAVE_REFILL_HEADROOM): immediately wakes publish_checked(). fw.ta_pending = 2; assert!(fw .poll_step(true, 0, &mut retry_tail, &mut deferred, &mut done) @@ -1007,6 +1032,19 @@ def item(declaration, text=source): assert_eq!(fw.publish_checked_calls, 1); assert!(fw.engine.short_repoll); + // Light TA wave cap (8): stays paused at 7 (> 8 - 2), wakes at 6 (<= 6). + fw.ta_wave_cap = hw::sizes::TA_WAVE_PASSES_LIGHT; + fw.ta_pending = 7; + assert!(fw + .poll_step(true, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 1); + fw.ta_pending = 6; + assert!(fw + .poll_step(true, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 2); + // Once ta_wave_wait clears, a TA-only 0x70 IRQ stays non_terminal_only (no spin/short_repoll). fw.engine.ta_wave_wait = false; retry_tail = false; @@ -1017,6 +1055,58 @@ def item(declaration, text=source): assert!(!fw.engine.short_repoll); } +#[test] +fn submit_locked_and_poll_step_micro_coalesce_busy_horizons() { + CLOCK.with(|c| c.set(100_000)); + let shared = Shared::new(); + let mut fw = Firmware::new(); + fw.engine.flights.push(Flight { + computes: 2, + compute_pipe: 0, + renders: 0, + target: 0x200, + fs_target: 0, + }); + fw.engine.target[0] = 0x200; + fw.coalesce_us = Some(18); + fw.engine.coalesce_deadline_ns = 118_000; + + // submit_locked skips publish_checked and arms rearm_after(18) when defer_busy_coalesce fires. + let mut done = vec![]; + shared + .submit_locked(&mut fw, Arc::new(Job { id: 3 }), &mut done) + .unwrap(); + assert_eq!(fw.publish_checked_calls, 0); + assert_eq!(shared.rearm_after_calls.get(), 1); + assert_eq!(shared.last_rearm_us.get(), 18); + assert_eq!(shared.rearmed.get(), 0); + + // An early non-retiring event poll before the deadline does not flush prematurely. + CLOCK.with(|c| c.set(105_000)); + let (mut retry_tail, mut deferred) = (false, false); + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 0); + + // Reaching the deadline on an event poll flushes immediately. + CLOCK.with(|c| c.set(118_000)); + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 1); + assert_eq!(fw.engine.coalesce_deadline_ns, 0); + + // A timer poll (!evented) with an active coalesce deadline also flushes immediately. + fw.engine.coalesce_deadline_ns = 136_000; + CLOCK.with(|c| c.set(125_000)); + assert!(fw + .poll_step(false, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 2); + assert_eq!(fw.engine.coalesce_deadline_ns, 0); +} + mod boot { pub fn eproto() -> super::Error { super::Error(-71) @@ -1328,6 +1418,7 @@ def item(declaration, text=source): __IDLE_RESNAP__ __REARM_US__ __REARM__ + __REARM_AFTER__ __NOTE_FLIGHT_US__ } @@ -1415,11 +1506,21 @@ def item(declaration, text=source): assert_eq!(shared.drops.load(Ordering::Acquire), 1); assert_eq!(shared.resnap_deadline_ns.load(Ordering::Acquire), 127_000); + // Coalesce rearm_after(18) pulls in a 25 us timer (>5 us earlier) and coalesces within 5 us. + shared.rearm_after(18); + assert_eq!(shared.starts.load(Ordering::Acquire), 3); + assert_eq!(shared.drops.load(Ordering::Acquire), 2); + assert_eq!(shared.resnap_deadline_ns.load(Ordering::Acquire), 120_000); + CLOCK.store(106_000, Ordering::Release); + shared.rearm_after(14); + assert_eq!(shared.starts.load(Ordering::Acquire), 3); + assert_eq!(shared.drops.load(Ordering::Acquire), 2); + // cancel_resnap unconditionally clears deadline and drops handle. shared.cancel_resnap(); assert_eq!(shared.resnap_deadline_ns.load(Ordering::Acquire), 0); assert!(shared.resnap_handle.lock().is_none()); - assert_eq!(shared.drops.load(Ordering::Acquire), 2); + assert_eq!(shared.drops.load(Ordering::Acquire), 3); } #[test] @@ -1578,6 +1679,7 @@ def item(declaration, text=source): '__IDLE_RESNAP__': 'pub(crate) fn idle_resnap(', '__REARM_US__': 'pub(crate) fn rearm_us(', '__REARM__': 'pub(crate) fn rearm(', + '__REARM_AFTER__': 'pub(crate) fn rearm_after(', '__POLL_NOW__': 'pub(crate) fn poll_now(', }.items(): harness = harness.replace(token, item(decl).replace('super::hw::', 'hw::')) diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py index 5cefe344b3090..ad2fac33e3c92 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -45,7 +45,7 @@ def item(declaration): assert 'const HORIZON_JOBS: u32 = COMPUTE_UNITS as u32;' in hw_src prefix_render_fn = item('fn prefix_render(') prefix_compute_fn = item('fn prefix_compute(') -can_queue_behind_fn = item('fn can_queue_behind(') +can_queue_behind_fn = item('fn can_queue_behind_with_ta(') assert 'let render_bar = cross_engine_barrier_type(producer_initbm, init_buffer);' in prefix_render_fn assert ( prefix_render_fn.index('let render_bar = cross_engine_barrier_type(producer_initbm, init_buffer);') @@ -80,6 +80,7 @@ def item(declaration): assert 'self.graph.render.threshold.w32(0, prefix.draw as u32)?;' in publish_prefix_body_fn assert 'self.graph.render.threshold.w32(8, prefix.draw as u32)?;' in publish_prefix_body_fn assert 'earliest_unfinished_ta_draw' not in source and 'rearm_ta_threshold' not in source +assert 'let pipe_fold_cap = if heavy_compute && c_waits == [None; sizes::COMPUTE_PIPES]' in publish_prefix_body_fn, 'pipe_fold_cap must only apply to heavy barrier-free compute' harness = r''' @@ -96,14 +97,19 @@ def item(declaration): #[derive(Copy,Clone,Debug,PartialEq,Eq)]enum Channel { Ta = 0, Fs = 1, Compute = 2 } #[derive(Copy,Clone)]struct ComputeCommand { query_access: bool, rt: bool } impl ComputeCommand { fn is_rt(&self) -> bool { self.rt } } -#[derive(Copy,Clone)]enum Command { Compute(ComputeCommand), Render(()) } +#[derive(Copy,Clone)]struct RenderCommand { heavy_ta: bool } +impl RenderCommand { fn is_heavy_ta(&self) -> bool { self.heavy_ta } } +const R_LIGHT: RenderCommand = RenderCommand { heavy_ta: false }; +const R_HEAVY: RenderCommand = RenderCommand { heavy_ta: true }; +#[derive(Copy,Clone)]enum Command { Compute(ComputeCommand), Render(RenderCommand) } struct Status(AtomicU32);impl Status{fn get(&self)->u32{self.0.load(Ordering::Relaxed)}} struct Vm { status:Status, slot:u32 } -struct Queue { turn:AtomicU64, priority:u32, completed:[AtomicU64;2], compute_ooo:AtomicU64 } +struct Queue { turn:AtomicU64, priority:u32, completed:[AtomicU64;2], compute_ooo:AtomicU64, compute_ewma_us:AtomicU32 } impl Queue { fn new(turn:u64, priority:u32)->Arc{ - Arc::new(Self{turn:AtomicU64::new(turn),priority,completed:[AtomicU64::new(0),AtomicU64::new(0)],compute_ooo:AtomicU64::new(0)}) + Arc::new(Self{turn:AtomicU64::new(turn),priority,completed:[AtomicU64::new(0),AtomicU64::new(0)],compute_ooo:AtomicU64::new(0),compute_ewma_us:AtomicU32::new(0)}) } + __NOTE_COMPUTE_US__ fn is_compute_retired(&self, seq:u64)->bool{ let c=self.completed[command::COMPUTE].load(Ordering::Acquire); if seq<=c { return true; } @@ -129,10 +135,10 @@ def item(declaration): fn complete(done:&mut Completions,job:&Arc,result:Result){done.push((job.id,result));} #[derive(Default)]struct Stats{hold:[u64;3],grouped:u64} struct Claims; -struct Flight{job:Arc,claims:Claims,group:Vec>,computes:u32,renders:u32,compute_pipe:u8,rt_compute:bool,doomed:bool,recovery_suspect:bool,initbm:bool} -impl Flight{fn new(job:Arc)->Self{Self{job,claims:Claims,group:vec![],computes:0,renders:0,compute_pipe:0,rt_compute:false,doomed:false,recovery_suspect:false,initbm:false}}} +struct Flight{job:Arc,claims:Claims,group:Vec>,computes:u32,renders:u32,compute_pipe:u8,rt_compute:bool,doomed:bool,recovery_suspect:bool,initbm:bool,heavy_render:bool} +impl Flight{fn new(job:Arc)->Self{Self{job,claims:Claims,group:vec![],computes:0,renders:0,compute_pipe:0,rt_compute:false,doomed:false,recovery_suspect:false,initbm:false,heavy_render:false}}} __SCS_COMPUTE_CONFLICT__ -struct Engine{ordinal:u64,draw:u64,pending:Vec>,flights:Vec,frozen:bool,turn:u64,stats:Stats,chan_wait:bool,slot_wait:bool,ta_wave_wait:bool} +struct Engine{ordinal:u64,draw:u64,pending:Vec>,flights:Vec,frozen:bool,turn:u64,stats:Stats,chan_wait:bool,slot_wait:bool,ta_wave_wait:bool,coalesce_deadline_ns:u64} impl Engine { __PICK__ __UNPEND__ @@ -178,7 +184,7 @@ def item(declaration): // containment branch below decides whether the unit becomes claimable again. pub fn preserve_compute_descriptor(refs:&ComputeRefs,_old:&[u8;160],_before:u64,_work:&mut[u8;8192])->Result<(),()>{if refs.invalid{Err(())}else{Ok(())}} } -mod hw { pub mod sizes { pub const FLIGHTS:usize=32; pub const TA_WAVE_PASSES:usize=4; pub const TA_WAVE_REFILL:usize=TA_WAVE_PASSES/2; pub const COMPUTE_PIPES:usize=2; pub const PIPE1_COMPUTE_START:usize=6; } } +mod hw { pub mod sizes { pub const FLIGHTS:usize=32; pub const TA_WAVE_PASSES:usize=4; pub const TA_WAVE_PASSES_LIGHT:usize=8; pub const TA_LIGHT_TILEMAP_BYTES:u64=64*1024; pub const TA_WAVE_REFILL_HEADROOM:usize=2; pub const COMPUTE_PIPES:usize=2; pub const COMPUTE_UNITS:usize=24; pub const PIPE1_COMPUTE_START:usize=6; pub const COMPUTE_SLOTS:usize=24; pub const RENDER_SLOTS:usize=48; pub const COALESCE_MAX_CMDS:usize=6; pub const COALESCE_WINDOW_US:u32=18; pub const COALESCE_WINDOW_NS:u64=18_000; pub const COMPUTE_HEAVY_EMA_US:u32=200; pub const COMPUTE_HEAVY_INFLIGHT_NS:u64=180_000; } } mod command {pub const RENDER:usize=0;pub const COMPUTE:usize=1;} thread_local!{static CLOCK:std::cell::Cell=const{std::cell::Cell::new(0)};} fn now_ns()->u64{CLOCK.with(|clock|clock.get())} @@ -218,25 +224,34 @@ def item(declaration): session:Session,objects:Checks,recovery:Recovery,engine:Engine,slots:Slots,pools:Pools,power:Power, unavailable:Vec<(usize,Error)>,stages:VecDeque,retained:Vec,attempted:Vec,fail_stops:u32, allow_behind:bool,block_render_behind:bool,block_compute_behind:bool, + ta_pending_calls:std::cell::Cell, } impl Firmware { fn mark_class_unavailable(&mut self,class:usize,error:Error){self.unavailable.push((class,error));} fn sync_quarantine_hints(&self){} __NEEDS_ENGINE_DRAIN__ + __TA_WAVE_CAP_FOR__ + __ACTIVE_TA_WAVE_CAP__ fn blocked_on_slot_headroom(&self,job:&Arc)->bool{ if self.engine.flights.is_empty()||self.needs_engine_drain(job){return false;} if job.check_command_dependencies(job.progress.sent()).is_err(){return false;} - (self.block_render_behind&&matches!(command(job,job.progress.sent()),Some(Command::Render(())))) + (self.block_render_behind&&matches!(command(job,job.progress.sent()),Some(Command::Render(_)))) ||(self.block_compute_behind&&matches!(command(job,job.progress.sent()),Some(Command::Compute(_)))) } fn ta_pending_passes(&self)->usize{ + self.ta_pending_calls.set(self.ta_pending_calls.get()+1); self.engine.flights.iter().map(|f|f.renders as usize).sum() } fn can_queue_behind(&self,job:&Arc)->bool{ + let mut ta_pending=None; + self.can_queue_behind_with_ta(job,&mut ta_pending) + } + fn can_queue_behind_with_ta(&self,job:&Arc,ta_pending:&mut Option)->bool{ if !self.allow_behind{return false;} if self.needs_engine_drain(job){return false;} - if matches!(command(job,job.progress.sent()),Some(Command::Render(()))){ - if self.block_render_behind||self.ta_pending_passes()>=hw::sizes::TA_WAVE_PASSES{return false;} + if let Some(Command::Render(r))=command(job,job.progress.sent()){ + let cap=self.ta_wave_cap_for(r.is_heavy_ta()); + if self.block_render_behind||*ta_pending.get_or_insert_with(||self.ta_pending_passes())>=cap{return false;} } if self.block_compute_behind&&matches!(command(job,job.progress.sent()),Some(Command::Compute(_))){return false;} true @@ -263,9 +278,10 @@ def item(declaration): let idx=job.progress.sent.fetch_add(1,Ordering::Relaxed); let mut fl=Flight::new(job.clone()); match command(job,idx){ - Some(Command::Render(()))=>{ + Some(Command::Render(r))=>{ *pending_rings|=(1<<(Channel::Fs as u8))|(1<<(Channel::Ta as u8)); fl.renders=1; + fl.heavy_render=r.is_heavy_ta(); fl.initbm=!self.pools.can_pipeline(&job.vm); } _=>{*pending_rings|=1<<(Channel::Compute as u8);fl.computes=1;} @@ -280,21 +296,25 @@ def item(declaration): __PUBLISH_CHECKED__ } fn mk_vm(slot:u32)->Arc{Arc::new(Vm{status:Status(AtomicU32::new(0)),slot})} -fn job_on_vm(id:u32,vm:Arc,render:bool,sent:u32,dependency:Result)->Arc{ +fn job_on_vm_mode(id:u32,vm:Arc,render:bool,heavy:bool,sent:u32,dependency:Result)->Arc{ Arc::new(Job{id,vm, queue:Queue::new(0,0), progress:Progress{sent:AtomicU32::new(sent),count:sent+1,pending:AtomicBool::new(true)}, - commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:true,rt:false})};sent as usize+1],dependency,terminal_marked:AtomicBool::new(false),resources:Resources}) + commands:vec![if render{Command::Render(RenderCommand{heavy_ta:heavy})}else{Command::Compute(ComputeCommand{query_access:true,rt:false})};sent as usize+1],dependency,terminal_marked:AtomicBool::new(false),resources:Resources}) +} +fn job_on_vm(id:u32,vm:Arc,render:bool,sent:u32,dependency:Result)->Arc{ + job_on_vm_mode(id,vm,render,false,sent,dependency) } fn job(id:u32,render:bool,sent:u32,dependency:Result)->Arc{ job_on_vm(id,mk_vm(id),render,sent,dependency) } fn firmware(jobs:Vec>,stages:Vec<(Result,bool)>)->Firmware{ Firmware{session:Session{shared:Shared{sleeping:AtomicBool::new(false)},rings:vec![],ring_fail:false,checks:AtomicU32::new(0),transports:AtomicU32::new(0)},objects:Checks,recovery:Recovery{error:None,publication_wait_deadline:None}, - engine:Engine{ordinal:0,draw:0,pending:jobs,flights:vec![],frozen:false,turn:0,stats:Stats::default(),chan_wait:false,slot_wait:false,ta_wave_wait:false}, + engine:Engine{ordinal:0,draw:0,pending:jobs,flights:vec![],frozen:false,turn:0,stats:Stats::default(),chan_wait:false,slot_wait:false,ta_wave_wait:false,coalesce_deadline_ns:0}, slots:Slots{compute_exhausted:false,render_exhausted:false,releases:0,quarantines:0},pools:Pools{exhausted:false,exhausted_vm:None,block_pipeline_vm:None},power:Power::default(), unavailable:vec![],stages:stages.into_iter().map(|(result,visible)|Stage{result,visible}).collect(), - retained:vec![],attempted:vec![],fail_stops:0,allow_behind:false,block_render_behind:false,block_compute_behind:false} + retained:vec![],attempted:vec![],fail_stops:0,allow_behind:false,block_render_behind:false,block_compute_behind:false, + ta_pending_calls:std::cell::Cell::new(0)} } #[cfg(test)]mod tests{ use super::*; @@ -438,7 +458,7 @@ def item(declaration): id,vm:vm1.clone(), queue:Queue::new(0,priority), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], + commands:vec![if render{Command::Render(R_LIGHT)}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], dependency:Ok(()),terminal_marked:AtomicBool::new(false),resources:Resources, }); // Head render (prio 2) is blocked behind active render flight; alt-class fallback @@ -557,7 +577,7 @@ def item(declaration): let mk_q=|id:u32,q:Arc,render:bool|Arc::new(Job{ id,vm:vm1.clone(),queue:q, progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], + commands:vec![if render{Command::Render(R_LIGHT)}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], dependency:Ok(()),terminal_marked:AtomicBool::new(false),resources:Resources, }); // q1 has blocked render job 1 followed by compute job 2 on the SAME queue q1; @@ -620,21 +640,57 @@ def item(declaration): assert_eq!(f.session.rings,[Channel::Compute,Channel::Fs,Channel::Ta]); } #[test]fn ta_wave_pacing_flushes_doorbell_at_four_passes_and_arms_ta_wave_wait(){ + // Heavy renders fill TA_WAVE_PASSES (4) and ring FS+TA immediately; pass 5 pauses. let vm1=mk_vm(1); - let mut jobs:Vec>=(1..=5).map(|id|job_on_vm(id,vm1.clone(),true,0,Ok(()))).collect(); - jobs.push(job_on_vm(6,vm1,false,0,Ok(()))); + let mut jobs:Vec>=(1..=5).map(|id|job_on_vm_mode(id,vm1.clone(),true,true,0,Ok(()))).collect(); + jobs.push(job_on_vm(6,vm1.clone(),false,0,Ok(()))); let stages=vec![(Ok(()),true);5]; let mut f=firmware(jobs,stages); f.allow_behind=true; let mut done=vec![]; assert_eq!(f.publish_checked(&mut done),Ok(())); - // Passes 1..4 fill TA_WAVE_PASSES (4) and ring FS+TA immediately; pass 5 pauses with - // ta_wave_wait=true while alt compute job 6 still publishes on Compute. assert_eq!(f.attempted,[1,2,3,4,6]); assert_eq!(f.session.rings,[Channel::Fs,Channel::Ta,Channel::Compute]); assert!(f.engine.ta_wave_wait); assert!(!f.engine.slot_wait); assert_eq!(f.engine.pending.len(),1); + + // Light renders fill TA_WAVE_PASSES_LIGHT (8) and ring FS+TA immediately; pass 9 pauses. + let mut light_jobs:Vec>=(1..=9).map(|id|job_on_vm_mode(id,vm1.clone(),true,false,0,Ok(()))).collect(); + light_jobs.push(job_on_vm(10,vm1,false,0,Ok(()))); + let mut fl=firmware(light_jobs,vec![(Ok(()),true);9]); + fl.allow_behind=true; + assert_eq!(fl.publish_checked(&mut done),Ok(())); + assert_eq!(fl.attempted,[1,2,3,4,5,6,7,8,10]); + assert_eq!(fl.session.rings,[Channel::Fs,Channel::Ta,Channel::Compute]); + assert!(fl.engine.ta_wave_wait); + assert!(!fl.engine.slot_wait); + assert_eq!(fl.engine.pending.len(),1); + } + #[test]fn publish_checked_d64_blocked_single_queue_hoists_ta_pending_and_skips_same_queue_in_o1(){ + let vm1=mk_vm(1); + let q1=Queue::new(0,0); + let mk=|id:u32|Arc::new(Job{ + id,vm:vm1.clone(),queue:q1.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Render(R_LIGHT)], + dependency:Ok(()),terminal_marked:AtomicBool::new(false),resources:Resources, + }); + let pending:Vec>=(9..=68).map(mk).collect(); + let mut f=firmware(pending,vec![]); + for id in 1..=8 { + let mut fl=Flight::new(mk(id)); + fl.renders=1; + f.engine.flights.push(fl); + } + f.allow_behind=true; + let mut done=vec![]; + assert_eq!(f.publish_checked(&mut done),Ok(())); + assert!(f.attempted.is_empty()); + assert!(f.engine.ta_wave_wait); + assert_eq!(f.engine.pending.len(),60); + // Hoisted ta_pending + O(1) same-queue skip reads TA stamp at most once across 60 jobs. + assert_eq!(f.ta_pending_calls.get(),1); } #[test]fn same_queue_independent_compute_bypasses_ta_wave_paused_render_only(){ let vm1=mk_vm(1); @@ -642,14 +698,15 @@ def item(declaration): let mk=|id:u32,render:bool,query_access:bool,dep:Result|Arc::new(Job{ id,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access,rt:false})}], + commands:vec![if render{Command::Render(R_HEAVY)}else{Command::Compute(ComputeCommand{query_access,rt:false})}], dependency:dep,terminal_marked:AtomicBool::new(false),resources:Resources, }); - // Seed 4 active TA passes so TA wave pacing is active. + // Seed 4 active heavy TA passes so TA wave pacing is active. let mut active_flights=Vec::new(); for id in 1..=4 { let mut fl=Flight::new(mk(id,true,false,Ok(()))); fl.renders=1; + fl.heavy_render=true; active_flights.push(fl); } // On q1: render 9 is TA-wave paused; independent !query_access compute 10 bypasses it. @@ -731,7 +788,7 @@ def item(declaration): struct QueueBehindRenderGraph{fw_stamp:[QueueBehindStamp;2]} struct QueueBehindGraph{render:QueueBehindRenderGraph} impl QueueBehindGraph{fn new()->Self{Self{render:QueueBehindRenderGraph{fw_stamp:[QueueBehindStamp::new(0),QueueBehindStamp::new(0)]}}}} -struct QueueBehindFlight{job:Arc,group:Vec>,first:usize,count:usize,computes:u32,renders:u32,compute_pipe:u8,rt_compute:bool,target:u32,cstamp:[u32;16],r_ta_stamp:[u32;16],r_fs_stamp:[u32;16],fs_target:u32,initbm:bool,has_timestamps:bool,doomed:bool,recovery_suspect:bool} +struct QueueBehindFlight{job:Arc,group:Vec>,first:usize,count:usize,computes:u32,renders:u32,compute_pipe:u8,rt_compute:bool,heavy_render:bool,published_ns:u64,target:u32,cstamp:[u32;16],r_ta_stamp:[u32;16],r_fs_stamp:[u32;16],fs_target:u32,initbm:bool,has_timestamps:bool,doomed:bool,recovery_suspect:bool} struct QueueBehindEngine{ordinal:u64,draw:u64,ta_target:u32,next_compute_pipe:u8,flights:Vec} struct QueueBehindSlots{compute_exhausted:bool,render_exhausted:bool,compute_available:bool,pass_available:bool} impl QueueBehindSlots{ @@ -794,11 +851,14 @@ def item(declaration): __NEEDS_ENGINE_DRAIN__ __BLOCKED_ON_SLOT_HEADROOM__ __TA_PENDING_PASSES__ + __TA_WAVE_CAP_FOR__ __CAN_QUEUE_BEHIND__ + __CAN_QUEUE_BEHIND_WITH_TA__ __WAIT_STAMP_FOR_WITH__ __WAIT_STAMP_FOR__ __CROSS_ENGINE_WAIT__ __WAIT_COMPUTE_STAMPS_FOR__ + __COMPUTE_QUEUE_IS_HEAVY__ __CHOOSE_COMPUTE_PIPE__ } #[test]fn timed_compute_queues_behind_same_vm_and_coexists_with_render(){ @@ -807,7 +867,7 @@ def item(declaration): let q1=Queue::new(0,0); let mk=|id:u32,vm:Arc,queue:Arc,render:bool|Arc::new(QueueBehindJob{ id,vm,queue,progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:true,rt:false})}], + commands:vec![if render{Command::Render(R_LIGHT)}else{Command::Compute(ComputeCommand{query_access:true,rt:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -817,7 +877,7 @@ def item(declaration): let j_render=mk(4,vm1.clone(),q1.clone(),true); let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:j1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:j1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; @@ -859,7 +919,7 @@ def item(declaration): order:Order{engine:command::COMPUTE,sequence:u64::from(id),wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); - let flight=|job:Arc,rt_compute:bool,compute_pipe:u8|QueueBehindFlight{job,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe,rt_compute,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}; + let flight=|job:Arc,rt_compute:bool,compute_pipe:u8|QueueBehindFlight{job,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe,rt_compute,heavy_render:false,published_ns:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}; let rq=mk(1,vm1.clone(),q1.clone(),true); let rq_next=mk(2,vm1.clone(),q1.clone(),true); let rq_post=mk(3,vm1.clone(),q1.clone(),false); @@ -917,7 +977,7 @@ def item(declaration): let other_queue=mk(2,q2.clone(),true,None,Some(1)); let p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:timed,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:timed,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false}]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; @@ -929,13 +989,13 @@ def item(declaration): let timed_render=Arc::new(QueueBehindJob{ id:1,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![Command::Render(())], + commands:vec![Command::Render(R_LIGHT)], order:Order{engine:command::RENDER,sequence:1,wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let pr=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:timed_render,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:timed_render,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false}]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; @@ -949,7 +1009,7 @@ def item(declaration): let q1=Queue::new(0,0); let mk=|id:u32,vm:Arc,render:bool|Arc::new(QueueBehindJob{ id,vm,queue:q1.clone(),progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:true,rt:false})}], + commands:vec![if render{Command::Render(R_LIGHT)}else{Command::Compute(ComputeCommand{query_access:true,rt:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -959,7 +1019,7 @@ def item(declaration): let c1=mk(4,vm1.clone(),false); let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; @@ -994,7 +1054,7 @@ def item(declaration): let q2=Queue::new(0,0); let mk=|id:u32,vm:Arc,queue:Arc,render:bool|Arc::new(QueueBehindJob{ id,vm,queue,progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], + commands:vec![if render{Command::Render(R_LIGHT)}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -1003,7 +1063,7 @@ def item(declaration): let vm2_r=mk(3,vm2.clone(),q2.clone(),true); let vm2_c=mk(4,vm2.clone(),q2.clone(),false); let mk_flight=|job:Arc,c:u32,r:u32|QueueBehindFlight{ - job,group:vec![],first:0,count:1,computes:c,renders:r,compute_pipe:0,rt_compute:false, + job,group:vec![],first:0,count:1,computes:c,renders:r,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0, target:if c!=0{0x100}else{0},cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a}, fs_target:if r!=0{0x200}else{0},initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }; @@ -1036,7 +1096,7 @@ def item(declaration): let mk=|id:u32,queue:Arc,render:bool,seq:u64,wait:[Option;2]|Arc::new(QueueBehindJob{ id,vm:vm1.clone(),queue, progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], + commands:vec![if render{Command::Render(R_LIGHT)}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:seq,wait_through:wait}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -1048,8 +1108,8 @@ def item(declaration): let p=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![ - QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x500;a},fs_target:0x500,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, - QueueBehindFlight{job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,target:0x700,cstamp:{let mut a=[0;16];a[0]=0x700;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, + QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x500;a},fs_target:0x500,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, + QueueBehindFlight{job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x700,cstamp:{let mut a=[0;16];a[0]=0x700;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, ]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, @@ -1085,7 +1145,7 @@ def item(declaration): let pm=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:3,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![ - QueueBehindFlight{job:multi_c,group:vec![],first:0,count:3,computes:3,renders:0,compute_pipe:0,rt_compute:false,target:0x300,cstamp,r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, + QueueBehindFlight{job:multi_c,group:vec![],first:0,count:3,computes:3,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x300,cstamp,r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, ]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, @@ -1108,7 +1168,7 @@ def item(declaration): let mk=|id:u32,render:bool,seq:u64,wait:[Option;2]|Arc::new(QueueBehindJob{ id,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], + commands:vec![if render{Command::Render(R_LIGHT)}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:seq,wait_through:wait}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -1118,7 +1178,7 @@ def item(declaration): let host=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ - job:r_initbm,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,target:0, + job:r_initbm,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0, cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x900;a},fs_target:0x900, initbm:true,has_timestamps:false,doomed:false,recovery_suspect:false, }]}, @@ -1157,14 +1217,14 @@ def item(declaration): let r_job=Arc::new(QueueBehindJob{ id:2,vm:vm1.clone(),queue:q_rend.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![Command::Render(())], + commands:vec![Command::Render(R_LIGHT)], order:Order{engine:command::RENDER,sequence:1,wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:1,draw:0,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ - job:c_job.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, + job:c_job.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, @@ -1175,7 +1235,7 @@ def item(declaration): assert_eq!(p.cross_engine_wait(&r_job,0,command::COMPUTE),Ok(None)); // Symmetrically, Queue 0 compute queues directly behind Queue 1 render on the same VM. p.engine.flights[0]=QueueBehindFlight{ - job:r_job,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200, + job:r_job,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }; assert!(p.can_queue_behind(&c_job)); @@ -1187,7 +1247,7 @@ def item(declaration): let mk=|id:u32,render:bool,seq:u64,wait:[Option;2]|Arc::new(QueueBehindJob{ id,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], + commands:vec![if render{Command::Render(R_LIGHT)}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:seq,wait_through:wait}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -1202,7 +1262,7 @@ def item(declaration): let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:3,draw:0,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ - job:c1,group:vec![c2,c3],first:0,count:1,computes:3,renders:0,compute_pipe:0,rt_compute:false,target:0x300,cstamp,r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, + job:c1,group:vec![c2,c3],first:0,count:1,computes:3,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x300,cstamp,r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, @@ -1221,7 +1281,7 @@ def item(declaration): let multi=Arc::new(QueueBehindJob{ id:1,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:3,pending:AtomicBool::new(true)}, - commands:vec![Command::Render(()),Command::Render(()),Command::Render(())], + commands:vec![Command::Render(R_LIGHT),Command::Render(R_LIGHT),Command::Render(R_LIGHT)], order:Order{engine:command::RENDER,sequence:1,wait_through:[None,None]}, extra_orders:vec![ Order{engine:command::RENDER,sequence:1,wait_through:[None,None]}, @@ -1233,7 +1293,7 @@ def item(declaration): let next_r=Arc::new(QueueBehindJob{ id:2,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![Command::Render(())], + commands:vec![Command::Render(R_LIGHT)], order:Order{engine:command::RENDER,sequence:4,wait_through:[Some(3),None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -1242,7 +1302,7 @@ def item(declaration): let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:0,draw:3,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ - job:multi.clone(),group:vec![],first:0,count:3,computes:0,renders:3,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:r_fs,fs_target:0x300, + job:multi.clone(),group:vec![],first:0,count:3,computes:0,renders:3,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:r_fs,fs_target:0x300, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, @@ -1257,7 +1317,7 @@ def item(declaration): let mut cur_fs=[0u32;16]; cur_fs[0]=0x400; let cur=QueueBehindFlight{ - job:next_r.clone(),group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:cur_fs,fs_target:0x400, + job:next_r.clone(),group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:cur_fs,fs_target:0x400, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }; assert_eq!(p.wait_stamp_for_with(&next_r,command::RENDER,Some(4),Some(&cur)),Ok(Some(WaitTarget{stamp:0x400,initbm:false}))); @@ -1265,21 +1325,21 @@ def item(declaration): let r_fold_a=Arc::new(QueueBehindJob{ id:10,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![Command::Render(())], + commands:vec![Command::Render(R_LIGHT)], order:Order{engine:command::RENDER,sequence:5,wait_through:[Some(4),None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let r_fold_b=Arc::new(QueueBehindJob{ id:11,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![Command::Render(())], + commands:vec![Command::Render(R_LIGHT)], order:Order{engine:command::RENDER,sequence:6,wait_through:[Some(5),None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let mut grp_fs=[0u32;16]; grp_fs[0]=0x400;grp_fs[1]=0x500;grp_fs[2]=0x600; let cur_grp=QueueBehindFlight{ - job:next_r.clone(),group:vec![r_fold_a.clone(),r_fold_b.clone()],first:0,count:1,computes:0,renders:3,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:grp_fs,fs_target:0x600, + job:next_r.clone(),group:vec![r_fold_a.clone(),r_fold_b.clone()],first:0,count:1,computes:0,renders:3,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:grp_fs,fs_target:0x600, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }; assert_eq!(p.wait_stamp_for_with(&r_fold_b,command::RENDER,Some(4),Some(&cur_grp)),Ok(Some(WaitTarget{stamp:0x400,initbm:false}))); @@ -1296,24 +1356,25 @@ def item(declaration): #[test]fn ta_pending_passes_paces_unfinished_ta_waves_without_throttling_finished_ta(){ let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); let q1=Queue::new(0,2); - let mk=|id:u32|Arc::new(QueueBehindJob{ + let mk=|id:u32,heavy:bool|Arc::new(QueueBehindJob{ id,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![Command::Render(())], + commands:vec![Command::Render(RenderCommand{heavy_ta:heavy})], order:Order{engine:command::RENDER,sequence:u64::from(id),wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); - let r_live=mk(1); - let next_r=mk(2); + let r_live=mk(1,false); + let next_light=mk(2,false); + let next_heavy=mk(3,true); let mut r_ta=[0u32;16]; - for i in 0..4 { + for i in 0..8 { r_ta[i]=(i as u32 + 1)*0x100; } let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:0,draw:4,ta_target:0x400,next_compute_pipe:0,flights:vec![QueueBehindFlight{ - job:r_live,group:vec![],first:0,count:4,computes:0,renders:3,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16], - r_ta_stamp:r_ta,r_fs_stamp:r_ta,fs_target:0x400, + engine:QueueBehindEngine{ordinal:0,draw:8,ta_target:0x800,next_compute_pipe:0,flights:vec![QueueBehindFlight{ + job:r_live,group:vec![],first:0,count:8,computes:0,renders:3,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16], + r_ta_stamp:r_ta,r_fs_stamp:r_ta,fs_target:0x800, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, @@ -1322,21 +1383,32 @@ def item(declaration): // Below TA_WAVE_PASSES (3 < 4): zero WC fw_stamp reads. assert_eq!(p.ta_pending_passes(),3); assert_eq!(p.graph.render.fw_stamp[0].reads.get(),0); - assert!(p.can_queue_behind(&next_r)); - // 4 unfinished TA passes: paces render queue_behind until TA advances. + assert!(p.can_queue_behind(&next_light)); + assert!(p.can_queue_behind(&next_heavy)); + // 4 unfinished TA passes: heavy render pauses at 4, light render keeps pipelining up to 8. p.engine.flights[0].renders=4; assert_eq!(p.ta_pending_passes(),4); assert!(p.graph.render.fw_stamp[0].reads.get()>0); - assert!(!p.can_queue_behind(&next_r)); - // Once pass 0 finishes TA (obs=0x100) while FS is still running, ta_pending drops to 3. + assert!(!p.can_queue_behind(&next_heavy)); + assert!(p.can_queue_behind(&next_light)); + // Heavy active flight also enforces conservative cap 4 on light followers. + p.engine.flights[0].heavy_render=true; + assert!(!p.can_queue_behind(&next_light)); + p.engine.flights[0].heavy_render=false; + // 8 unfinished light TA passes pauses light renders until TA advances. + p.engine.flights[0].renders=8; + assert_eq!(p.ta_pending_passes(),8); + assert!(!p.can_queue_behind(&next_light)); + // Once pass 0 finishes TA (obs=0x100) while FS is still running, ta_pending drops to 7. p.graph.render.fw_stamp[0].val.set(0x100); - assert_eq!(p.ta_pending_passes(),3); - assert!(p.can_queue_behind(&next_r)); - // Even with 16 active FS passes, finished TA (obs=0x400) leaves single-pass pipelining unthrottled. - p.graph.render.fw_stamp[0].val.set(0x400); + assert_eq!(p.ta_pending_passes(),7); + assert!(p.can_queue_behind(&next_light)); + // Even with 16 active FS passes, finished TA (obs=0x800) leaves single-pass pipelining unthrottled. + p.graph.render.fw_stamp[0].val.set(0x800); p.engine.flights[0].renders=16; assert_eq!(p.ta_pending_passes(),0); - assert!(p.can_queue_behind(&next_r)); + assert!(p.can_queue_behind(&next_light)); + assert!(p.can_queue_behind(&next_heavy)); } #[test]fn slot_wait_arms_only_for_same_vm_slot_or_flight_headroom_blocks(){ let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); @@ -1345,7 +1417,7 @@ def item(declaration): let mk=|id:u32,vm:Arc,render:bool,dep:Result,query_access:bool,wait:[Option;2]|Arc::new(QueueBehindJob{ id,vm,queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access,rt:false})}], + commands:vec![if render{Command::Render(R_LIGHT)}else{Command::Compute(ComputeCommand{query_access,rt:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:wait}, extra_orders:vec![],dependency:dep,resources:Resources,fw_waits:vec![], }); @@ -1357,7 +1429,7 @@ def item(declaration): let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ - job:r_live,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16], + job:r_live,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16], r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x100;a},fs_target:0x100, initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false, }]}, @@ -1696,37 +1768,62 @@ def item(declaration): let c1=mk(1,vm1.clone(),q1.clone(),1); let c2=mk(2,vm1.clone(),q1.clone(),2); let c_vm2=mk(3,vm2.clone(),q2.clone(),1); + let q3=Queue::new(0,2); let mut host=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:0,draw:0,ta_target:0,next_compute_pipe:0,flights:vec![]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; - // Empty engine uses next_compute_pipe (0), then balances onto pipe 1 while pipe 0 is active. - assert_eq!(host.choose_compute_pipe([None, None], (1u32 << 24) - 1, false), 0); + // Empty engine uses next_compute_pipe (0). + assert_eq!(host.choose_compute_pipe(&q1, [None, None], (1u32 << 24) - 1, false, false), 0); host.engine.flights.push(QueueBehindFlight{ - job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,target:0x100, + job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:1_000_000,target:0x100, cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false, has_timestamps:false,doomed:false,recovery_suspect:false, }); - assert_eq!(host.choose_compute_pipe([None, None], (1u32 << 24) - 1, false), 1); - // RT/SCS compute stays pinned to pipe 0 even while pipe 0 is active. - assert_eq!(host.choose_compute_pipe([None, None], (1u32 << 24) - 1, true), 0); - // A 2-unit base-only VM stays pinned to pipe 0 even while pipe 0 is active. - assert_eq!(host.choose_compute_pipe([None, None], 0b11, false), 0); - assert_eq!(host.choose_compute_pipe([None, None], 0b110, false), 0); + // Cold-start heavy probe: sole single-command compute flight becomes heavy at >= 180 us. + assert!(!host.compute_queue_is_heavy(&q1, 1_179_999)); + assert!(host.compute_queue_is_heavy(&q1, 1_180_000)); + // Folded multi-command light flight does not trigger the cold-start probe. + host.engine.flights[0].computes = 3; + assert!(!host.compute_queue_is_heavy(&q1, 2_000_000)); + host.engine.flights[0].computes = 1; + // Per-queue retired hardware CDM EWMA transitions cleanly at 200 us. + q1.note_compute_us(30); + assert!(!host.compute_queue_is_heavy(&q1, 1_050_000)); + q1.note_compute_us(500); + assert!(host.compute_queue_is_heavy(&q1, 1_050_000)); + q1.note_compute_us(20); + assert!(!host.compute_queue_is_heavy(&q1, 1_050_000)); + q1.compute_ewma_us.store(0, Ordering::Relaxed); + // Light single-queue barrier-free compute stays affine to its active pipe (pipe 0), + // while heavy single-queue compute and a second independent queue balance onto idle pipe 1. + assert_eq!(host.choose_compute_pipe(&q1, [None, None], (1u32 << 24) - 1, false, false), 0); + assert_eq!(host.choose_compute_pipe(&q1, [None, None], (1u32 << 24) - 1, false, true), 1); + assert_eq!(host.choose_compute_pipe(&q2, [None, None], (1u32 << 24) - 1, false, false), 1); + // RT/SCS compute stays pinned to pipe 0 even for another queue or heavy compute. + assert_eq!(host.choose_compute_pipe(&q2, [None, None], (1u32 << 24) - 1, true, true), 0); + // A 2-unit base-only or SCS VM (bits < PIPE1_COMPUTE_START) stays pinned to pipe 0. + assert_eq!(host.choose_compute_pipe(&q2, [None, None], 0b11, false, true), 0); + assert_eq!(host.choose_compute_pipe(&q2, [None, None], 0b110, false, true), 0); assert!(host.can_queue_behind(&c2)); - // Add second concurrent flight on pipe 1: both pipes active, - // tie-break uses next_compute_pipe, and cross-VM compute overlaps cleanly. + // Add second concurrent flight on pipe 1 from q2: both pipes active, + // q1 stays affine to pipe 0, q2 stays affine to pipe 1, and a third queue q3 + // tie-breaks by next_compute_pipe. host.engine.flights.push(QueueBehindFlight{ - job:c2.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:1,rt_compute:false,target:0x100, + job:c_vm2.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:1,rt_compute:false,heavy_render:false,published_ns:1_000_000,target:0x100, cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false, has_timestamps:false,doomed:false,recovery_suspect:false, }); + assert_eq!(host.choose_compute_pipe(&q1, [None, None], (1u32 << 24) - 1, false, false), 0); + assert_eq!(host.choose_compute_pipe(&q2, [None, None], (1u32 << 24) - 1, false, false), 1); host.engine.next_compute_pipe=1; - assert_eq!(host.choose_compute_pipe([None, None], (1u32 << 24) - 1, false), 1); + assert_eq!(host.choose_compute_pipe(&q3, [None, None], (1u32 << 24) - 1, false, false), 1); + assert_eq!(host.choose_compute_pipe(&q1, [None, None], (1u32 << 24) - 1, false, true), 1); host.engine.next_compute_pipe=0; - assert_eq!(host.choose_compute_pipe([None, None], (1u32 << 24) - 1, false), 0); + assert_eq!(host.choose_compute_pipe(&q3, [None, None], (1u32 << 24) - 1, false, false), 0); + assert_eq!(host.choose_compute_pipe(&q1, [None, None], (1u32 << 24) - 1, false, true), 0); assert!(host.can_queue_behind(&c_vm2)); // Same-VM compute still pipelines without draining. assert!(host.can_queue_behind(&c2)); @@ -1749,12 +1846,12 @@ def item(declaration): graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:2,draw:0,ta_target:0,next_compute_pipe:0,flights:vec![ QueueBehindFlight{ - job:c1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,target:0x100, + job:c1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x100, cstamp:{let mut a=[0;16];a[0]=0x100;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }, QueueBehindFlight{ - job:c2,group:vec![],first:0,count:1,computes:2,renders:0,compute_pipe:1,rt_compute:false,target:0x200, + job:c2,group:vec![],first:0,count:1,computes:2,renders:0,compute_pipe:1,rt_compute:false,heavy_render:false,published_ns:0,target:0x200, cstamp:{let mut a=[0;16];a[0]=0x200;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }, @@ -1767,13 +1864,13 @@ def item(declaration): // Waiting on seq 1 (pipe 0 only) returns [Some(0x100), None] and reuses pipe 0 (zero c2c barrier). let w1 = host.wait_compute_stamps_for(&c3, Some(1)).unwrap(); assert_eq!(w1, [Some(WaitTarget{stamp:0x100,initbm:false}), None]); - assert_eq!(host.choose_compute_pipe(w1, (1u32 << 24) - 1, false), 0); + assert_eq!(host.choose_compute_pipe(&q1, w1, (1u32 << 24) - 1, false, true), 0); // Waiting on seq 2 (both pipe 0 seq 1 and pipe 1 seq 2 <= 2) returns both stamps and // selects the least-loaded pipe (pipe 0 has 1 active vs pipe 1 has 2 -> picks pipe 0, // so prefix_compute emits one cross-pipe c2c barrier on pipe 1's 0x200). let w2 = host.wait_compute_stamps_for(&c4, Some(2)).unwrap(); assert_eq!(w2, [Some(WaitTarget{stamp:0x100,initbm:false}), Some(WaitTarget{stamp:0x200,initbm:false})]); - assert_eq!(host.choose_compute_pipe(w2, (1u32 << 24) - 1, false), 0); + assert_eq!(host.choose_compute_pipe(&q1, w2, (1u32 << 24) - 1, false, false), 0); // Unpublished seq 3 returns Err(EAGAIN). assert_eq!(host.wait_compute_stamps_for(&c4, Some(3)), Err(EAGAIN)); // If seq 2 retired out-of-order on pipe 1 while seq 1 is still active on pipe 0, @@ -1784,7 +1881,7 @@ def item(declaration): assert!(q1.is_compute_retired(2)); let w2_ooo = host.wait_compute_stamps_for(&c4, Some(2)).unwrap(); assert_eq!(w2_ooo, [Some(WaitTarget{stamp:0x100,initbm:false}), None]); - assert_eq!(host.choose_compute_pipe(w2_ooo, (1u32 << 24) - 1, false), 0); + assert_eq!(host.choose_compute_pipe(&q1, w2_ooo, (1u32 << 24) - 1, false, true), 0); // Once contiguous completed[COMPUTE] reaches 2, wait_compute_stamps_for returns [None, None]. q1.completed[command::COMPUTE].store(2, Ordering::Release); q1.compute_ooo.store(0, Ordering::Release); @@ -1804,7 +1901,7 @@ def item(declaration): let r1=Arc::new(QueueBehindJob{ id:2,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![Command::Render(())], + commands:vec![Command::Render(R_LIGHT)], order:Order{engine:command::RENDER,sequence:1,wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -1828,12 +1925,12 @@ def item(declaration): graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![ QueueBehindFlight{ - job:c1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,target:0x100, + job:c1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x100, cstamp:{let mut a=[0;16];a[0]=0x100;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false, }, QueueBehindFlight{ - job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,target:0, + job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0, cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }, @@ -1844,7 +1941,7 @@ def item(declaration): // Cross-queue compute wait resolves pipe 0 stamp 0x100 and keeps q2 on pipe 0 (zero c2c). let cw=host.wait_compute_stamps_for(&c2_wait_q1,None).unwrap(); assert_eq!(cw,[Some(WaitTarget{stamp:0x100,initbm:false}),None]); - assert_eq!(host.choose_compute_pipe(cw,(1u32<<24)-1,false),0); + assert_eq!(host.choose_compute_pipe(&q2,cw,(1u32<<24)-1,false,false),0); // Cross-queue render wait resolves q1's FS stamp 0x200. assert_eq!(host.wait_stamp_for(&c2_wait_q1,command::RENDER,None),Ok(Some(WaitTarget{stamp:0x200,initbm:false}))); // query_access compute waiting via fw_waits on a timestamped q1 flight must wait to retire; @@ -2506,6 +2603,196 @@ def item(declaration): assert_eq!(fw.recovery_prepare(1, 16, 0x300, [0, 0, 0, 0]), Err(ENOENT)); } } +mod busy_coalesce_scope { + use super::{Arc, AtomicBool, AtomicU32, Command, ComputeCommand, Order, Ordering, Progress, Queue, Recovery, RenderCommand, Result, Status, Vm}; + mod params { + pub fn compute_flights() -> usize { 23 } + pub fn render_flights() -> usize { 47 } + } + struct Resources { units: usize, scs: bool } + impl Resources { + fn compute_slot_mask(&self) -> Result { + Ok(if self.units >= 32 { u32::MAX } else { (1u32 << self.units) - 1 }) + } + fn compute_scs(&self) -> bool { self.scs } + fn render_scs(&self) -> bool { self.scs } + } + struct Job { + vm: Arc, + queue: Arc, + progress: Progress, + commands: Vec, + orders: Vec, + fw_waits: Vec<()>, + resources: Resources, + is_long: bool, + foldable: bool, + } + impl Job { + fn long(&self) -> bool { self.is_long } + fn command_order(&self, idx: u32) -> Option { self.orders.get(idx as usize).copied() } + fn can_fold_horizon_cmd(&self, idx: u32, expected: u64) -> bool { + self.foldable + && self.orders.get(idx as usize).is_some_and(|o| o.engine == crate::command::COMPUTE && o.sequence == expected && o.wait_through == [None, None]) + } + fn can_fold_horizon_job(&self, first: u64) -> bool { + self.foldable + && self.orders.iter().enumerate().all(|(i, o)| o.engine == crate::command::COMPUTE && o.sequence == first + i as u64 && o.wait_through == [None, None]) + } + fn can_fold_render_cmd(&self, idx: u32, expected: u64) -> bool { + self.foldable + && self.orders.get(idx as usize).is_some_and(|o| o.engine == crate::command::RENDER && o.sequence == expected) + } + fn can_fold_render_horizon_job(&self, first: u64) -> bool { + self.foldable + && self.orders.iter().enumerate().all(|(i, o)| o.engine == crate::command::RENDER && o.sequence == first + i as u64) + } + } + fn command(job: &Job, k: u32) -> Option<&Command> { job.commands.get(k as usize) } + struct Flight { + job: Arc, + computes: u32, + renders: u32, + compute_pipe: u8, + published_ns: u64, + doomed: bool, + recovery_suspect: bool, + initbm: bool, + heavy_render: bool, + } + struct Engine { + flights: Vec, + pending: Vec>, + frozen: bool, + chan_wait: bool, + slot_wait: bool, + ta_wave_wait: bool, + coalesce_deadline_ns: u64, + } + struct Slots { free_c: u32 } + impl Slots { + fn free_compute_in_mask_for_pipe(&self, _m: u32, _p: usize) -> u32 { self.free_c } + } + struct Host { + recovery: Recovery, + engine: Engine, + slots: Slots, + allow_behind: bool, + ta_pending: usize, + } + impl Host { + fn can_queue_behind(&self, _job: &Arc) -> bool { self.allow_behind } + fn choose_compute_pipe(&self, _q: &Arc, _w: [Option<()>; 2], _m: u32, _rt: bool, _heavy: bool) -> usize { 0 } + fn ta_pending_passes(&self) -> usize { self.ta_pending } + __COMPUTE_QUEUE_IS_HEAVY__ + __TA_WAVE_CAP_FOR__ + __CAN_DEFER_BUSY_COALESCE__ + __DEFER_BUSY_COALESCE__ + } + fn mk_job_mode(vm: &Arc, q: &Arc, render: bool, heavy: bool, seq: u64, wait: [Option; 2]) -> Arc { + Arc::new(Job { + vm: vm.clone(), + queue: q.clone(), + progress: Progress { sent: AtomicU32::new(0), count: 1, pending: AtomicBool::new(true) }, + commands: vec![if render { Command::Render(RenderCommand { heavy_ta: heavy }) } else { Command::Compute(ComputeCommand { query_access: false, rt: false }) }], + orders: vec![Order { engine: if render { crate::command::RENDER } else { crate::command::COMPUTE }, sequence: seq, wait_through: wait }], + fw_waits: vec![], + resources: Resources { units: 24, scs: false }, + is_long: false, + foldable: true, + }) + } + fn mk_job(vm: &Arc, q: &Arc, render: bool, seq: u64, wait: [Option; 2]) -> Arc { + mk_job_mode(vm, q, render, false, seq, wait) + } + #[test] + fn busy_coalesce_holds_deep_single_queue_bursts_and_never_delays_shallow_or_other_queues() { + let vm1 = Arc::new(Vm { status: Status(AtomicU32::new(0)), slot: 1 }); + let q1 = Queue::new(0, 2); + let q2 = Queue::new(0, 2); + let c1 = mk_job(&vm1, &q1, false, 1, [None, None]); + let mut h = Host { + recovery: Recovery { error: None, publication_wait_deadline: None }, + engine: Engine { + flights: vec![Flight { job: c1.clone(), computes: 1, renders: 0, compute_pipe: 0, published_ns: 90_000, doomed: false, recovery_suspect: false, initbm: false, heavy_render: false }], + pending: vec![mk_job(&vm1, &q1, false, 2, [None, None])], + frozen: false, + chan_wait: false, + slot_wait: false, + ta_wave_wait: false, + coalesce_deadline_ns: 0, + }, + slots: Slots { free_c: 20 }, + allow_behind: true, + ta_pending: 0, + }; + // d=2 (queue_active == 1 < 2): ZERO coalescing delay. + assert_eq!(h.defer_busy_coalesce(100_000), None); + + // Once queue_active >= 2, barrier-free compute holds up to 18 us and accumulates up to K=6. + h.engine.flights[0].computes = 2; + h.engine.pending = vec![mk_job(&vm1, &q1, false, 3, [None, None])]; + assert_eq!(h.defer_busy_coalesce(100_000), Some(18)); + assert_eq!(h.engine.coalesce_deadline_ns, 118_000); + // Second job arrives 5 us later -> remaining 13 us. + h.engine.pending.push(mk_job(&vm1, &q1, false, 4, [None, None])); + assert_eq!(h.defer_busy_coalesce(105_000), Some(13)); + // Reaching K=6 pending commands flushes immediately. + for seq in 5..=8 { + h.engine.pending.push(mk_job(&vm1, &q1, false, seq, [None, None])); + } + assert_eq!(h.defer_busy_coalesce(110_000), None); + assert_eq!(h.engine.coalesce_deadline_ns, 0); + + // Deadline expiry flushes even with 1 pending command. + h.engine.pending = vec![mk_job(&vm1, &q1, false, 3, [None, None])]; + assert_eq!(h.defer_busy_coalesce(200_000), Some(18)); + assert_eq!(h.defer_busy_coalesce(218_000), None); + assert_eq!(h.engine.coalesce_deadline_ns, 0); + + // Another queue arriving in pending flushes immediately (no cross-queue head-of-line delay). + assert_eq!(h.defer_busy_coalesce(300_000), Some(18)); + h.engine.pending.push(mk_job(&vm1, &q2, false, 1, [None, None])); + assert_eq!(h.defer_busy_coalesce(302_000), None); + + // Barriered compute flushes immediately (0 delay). + h.engine.pending = vec![mk_job(&vm1, &q1, false, 3, [None, Some(2)])]; + assert_eq!(h.defer_busy_coalesce(400_000), None); + + // Heavy compute queue (EWMA >= 200 us) bypasses busy coalescing so 2-pipe fanout runs immediately. + h.engine.pending = vec![mk_job(&vm1, &q1, false, 3, [None, None])]; + q1.note_compute_us(500); + assert_eq!(h.defer_busy_coalesce(420_000), None); + q1.compute_ewma_us.store(25, Ordering::Relaxed); + assert_eq!(h.defer_busy_coalesce(420_000), Some(18)); + + // Active flight from another queue bypasses busy coalescing immediately (multi-queue/async_cr). + let r_other = mk_job(&vm1, &q2, true, 1, [None, None]); + h.engine.flights.push(Flight { job: r_other, computes: 0, renders: 1, compute_pipe: 0, published_ns: 410_000, doomed: false, recovery_suspect: false, initbm: false, heavy_render: false }); + assert_eq!(h.defer_busy_coalesce(425_000), None); + h.engine.flights.pop(); + + // Light render with queue_active == 2 and ta_pending == 2 (wave_cap 8 -> ta_room 6) + // coalesces up to K=6 passes before flushing. + let r1 = mk_job(&vm1, &q1, true, 1, [None, None]); + h.engine.flights = vec![Flight { job: r1, computes: 0, renders: 2, compute_pipe: 0, published_ns: 490_000, doomed: false, recovery_suspect: false, initbm: false, heavy_render: false }]; + h.ta_pending = 2; + h.engine.pending = vec![mk_job(&vm1, &q1, true, 3, [Some(2), None])]; + assert_eq!(h.defer_busy_coalesce(500_000), Some(18)); + for seq in 4..=7 { + h.engine.pending.push(mk_job(&vm1, &q1, true, seq, [Some(seq - 1), None])); + assert_eq!(h.defer_busy_coalesce(502_000), Some(16)); + } + h.engine.pending.push(mk_job(&vm1, &q1, true, 8, [Some(7), None])); + assert_eq!(h.defer_busy_coalesce(505_000), None); + + // Heavy render keeps conservative wave_cap 4 (ta_room == 2): holds 1 pass, flushes at 2. + h.engine.pending = vec![mk_job_mode(&vm1, &q1, true, true, 3, [Some(2), None])]; + assert_eq!(h.defer_busy_coalesce(600_000), Some(18)); + h.engine.pending.push(mk_job_mode(&vm1, &q1, true, true, 4, [Some(3), None])); + assert_eq!(h.defer_busy_coalesce(605_000), None); + } +} ''' harness = harness.replace('__LOGIC__', str(production.parent / 'recovery/logic.rs')) harness = harness.replace('__USAGE__', str(production.parent.parent / 'usage.rs')) @@ -2516,6 +2803,7 @@ def item(declaration): harness = harness.replace('__QUEUE_CREDIT_STRUCT__', item_in(queue_src, 'struct QueueCredit {')) harness = harness.replace('__QUEUE_CREDIT_IMPL__', item_in(queue_src, 'impl QueueCredit {')) harness = harness.replace('__QUEUE_CREDIT_DROP__', item_in(queue_src, 'impl Drop for QueueCredit {')) +harness = harness.replace('__NOTE_COMPUTE_US__', item_in(queue_src, 'pub(crate) fn note_compute_us(')) harness = harness.replace( '__CAN_FOLD_CMD__', item_in(job_src, 'pub(crate) fn can_fold_horizon_cmd(') @@ -2564,11 +2852,17 @@ def item(declaration): '__DESCRIPTOR_CONTAINMENT__': 'if encode::preserve_compute_descriptor(', '__PUBLISH_PRODUCER__': 'fn publish_producer(', '__TA_PENDING_PASSES__': 'pub(crate) fn ta_pending_passes(', + '__TA_WAVE_CAP_FOR__': 'fn ta_wave_cap_for(', + '__ACTIVE_TA_WAVE_CAP__': 'pub(crate) fn active_ta_wave_cap(', '__CAN_QUEUE_BEHIND__': 'fn can_queue_behind(', + '__CAN_QUEUE_BEHIND_WITH_TA__': 'fn can_queue_behind_with_ta(', + '__CAN_DEFER_BUSY_COALESCE__': 'fn can_defer_busy_coalesce(', + '__DEFER_BUSY_COALESCE__': 'pub(crate) fn defer_busy_coalesce(', '__WAIT_STAMP_FOR_WITH__': 'fn wait_stamp_for_with(', '__WAIT_STAMP_FOR__': 'fn wait_stamp_for(', '__CROSS_ENGINE_WAIT__': 'fn cross_engine_wait(', '__WAIT_COMPUTE_STAMPS_FOR__': 'fn wait_compute_stamps_for(', + '__COMPUTE_QUEUE_IS_HEAVY__': 'fn compute_queue_is_heavy(', '__CHOOSE_COMPUTE_PIPE__': 'fn choose_compute_pipe(', '__SCS_COMPUTE_CONFLICT__': 'fn scs_compute_conflict(', '__WAIT_TARGET__': 'struct WaitTarget {', diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py index 2df865d4f856a..5aa9f7afbabfd 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -119,21 +119,29 @@ def module(text, name): pub fn objects(&self,_:&super::vm::MockVm)->Objects{Objects::new()} pub fn fw_objects(&self)->Objects{Objects::new()} pub fn persistent_objects(&self)->Objects{Objects::persistent()} + pub fn persistent_objects_probe(&self)->Objects{Objects::persistent()} } pub static NEXT_VA: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0xfffffc2001000000); std::thread_local!{pub static ALL_OBJECTS:std::cell::RefCell>>=const{std::cell::RefCell::new(Vec::new())};} pub struct Objects{pub objects:Vec>,pub persistent:bool} - // Device-lifetime render records of each pass slot index, per test thread (the - // production table is resources::RenderCmds): one never-dropped allocator owns them. + // Device-lifetime render and compute command records, per test thread (the production + // tables are resources::RenderCmds and resources::ComputeCmds): one never-dropped + // allocator owns them. std::thread_local!{ pub static PERSISTENT:std::cell::RefCell>=const{std::cell::RefCell::new(None)}; pub static PASS_CMDS:std::cell::RefCell>=const{std::cell::RefCell::new(Vec::new())}; + pub static UNIT_CMDS:std::cell::RefCell>=const{std::cell::RefCell::new(Vec::new())}; } pub fn test_cmds(k:u64)->crate::g16::slots::PassCmds{ if let Some(c)=PASS_CMDS.with(|p|p.borrow().iter().find(|e|e.0==k).map(|e|e.1.clone())){return c;} let c=PERSISTENT.with(|p|{let mut p=p.borrow_mut();crate::g16::slots::PassCmds::new(p.get_or_insert_with(Objects::persistent),k).unwrap()}); PASS_CMDS.with(|p|p.borrow_mut().push((k,c.clone())));c } + pub fn test_unit_cmds(k:u64)->crate::g16::slots::UnitCmds{ + if let Some(c)=UNIT_CMDS.with(|p|p.borrow().iter().find(|e|e.0==k).map(|e|e.1.clone())){return c;} + let c=PERSISTENT.with(|p|{let mut p=p.borrow_mut();crate::g16::slots::UnitCmds::new(p.get_or_insert_with(Objects::persistent)).unwrap()}); + UNIT_CMDS.with(|p|p.borrow_mut().push((k,c.clone())));c + } impl Objects{ pub fn new()->Self{Self{objects:vec![],persistent:false}} pub fn persistent()->Self{Self{objects:vec![],persistent:true}} @@ -287,7 +295,7 @@ def module(text, name): fn arenas(o:&mut Objects)->Arenas{ let mut compute=KVec::new();let mut passes=KVec::new(); let f=g16::object::Factory; - for k in 0..2{compute.push(g16::slots::ComputeSlot::new(o,&f,k).unwrap(),0).unwrap();passes.push(g16::slots::PassSlot::new(o, k, 1, &crate::g16::object::test_cmds((k) as u64)).unwrap(),0).unwrap();} + for k in 0..2{compute.push(g16::slots::ComputeSlot::new(o,&f,k,&crate::g16::object::test_unit_cmds(k)).unwrap(),0).unwrap();passes.push(g16::slots::PassSlot::new(o, k, 1, &crate::g16::object::test_cmds((k) as u64)).unwrap(),0).unwrap();} Arenas{compute:g16::resources::ComputeArena{compute,render:None,hw_slots:None},render:render_arena(passes)} } fn retire_render(s:&mut Slots,k:usize){let mut c=Claims::new();c.pass[0]=k as u32;c.pass_mask=1<>' in resources_source, 'compute_ext must use ComputeUnitSet so undisplaced slots pin only one unit' assert 'base.arena(k)' in resources_source and 'ext.arena(k - base.len())' in resources_source, 'Prepared::compute_arena must return the per-unit ComputeArena' +engine_source = (production/'engine.rs').read_text() +prefix_compute_fn = item(engine_source, 'fn prefix_compute(') +assert 'seq: s.seq.va,' in prefix_compute_fn, 'prefix_compute must point ComputeRefs::seq at firmware-cached s.seq' +assert 's.seq.write(0, q)?;' in prefix_compute_fn, 'prefix_compute must write encoded sequence into s.seq' +assert '&w[work::compute::BODY_ACTIVE_START..work::compute::SEQ_EMBEDDED]' in prefix_compute_fn, 'clean compute reuse must skip embedded sequence copy into WC work' +graphs_finish_fn = item(graph_source, 'pub(crate) fn finish(') +assert 'core::mem::ManuallyDrop::new(factory.persistent_objects_probe())' in graphs_finish_fn, 'Graphs::finish must keep probe-time FwCoherent ring allocator in ManuallyDrop' +assert 'ring_objects.finish_private()?;' in graphs_finish_fn, 'Graphs::finish must publish persistent ring mappings' +alloc_private_in_fn = item(object_source, 'fn alloc_private_in(') +assert 'pub(crate) fn persistent_objects_probe(&self) -> Objects' in object_source, 'Factory must expose persistent_objects_probe for probe-time work rings' +assert 'if self.probe {' in alloc_private_in_fn and 'self.dev.registration_guard().ok_or(ENODEV)?' in alloc_private_in_fn, 'alloc_private_in must gate as_bound() on self.probe and keep registration_guard() otherwise' ext_tiers_start = resources_source.index('pub(crate) const EXT_RENDER_TIERS:') ext_tiers_end = resources_source.index('];\n', ext_tiers_start) + 3 render_burst_lines = ( @@ -2903,12 +3060,18 @@ def module(text, name): item(graph_source, decl) for decl in ( 'pub(crate) struct ComputeGraph {', + 'struct QueueSession {', + 'impl QueueSession {', 'struct QueueObjects {', 'impl QueueObjects {', 'fn init_queue(', 'fn init_notifier(', + 'struct ComputeGraphSession {', + 'impl ComputeGraphSession {', 'impl ComputeGraph {', 'pub(crate) struct RenderGraph {', + 'struct RenderGraphSession {', + 'impl RenderGraphSession {', 'impl RenderGraph {', ) ).replace('fn new(', 'pub(crate) fn new(').replace('fn init(', 'pub(crate) fn init(') diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-timestamps.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-timestamps.py index f0e9c9ffb0d4c..06b87ba9ef64b 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-timestamps.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-timestamps.py @@ -22,6 +22,7 @@ def function(source, marker): mmu = (backend / 'mmu.rs').read_text() shared = (backend / 'timestamp.rs').read_text() poll = (backend / 'g16/poll.rs').read_text() +obj = (backend / 'g16/object.rs').read_text() cache_policy = function((backend / 'gem.rs').read_text(), 'pub(crate) fn is_writeback(') store = function(mmu, 'pub(crate) fn write(&self, value: u64)') vmap_store = function(mmu, 'pub(crate) fn write(&self, offset: usize, value: u64)') @@ -31,6 +32,8 @@ def function(source, marker): retire = function(poll, 'fn publish_timestamps(&self, flight: &Flight, claims: &super::slots::Claims)') compute_ticks = function(poll, 'fn compute_ticks(&self, unit: &super::slots::ComputeSlot)') compute_ticks_with = function(poll, 'fn compute_ticks_with(') +fw_r64 = function(obj, 'pub(crate) fn r64(&self, offset: usize)') +fw_read = function(obj, 'pub(crate) fn read(&self, offset: usize, out: &mut [u8])') source = r''' #![allow(dead_code)] use core::sync::atomic::{AtomicU8, AtomicU64, Ordering, fence as barrier}; @@ -161,12 +164,40 @@ def function(source, marker): pub struct Render{pub timestamp_outputs:Destinations} pub enum Command{Compute(Compute),Render(Render)} } - pub struct Cells(pub [u64;4]);impl Cells{ - pub fn r64(&self,offset:usize)->Result{ - match offset{0=>Ok(self.0[0]),8=>Ok(self.0[1]),0x600=>Ok(self.0[0]),0x608=>Ok(self.0[1]),0x620=>Ok(self.0[2]),0x628=>Ok(self.0[3]),_=>Err(EINVAL)} + pub struct Cells { + pub vals: [u64; 4], + pub r64_calls: std::cell::Cell, + pub r32_calls: std::cell::Cell, + } + impl Cells { + pub fn new(vals: [u64; 4]) -> Self { + Self { + vals, + r64_calls: std::cell::Cell::new(0), + r32_calls: std::cell::Cell::new(0), + } + } + pub fn r64(&self, offset: usize) -> Result { + self.r64_calls.set(self.r64_calls.get() + 1); + match offset { + 0 => Ok(self.vals[0]), + 8 => Ok(self.vals[1]), + 0x600 => Ok(self.vals[0]), + 0x608 => Ok(self.vals[1]), + 0x620 => Ok(self.vals[2]), + 0x628 => Ok(self.vals[3]), + _ => Err(EINVAL), + } } - pub fn r32(&self,offset:usize)->Result{ - let v=match offset{0x100=>self.0[0],0x104=>self.0[0]>>32,0x108=>self.0[1],0x10c=>self.0[1]>>32,_=>return Err(EINVAL)}; + pub fn r32(&self, offset: usize) -> Result { + self.r32_calls.set(self.r32_calls.get() + 1); + let v = match offset { + 0x100 => self.vals[0], + 0x104 => self.vals[0] >> 32, + 0x108 => self.vals[1], + 0x10c => self.vals[1] >> 32, + _ => return Err(EINVAL), + }; Ok(v as u32) } } @@ -195,11 +226,11 @@ def function(source, marker): fn firmware()->Firmware{Firmware{slots:Slots{scrub:Scrub{compute:vec![],passes:vec![]}},init:Init{abi:Abi{compute:ComputeAbi{work_ticks:None}}}}} fn resources()->Resources{Resources{ compute:vec![ - Compute{its:Cells([10,20,0,0]),work:Cells([0,0,0,0])}, - Compute{its:Cells([30,40,0,0]),work:Cells([0,0,0,0])}, - Compute{its:Cells([50,60,0,0]),work:Cells([0,0,0,0])}, + Compute{its:Cells::new([10,20,0,0]),work:Cells::new([0,0,0,0])}, + Compute{its:Cells::new([30,40,0,0]),work:Cells::new([0,0,0,0])}, + Compute{its:Cells::new([50,60,0,0]),work:Cells::new([0,0,0,0])}, ], - passes:vec![Pass{scene:Cells([100,200,300,400])},Pass{scene:Cells([500,600,700,800])},Pass{scene:Cells([900,1000,1100,1200])}] + passes:vec![Pass{scene:Cells::new([100,200,300,400])},Pass{scene:Cells::new([500,600,700,800])},Pass{scene:Cells::new([900,1000,1100,1200])}] }} #[test]fn retirement_uses_claimed_hardware_cells_and_endpoint_order(){ let compute=backing();let render=backing(); @@ -276,8 +307,8 @@ def function(source, marker): fw.init.abi.compute.work_ticks=Some((0x100,0x108)); let res=Resources{ compute:vec![ - Compute{its:Cells([0,0,0,0]),work:Cells([0x1_0000_0070,0x1_0000_0090,0,0])}, - Compute{its:Cells([0,0,0,0]),work:Cells([0x2_0000_0010,0x2_0000_0040,0,0])}, + Compute{its:Cells::new([0,0,0,0]),work:Cells::new([0x1_0000_0070,0x1_0000_0090,0,0])}, + Compute{its:Cells::new([0,0,0,0]),work:Cells::new([0x2_0000_0010,0x2_0000_0040,0,0])}, ], passes:vec![], }; @@ -291,8 +322,151 @@ def function(source, marker): fw.publish_timestamps(&flight,&claims).unwrap(); assert_eq!((c0.words[0].load(Ordering::Relaxed),c0.words[1].load(Ordering::Relaxed)),(expected(0x1_0000_0070),expected(0x1_0000_0090))); assert_eq!((c1.words[0].load(Ordering::Relaxed),c1.words[1].load(Ordering::Relaxed)),(expected(0x2_0000_0010),expected(0x2_0000_0040))); + // 26B123 work_ticks-first path must skip redundant ITS WC reads when work ticks are valid. + assert_eq!(flight.job.resources.compute[0].its.r64_calls.get(), 0); + assert_eq!(flight.job.resources.compute[1].its.r64_calls.get(), 0); + // When work_ticks holds no interval (0/0), fall back to ITS cleanly. + let fallback_unit = Compute { + its: Cells::new([0x300, 0x400, 0, 0]), + work: Cells::new([0, 0, 0, 0]), + }; + assert_eq!(fw.compute_ticks(&fallback_unit), Ok((0x300, 0x400))); + assert_eq!(fallback_unit.its.r64_calls.get(), 2); + // 25G83 (work_ticks = None) reads ITS directly with zero work reads. + let fw25 = firmware(); + let unit25 = Compute { + its: Cells::new([0x500, 0x600, 0, 0]), + work: Cells::new([0x700, 0x800, 0, 0]), + }; + assert_eq!(fw25.compute_ticks(&unit25), Ok((0x500, 0x600))); + assert_eq!(unit25.its.r64_calls.get(), 2); + assert_eq!(unit25.work.r32_calls.get(), 0); +} +mod r64_scope { + use super::{Result, EINVAL}; + use std::cell::Cell; + use std::sync::atomic::{AtomicU32, Ordering}; + const EAGAIN: i32 = -11; + thread_local! { + static RMB_COUNT: Cell = const { Cell::new(0) }; + static MUTATE_HOOK: Cell> = const { Cell::new(None) }; + } + fn rmb() { + RMB_COUNT.with(|c| c.set(c.get() + 1)); + std::sync::atomic::fence(Ordering::SeqCst); + if let Some(hook) = MUTATE_HOOK.with(|h| h.get()) { + hook(); + } + } + #[repr(C, align(8))] + struct Buf([u8; 32]); + struct FwObject { + ptr: *mut u8, + len: usize, + read_calls: Cell, + } + impl FwObject { + fn ptr(&self, offset: usize, len: usize) -> Result<*mut u8> { + if offset.checked_add(len).is_none_or(|e| e > self.len) { + return Err(EINVAL); + } + Ok(unsafe { self.ptr.add(offset) }) + } + fn read_impl(&self, offset: usize, out: &mut [u8]) -> Result { + self.read_calls.set(self.read_calls.get() + 1); + self.read_prod(offset, out) + } + __FW_READ__ + __FW_R64__ + } + #[test] + fn r64_4byte_aligned_uses_word_pairs_handles_carry_and_rejects_churn() { + let mut buf = Buf([0u8; 32]); + let val_a: u64 = 0x1122_3344_5566_7788; + let val_b: u64 = 0x0123_4567_89ab_cdef; + let val_c: u64 = 0xfedc_ba98_7654_3210; + buf.0[0..8].copy_from_slice(&val_a.to_le_bytes()); + buf.0[4 + 8..4 + 16].copy_from_slice(&val_b.to_le_bytes()); + buf.0[21..29].copy_from_slice(&val_c.to_le_bytes()); + let obj = FwObject { + ptr: buf.0.as_mut_ptr(), + len: buf.0.len(), + read_calls: Cell::new(0), + }; + // 8-byte aligned: single volatile u64 + 1 rmb, never calls byte read(). + RMB_COUNT.with(|c| c.set(0)); + assert_eq!(obj.r64(0), Ok(val_a)); + assert_eq!(obj.read_calls.get(), 0); + assert_eq!(RMB_COUNT.with(|c| c.get()), 1); + // 4-byte aligned (matching compute::DESCRIPTOR_COUNTER 0xe4c / COMPLETED 0xe54): + // uses 32-bit word pairs (3 rmbs), never falls back to byte read(). + RMB_COUNT.with(|c| c.set(0)); + assert_eq!(obj.r64(12), Ok(val_b)); + assert_eq!(obj.read_calls.get(), 0); + assert_eq!(RMB_COUNT.with(|c| c.get()), 3); + // Unaligned (offset % 4 != 0): still uses read() double-snapshot fallback. + assert_eq!(obj.r64(21), Ok(val_c)); + assert_eq!(obj.read_calls.get(), 2); + // Actively mutating 4-byte-aligned receipt returns EAGAIN instead of a torn word. + static TARGET: std::sync::atomic::AtomicPtr = + std::sync::atomic::AtomicPtr::new(core::ptr::null_mut()); + static TICK: AtomicU32 = AtomicU32::new(0); + fn bump() { + let p = TARGET.load(Ordering::Relaxed); + if !p.is_null() { + let n = TICK.fetch_add(1, Ordering::Relaxed); + unsafe { p.write_volatile(n) }; + } + } + TARGET.store(unsafe { buf.0.as_mut_ptr().add(12).cast::() }, Ordering::Relaxed); + MUTATE_HOOK.with(|h| h.set(Some(bump))); + assert_eq!(obj.r64(12), Err(EAGAIN)); + MUTATE_HOOK.with(|h| h.set(None)); + TARGET.store(core::ptr::null_mut(), Ordering::Relaxed); + // Torn carry-wrap snapshot recovery: snapshot 1 sees LOW_WRAP, snapshot 2 sees torn + // (0xffff_ffff, 1), snapshots 3 & 4 see settled HIGH_WRAP -> returns HIGH_WRAP. + const LOW_WRAP: u64 = 0x0000_0000_ffff_ffff; + const HIGH_WRAP: u64 = 0x0000_0001_0000_0000; + static WRAP_PTR: std::sync::atomic::AtomicPtr = + std::sync::atomic::AtomicPtr::new(core::ptr::null_mut()); + static WRAP_STEP: AtomicU32 = AtomicU32::new(0); + fn step_wrap() { + let p = WRAP_PTR.load(Ordering::Relaxed); + if p.is_null() { + return; + } + match WRAP_STEP.fetch_add(1, Ordering::Relaxed) { + 0 => { + unsafe { + p.write_volatile(LOW_WRAP as u32); + p.add(1).write_volatile((LOW_WRAP >> 32) as u32); + } + } + 1 => { + // Torn intermediate across the 32-bit carry boundary. + unsafe { + p.write_volatile(0xffff_ffff); + p.add(1).write_volatile(1); + } + } + _ => { + unsafe { + p.write_volatile(HIGH_WRAP as u32); + p.add(1).write_volatile((HIGH_WRAP >> 32) as u32); + } + } + } + } + WRAP_STEP.store(0, Ordering::Relaxed); + WRAP_PTR.store(unsafe { buf.0.as_mut_ptr().add(12).cast::() }, Ordering::Relaxed); + MUTATE_HOOK.with(|h| h.set(Some(step_wrap))); + assert_eq!(obj.r64(12), Ok(HIGH_WRAP)); + MUTATE_HOOK.with(|h| h.set(None)); + WRAP_PTR.store(core::ptr::null_mut(), Ordering::Relaxed); + assert_eq!(obj.read_calls.get(), 2); + } } -'''.replace('__CHECKED_OFFSET__', checked_offset).replace('__STORE__', store).replace('__VMAP_STORE__', vmap_store.replace('.timestamp_lock.lock()', '.timestamp_lock.lock().unwrap()')).replace('__CACHE_POLICY__', cache_policy).replace('__WRITE__', write).replace('__PUBLISH__', publish).replace('__COMPUTE_TICKS__', compute_ticks).replace('__COMPUTE_TICKS_WITH__', compute_ticks_with).replace('__RETIRE__', retire.replace('fn publish_timestamps', 'pub(crate) fn publish_timestamps')) +'''.replace('__CHECKED_OFFSET__', checked_offset).replace('__STORE__', store).replace('__VMAP_STORE__', vmap_store.replace('.timestamp_lock.lock()', '.timestamp_lock.lock().unwrap()')).replace('__CACHE_POLICY__', cache_policy).replace('__WRITE__', write).replace('__PUBLISH__', publish).replace('__COMPUTE_TICKS__', compute_ticks.replace('fn compute_ticks', 'pub(crate) fn compute_ticks')).replace('__COMPUTE_TICKS_WITH__', compute_ticks_with).replace('__RETIRE__', retire.replace('fn publish_timestamps', 'pub(crate) fn publish_timestamps')).replace('__FW_READ__', fw_read.replace('pub(crate) fn read(', 'fn read_prod(')).replace('__FW_R64__', fw_r64.replace('self.read(', 'self.read_impl(')) path = out / 'timestamps-host.rs' path.write_text(source) subprocess.run(rustc() + ['--edition=2021', '--test', str(path), '-o', str(out / 'timestamps-host')], check=True)