diff --git a/drivers/gpu/drm/asahi/g17/completion.rs b/drivers/gpu/drm/asahi/g17/completion.rs index 8950c73d43af4..dd9e1a945ee4a 100644 --- a/drivers/gpu/drm/asahi/g17/completion.rs +++ b/drivers/gpu/drm/asahi/g17/completion.rs @@ -915,6 +915,20 @@ impl Completion { } } + /// Called under the device mutex and render lock when recovery parks the render for replay. + pub(crate) fn note_render_parked_for_replay(&self) { + if let Some(lease) = self.render.lock().as_ref() { + lease.note_parked_for_replay(); + } + } + + /// Called under the device mutex and render lock when an executed render retires normally. + pub(crate) fn note_render_executed(&self) { + if let Some(lease) = self.render.lock().as_ref() { + lease.note_executed(); + } + } + /// Called under the device mutex before deferring the error signal. pub(crate) fn quarantine_render(&self) { if let Some(lease) = self.render.lock().as_ref() { diff --git a/drivers/gpu/drm/asahi/g17/job.rs b/drivers/gpu/drm/asahi/g17/job.rs index 3048fd4528411..cec4cb5e09a83 100644 --- a/drivers/gpu/drm/asahi/g17/job.rs +++ b/drivers/gpu/drm/asahi/g17/job.rs @@ -322,9 +322,12 @@ impl Packet { self.publication.load(Ordering::Acquire) == 2 } /// A published group retired by firmware without executing is published - /// again from the same packet. Publication state returns to "begun". + /// again from the same packet. Publication state returns to "begun", and + /// its admission hazard record drops the discarded fragment kick until it + /// republishes or retires. pub(crate) fn reset_publication_for_replay(&self) { self.publication.store(1, Ordering::Release); + self.completion.note_render_parked_for_replay(); } pub(crate) fn cancel_requested(&self) -> bool { self.cancelled.load(Ordering::Acquire) diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index 3c77fe8de654a..7451fc7b4b125 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -1284,11 +1284,12 @@ fn compute_channel_features(channels: u8) -> u64 { } } -/// Whether the firmware keeps partial renders (tiler-heap overflow fragment passes) strictly -/// ordered behind earlier fragment work: advertised where `fragment_busy` drains an outstanding -/// fragment pass on the pair and each logical render queue uses a single physical render pair. -fn ordered_partial_renders_feature(fragment_busy: bool, render_pairs: u8) -> u64 { - if fragment_busy && render_pairs == 1 { +/// Whether the firmware and queue barrier promotion keep partial renders (tiler-heap overflow +/// fragment passes) strictly ordered behind earlier fragment work: advertised where +/// `fragment_busy` drains an outstanding fragment pass on the same physical render pair and +/// `render_barriers` orders tiling behind any cross-pair fragment dependency. +fn ordered_partial_renders_feature(fragment_busy: bool) -> u64 { + if fragment_busy { uapi::DRM_ASAHI_FEATURE_ORDERED_PARTIAL_RENDERS as u64 } else { 0 @@ -3108,8 +3109,7 @@ impl gpu::Gpu for Gpu { | crate::file::DRM_ASAHI_FEATURE_COMPUTE_TIMEOUT | compute_channel_features(pairs::compute_channels_per_owner()); let variant = self.shared.variant; - params.features |= - ordered_partial_renders_feature(variant.fragment_busy, pairs::per_owner()); + params.features |= ordered_partial_renders_feature(variant.fragment_busy); // The M5 command set has no AS-build flag: its validation refuses one. if !variant.m5_commands { params.features |= u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_BOUNDED_AS_BUILD); diff --git a/drivers/gpu/drm/asahi/g17/queue/admission.rs b/drivers/gpu/drm/asahi/g17/queue/admission.rs index 8a1b8328dc6fb..d7900139886b8 100644 --- a/drivers/gpu/drm/asahi/g17/queue/admission.rs +++ b/drivers/gpu/drm/asahi/g17/queue/admission.rs @@ -48,6 +48,15 @@ struct InFlight { /// Fragment kick of the published render; a later same-VM overlap of /// another pair waits for it in firmware. fragment: Option, + /// Monotonic publication order assigned on first publication, preserved + /// across replays to break mutual waits between overlapping parked renders. + published_order: Option, + /// True after recovery parks the render for replay and discards its old + /// fragment kick, until it republishes a replacement kick or retires. + parked: bool, + /// True if a later-published overlapping same-VM render executed and + /// retired normally, so replaying this producer would overwrite its output. + later_consumer_executed: bool, } const QUARANTINE_WAIT_MS: u32 = 1000; @@ -113,6 +122,7 @@ struct State { epoch: u64, footprints: KVec, next_ticket: u64, + next_publication: u64, } impl State { @@ -139,6 +149,7 @@ impl State { epoch: 0, footprints: KVec::new(), next_ticket: 1, + next_publication: 1, } } fn owns_live(&self, owner: u64, slot: usize) -> bool { @@ -835,6 +846,9 @@ impl State { ticket, footprint: request.footprint.clone(), fragment: None, + published_order: None, + parked: false, + later_consumer_executed: false, }, GFP_KERNEL, ) @@ -1639,13 +1653,68 @@ impl RenderLease { return; }; if let Some(index) = state.position(self.slot, record) { - state.footprints[index].fragment = Some(fragment); + let order = match state.footprints[index].published_order { + Some(order) => order, + None => { + let order = state.next_publication; + state.next_publication = order.wrapping_add(1).max(1); + order + } + }; + let entry = &mut state.footprints[index]; + entry.fragment = Some(fragment); + entry.published_order = Some(order); + entry.parked = false; + } + } + + /// Called under `port.render_lock()` when recovery parks a previously + /// published render for replay so overlapping renders cannot consume its + /// discarded fragment kick before it republishes or retires. + pub(crate) fn note_parked_for_replay(&self) { + let mut state = self.pool.state.lock(); + let Some(record) = self.record else { + return; + }; + if let Some(index) = state.position(self.slot, record) { + let entry = &mut state.footprints[index]; + entry.fragment = None; + entry.parked = true; + } + } + + /// Called under `port.render_lock()` when an executed render retires + /// normally: any earlier-published overlapping same-VM render still in + /// flight can no longer replay ahead of it. + pub(crate) fn note_executed(&self) { + let mut state = self.pool.state.lock(); + let Some(record) = self.record else { + return; + }; + let Some(index) = state.position(self.slot, record) else { + return; + }; + let Some(my_order) = state.footprints[index].published_order else { + return; + }; + let my_footprint = state.footprints[index].footprint.clone(); + for (other_idx, other) in state.footprints.iter_mut().enumerate() { + if other_idx == index { + continue; + } + if other.published_order.is_some_and(|order| order < my_order) + && other.footprint.same_vm(&my_footprint) + && other.footprint.overlaps(&my_footprint) + { + other.later_consumer_executed = true; + } } } } impl Pool { - /// Under the device mutex, which orders every publication: the newest + /// Under `port.render_lock()`, which orders every device-mutex and direct + /// render publication as well as replay-parking transitions: the newest /// published fragment kick of each other pair whose live same-VM render /// overlaps `footprint`. Quarantined pairs are skipped as in admission. /// @@ -1660,15 +1729,23 @@ impl Pool { &self, owner: u64, slot: u8, + sequence: u64, footprint: &Footprint, prefix: Option, barriers: &mut [KickDependency; hazard::PUBLICATION_BARRIERS], ) -> Result { let state = self.state.lock(); + let self_entry = state + .position(slot, (owner, sequence)) + .map(|index| &state.footprints[index]); + if self_entry.is_some_and(|entry| entry.later_consumer_executed) { + return Err(ENODATA); + } + let self_order = self_entry.and_then(|entry| entry.published_order); let mut slots = [0u8; hazard::PUBLICATION_BARRIERS]; let mut count = 0; for entry in state.footprints.iter() { - let (Some(other), Some(fragment)) = (entry.slot, entry.fragment) else { + let Some(other) = entry.slot else { continue; }; if other == slot @@ -1679,6 +1756,32 @@ impl Pool { { continue; } + if let Some(mine) = self_order { + let Some(theirs) = entry.published_order else { + continue; + }; + if theirs > mine { + // Preserve original publication direction: never wait on a + // later-published overlapping consumer. If it is already + // parked unexecuted we republish first; if it is still live + // or unobserved, defer until it either parks or retires. + if entry.parked { + continue; + } + if entry.fragment.is_some() { + return Err(EBUSY); + } + continue; + } + if entry.parked { + return Err(EBUSY); + } + } else if entry.parked { + return Err(EBUSY); + } + let Some(fragment) = entry.fragment else { + continue; + }; match slots[..count].iter().position(|known| *known == other) { // One fragment ring completes in kick order; same QID, so the // word orders by timestamp. @@ -2094,6 +2197,9 @@ mod owner_pair_tests { ticket: 0, footprint: footprint.clone(), fragment: Some(kick(10 + slot, timestamp)), + published_order: Some(sequence), + parked: false, + later_consumer_executed: false, }, GFP_KERNEL, ) @@ -2102,15 +2208,44 @@ mod owner_pair_tests { } let mut barriers = [KickDependency::ZERO; hazard::PUBLICATION_BARRIERS]; // On pair 2: pair 1's newest overlapping fragment kick, never its own. - assert_eq!(pool.publication_barriers(1, 2, &footprint, None, &mut barriers).unwrap(), 1); + assert_eq!(pool.publication_barriers(1, 2, 6, &footprint, None, &mut barriers).unwrap(), 1); assert!(barriers[0] == kick(11, 9)); - assert_eq!(pool.publication_barriers(1, 2, &footprint, Some(4), &mut barriers).unwrap(), 1); + assert_eq!(pool.publication_barriers(1, 2, 6, &footprint, Some(4), &mut barriers).unwrap(), 1); assert!(barriers[0] == kick(11, 9)); // The queue prefix already orders them. - assert_eq!(pool.publication_barriers(1, 2, &footprint, Some(5), &mut barriers).unwrap(), 0); + assert_eq!(pool.publication_barriers(1, 2, 6, &footprint, Some(5), &mut barriers).unwrap(), 0); // Another owner's render is a barrier whatever the prefix. - assert_eq!(pool.publication_barriers(3, 2, &footprint, Some(9), &mut barriers).unwrap(), 1); - assert_eq!(pool.publication_barriers(3, 3, &footprint, Some(9), &mut barriers).unwrap(), 2); + assert_eq!(pool.publication_barriers(3, 2, 1, &footprint, Some(9), &mut barriers).unwrap(), 1); + assert_eq!(pool.publication_barriers(3, 3, 1, &footprint, Some(9), &mut barriers).unwrap(), 2); + + // If an earlier render (seq 4, order 4) parks while a later overlapping + // render (seq 6, order 6) is still live/unobserved, seq 4 defers instead + // of reversing order onto seq 6. + { + let mut state = pool.state.lock(); + state.footprints[0].fragment = None; + state.footprints[0].parked = true; + } + assert_eq!(pool.publication_barriers(1, 1, 4, &footprint, None, &mut barriers), Err(EBUSY)); + // Once the later render (seq 6) is also parked unexecuted, seq 4 goes first + // while seq 6 and any unrelated new render defer behind seq 4. + { + let mut state = pool.state.lock(); + state.footprints[2].fragment = None; + state.footprints[2].parked = true; + } + assert_eq!(pool.publication_barriers(3, 3, 1, &footprint, None, &mut barriers), Err(EBUSY)); + assert_eq!(pool.publication_barriers(1, 2, 6, &footprint, None, &mut barriers), Err(EBUSY)); + assert_eq!(pool.publication_barriers(1, 1, 4, &footprint, None, &mut barriers).unwrap(), 0); + // If a later overlapping consumer already executed, seq 4 fails with ENODATA. + { + let mut state = pool.state.lock(); + state.footprints[0].later_consumer_executed = true; + } + assert_eq!( + pool.publication_barriers(1, 1, 4, &footprint, None, &mut barriers), + Err(ENODATA) + ); } } diff --git a/drivers/gpu/drm/asahi/g17/queue/compute.rs b/drivers/gpu/drm/asahi/g17/queue/compute.rs index 66dc87d5aa07e..0b26a25b36f11 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute.rs @@ -699,6 +699,11 @@ pub(crate) struct Queue { graph: Graph, active: Fifo, replays: Fifo>, + /// Sequence and completion fence of failed commands whose + /// `Deferred::Retired(_, Err(_))` fence signal has not yet run outside the + /// device mutex; keeps consumers from bypassing them in the same event pass + /// without pinning `Packet`/`Context`/VM memory. + pending_failed: KVec<(u64, kernel::dma_fence::Fence)>, replay_retirement: bool, replay_error: Option, replay_prepared: bool, @@ -801,6 +806,7 @@ impl Queue { ) -> Result { let Backing { mut pool, mut kick } = backing; let (active, replays) = (Fifo::new()?, Fifo::new()?); + let pending_failed = KVec::with_capacity(IN_FLIGHT, GFP_KERNEL)?; let mut graph = Graph::new(alloc, objects, &context, pointers, operand_state, board, program, m5, mcache)?; let kick_alias = kick.map_client(context.vm())?; @@ -831,6 +837,7 @@ impl Queue { graph, active, replays, + pending_failed, replay_retirement: false, replay_error: None, replay_prepared: false, @@ -968,6 +975,7 @@ impl Queue { self.owner = None; self.channel_index = 0; self.heavy_run = 0; + self.pending_failed.clear(); if stamp_released_at { self.released_at = now_ns(); } @@ -1434,17 +1442,23 @@ impl Queue { ); } self.retire_pending = true; - let completion = front.packet.completion.clone(); - let producers = front.packet.check_firmware_producers(); + let packet = front.packet.clone(); + let completion = packet.completion.clone(); + let observed = front.observed.map(|record| record.timestamps); + let producers = packet.check_firmware_producers(); + let failed = producers.is_err(); defer(match producers { Ok(()) if self.graph.m5 => Deferred::RetiredCompute( completion, [timestamps[0], timestamps[1], 0, 0], - front.observed.map(|record| record.timestamps), + observed, ), Ok(()) => Deferred::Retired(completion, Ok([timestamps[0], timestamps[1], 0, 0])), Err(error) => Deferred::Retired(completion, Err(error)), })?; + if failed { + self.note_pending_failed(&packet); + } self.retire_pending = false; if let Some([start, end]) = execution { self.heavy_run = crate::g17::pairs::heavy_run(self.heavy_run, start, end); @@ -1619,10 +1633,12 @@ impl Queue { self.active.iter_mut().next().ok_or(EIO)?.qos_pending = false; } let front = self.active.front().ok_or(EIO)?; - let completion = front.packet.completion.clone(); + let packet = front.packet.clone(); + let completion = packet.completion.clone(); if self.replay_retirement { - self.replays.push(front.packet.clone()).map_err(|_| EIO)?; + self.replays.push(packet).map_err(|_| EIO)?; } else if self.spared_deferred { + self.note_pending_failed(&packet); defer(Deferred::Retired(completion, Err(ENODATA)))?; } else { defer(Deferred::Release(completion))?; @@ -1668,6 +1684,32 @@ impl Queue { self.replays.front().cloned() } + /// The oldest parked compute command precedes a consumer waiting through `through`. + pub(crate) fn replay_through(&self, through: Option) -> bool { + self.replays + .front() + .is_some_and(|packet| crate::g17::job::Order::contains(through, packet.order.sequence)) + } + + /// Record a failed compute command's sequence and completion fence while its + /// `Deferred::Retired` signal is still queued, so same-pass consumers defer + /// until the error status is visible on its fence without retaining `Packet` + /// or `Context`. + pub(crate) fn note_pending_failed(&mut self, packet: &Packet) { + let mut i = 0; + while i < self.pending_failed.len() { + if crate::g17::job::fence_status(&self.pending_failed[i].1) != 0 { + self.pending_failed.swap_remove(i); + } else { + i += 1; + } + } + let _ = self.pending_failed.push( + (packet.order.sequence, packet.completion.fence()), + GFP_KERNEL, + ); + } + /// Drop the witnessed owner only after either publication retained it or /// the off-lock completion collector accepted its terminal result. pub(crate) fn finish_replay(&mut self, packet: &Arc) -> Result { @@ -1716,6 +1758,7 @@ impl Queue { /// Caller already stopped both processors. No firmware owner can access retained mappings. pub(crate) fn stopped(&mut self, defer: &mut impl FnMut(Deferred) -> Result) -> Result { if let Some(configuration) = self.configuration.take() { configuration.release(); } + self.pending_failed.clear(); while let Some(packet) = self.replays.front() { defer(Deferred::Retired(packet.completion.clone(), Err(EIO)))?; drop(self.replays.pop()); @@ -2687,6 +2730,18 @@ impl Queue { if through.is_none() || self.owner != Some(owner) { return Ok(None); } + // A covered compute command parked for replay (or failed with its + // deferred fence signal still pending in this pass) has left `active` + // without a replacement kick; ask the consumer to retry once it + // republishes or its terminal fence status is visible. + if self.replay_through(through) + || self.pending_failed.iter().any(|(sequence, fence)| { + crate::g17::job::Order::contains(through, *sequence) + && crate::g17::job::fence_status(fence) == 0 + }) + { + return Err(EAGAIN); + } let mut newest = None; for active in self .active diff --git a/drivers/gpu/drm/asahi/g17/queue/render.rs b/drivers/gpu/drm/asahi/g17/queue/render.rs index 5b81b603a66bc..0c92c7cab4e27 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render.rs @@ -147,6 +147,12 @@ pub(crate) trait Host { generation: u64, buffer_id: u8, ) -> Result; + /// Serializes hazard-record state transitions (parking for replay, normal + /// execution retirement) against direct render publication's barrier + /// selection and commit. + fn with_render_lock(&self, f: impl FnOnce()) { + f(); + } } struct Prepared { @@ -708,12 +714,14 @@ impl Pair { /// 1 the tiling encoder, 2 a full channel or compute completion, 3 the /// fragment encoder; the last class is the implicit parent's. struct RenderBarriers { - tiling: [KickDependency; 4 + crate::g17::pairs::COMPUTE_CHANNELS_MAX], + tiling: [KickDependency; + 7 + 2 * crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS], tiling_count: usize, fragment: [KickDependency; 3 + crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS], fragment_count: usize, - tiling_types: [u8; 5 + crate::g17::pairs::COMPUTE_CHANNELS_MAX], + tiling_types: [u8; + 8 + 2 * crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS], fragment_types: [u8; 4 + crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS], } @@ -779,17 +787,27 @@ impl CrossPairOrder { fn render_barriers( fragment_stage: bool, stage_prefixes: bool, + ordered_partial: bool, + render_pairs: u8, dependencies: &RenderDependencies, own_tiling: KickDependency, + own_fragment_qid: u8, compute_class: u8, ) -> RenderBarriers { let fragment_stage = fragment_stage || stage_prefixes; - let mut tiling_barriers = [KickDependency::ZERO; 4 + crate::g17::pairs::COMPUTE_CHANNELS_MAX]; + // Ordered partial rendering covers this pair's earlier fragment work, which `fragment_busy` + // drains, and the renders the fragment barriers name. Only a queue of several pairs can reach + // such a render on another pair through a compute wait; with one pair per queue the tiling + // kick keeps overlapping compute waits and other queues' attachments. + let ordered_indirect = ordered_partial && render_pairs > 1; + let mut tiling_barriers = [KickDependency::ZERO; + 7 + 2 * crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS]; let mut tiling_count = 0; let mut fragment_barriers = [own_tiling; 3 + crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS]; let mut fragment_count = 1; - let mut tiling_types = [1; 5 + crate::g17::pairs::COMPUTE_CHANNELS_MAX]; + let mut tiling_types = + [1; 8 + 2 * crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS]; let mut fragment_types = [3; 4 + crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS]; fragment_types[0] = 1; @@ -802,6 +820,15 @@ fn render_barriers( if fragment_stage { fragment_barriers[fragment_count] = *dependency; fragment_count += 1; + // `fragment_busy` drains only this physical pair's fragment ring before a partial + // render. When a fragment-stage render dependency lives on another physical pair, + // order this pair's tiling kick behind that fragment completion too so a tiler-heap + // overflow partial render cannot execute ahead of it. + if ordered_partial && dependency.qid() != own_fragment_qid { + tiling_barriers[tiling_count] = *dependency; + tiling_types[tiling_count] = 2; + tiling_count += 1; + } } else { tiling_barriers[tiling_count] = *dependency; // A full channel barrier uses the tiling encoder's class 2. @@ -830,8 +857,28 @@ fn render_barriers( fragment_barriers[fragment_count] = *compute; fragment_types[fragment_count] = compute_class; fragment_count += 1; + // A fragment-only compute wait may transitively order an earlier render on another + // pair (or write attachments read by a partial render), so promote it to tiling when + // ordered partial rendering is advertised on a queue of several pairs. + if ordered_indirect { + tiling_barriers[tiling_count] = *compute; + tiling_types[tiling_count] = compute_class; + tiling_count += 1; + } + } + // Only tile stores overlap: the tiling kick stays concurrent unless ordered partial + // rendering is advertised on a queue of several pairs, where a tiler-heap overflow partial + // render can touch the overlapping attachment before another pair's fragment pass completes. + for hazard in &dependencies.hazards[..dependencies.hazard_count] { + fragment_barriers[fragment_count] = *hazard; + fragment_count += 1; + if ordered_indirect { + tiling_barriers[tiling_count] = *hazard; + tiling_types[tiling_count] = 2; + tiling_count += 1; + } } - if stage_prefixes { + if stage_prefixes || ordered_partial { // Only identical words of the same class are interchangeable. let mut kept = 0; for read in 0..tiling_count { @@ -848,11 +895,6 @@ fn render_barriers( tiling_count = kept; tiling_types[kept] = 1; } - // Only tile stores overlap: the tiling kick stays concurrent. - for hazard in &dependencies.hazards[..dependencies.hazard_count] { - fragment_barriers[fragment_count] = *hazard; - fragment_count += 1; - } RenderBarriers { tiling: tiling_barriers, tiling_count, @@ -1085,9 +1127,16 @@ impl Pair { }; let task = resources.as_ref().is_some_and(|programs| programs.uses_task()); let own_tiling = KickDependency::new(qids[0], kicks[0]).ok_or(EINVAL)?; - let mut barriers = - render_barriers(pass.fragment_barriers, pass.stage_prefixes, dependencies, own_tiling, - self.board.map_or(2, crate::g17::fw::m5::compute::explicit_dependency)); + let mut barriers = render_barriers( + pass.fragment_barriers, + pass.stage_prefixes, + self.variant.fragment_busy, + crate::g17::pairs::per_owner(), + dependencies, + own_tiling, + qids[1], + self.board.map_or(2, crate::g17::fw::m5::compute::explicit_dependency), + ); // On the J813 a tiling kick also waits for the last fragment kick published, on any // pair, as macOS 27.0 orders them there: its TA kick for render n names render n - 1's // 3D kick (every such dependency in its captured queues). Without it a TA ran beside @@ -1118,10 +1167,13 @@ impl Pair { } else { None }; - let mut fragment_types = [0u8; 5 + crate::g17::hazard::PUBLICATION_BARRIERS]; + let mut fragment_types = [0u8; + 5 + crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS]; fragment_types[..barriers.fragment_count + 1] .copy_from_slice(&barriers.fragment_types[..barriers.fragment_count + 1]); - fragment_types[barriers.fragment_count + 1] = 1; + if ancestor.is_some() { + fragment_types[barriers.fragment_count + 1] = 1; + } let fragment_typed = barriers.fragment_count + 1 + usize::from(ancestor.is_some()); if m5 && j813 { // The J813 forms' firmware cross waits (Board::firmware_cross_waits): every TA and 3D @@ -2415,6 +2467,7 @@ impl Pair { &front.packet, [timestamps[0], timestamps[3]], ); + host.with_render_lock(|| front.packet.completion.note_render_executed()); defer(Deferred::Retired( front.packet.completion.clone(), front.packet.check_firmware_producers().map(|()| timestamps), @@ -2455,6 +2508,11 @@ impl Pair { }) } + /// Owner and oldest parked sequence when this pair holds replay work. + pub(crate) fn replay_frontier(&self) -> Option<(u64, u64)> { + Some((self.owner?, self.replay.front()?.packet.order.sequence)) + } + /// Every retained group was retired and unlinked by firmware without /// executing (job list empty, stamps cover it, no recovery, fragment end /// never written): after another VM's recovery the firmware drops an @@ -2622,7 +2680,7 @@ impl Pair { let parked = ParkedReplay::new(packet.clone()); self.memory.retire(ordinal)?; self.active.pop().ok_or(EIO)?; - packet.reset_publication_for_replay(); + host.with_render_lock(|| packet.reset_publication_for_replay()); self.published_completions = None; self.replay.push(parked).map_err(|_| EIO)?; } @@ -2766,6 +2824,9 @@ impl Pair { } } while let Some(parked) = self.replay.pop() { + if error == ENODATA && !parked.packet.completion.guilty() { + parked.packet.completion.classify(recovery::Class::Spared); + } defer(Deferred::Retired(parked.packet.completion.clone(), Err(error)))?; } Ok(()) @@ -3824,6 +3885,155 @@ mod cross_pair_order_tests { } } +#[kunit_tests(asahi_g17_render_ordered_partial)] +mod ordered_partial_tests { + use super::{render_barriers, RenderDependencies}; + use crate::g17::fw::kick::{KickDependency, KickTimestamp}; + + fn dep(qid: u8) -> KickDependency { + KickDependency::new(qid, KickTimestamp::FIRST).unwrap() + } + + #[test] + fn same_pair_fragment_dep_stays_off_tiling_while_cross_pair_promotes() { + let own_tiling = dep(4); + let own_fragment_qid = 5; + let same_pair_frag = dep(5); + let other_pair_frag = dep(7); + + let mut deps = RenderDependencies::EMPTY; + deps.render[0] = same_pair_frag; + deps.render_count = 1; + let b = render_barriers(false, true, true, 2, &deps, own_tiling, own_fragment_qid, 2); + assert_eq!(b.tiling_count, 0); + assert_eq!(b.fragment_count, 2); + assert_eq!(b.fragment[1].word(), same_pair_frag.word()); + + deps.render[1] = other_pair_frag; + deps.render_count = 2; + let b = render_barriers(false, true, true, 2, &deps, own_tiling, own_fragment_qid, 2); + assert_eq!(b.tiling_count, 1); + assert_eq!(b.tiling[0].word(), other_pair_frag.word()); + assert_eq!(b.tiling_types[0], 2); + assert_eq!(b.tiling_types[1], 1); + assert_eq!(b.fragment_count, 3); + + // When render_tiling already carries the cross-pair fragment dependency, dedup keeps one. + deps.render_tiling[0] = other_pair_frag; + deps.render_tiling_count = 1; + let b = render_barriers(false, true, true, 2, &deps, own_tiling, own_fragment_qid, 2); + assert_eq!(b.tiling_count, 1); + assert_eq!(b.tiling[0].word(), other_pair_frag.word()); + assert_eq!(b.tiling_types[0], 2); + assert_eq!(b.tiling_types[1], 1); + + // Without ordered_partial (no fragment_busy), cross-pair fragment-only deps stay off TA. + deps.render_tiling_count = 0; + let b = render_barriers(false, true, false, 2, &deps, own_tiling, own_fragment_qid, 2); + assert_eq!(b.tiling_count, 0); + + // Hazards and fragment_compute waits also promote to tiling under ordered_partial, + // deduplicating against existing tiling barriers and staying off tiling without it. + let haz = dep(9); + let fcomp = dep(12); + deps.hazards[0] = haz; + deps.hazards[1] = other_pair_frag; + deps.hazard_count = 2; + deps.fragment_compute[0] = fcomp; + deps.fragment_compute_count = 1; + let b = render_barriers(false, true, true, 2, &deps, own_tiling, own_fragment_qid, 3); + assert_eq!(b.tiling_count, 3); + assert_eq!(b.tiling[0].word(), other_pair_frag.word()); + assert_eq!(b.tiling_types[0], 2); + assert_eq!(b.tiling[1].word(), fcomp.word()); + assert_eq!(b.tiling_types[1], 3); + assert_eq!(b.tiling[2].word(), haz.word()); + assert_eq!(b.tiling_types[2], 2); + assert_eq!(b.tiling_types[3], 1); + + let b_off = render_barriers(false, true, false, 2, &deps, own_tiling, own_fragment_qid, 3); + assert_eq!(b_off.tiling_count, 0); + } + + #[test] + fn a_one_pair_queue_tiles_beside_its_compute_waits_and_hazards() { + let own_tiling = dep(4); + let own_fragment_qid = 5; + let mut deps = RenderDependencies::EMPTY; + deps.render[0] = dep(5); + deps.render_count = 1; + deps.fragment_compute[0] = dep(12); + deps.fragment_compute_count = 1; + deps.hazards[0] = dep(9); + deps.hazard_count = 1; + let one = render_barriers(false, true, true, 1, &deps, own_tiling, own_fragment_qid, 3); + assert_eq!(one.tiling_count, 0); + assert_eq!(one.tiling_types[0], 1); + // The fragment kick keeps every wait, and a queue of two pairs tiles behind both. + assert_eq!(one.fragment_count, 4); + let two = render_barriers(false, true, true, 2, &deps, own_tiling, own_fragment_qid, 3); + assert_eq!(two.tiling_count, 2); + assert_eq!(two.fragment_count, 4); + // A named render on another pair is ordered whatever the count. + deps.render[0] = dep(7); + let one = render_barriers(false, true, true, 1, &deps, own_tiling, own_fragment_qid, 3); + assert_eq!(one.tiling_count, 1); + assert_eq!(one.tiling[0].word(), dep(7).word()); + assert_eq!(one.tiling_types[0], 2); + } + + #[test] + fn max_sized_barriers_fit_kick_entry_with_and_without_ancestor() { + let own_tiling = dep(4); + let own_fragment_qid = 5; + let mut deps = RenderDependencies::EMPTY; + let mut qid = 10u8; + let mut next = || { + let d = dep(qid); + qid += 1; + d + }; + for i in 0..deps.render.len() { + deps.render[i] = next(); + } + deps.render_count = deps.render.len(); + for i in 0..deps.render_tiling.len() { + deps.render_tiling[i] = next(); + } + deps.render_tiling_count = deps.render_tiling.len(); + for i in 0..deps.tiling.len() { + deps.tiling[i] = next(); + } + deps.tiling_count = deps.tiling.len(); + for i in 0..deps.compute.len() { + deps.compute[i] = next(); + } + deps.compute_count = deps.compute.len(); + for i in 0..deps.fragment_compute.len() { + deps.fragment_compute[i] = next(); + } + deps.fragment_compute_count = deps.fragment_compute.len(); + for i in 0..deps.hazards.len() { + deps.hazards[i] = next(); + } + deps.hazard_count = deps.hazards.len(); + + let b = render_barriers(false, true, true, 2, &deps, own_tiling, own_fragment_qid, 3); + // Reserve one slot for CrossPairOrder and one for the implicit self-parent. + assert!(b.tiling_count < b.tiling.len()); + assert!(b.tiling_count + 2 <= 32); + // Verify fragment_types assembly fits both without and with a G17D ancestor. + let mut fragment_types = [0u8; + 5 + crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS]; + fragment_types[..b.fragment_count + 1] + .copy_from_slice(&b.fragment_types[..b.fragment_count + 1]); + assert!(b.fragment_count + 1 <= 32); + fragment_types[b.fragment_count + 1] = 1; + assert_eq!(fragment_types[b.fragment_count + 1], 1); + assert!(b.fragment_count + 2 <= 32); + } +} + #[kunit_tests(asahi_g17_render_completion_noted)] mod completion_noted_tests { use super::completion_noted; diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index 6d22cd357fb50..38eb593bdfcbc 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -2308,7 +2308,7 @@ impl DeferredBatch { } } /// Holds nothing: finished, or never used. - fn is_idle(&self) -> bool { + pub(super) fn is_idle(&self) -> bool { !self.has_source_completions && self.values.is_empty() && self.bindings.is_empty() @@ -2703,6 +2703,7 @@ impl super::Firmware { &mut combined, )?; } + packet.check_firmware_producers()?; if packet.completion.sources().is_some() { self.publish_compute_inputs(owner, qid, packet, combined.as_slice(), deferred) } else { @@ -4125,6 +4126,10 @@ impl Backend { bound = false; drop(state); drop(lease); + if !deferred.is_idle() { + deferred.finish(); + packet.check_dependencies()?; + } continue; } if !sibling_tried @@ -4154,6 +4159,10 @@ impl Backend { Some(false) => { drop(state); drop(lease); + if !deferred.is_idle() { + deferred.finish(); + packet.check_dependencies()?; + } if self.try_add_compute_sibling(required, &admission)? { self.sibling_backoff_until.store(0, Ordering::Relaxed); } else { @@ -4185,6 +4194,10 @@ impl Backend { // free it. drop(state); drop(lease); + if !deferred.is_idle() { + deferred.finish(); + packet.check_dependencies()?; + } self.shared.queue_events(); admission.timed(AdmissionWait::OuterRoom, || { self.wait_release(domain, claimed, &admission) @@ -4209,6 +4222,14 @@ impl Backend { } drop(state); drop(lease); + if !deferred.is_idle() { + // Inline `replay_compute` above may have queued a failed + // predecessor's fence signal in this batch; drain it off-lock + // and revalidate dependencies before waiting or retrying. + deferred.finish(); + packet.check_dependencies()?; + continue; + } self.shared.queue_events(); let wait = if recovering { AdmissionWait::Recovery } else { AdmissionWait::Publication }; admission.timed(wait, || self.wait_release(progress, observed, &admission))?; diff --git a/drivers/gpu/drm/asahi/g17/runtime/compute_replay.rs b/drivers/gpu/drm/asahi/g17/runtime/compute_replay.rs index 2cc12116bfc5a..ecf0f39be0825 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/compute_replay.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/compute_replay.rs @@ -48,143 +48,183 @@ impl Firmware { )?; } } - for index in 0..self.queues.compute.len() { - loop { - if self.recovery.pending() || recovery::Memory::recovery_state(&self.init)? != 0 { - return Ok(()); - } - let Some((packet, owner)) = self.queues.compute[index] - .as_ref() - .and_then(|entry| entry.queue.as_deref()) - .and_then(|queue| Some((queue.replay_front()?, queue.owner()))) - else { - break; - }; - // A render consumer named this command through a firmware dependency. - // Republish only while no render of the owner has executed since this recovery - // (none consumed the dead token), after every live render of the owner is - // parked for replay; the render replay then depends on the new command. A - // parked render this command waits through is republished first, so the new - // command depends on it again. - let generation = self.recovery.generation(); - let parked_prefix = owner.is_some_and(|owner| { - self.queues.render.owner_parked_through(owner, packet.order.wait_through[0]) - }); - let (executed, live) = if packet.completion.has_firmware_consumer() { - owner.map_or((true, false), |owner| self.queues.render.owner_render_state(owner, generation)) - } else { - (false, false) - }; - let must_wait = parked_prefix || (!executed && live); - let now = super::now_ns(); - let waited = if must_wait { + let mut progressed = true; + let mut waiting = false; + while progressed { + progressed = false; + waiting = false; + for index in 0..self.queues.compute.len() { + loop { + if self.recovery.pending() || recovery::Memory::recovery_state(&self.init)? != 0 + { + return Ok(()); + } + let Some((packet, owner)) = self.queues.compute[index] + .as_ref() + .and_then(|entry| entry.queue.as_deref()) + .and_then(|queue| Some((queue.replay_front()?, queue.owner()))) + else { + break; + }; + // Defer behind a covered compute predecessor parked on another channel so + // `append_compute_prefix` resolves its replacement kick in order. + let parked_compute = owner.is_some_and(|owner| { + self.queues.compute.iter().enumerate().any(|(other, entry)| { + other != index + && entry + .as_ref() + .and_then(|entry| entry.queue.as_deref()) + .is_some_and(|queue| { + queue.owner() == Some(owner) + && queue.replay_through(packet.order.wait_through[1]) + }) + }) + }); + if parked_compute { + waiting = true; + break; + } + // A render consumer named this command through a firmware dependency. + // Republish only while no render of the owner has executed since this recovery + // (none consumed the dead token), after every live render of the owner is + // parked for replay; the render replay then depends on the new command. A + // parked render this command waits through is republished first, so the new + // command depends on it again. + let generation = self.recovery.generation(); + let parked_prefix = owner.is_some_and(|owner| { + self.queues + .render + .owner_parked_through(owner, packet.order.wait_through[0]) + }); + let (executed, live) = if packet.completion.has_firmware_consumer() { + owner.map_or((true, false), |owner| { + self.queues.render.owner_render_state(owner, generation) + }) + } else { + (false, false) + }; + let must_wait = parked_prefix || (!executed && live); + let now = super::now_ns(); + let waited = if must_wait { + self.queues.compute[index] + .as_mut() + .and_then(|entry| entry.queue.as_deref_mut()) + .ok_or(EIO)? + .consumer_wait(now) + } else { + 0 + }; + if must_wait && waited < CONSUMER_WAIT_NS { + // The event worker polls while this waits. + waiting = true; + break; + } + let consumer = (executed || must_wait).then_some(ENODATA); self.queues.compute[index] .as_mut() .and_then(|entry| entry.queue.as_deref_mut()) .ok_or(EIO)? - .consumer_wait(now) - } else { - 0 - }; - if must_wait && waited < CONSUMER_WAIT_NS { - // The event worker polls while this waits. - self.queues.replay_consumer_wait = Some(now); - return Ok(()); - } - let consumer = (executed || must_wait).then_some(ENODATA); - self.queues.compute[index] - .as_mut() - .and_then(|entry| entry.queue.as_deref_mut()) - .ok_or(EIO)? - .clear_consumer_wait(); - // M5 compute takes its slot on the work ring M5 render shares, whose unclaimed - // room the publication checks (InitData::work_ready). - let priority = packet.context.policy().priority(); - let outer_ready = if self.init.is_m5() { - self.init.work_ready(priority, crate::g17::fw::queue::DataMaster::Compute)? - } else { - self.port.compute_ready(priority)? - }; - if !outer_ready { - let now = super::now_ns(); - let since = *self.queues.replay_outer_wait.get_or_insert(now); - if now.saturating_sub(since) < super::WORK_RING_WAIT_NS { - // Keep the FIFO and its replay credit untouched. The - // event worker schedules the existing delayed poll. - return Ok(()); + .clear_consumer_wait(); + // M5 compute takes its slot on the work ring M5 render shares, whose unclaimed + // room the publication checks (InitData::work_ready). + let priority = packet.context.policy().priority(); + let outer_ready = if self.init.is_m5() { + self.init + .work_ready(priority, crate::g17::fw::queue::DataMaster::Compute)? + } else { + self.port.compute_ready(priority)? + }; + if !outer_ready { + let now = super::now_ns(); + let since = *self.queues.replay_outer_wait.get_or_insert(now); + if now.saturating_sub(since) < super::WORK_RING_WAIT_NS { + // Keep the FIFO and its replay credit untouched. The + // event worker schedules the existing delayed poll. + return Ok(()); + } + } else { + self.queues.replay_outer_wait = None; } - } else { - self.queues.replay_outer_wait = None; - } - let result = if let Some(error) = consumer { - Err(error) - } else if !outer_ready { - // This replay has no live firmware ownership. Persistent - // backpressure uses the existing failed-replay retirement. - Err(EBUSY) - } else { (|| { - let qid = { - let mut queue = self.queues.compute[index] - .as_mut() - .and_then(|entry| entry.queue.as_deref_mut()) - .ok_or(EIO)?; - queue.prepare_replay(&packet)?; - queue.qid() + let result = if let Some(error) = consumer { + Err(error) + } else if !outer_ready { + // This replay has no live firmware ownership. Persistent + // backpressure uses the existing failed-replay retirement. + Err(EBUSY) + } else { + (|| { + let qid = { + let mut queue = self.queues.compute[index] + .as_mut() + .and_then(|entry| entry.queue.as_deref_mut()) + .ok_or(EIO)?; + queue.prepare_replay(&packet)?; + queue.qid() + }; + let owner = owner.ok_or(EIO)?; + packet.check_replay_dependencies()?; + let mut dependencies = self.queues.render_prefix(owner, &packet)?; + let recovery_state = recovery::Memory::recovery_state(&self.init)?; + let require_visible = self + .primary + .state + .shared + .m5_board + .is_some_and(|board| board.firmware_cross_waits()); + self.queues.append_compute_prefix( + owner, + Some(qid), + &packet, + recovery_state, + require_visible, + &mut dependencies, + )?; + self.publish_compute_on( + owner, + Some(qid), + packet.clone(), + dependencies.as_slice(), + deferred, + ) + })() }; - let owner = owner.ok_or(EIO)?; - packet.check_replay_dependencies()?; - let mut dependencies = self.queues.render_prefix(owner, &packet)?; - let recovery_state = recovery::Memory::recovery_state(&self.init)?; - let require_visible = self - .primary - .state - .shared - .m5_board - .is_some_and(|board| board.firmware_cross_waits()); - self.queues.append_compute_prefix( - owner, - Some(qid), - &packet, - recovery_state, - require_visible, - &mut dependencies, - )?; - self.publish_compute_on( - owner, - Some(qid), - packet.clone(), - dependencies.as_slice(), - deferred, - ) - })() }; - let recovery_wait = matches!(result, Err(EAGAIN) | Err(EBUSY)) - && (self.recovery.pending() - || recovery::Memory::recovery_state(&self.init)? != 0); - let mut queue = self.queues.compute[index] - .as_mut() - .and_then(|entry| entry.queue.as_deref_mut()) - .ok_or(EIO)?; - if let Err(error) = result { - if recovery_wait && !queue.owns_packet(&packet) { - // Keep this prepared attempt and its one timeout credit - // while the outer worker closes the new recovery. - return Ok(()); - } - queue.fail_replays(error); - if !queue.owns_packet(&packet) { - // Replays are spared work a recovery dropped before it ran: it fails - // without poisoning its VM, as a dropped render group does. - if !packet.completion.guilty() { - packet.completion.classify(recovery::Class::Spared); + let recovery_wait = matches!(result, Err(EAGAIN) | Err(EBUSY)) + && (self.recovery.pending() + || recovery::Memory::recovery_state(&self.init)? != 0); + let mut queue = self.queues.compute[index] + .as_mut() + .and_then(|entry| entry.queue.as_deref_mut()) + .ok_or(EIO)?; + if let Err(error) = result { + if recovery_wait && !queue.owns_packet(&packet) { + // Keep this prepared attempt and its one timeout credit + // while the outer worker closes the new recovery. + return Ok(()); + } + queue.fail_replays(error); + if !queue.owns_packet(&packet) { + // Replays are spared work a recovery dropped before it ran: it fails + // without poisoning its VM, as a dropped render group does. + if !packet.completion.guilty() { + packet.completion.classify(recovery::Class::Spared); + } + queue.note_pending_failed(&packet); + deferred.push(Deferred::Retired( + packet.completion.clone(), + Err(ENODATA), + ))?; } - deferred - .push(Deferred::Retired(packet.completion.clone(), Err(ENODATA)))?; } + queue.finish_replay(&packet)?; + progressed = true; } - queue.finish_replay(&packet)?; } } + if waiting { + self.queues.replay_consumer_wait = Some(super::now_ns()); + return Ok(()); + } self.queues.replay_outer_wait = None; // Publication behind these replays may proceed. self.primary.state.shared.progress.notify(); diff --git a/drivers/gpu/drm/asahi/g17/runtime/render.rs b/drivers/gpu/drm/asahi/g17/runtime/render.rs index ca3c76df4a785..bd01806853549 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render.rs @@ -49,6 +49,8 @@ struct Entry { pending_owner_closed: bool, borrowed_active: bool, borrowed_dependencies: Option, + /// Owner and oldest parked sequence of a borrowed pair, if any. + borrowed_replay: Option<(u64, u64)>, /// `Pair::switch_in_flight` of a borrowed pair. A borrowed pair publishes /// nothing, so the snapshot can only be stale towards an older switch. borrowed_switch: Option, @@ -191,8 +193,14 @@ impl RenderState { if !pair.matches(owner, &packet.context)? { return Err(EIO); } + // Refuse to loan a pair with parked replay work so its parked frontier + // stays resident and ordered ahead of any new preparation on it. + if pair.replay_front().is_some() { + return Err(EBUSY); + } entry.borrowed_active = pair.published_in_flight(); entry.borrowed_dependencies = Some(pair.dependency_snapshot()); + entry.borrowed_replay = pair.replay_frontier(); entry.borrowed_switch = pair.switch_in_flight(); entry.preparing = Some(packet.clone()); entry.pair.take().ok_or(EIO) @@ -213,6 +221,7 @@ impl RenderState { } entry.pair = pair.take(); entry.borrowed_dependencies = None; + entry.borrowed_replay = None; entry.borrowed_switch = None; entry.preparing = None; Ok(()) @@ -663,6 +672,7 @@ impl Registry { pending_owner_closed: false, borrowed_active: false, borrowed_dependencies: None, + borrowed_replay: None, borrowed_switch: None, event_masks: [0; 2], missed_event: false, @@ -907,6 +917,10 @@ impl crate::g17::queue::render::Host for Host<'_> { fn generation(&self) -> u64 { self.firmware.recovery.generation() } + fn with_render_lock(&self, f: impl FnOnce()) { + let _render = self.firmware.port.render_lock(); + f(); + } fn epoch(&self) -> Result<(u64, u32)> { Ok(( self.firmware.recovery.generation(), diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs b/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs index f29c82fa641cd..3478e844f1677 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs @@ -227,6 +227,14 @@ impl crate::g17::Firmware { if self.queues.has_other_pair_dependencies(slot, owner, packet)? { return Ok(None); } + if self.queues.render.owner_parked_other_through( + owner, + usize::from(slot), + packet.order.wait_through[0], + packet.order.tiling_wait_through[0], + ) { + return Ok(None); + } let Ok(entry) = self.queues.render.entry_mut(slot) else { return Ok(None); }; @@ -507,6 +515,7 @@ impl Backend { dependencies.hazard_count = self.admission.publication_barriers( self.owner, slot, + packet.order.sequence, footprint, packet.order.wait_through[0], &mut dependencies.hazards, diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/grow.rs b/drivers/gpu/drm/asahi/g17/runtime/render/grow.rs index 913f0a503c785..02e2ac475b4a2 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/grow.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/grow.rs @@ -395,6 +395,8 @@ impl crate::g17::Shared { .is_some_and(|pair| pair.published_in_flight()); entry.borrowed_dependencies = entry.pair.as_ref().map(|pair| pair.dependency_snapshot()); + entry.borrowed_replay = + entry.pair.as_ref().and_then(|pair| pair.replay_frontier()); entry.borrowed_switch = entry.pair.as_ref().and_then(|pair| pair.switch_in_flight()); entry.growing = true; @@ -439,6 +441,7 @@ impl crate::g17::Shared { } entry.pair = pair.take(); entry.borrowed_dependencies = None; + entry.borrowed_replay = None; entry.borrowed_switch = None; entry.growing = false; // The grow work item requests an event pass when it finishes. diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs b/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs index 60eb1620fd985..8b4ca024ec222 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs @@ -370,6 +370,8 @@ impl super::super::Backend { .is_some_and(|pair| pair.published_in_flight()); entry.borrowed_dependencies = entry.pair.as_ref().map(|pair| pair.dependency_snapshot()); + entry.borrowed_replay = + entry.pair.as_ref().and_then(|pair| pair.replay_frontier()); entry.borrowed_switch = entry.pair.as_ref().and_then(|pair| pair.switch_in_flight()); Build::Rebind { @@ -754,6 +756,7 @@ impl super::super::Backend { entry.pending_owner_closed = false; entry.pair = Some(pair); entry.borrowed_dependencies = None; + entry.borrowed_replay = None; entry.borrowed_switch = None; // A displaced context's release is armed now: its other pairs are held as well. firmware.queues.sync_render_holds(); diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/replay.rs b/drivers/gpu/drm/asahi/g17/runtime/render/replay.rs index 2a8b406f288c7..6c1d0a2037c55 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/replay.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/replay.rs @@ -24,22 +24,52 @@ impl super::RenderState { } (executed, live) } + fn entry_parked_through(entry: &super::Entry, owner: u64, through: Option) -> bool { + if let Some(pair) = entry.pair.as_ref() { + pair.owner() == Some(owner) && pair.replay_through(through) + } else if let Some((borrowed_owner, sequence)) = entry.borrowed_replay { + borrowed_owner == owner && crate::g17::job::Order::contains(through, sequence) + } else { + false + } + } + /// A parked render of the owner precedes a command waiting through `through`. pub(in crate::g17) fn owner_parked_through(&self, owner: u64, through: Option) -> bool { self.entries .iter() .flatten() - .filter_map(|entry| entry.pair.as_ref()) - .any(|pair| pair.owner() == Some(owner) && pair.replay_through(through)) + .any(|entry| Self::entry_parked_through(entry, owner, through)) } - /// Whether any pair holds a group parked for replay. - pub(in crate::g17) fn replay_parked(&self) -> bool { + /// A parked render of the owner on a sibling slot precedes `through` (either wait frontier). + pub(in crate::g17) fn owner_parked_other_through( + &self, + owner: u64, + slot: usize, + through: Option, + tiling_through: Option, + ) -> bool { self.entries .iter() - .flatten() - .filter_map(|entry| entry.pair.as_ref()) - .any(|pair| pair.replay_front().is_some()) + .enumerate() + .filter(|(index, _)| *index != slot) + .filter_map(|(_, entry)| entry.as_ref()) + .any(|entry| { + Self::entry_parked_through(entry, owner, through) + || Self::entry_parked_through(entry, owner, tiling_through) + }) + } + + /// Whether any pair holds a group parked for replay. + pub(in crate::g17) fn replay_parked(&self) -> bool { + self.entries.iter().flatten().any(|entry| { + entry + .pair + .as_ref() + .is_some_and(|pair| pair.replay_front().is_some()) + || entry.borrowed_replay.is_some() + }) } pub(in crate::g17) fn replay_polling(&self) -> bool { @@ -61,9 +91,15 @@ impl Firmware { if crate::g17::recovery::Memory::recovery_state(&self.init)? != 0 { return Ok(()); } - for slot in 0..self.queues.render.entries.len() { - // Publish the parked groups front first; a pause keeps the rest parked. - while self.replay_render_front(slot, deferred)? {} + let mut progressed = true; + while progressed { + progressed = false; + for slot in 0..self.queues.render.entries.len() { + // Publish the parked groups front first; a pause keeps the rest parked. + while self.replay_render_front(slot, deferred)? { + progressed = true; + } + } } Ok(()) } @@ -100,6 +136,16 @@ impl Firmware { if busy { return Ok(false); } + // Defer while a covered sibling predecessor of the same owner is still parked on + // another slot so republication resolves its replacement kick into `render_prefix`. + if self.queues.render.owner_parked_other_through( + owner, + slot, + packet.order.wait_through[0], + packet.order.tiling_wait_through[0], + ) { + return Ok(false); + } if closed || packet.cancel_requested() || !packet.context.is_current() { self.with_render(slot, |pair, _| { pair.fail_replay(ECANCELED, &mut |event| deferred.push(event)) @@ -112,6 +158,18 @@ impl Firmware { })?; return Ok(false); } + // Fail before preparing or publishing if a producer's fence already + // signalled an error (for example a dropped compute replay); defer if + // a host input fence is still pending. + if let Err(error) = packet.check_replay_dependencies() { + if error == EBUSY || error == EAGAIN { + return Ok(false); + } + self.with_render(slot, |pair, _| { + pair.fail_replay(error, &mut |event| deferred.push(event)) + })?; + return Ok(false); + } let addresses = RenderAddresses { stamps: [ self.init.stamp_addresses(qids[0])?, diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs b/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs index a4f1e442c0fc4..d2ecfa19d7253 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs @@ -299,6 +299,30 @@ impl Backend { self.wait_domain(&self.shared.renders, sample, deadline, packet) } + /// A compute command this render waits for has no kick to name: it is parked for replay, or + /// failed and its fence is not signalled yet (`compute::Queue::dependency_checked`). Only an + /// event pass, which needs the device mutex, republishes or fails it, and then signals + /// `progress`. A compute publication behind the same command waits there too, and as long. + fn wait_compute_dependency( + &self, + clock: &mut WaitClock, + observed: &mut Option, + sleep: bool, + packet: &Packet, + ) -> Result { + if !sleep { + return Err(FALLBACK); + } + let deadline = self.wait_deadline(clock, crate::g17::preparation::QUEUE_WAIT_NS)?; + // Sample, then retry once: only a refusal after the sample waits. + let Some(sample) = observed.take() else { + *observed = Some(self.shared.progress.observe()); + return Ok(()); + }; + self.shared.queue_events(); + self.wait_domain(&self.shared.progress, sample, deadline, packet) + } + /// Render capacity is short: return what idle owners hold, then block until /// a pair, lease or owner returns. No packet is firmware-visible here, and /// neither the device mutex nor a preparation lease is held while waiting. @@ -454,6 +478,8 @@ impl Backend { let mut states = None; let mut outer_wait = None; let mut channel = WaitClock::default(); + let mut parked = WaitClock::default(); + let mut progress = None; loop { if packet.cancel_requested() { return Err(ECANCELED); @@ -536,6 +562,14 @@ impl Backend { continue; } Err(error) if !packet.is_published() && [EAGAIN, EBUSY].contains(&error) => { + if !deferred.is_idle() { + deferred.finish(); + if sleep { + packet.check_dependencies()?; + } else { + packet.check_firmware_producers()?; + } + } let (recovering, gate) = { let state = self.shared.state.lock(); let firmware = (*state).as_deref().ok_or(ENODEV)?; @@ -568,8 +602,8 @@ impl Backend { self.wait_domain(&domain, observed, deadline, packet)?; } else if error == EBUSY { self.wait_render_busy(&mut busy, &mut seen, sleep, packet)?; - } else if !sleep { - return Err(FALLBACK); + } else { + self.wait_compute_dependency(&mut parked, &mut progress, sleep, packet)?; } } result => return result, @@ -783,7 +817,16 @@ impl crate::g17::Firmware { if packet.completion.status().get() != 0 { return Err(EIO); } + if self.queues.render.owner_parked_other_through( + owner, + usize::from(slot), + packet.order.wait_through[0], + packet.order.tiling_wait_through[0], + ) { + return Err(EBUSY); + } let mut dependencies = self.queues.render_dependencies(owner, packet, state)?; + packet.check_firmware_producers()?; // Every render publication, with or without the device mutex, holds the // port's render lock: the render work rings have one host producer at a // time and attachment overlaps are ordered by publication order. @@ -812,6 +855,7 @@ impl crate::g17::Firmware { dependencies.hazard_count = self.queues.admission.publication_barriers( owner, slot, + packet.order.sequence, footprint, packet.order.wait_through[0], &mut dependencies.hazards, diff --git a/tools/asahi/g17-capacity-fault-tests.py b/tools/asahi/g17-capacity-fault-tests.py index 46b6ec3c51438..a51fee042923e 100644 --- a/tools/asahi/g17-capacity-fault-tests.py +++ b/tools/asahi/g17-capacity-fault-tests.py @@ -31,7 +31,8 @@ def fixture(): methods = '\n'.join(item(source, sig) for sig in [ 'fn witness_stamp(', 'pub(crate) fn release_owner(', 'pub(crate) fn reusable(', 'pub(crate) fn recycle_quarantined_idle(', 'pub(crate) fn recycle_killed(', - 'fn recycle_settled(', 'fn release_witnessed_inner(', 'pub(crate) fn share_idle(', 'pub(crate) fn shareable(', 'pub(crate) fn can_rearm(', 'pub(crate) fn recycled_pending(']) + 'fn recycle_settled(', 'fn release_witnessed_inner(', 'pub(crate) fn note_pending_failed(', + 'fn clear_owner(', 'pub(crate) fn share_idle(', 'pub(crate) fn shareable(', 'pub(crate) fn can_rearm(', 'pub(crate) fn recycled_pending(']) exit_source = (ROOT / 'queue/compute/exit.rs').read_text() methods += '\n' + (item(exit_source, 'pub(crate) fn settle_exit(').replace('super::Previous', 'Previous') .replace('crate::g17::qos::Owner', 'qos::Owner').replace('super::retirement::', 'retirement::')) @@ -43,7 +44,7 @@ def fixture(): proof += '\n' + item(retirement, 'pub(crate) fn unexecuted(') return r''' #![allow(dead_code)] -use std::sync::{Arc, atomic::{AtomicUsize, AtomicU32, Ordering}}; +use std::sync::{Arc, atomic::{AtomicI32, AtomicUsize, AtomicU32, Ordering}}; type Error = i32; type Result = std::result::Result; const EIO: Error = -5; @@ -52,6 +53,17 @@ def fixture(): const ENODATA: Error = -61; const ECANCELED: Error = -125; fn now_ns() -> u64 { 123 } +/// A completion fence: 0 until it signals, then 1 or a negative error. +#[derive(Clone)] struct CompletionFence(Arc); +mod g17 { pub(crate) mod job { + pub(crate) fn fence_status(fence: &crate::CompletionFence) -> i32 { fence.0.load(std::sync::atomic::Ordering::SeqCst) } +} } +struct Gfp; +const GFP_KERNEL: Gfp = Gfp; +struct KVec(Vec); +impl KVec { fn push(&mut self, value: T, _: Gfp) -> Result { self.0.push(value); Ok(()) } } +impl std::ops::Deref for KVec { type Target = Vec; fn deref(&self) -> &Vec { &self.0 } } +impl std::ops::DerefMut for KVec { fn deref_mut(&mut self) -> &mut Vec { &mut self.0 } } struct Context { id: u64, live: Arc, killed: AtomicU32 } impl Context { fn note_compute_binding(&self, _: bool) {} @@ -87,14 +99,20 @@ def fixture(): impl Exit { fn released(&self) -> bool { self.phase == Phase::Released } } struct State { killed: u32 } impl State { fn read(context: &Context) -> Result { Ok(Self { killed: context.killed.load(Ordering::SeqCst) }) } } -struct Completion; +struct Completion { fence: CompletionFence } impl Completion { + fn fence(&self) -> CompletionFence { self.fence.clone() } fn has_firmware_consumer(&self) -> bool { false } fn compute_words(&self) -> Result<[u32; 2]> { Ok([0, 0]) } fn replay_witness_words(&self) -> Option<[u32; 2]> { Some([0, 0]) } fn signalled(&self) -> bool { false } } -struct Packet { completion: Arc } +struct Order { sequence: u64 } +struct Packet { completion: Arc, order: Order } +fn command(sequence: u64) -> Arc { + Arc::new(Packet { completion: Arc::new(Completion { fence: CompletionFence(Arc::new(AtomicI32::new(0))) }), + order: Order { sequence } }) +} struct Active { packet: Arc, ticket: Option, observed: Option, qos_pending: bool, stamps_owed: bool } struct Fifo { entries: Vec, len: usize } impl Fifo { @@ -121,7 +139,7 @@ def fixture(): config_cache: Option<()>, source_hint: ReaderHint, source_readers: AtomicU32, claims: u32, fault_stamp: Option, configuration: Option<()>, retained_owner: Option<()>, timed_out_at: u64, m5_install: Option<()>, published_config: Option<()>, outer_started: u32, ordinal: u64, - channel_error: bool, + channel_error: bool, heavy_run: u8, pending_failed: KVec<(u64, CompletionFence)>, } impl Queue { fn valid_ticket(&self, _: &Active, _: &Ticket) -> Result { Ok(()) } @@ -133,12 +151,6 @@ def fixture(): self.binding_noted = false; } } - fn clear_owner(&mut self, stamp_released_at: bool) { - self.clear_binding_note(); - self.owner = None; - self.channel_index = 0; - if stamp_released_at { self.released_at = now_ns(); } - } ''' + methods + r''' } fn idle(live: &Arc) -> Queue { @@ -155,7 +167,7 @@ def fixture(): retire_pending: false, retirement_proved: false, replay_retirement: false, replay_error: None, replay_prepared: false, submitted: 0, kick: Kick, fault_stamp: None, config_cache: None, source_hint: ReaderHint { possible: false }, source_readers: AtomicU32::new(0), claims: 0, - configuration: None, retained_owner: None, timed_out_at: 0, + configuration: None, retained_owner: None, timed_out_at: 0, heavy_run: 0, pending_failed: KVec(vec![]), m5_install: None, published_config: None, outer_started: 0, ordinal: 0, } } @@ -163,7 +175,7 @@ def fixture(): let mut queue = idle(live); let old = Context::new(1, live); queue.previous = Some(Previous { binding: Some(Binding { context: old.clone() }), context: old, publication: Some((11, 3)), moved: false }); - queue.active.push(Active { packet: Arc::new(Packet { completion: Arc::new(Completion) }), + queue.active.push(Active { packet: command(7), ticket: Some(Ticket { owner: 2, item_count: 1280, descriptor: 0x1000, item_producer: 4, kick: 7 }), observed: None, qos_pending: true, stamps_owed: false }).unwrap(); queue.quarantined = true; queue.awaiting_witness = true; @@ -284,6 +296,31 @@ def fixture(): drop(queue); assert_eq!(live.load(Ordering::SeqCst), 0); } + // Spared work whose replay is refused fails with ENODATA. Its command stays noted, so that no + // consumer overtakes it, until that fence signals: the next failure, or a new owner, drops it. + let mut queue = fault(&live); + queue.spared_deferred = true; + let mut queued = Vec::new(); + assert_eq!(queue.release_witnessed_inner(0, true, |_| Ok(()), &mut |_| Err(EBUSY)), Err(EBUSY)); + assert_eq!(queue.active.len, 1); + queue.pending_failed.clear(); // Noted by the refused attempt, which stays retained. + queue.release_witnessed_inner(0, true, |_| Ok(()), &mut |event| { queued.push(event); Ok(()) }).unwrap(); + assert!(matches!(queued.pop(), Some(Deferred::Retired(_, Err(ENODATA))))); + assert_eq!((queue.active.len, queue.replays.len), (0, 0)); + let pending = |queue: &Queue| queue.pending_failed.iter().map(|(sequence, _)| *sequence).collect::>(); + assert_eq!(pending(&queue), vec![7], "a spared failure is noted until its fence signals"); + queue.pending_failed[0].1.0.store(ENODATA, Ordering::SeqCst); + let second = command(8); + queue.note_pending_failed(&second); + assert_eq!(pending(&queue), vec![8], "a signalled failure is dropped"); + queue.note_pending_failed(&command(9)); + assert_eq!(pending(&queue), vec![8, 9]); + queue.clear_owner(true); + assert_eq!(pending(&queue), Vec::::new(), "a new owner has no pending failures"); + assert_eq!(Arc::strong_count(&second), 1, "the note keeps the fence, not the packet"); + drop(queue); + drop(queued); + assert_eq!(live.load(Ordering::SeqCst), 0); let mut queue = idle(&live); let old = Context::new(1, &live); queue.previous = Some(Previous { binding: Some(Binding { context: old.clone() }), context: old, publication: None, moved: false }); @@ -315,11 +352,15 @@ def mutate(pattern, replacement): ('missing-idle-close', source.replace(idle_fix, ''), False), ('missing-fault-release', source.replace(fault_fix, '', 1), False), ('missing-kill-release', source.replace('Previous::retire_witnessed(&mut self.previous);\n self.exit', 'self.exit'), False), + ('spared-failure-unnoted', source.replace('self.note_pending_failed(&packet);', ''), False), + ('signalled-failure-kept', source.replace('if crate::g17::job::fence_status(&self.pending_failed[i].1) != 0 {', 'if false {'), False), + ('owner-keeps-failures', source.replace(' self.pending_failed.clear();\n if stamp', ' if stamp'), False), ('missing-reclaim-wake', source.replace('self.queue_events();', ''), False), ('share-before-retirement', mutate(r'(&&\s*self\.owner\.is_some\(\))\s*&&\s*self\.retirement_ready', r'\1'), False), ('share-during-kill', mutate(r'&&\s*self\.exit\.is_none\(\)\s*(?=&&\s*self\.active\.len)', ''), False)] with tempfile.TemporaryDirectory(prefix='g17-capacity-') as tmp: for name, rust, passes in controls: + assert passes or rust != source, f'vacuous control: {name}' path = Path(tmp) / (name + '.rs') binary = Path(tmp) / name path.write_text(rust) diff --git a/tools/asahi/g17-compute-deadline-tests.py b/tools/asahi/g17-compute-deadline-tests.py index fb3585ea7ec90..66da21b9fae93 100644 --- a/tools/asahi/g17-compute-deadline-tests.py +++ b/tools/asahi/g17-compute-deadline-tests.py @@ -5,7 +5,10 @@ Firmware/allocation/locking boundaries are mocks. Binding theft is the review's legal interleaving: every successful build loses its idle binding before publish. The oracle measures one total budget, including nested waits, rather than a -fresh timeout per attempt. Mutants must fail at the named assertion. +fresh timeout per attempt. A publication attempt replays parked commands first; +a predecessor that fails there has its fence signalled from the attempt's batch, +off the device mutex, before any retry or wait, and then fails the packet. +Mutants must fail at the named assertion. """ from pathlib import Path import os @@ -60,6 +63,12 @@ def fixture(): static MODE:AtomicUsize=AtomicUsize::new(0);static CANCEL:AtomicU64=AtomicU64::new(u64::MAX); static STATUS:AtomicU64=AtomicU64::new(u64::MAX);static CLOSED:AtomicBool=AtomicBool::new(false); static REPORTED:AtomicUsize=AtomicUsize::new(usize::MAX); +// The refusal a failed predecessor meets, and whether its fence signalled. +static REFUSAL:AtomicUsize=AtomicUsize::new(NONE);static SIGNALLED:AtomicBool=AtomicBool::new(false); +// Where an attempt is refused with a failed predecessor queued in its batch. +const NONE:usize=0;const UNBOUND:usize=1;const SIBLING:usize=2;const OUTER:usize=3;const PUBLICATION:usize=4; +fn refusal()->usize{REFUSAL.load(Ordering::SeqCst)} +thread_local!{static STATE_HELD:Cell=const{Cell::new(false)};} fn now_ns()->u64{NOW.load(Ordering::SeqCst)} fn advance(ns:u64){NOW.fetch_add(ns,Ordering::SeqCst);assert!(now_ns()<=PUBLICATION_WAIT_NS+4_000_000_000,"admission budget exceeded");} mod kernel{pub mod time{ @@ -88,29 +97,43 @@ def fixture(): struct Completion;impl Completion{fn status(&self)->Status{Status}fn work_state(&self)->Result{Ok(Work)}} struct Order{wait_through:[Option;2]} struct Packet{command:Validated,completion:Completion,order:Order} -impl Packet{fn check_dependencies(&self)->Result{Ok(())}fn cancel_requested(&self)->bool{now_ns()>=CANCEL.load(Ordering::SeqCst)}fn is_published(&self)->bool{false}} -struct DeferredBatch;impl DeferredBatch{fn publication()->Result{Ok(Self)}fn finish(&mut self){}} +impl Packet{fn check_dependencies(&self)->Result{if SIGNALLED.load(Ordering::SeqCst){Err(PRODUCER_FAILED)}else{Ok(())}}fn cancel_requested(&self)->bool{now_ns()>=CANCEL.load(Ordering::SeqCst)}fn is_published(&self)->bool{false}} +const PRODUCER_FAILED:i32=ECANCELED; +#[derive(Default)]struct DeferredBatch{failed:usize} +impl DeferredBatch{ + fn publication()->Result{Ok(Self::default())} + fn is_idle(&self)->bool{self.failed==0} + fn finish(&mut self){ + assert!(!STATE_HELD.with(Cell::get),"fences signal off the device mutex"); + if self.failed!=0{self.failed=0;SIGNALLED.store(true,Ordering::SeqCst);} + } +} struct Recovery;impl Recovery{fn pending(&self)->bool{MODE.load(Ordering::SeqCst)==1}} struct Init;impl Init{fn compute_vm_cached(&self,_:&())->bool{true}} struct Context;impl Context{fn vm(&self)->&(){&()}} struct Memory;impl Memory{fn recovery_state(_:&Init)->Result{Ok(0)}} struct Queues; impl Queues{ - fn compute_bound(&self,_:u64,_:&Context,_:usize)->Result{Ok(MODE.load(Ordering::SeqCst)!=0)} + fn compute_bound(&self,_:u64,_:&Context,_:usize)->Result{Ok(MODE.load(Ordering::SeqCst)!=0&&refusal()!=UNBOUND)} fn compute(&self,_:u64)->Option<()>{if MODE.load(Ordering::SeqCst)==0{None}else{Some(())}} fn render_prefix(&self,_:u64,_:&Arc)->Result>{Ok(vec![])} fn release_compute_witness(&self,_:&Init,_:&(),_:u64,_:&mut DeferredBatch)->Result{Ok(MODE.load(Ordering::SeqCst)==2)} - fn wants_compute_sibling(&self,_:u64,_:&Context,_:u8,_:usize)->bool{false} + fn wants_compute_sibling(&self,_:u64,_:&Context,_:u8,_:usize)->bool{refusal()==SIBLING} fn has_compute_sibling_headroom(&self,_:u64,_:&Context,_:usize)->bool{true} - fn bind_reusable_sibling(&mut self,_:u64,_:&Context,_:u8,_:usize)->Result>{Ok(None)} - fn compute_primary(&self,_:u64)->Option{None} + fn bind_reusable_sibling(&mut self,_:u64,_:&Context,_:u8,_:usize)->Result>{Ok(if refusal()==SIBLING{Some(false)}else{None})} + fn compute_primary(&self,_:u64)->Option{if refusal()==SIBLING{Some(Primary)}else{None}} } -struct Primary;impl Primary{fn sustained(&self)->bool{false}} +struct Primary;impl Primary{fn sustained(&self)->bool{true}} const SIBLING_HEADROOM_BACKOFF_NS:u64=10_000_000; struct Firmware{recovery:Recovery,init:Init,queues:Queues,port:()} // Mode 6: the publication itself refuses with EBUSY (no recovery): an immediate error, not a spent budget. -impl Firmware{fn replay_compute(&mut self,_:&mut DeferredBatch)->Result{Ok(())}fn publish_compute(&mut self,_:u64,_:Arc,_:&[()],_:&mut DeferredBatch)->Result{if MODE.load(Ordering::SeqCst)==6{advance(5_000_000);Err(EBUSY)}else{Err(EAGAIN)}}} -struct State(Mutex>>);impl State{fn lock(&self)->MutexGuard<'_,Option>>{self.0.lock().unwrap()}} +// A parked predecessor whose replay fails queues its error in the attempt's batch, once. +impl Firmware{fn replay_compute(&mut self,deferred:&mut DeferredBatch)->Result{if refusal()!=NONE&&!SIGNALLED.load(Ordering::SeqCst){deferred.failed+=1;}Ok(())}fn publish_compute(&mut self,_:u64,_:Arc,_:&[()],_:&mut DeferredBatch)->Result{if MODE.load(Ordering::SeqCst)==6{advance(5_000_000);Err(EBUSY)}else{Err(EAGAIN)}}} +struct Held<'a>(MutexGuard<'a,Option>>); +impl Drop for Held<'_>{fn drop(&mut self){STATE_HELD.with(|held|held.set(false));}} +impl std::ops::Deref for Held<'_>{type Target=Option>;fn deref(&self)->&Self::Target{&self.0}} +impl std::ops::DerefMut for Held<'_>{fn deref_mut(&mut self)->&mut Self::Target{&mut self.0}} +struct State(Mutex>>);impl State{fn lock(&self)->Held<'_>{let held=self.0.lock().unwrap();STATE_HELD.with(|flag|flag.set(true));Held(held)}} struct Available;impl Available{fn observe(&self)->u64{now_ns()}} struct Shared{preparations:Arc,state:State,crashed:AtomicBool,compute_blocks:usize,active_cores:u32,progress:Available}impl Shared{fn queue_events(&self){}} struct ComputeDemand;impl ComputeDemand{fn new(_:&Shared)->Self{Self}} @@ -120,15 +143,16 @@ def fixture(): impl Backend{ fn compute_capacity(&self,command:&Validated)->Result{let Validated::Compute{scratch}=command;required_blocks(self.shared.compute_blocks,self.shared.active_cores,scratch.pages())} // Off M5 there is no shared work ring: no outer domain, and a claim always holds. - fn outer_domain(&self)->Option>{None} - fn claim_outer(&self,_:&Firmware,engine:g17::job::Engine)->Result{assert_eq!(engine,g17::job::Engine::Compute,"compute admission takes a compute work state");Ok(true)} + fn outer_domain(&self)->Option>{if refusal()==OUTER{Some(Arc::new(Available))}else{None}} + fn claim_outer(&self,_:&Firmware,engine:g17::job::Engine)->Result{assert_eq!(engine,g17::job::Engine::Compute,"compute admission takes a compute work state");Ok(refusal()!=OUTER)} fn publish_claimed(&self,firmware:&mut Firmware,packet:&Arc,dependencies:&[()],deferred:&mut DeferredBatch)->Result{firmware.publish_compute(self.owner,packet.clone(),dependencies,deferred)} fn compute_direct(&self,_:&Arc,_:usize,_:&mut DeferredBatch)->Option{None} fn sources_published(&self,_:&Arc)->Result{Ok(true)} fn remember_direct(&self,_:&Queues){} - fn try_add_compute_sibling(&self,_:usize,_:&Admission<'_>)->Result{Ok(false)} + fn try_add_compute_sibling(&self,_:usize,_:&Admission<'_>)->Result{assert!(SIGNALLED.load(Ordering::SeqCst),"a failed predecessor ends the retry");Ok(false)} fn fans_out(&self,_:&Packet,primary_sustained:impl FnOnce()->bool)->bool{self.compute_channels>1&&primary_sustained()} fn wait_release(&self,_:&Available,_:u64,admission:&Admission<'_>)->Result{ + assert!(refusal()==NONE||SIGNALLED.load(Ordering::SeqCst),"no wait while a failed predecessor's fence is unsignalled"); let _=admission.slice_ms()?; advance(1_000_000); admission.check() @@ -149,12 +173,15 @@ def fixture(): } ''' + ensure + '\n' + packet + r''' } +fn backend()->Backend{ + Backend{owner:1,context:Context,compute_channels:1,sibling_backoff_until:AtomicU64::new(0),shared:Shared{compute_blocks:21,active_cores:1,progress:Available,preparations:Arc::new(Gate{wait:Wait,changed:Changed}),state:State(Mutex::new(Some(Box::new(Firmware{recovery:Recovery,init:Init,queues:Queues,port:()})))),crashed:AtomicBool::new(false)}} +} fn main(){ - let b=Backend{owner:1,context:Context,compute_channels:1,sibling_backoff_until:AtomicU64::new(0),shared:Shared{compute_blocks:21,active_cores:1,progress:Available,preparations:Arc::new(Gate{wait:Wait,changed:Changed}),state:State(Mutex::new(Some(Box::new(Firmware{recovery:Recovery,init:Init,queues:Queues,port:()})))),crashed:AtomicBool::new(false)}}; + let b=backend(); let p=Arc::new(Packet{command:Validated::Compute{scratch:Scratch},completion:Completion,order:Order{wait_through:[None,None]}}); for mode in 0..4 { MODE.store(mode,Ordering::SeqCst);NOW.store(0,Ordering::SeqCst);CALLS.store(0,Ordering::SeqCst);REPORTED.store(usize::MAX,Ordering::SeqCst); - let r=b.compute_packet(&p,&mut DeferredBatch); + let r=b.compute_packet(&p,&mut DeferredBatch::default()); assert_eq!(r,Err(EBUSY),"one admission budget covers binding theft/recovery/publication"); let named=[AdmissionWait::Channel,AdmissionWait::Recovery,AdmissionWait::Publication,AdmissionWait::Publication][mode]; assert_eq!(REPORTED.load(Ordering::SeqCst),named as usize,"the report names the wait the budget went to"); @@ -166,14 +193,14 @@ def fixture(): // A context without a free work state waits for one under the admission // deadline instead of failing the packet at once. MODE.store(4,Ordering::SeqCst);NOW.store(0,Ordering::SeqCst);CALLS.store(0,Ordering::SeqCst);REPORTED.store(usize::MAX,Ordering::SeqCst); - let r=b.compute_packet(&p,&mut DeferredBatch); + let r=b.compute_packet(&p,&mut DeferredBatch::default()); assert_eq!(r,Err(EBUSY),"a busy work state ends at the admission deadline"); assert_eq!(REPORTED.load(Ordering::SeqCst),AdmissionWait::WorkState as usize,"the report names the wait the budget went to"); assert!(now_ns()>=QUEUE_WAIT_NS&&now_ns()<=QUEUE_WAIT_NS+10_000_000,"a busy work state waits for the admission deadline"); println!("PASS busy work state waits elapsed_ms={}",now_ns()/1_000_000); // An EBUSY refusal before the deadline is returned as before and is not a spent budget. MODE.store(6,Ordering::SeqCst);NOW.store(0,Ordering::SeqCst);REPORTED.store(usize::MAX,Ordering::SeqCst); - let r=b.compute_packet(&p,&mut DeferredBatch); + let r=b.compute_packet(&p,&mut DeferredBatch::default()); assert_eq!(r,Err(EBUSY),"a refusal is returned at once"); assert!(now_ns() i32 { fence.0.get() } } pub(crate) mod pairs { ''' + gate + r''' @@ -162,22 +164,34 @@ def fixture(): impl KVec { fn with_capacity(capacity: usize, _: Flags) -> Result { Ok(Self(Vec::with_capacity(capacity))) } fn push_within_capacity(&mut self, value: T) -> std::result::Result<(), T> { self.0.push(value); Ok(()) } + fn push(&mut self, value: T, _: Flags) -> Result { self.0.push(value); Ok(()) } } impl Deref for KVec { type Target = Vec; fn deref(&self) -> &Vec { &self.0 } } impl DerefMut for KVec { fn deref_mut(&mut self) -> &mut Vec { &mut self.0 } } +/// A completion fence: 0 until it signals, then 1 or a negative error. +#[derive(Clone)] +pub struct CompletionFence(std::rc::Rc>); pub struct VmStatus; pub struct Completion { result: RefCell>>, + fence: CompletionFence, class: Cell>, status: Arc, } impl Completion { - fn new() -> Self { Self { result: RefCell::new(None), class: Cell::new(None), status: Arc::new(VmStatus) } } + fn new() -> Self { + Self { result: RefCell::new(None), fence: CompletionFence(Default::default()), class: Cell::new(None), + status: Arc::new(VmStatus) } + } + fn fence(&self) -> CompletionFence { self.fence.clone() } /// The first result signals the fence; later ones change nothing. fn signal(&self, result: Result<[u64; 4]>) { let mut slot = self.result.borrow_mut(); - if slot.is_none() { *slot = Some(result); } + if slot.is_none() { + *slot = Some(result); + self.fence.0.set(result.map_or_else(|error| error.0, |_| 1)); + } } fn spared(&self) -> bool { self.class.get() == Some(recovery::Class::Spared) } fn guilty(&self) -> bool { self.class.get() == Some(recovery::Class::Guilty) } @@ -211,9 +225,12 @@ def fixture(): pub struct Context { vm: Vm } impl Context { fn vm(&self) -> &Vm { &self.vm } } pub struct Order { sequence: u64 } -pub struct Packet { completion: Arc, order: Order, context: Context, forfeited: Cell } +pub struct Packet { + completion: Arc, order: Order, context: Context, forfeited: Cell, + producers: Cell, +} impl Packet { - fn check_firmware_producers(&self) -> Result { Ok(()) } + fn check_firmware_producers(&self) -> Result { self.producers.get() } fn within_allowance(&self, _: u64) -> bool { false } fn forfeit_allowance(&self) -> bool { !self.forfeited.replace(true) } fn allowance_forfeited(&self) -> bool { self.forfeited.get() } @@ -260,6 +277,8 @@ def fixture(): fault_stamp: Option, timed_out_at: u64, exit: Option<()>, + channel_index: u8, + pending_failed: KVec<(u64, CompletionFence)>, } impl Queue { fn qid(&self) -> u8 { 28 } @@ -267,10 +286,7 @@ def fixture(): fn retire_configuration(&mut self, _: u64) -> Result { Ok(()) } fn valid_ticket(&self, _: &Active, _: &Ticket) -> Result { Ok(()) } fn qos_owner(&self) -> qos::Owner { qos::Owner } - fn clear_owner(&mut self, stamp_released_at: bool) { - self.owner = None; - if stamp_released_at { self.released_at = now_ns(); } - } + fn clear_binding_note(&mut self) {} ''' + queue + r''' } @@ -350,14 +366,15 @@ def fixture(): spared_deferred: false, awaiting_witness: false, retire_pending: false, last_end: 0, previous: None, submitted: 0, retirement_ready: true, released: false, owner: Some(OWNER), released_at: 0, heavy_run: 0, terminal: None, fault_stamp: None, timed_out_at: 0, - exit: None, + exit: None, channel_index: 0, pending_failed: KVec(Vec::new()), } } /// Publishes the command of kick `kick`; `drained`: the rest of its ioctl completed. fn publish(queue: &mut Queue, kick: u64, drained: bool) -> Arc { let packet = Arc::new(Packet { completion: Arc::new(Completion::new()), - order: Order { sequence: kick }, context: Context { vm: Vm(70) }, forfeited: Cell::new(false) }); + order: Order { sequence: kick }, context: Context { vm: Vm(70) }, forfeited: Cell::new(false), + producers: Cell::new(Ok(())) }); let ticket = Ticket { owner: OWNER, submission: kick, context_id: 1, qid: 28, descriptor: 0x1000 + kick, work_node: 0x2000, kick, ordinal: kick as u32, item_producer: 4, item_count: 64, epoch: EPOCH }; @@ -758,6 +775,45 @@ def fixture(): with_queue(&b, |q| assert!(q.quarantined)); } + #[test] + fn a_command_failed_by_its_producer_is_noted_until_its_fence_signals() { + for m5 in [true, false] { + let mut q = queue(m5); + let p1 = publish(&mut q, 0x10, true); + let p2 = publish(&mut q, 0x11, true); + record(&mut q, &p1, [100, 200]); + record(&mut q, &p2, [210, 300]); + p1.producers.set(Err(EIO)); + q.graph.stamp.set(stamp_of(0x11)); + let b = backend(q, vec![]); + let noted = |b: &Backend| with_queue(b, |q| { + q.pending_failed.iter().map(|(sequence, fence)| (*sequence, g17::job::fence_status(fence))).collect::>() + }); + let mut deferred = DeferredBatch::worker().unwrap(); + with_firmware(&b, |firmware| firmware.scan_compute(None, &mut deferred)).unwrap(); + with_queue(&b, |q| assert_eq!(q.active.len, 0, "both left the ring")); + assert_eq!(noted(&b), vec![(0x10, 0)], "m5 {m5}: only the failed command, its fence not signalled"); + deferred.finish(); + assert_eq!(result(&p1), Some(Err(EIO))); + assert_eq!(result(&p2), Some(Ok([210, 300, 0, 0]))); + assert_eq!(noted(&b), vec![(0x10, EIO.0)]); + // The next failure drops what signalled meanwhile. + let p3 = with_queue(&b, |q| { + let p3 = publish(q, 0x12, true); + record(q, &p3, [310, 400]); + p3.producers.set(Err(EIO)); + q.graph.stamp.set(stamp_of(0x12)); + p3 + }); + with_firmware(&b, |firmware| firmware.scan_compute(None, &mut deferred)).unwrap(); + assert_eq!(noted(&b), vec![(0x12, 0)], "m5 {m5}: the signalled one is dropped"); + with_queue(&b, |q| q.clear_owner(true)); + assert_eq!(noted(&b), vec![], "a new owner starts without pending failures"); + deferred.finish(); + assert_eq!(result(&p3), Some(Err(EIO))); + } + } + #[test] fn only_the_recorded_oldest_command_has_its_stamp_wait_ended() { let mut q = queue(false); @@ -813,6 +869,12 @@ def fixture(): 'if !queue.owns_packet(packet) {')], 'no-owed-poll': [(' if at != 0 {\n // Owed stamps come without a completion event', ' if false {\n // Owed stamps come without a completion event')], + # A failed command leaves the ring unnoted, stays noted after its fence signalled, or + # outlives its owner. + 'failed-unnoted': [('if failed {\n self.note_pending_failed(&packet);', 'if false {\n self.note_pending_failed(&packet);')], + 'succeeded-noted': [('if failed {\n self.note_pending_failed(&packet);', 'if true {\n self.note_pending_failed(&packet);')], + 'signalled-kept': [('if crate::g17::job::fence_status(&self.pending_failed[i].1) != 0 {', 'if false {')], + 'owner-keeps-failures': [(' self.pending_failed.clear();\n if stamp_released_at {', ' if stamp_released_at {')], # A recordless retirement's synthesized envelope counts as an execution. 'count-recordless': [('let execution = front.observed.map(|record| record.timestamps);', 'let execution = Some(timestamps);')], diff --git a/tools/asahi/g17-render-owed-stamp-tests.py b/tools/asahi/g17-render-owed-stamp-tests.py index ae28621ebf193..ce9f054e0c1ee 100755 --- a/tools/asahi/g17-render-owed-stamp-tests.py +++ b/tools/asahi/g17-render-owed-stamp-tests.py @@ -37,7 +37,11 @@ - `Backend::defer_timeout()`, `Registry::render_timeout_decision()`, `Firmware::fail_render_packet()`, and `Pair::fail_after_observation()` return cleanly (`Decision::Retire` / `None` / `Ok(())` / `Ok(false)`) for groups that - retired stampless rather than failing them or quarantining running successors. + retired stampless rather than failing them or quarantining running successors; +- `replay_abandoned()` parks each dropped group, and `retire_front_command()` notes each executed + one, in its admission record (`Packet::reset_publication_for_replay()`, + `Completion::note_render_parked_for_replay()`, `Completion::note_render_executed()`) inside + `Host::with_render_lock()`, exactly once. Each `--mutation` restores one defect or drops one guard and must fail. """ @@ -82,6 +86,7 @@ def fixture(): render_src = (G17 / 'queue/render.rs').read_text() replay_src = (G17 / 'replay.rs').read_text() completion_src = (G17 / 'completion.rs').read_text() + job_src = (G17 / 'job.rs').read_text() settle_src = (G17 / 'runtime/render/settle.rs').read_text() rt_render_src = (G17 / 'runtime/render.rs').read_text() backend_src = (G17 / 'runtime/backend.rs').read_text() @@ -183,12 +188,21 @@ def fixture(): ] ) defer_timeout_fn = item(backend_src, ' fn defer_timeout(') + hazard_record_fns = '\n'.join(item(completion_src, sig) for sig in [ + 'pub(crate) fn note_render_parked_for_replay(', + 'pub(crate) fn note_render_executed(', + ]) + reset_fn = item(job_src, 'pub(crate) fn reset_publication_for_replay(') + render_lock_fn = item(render_src, 'fn with_render_lock(&self, f: impl FnOnce())') + # The firmware host serializes against direct publication with the port's render lock. + locked = item(rt_render_src, 'fn with_render_lock(&self, f: impl FnOnce())') + assert locked.index('let _render = self.firmware.port.render_lock();') < locked.index('f();') return r''' #![allow(warnings)] use std::cell::{Cell, RefCell, RefMut}; use std::collections::{BTreeMap, VecDeque}; -use std::sync::atomic::{fence, Ordering}; +use std::sync::atomic::{fence, AtomicU8, Ordering}; use std::sync::Arc; #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -205,6 +219,7 @@ def fixture(): thread_local! { static NOW: Cell = Cell::new(1_000_000_000); static WARNS: RefCell> = RefCell::new(Vec::new()); + static RENDER_LOCK: Cell = Cell::new(false); } pub fn now_ns() -> u64 { NOW.with(|now| now.get()) } fn advance(ns: u64) { NOW.with(|now| now.set(now.get() + ns)); } @@ -293,8 +308,23 @@ def fixture(): fn drained(&self) -> Result { Ok(self.drained.get()) } } +/// The admission record of a render: which transitions it saw, each under the render lock. +#[derive(Default)] +pub struct RenderLease { parked: Cell, executed: Cell } +impl RenderLease { + fn noted(count: &Cell) { + assert!(RENDER_LOCK.with(|held| held.get()), "hazard records change under the render lock"); + count.set(count.get() + 1); + } + fn note_parked_for_replay(&self) { Self::noted(&self.parked); } + fn note_executed(&self) { Self::noted(&self.executed); } +} +pub struct RenderSlot(RefCell>); +impl RenderSlot { fn lock(&self) -> RefMut<'_, Option> { self.0.borrow_mut() } } + pub struct Completion { status: Arc, + render: RenderSlot, slot: Cell>, work: WorkState, class: Cell>, @@ -311,6 +341,7 @@ def fixture(): fn new(status: Arc, slot: u8, drained: bool) -> Arc { Arc::new(Self { status, + render: RenderSlot(RefCell::new(Some(RenderLease::default()))), slot: Cell::new(Some(slot)), work: WorkState { drained: Cell::new(drained) }, class: Cell::new(None), @@ -352,6 +383,11 @@ def fixture(): } } fn quarantine_render(&self) { self.quarantined.set(true); } + /// How often the admission record was parked for replay and noted as executed. + fn recorded(&self) -> (usize, usize) { + self.render.lock().as_ref().map(|lease| (lease.parked.get(), lease.executed.get())).unwrap() + } +''' + hazard_record_fns + r''' fn signal(&self, result: Result<[u64; 4]>) { self.results.borrow_mut().push(result); } fn result(&self) -> Option> { self.results.borrow().first().copied() } fn signal_count(&self) -> usize { self.results.borrow().len() } @@ -400,6 +436,7 @@ def fixture(): completion: Arc, context: Arc, allowance: Cell, + publication: AtomicU8, } impl Packet { // Compute-allowance forfeit (main, after this test was written): the render @@ -409,7 +446,7 @@ def fixture(): fn engine(&self) -> Engine { Engine::Render } fn check_firmware_producers(&self) -> Result { Ok(()) } fn within_allowance(&self, _: u64) -> bool { self.allowance.get() } - fn reset_publication_for_replay(&self) {} +''' + reset_fn + r''' } pub struct KickTimestamp; @@ -476,6 +513,7 @@ def fixture(): use observation::snapshot; pub trait Host { +''' + render_lock_fn + r''' fn epoch(&self) -> Result<(u64, u32)>; fn generation(&self) -> u64; fn stamps(&self, qids: [u8; 2]) -> Result<[u32; 2]>; @@ -518,6 +556,11 @@ def fixture(): } } impl Host for FakeHost { + fn with_render_lock(&self, f: impl FnOnce()) { + assert!(!RENDER_LOCK.with(|held| held.replace(true)), "the render lock does not nest"); + f(); + RENDER_LOCK.with(|held| held.set(false)); + } fn epoch(&self) -> Result<(u64, u32)> { self.epoch_reads.set(self.epoch_reads.get() + 1); Ok((self.generation, self.recovery_state)) @@ -814,6 +857,7 @@ def fixture(): completion: Completion::new(status.clone(), pair.slot, drained), context: ctx.clone(), allowance: Cell::new(false), + publication: AtomicU8::new(2), }); let win = Window::new(base, 2, CAP).unwrap(); let prev = Cursors { done: base, read: base, write: base }; @@ -1454,6 +1498,56 @@ def fixture(): ); } + #[test] + fn parking_and_execution_are_recorded_once_under_the_render_lock() { + let (mut pair, ctx, status) = make_pair(99, false); + let p0 = push_group(&mut pair, &ctx, &status, 10, 100, 0, true); + let p1 = push_group(&mut pair, &ctx, &status, 11, 101, 2, true); + let p2 = push_group(&mut pair, &ctx, &status, 12, 102, 4, true); + let mut batch = DeferredBatch::new(); + let mut host = FakeHost::new([stamp(11), stamp(11)]); + + // The first group executes and retires with its stamps. + finish_gpu(&pair, 10, [100, 200], 2); + assert_eq!(pair.retire(None, 1, 0, &mut host, &mut |e| batch.push(e)), Ok(true)); + batch.finish(); + assert_eq!(p0.completion.result(), Some(Ok([100, 100, 100, 200]))); + assert_eq!(p0.completion.recorded(), (0, 1), "an executed render is noted once"); + + // The firmware dropped the other two unexecuted: both are parked after the grace. + let mut cursors = pair.memory.cursors.get(); + for c in &mut cursors { c.done = 6; c.read = 6; } + pair.memory.cursors.set(cursors); + pair.memory.job_list_empty.set(true); + host.set_stamps([stamp(13), stamp(13)]); + assert_eq!(pair.retire(None, 1, 0, &mut host, &mut |e| batch.push(e)), Ok(false)); + assert_eq!((p1.completion.recorded(), p2.completion.recorded()), ((0, 0), (0, 0))); + advance(ABANDON_GRACE_NS); + assert_eq!(pair.retire(None, 1, 0, &mut host, &mut |e| batch.push(e)), Ok(true)); + assert_eq!((pair.active.len(), pair.replay.len()), (0, 2)); + for p in [&p1, &p2] { + assert_eq!(p.completion.recorded(), (1, 0), "a parked render drops its discarded kick"); + assert_eq!(p.publication.load(Ordering::Acquire), 1, "it publishes again"); + assert_eq!(p.completion.result(), None); + } + + // A group retired without its stamps executed too; its late stamp notes nothing again. + let (mut pair, ctx, status) = make_pair(100, false); + let late = push_group(&mut pair, &ctx, &status, 10, 100, 0, true); + finish_gpu(&pair, 10, [100, 200], 2); + host.set_stamps([stamp(10), stamp(10)]); + assert_eq!(pair.note_stamp_wait([stamp(10), stamp(10)], 0, now_ns()), Ok(false)); + advance(STAMP_FALLBACK_NS); + assert_eq!(pair.retire(None, 1, 0, &mut host, &mut |e| batch.push(e)), Ok(true)); + assert!(pair.retired_held(&late)); + assert_eq!(late.completion.recorded(), (0, 1)); + host.set_stamps([stamp(11), stamp(11)]); + assert_eq!(pair.retire(None, 1, 0, &mut host, &mut |e| batch.push(e)), Ok(true)); + batch.finish(); + assert_eq!(late.completion.recorded(), (0, 1)); + assert!(!RENDER_LOCK.with(|held| held.get())); + } + #[test] fn recovery_context_pass_started_and_running_start_ignore_stamps_owed() { // An all-stamps_owed pair must be omitted from visit_contexts(), pass_started(), @@ -1694,6 +1788,20 @@ def fixture(): ('.find(|pair| pair.contains_packet(packet) && !pair.retired_held(packet))', '.find(|pair| pair.contains_packet(packet))'), ], + 'park-outside-render-lock': [ + ('host.with_render_lock(|| packet.reset_publication_for_replay());', + 'packet.reset_publication_for_replay();'), + ], + 'park-keeps-kick': [ + (' self.completion.note_render_parked_for_replay();\n', ''), + ], + 'executed-outside-render-lock': [ + ('host.with_render_lock(|| front.packet.completion.note_render_executed());', + 'front.packet.completion.note_render_executed();'), + ], + 'executed-not-noted': [ + (' host.with_render_lock(|| front.packet.completion.note_render_executed());\n', ''), + ], 'visit-contexts-includes-owed': [ ('pub(crate) fn visit_contexts(&self, visit: &mut dyn FnMut(u32)) {\n' ' for active in self.active.iter().filter(|active| !active.stamps_owed) {', diff --git a/tools/asahi/g17-render-parked-dependency-tests.py b/tools/asahi/g17-render-parked-dependency-tests.py new file mode 100755 index 0000000000000..1687c3a64ecae --- /dev/null +++ b/tools/asahi/g17-render-parked-dependency-tests.py @@ -0,0 +1,596 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""A render whose compute dependency is parked for replay waits for it, within a bound. + +A compute command a recovery dropped leaves its ring and waits, parked, until an event pass +republishes or fails it. Until then a render that waits for it has no kick to name, and +`compute::Queue::dependency_checked()` refuses it with EAGAIN. The event pass needs the device +mutex, which every publication attempt takes as well. + +The production publication loop and its waits (`runtime/render/submit.rs`: +`render_with_lease()`, `publication_open()` to `wait_compute_dependency()`, `WaitClock`) and the +production refusal (`queue/compute.rs`: `replay_through()`, `note_pending_failed()`, +`dependency()`, `dependency_checked()`) run here against a modelled clock and event worker. +Preparation itself, allocation and the firmware are stubs. It checks that a sleeping publisher + +- makes at most one further attempt before each wait, holds neither the device mutex nor a + preparation lease while it waits, and requests an event pass first; +- publishes behind the replacement kick as soon as the replay notifies, also after the longest a + replay may stay parked (a live consumer, then a full work ring); +- fails with the producer's error once a failed replay's fence signals, and not before; +- gives up at one deadline, and at once when cancelled; + +and that the submitting ioctl falls back without waiting, that a busy pair keeps its own bound and +wake-up, and that an attempt's queued completions are signalled off the device mutex before the +next wait. + +Each `--mutation` restores an old behaviour or drops one part of the rule and must fail. +""" +from pathlib import Path +import argparse +import os +import re +import subprocess +import tempfile + +G17 = Path(__file__).resolve().parents[2] / 'drivers/gpu/drm/asahi/g17' + + +def item(source, signature): + """The item that starts at `signature`, through its closing brace.""" + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def constant(source, name): + found = re.findall(r'^(?:pub\(\w+\) )?(const ' + name + r': [^;]+;)', source, re.M) + assert len(found) == 1, name + return found[0] + + +def fixture(): + submit = (G17 / 'runtime/render/submit.rs').read_text() + compute = (G17 / 'queue/compute.rs').read_text() + job = (G17 / 'job.rs').read_text() + # The waits of one publication, in source order. + first = ' /// Conditions which end a publication that has not become visible yet.\n' + last = ' /// Render capacity is short: ' + assert submit.count(first) == 1 and submit.count(last) == 1 + waits = submit[submit.index(first):submit.index(last)] + backend = waits + item(submit, 'fn render_with_lease(') + clock = '\n'.join([ + constant(submit, 'CAPACITY_PAUSE_MIN_NS'), constant(submit, 'CAPACITY_PAUSE_MAX_NS'), + '#[derive(Default)]', item(submit, 'struct WaitClock {'), item(submit, 'impl WaitClock {'), + item(submit, 'fn recovery_wait_ns()')]) + queue = '\n'.join(item(compute, signature) for signature in [ + 'pub(crate) fn replay_through(', 'pub(crate) fn note_pending_failed(', + 'pub(crate) fn dependency(', 'pub(crate) fn dependency_checked(']) + order = item(job, 'pub(crate) fn contains(') + consumer_wait = constant((G17 / 'runtime/compute_replay.rs').read_text(), 'CONSUMER_WAIT_NS') + queue_wait = constant((G17 / 'preparation.rs').read_text(), 'QUEUE_WAIT_NS') + timeout = (G17 / 'timeout.rs').read_text() + timeouts = '\n'.join('pub(crate) ' + constant(timeout, name) for name in [ + 'POLL_MS', 'EXECUTION_RENEWALS', 'MAX_RENEWALS', 'RECOVERY_WAIT_MS']) + ring_wait = constant((G17 / 'runtime.rs').read_text(), 'WORK_RING_WAIT_NS').replace( + 'super::job::TIMEOUT_MS', 'crate::g17::timeout::POLL_MS') + assert 'TIMEOUT_MS: kernel::time::Msecs = super::timeout::POLL_MS;' in job + + def host(code): + return code.replace('super::super::', 'rt::') + + return r''' +#![allow(warnings)] +use std::cell::{Cell, RefCell, RefMut}; +use std::collections::VecDeque; +use std::rc::Rc; +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; +use std::sync::Arc; + +pub type Result = std::result::Result; +pub const EIO: i32 = -5; +pub const EAGAIN: i32 = -11; +pub const EFAULT: i32 = -14; +pub const EBUSY: i32 = -16; +pub const ENODEV: i32 = -19; +pub const ENOSPC: i32 = -28; +pub const ETIMEDOUT: i32 = -110; +pub const FALLBACK: i32 = -115; +pub const ECANCELED: i32 = -125; +const MS: u64 = 1_000_000; + +mod g17 { + pub(crate) mod timeout { +''' + timeouts + r''' + } + pub(crate) mod preparation { pub(crate) ''' + queue_wait + r''' } + pub(crate) mod context { pub(crate) const RENDER_CHANNEL_PENDING: i32 = -1000; } + pub(crate) mod dependency { pub(crate) const PRODUCER_FAILED: i32 = crate::ECANCELED; } + pub(crate) mod availability { pub(crate) use crate::Availability; } + pub(crate) mod recovery { + pub(crate) struct Memory; + impl Memory { pub(crate) fn recovery_state(_: &crate::Init) -> crate::Result { Ok(0) } } + } + pub(crate) mod command { + pub(crate) enum Validated { Compute { visible_completion: bool }, Render } + } + pub(crate) mod job { + #[derive(Clone, Copy, Debug, PartialEq)] + pub(crate) enum Engine { Render, Compute } + #[derive(Default)] + pub(crate) struct Order { pub(crate) sequence: u64, pub(crate) wait_through: [Option; 2] } + impl Order { +''' + order + r''' + } + pub(crate) fn fence_status(fence: &crate::CompletionFence) -> i32 { fence.0.get() } + } + pub(crate) mod fw { pub(crate) mod kick { + #[derive(Clone, Copy, Debug, PartialEq)] + pub(crate) struct KickTimestamp(u64); + impl KickTimestamp { pub(crate) fn new(kick: u64) -> Option { Some(Self(kick)) } } + #[derive(Clone, Copy, Debug, PartialEq)] + pub(crate) struct KickDependency(pub(crate) u8, pub(crate) KickTimestamp); + impl KickDependency { + pub(crate) fn new(qid: u8, kick: KickTimestamp) -> Option { Some(Self(qid, kick)) } + } + } } +} +use g17::fw::kick::{KickDependency, KickTimestamp}; +use g17::job::Order; + +mod rt { + pub(crate) fn now_ns() -> u64 { crate::NOW.with(|now| now.get()) } + pub(crate) ''' + ring_wait + r''' +} +''' + consumer_wait + r''' + +// The modelled clock, and the event worker's steps on it. +thread_local! { + static NOW: Cell = const { Cell::new(0) }; + static STEPS: RefCell)>> = const { RefCell::new(VecDeque::new()) }; + static STATE_HELD: Cell = const { Cell::new(false) }; + static LEASES: Cell = const { Cell::new(0) }; + static BLOCKS: Cell = const { Cell::new(0) }; + static ATTEMPTS: Cell = const { Cell::new(0) }; + static REQUESTED: Cell = const { Cell::new(false) }; +} +fn now() -> u64 { rt::now_ns() } +/// Runs the worker's steps due by `until`, up to and including the first that ends `done`. +fn advance_until(until: u64, done: impl Fn() -> bool) { + loop { + let due = STEPS.with(|steps| steps.borrow().front().is_some_and(|(at, _)| *at <= until)); + if !due { break; } + let (at, step) = STEPS.with(|steps| steps.borrow_mut().pop_front().unwrap()); + NOW.with(|now| now.set(now.get().max(at))); + step(); + if done() { return; } + } + NOW.with(|now| now.set(now.get().max(until))); +} +fn at(when: u64, step: impl FnOnce() + 'static) { + STEPS.with(|steps| steps.borrow_mut().push_back((when, Box::new(step)))); +} + +pub struct Availability { name: &'static str, generation: Cell, blocks: Cell } +impl Availability { + fn new(name: &'static str) -> Self { Self { name, generation: Cell::new(0), blocks: Cell::new(0) } } + fn observe(&self) -> u64 { self.generation.get() } + fn notify(&self) { self.generation.set(self.generation.get() + 1); } + fn block(&self, sample: u64, ms: u32, _interruptible: bool) -> Result { + assert!((1..=10).contains(&ms), "waits are sliced for cancellation"); + assert!(!STATE_HELD.with(Cell::get), "a publisher waits without the device mutex"); + assert_eq!(LEASES.with(Cell::get), 0, "a publisher waits without a preparation lease"); + assert!(REQUESTED.with(|requested| requested.replace(false)), "an event pass was requested"); + BLOCKS.with(|blocks| blocks.set(blocks.get() + 1)); + self.blocks.set(self.blocks.get() + 1); + if self.generation.get() == sample { + advance_until(now() + u64::from(ms) * MS, || self.generation.get() != sample); + } + Ok(()) + } +} + +/// A completion fence: 0 until it signals, then 1 or a negative error. +#[derive(Clone, Default)] +pub struct CompletionFence(Rc>); +pub struct VmStatus; +impl VmStatus { fn get(&self) -> i32 { 0 } } +pub struct WorkState { returns: Availability } +impl WorkState { + fn acquire(&self, engine: g17::job::Engine) -> Result { + assert_eq!(engine, g17::job::Engine::Render); + Ok(1) + } + fn returns(&self) -> &Availability { &self.returns } +} +pub struct Completion { + status: Arc, fence: CompletionFence, work: WorkState, consumer: Cell, + lease: RefCell>, +} +impl Completion { + fn status(&self) -> &Arc { &self.status } + fn fence(&self) -> CompletionFence { self.fence.clone() } + fn work_state(&self) -> Result<&WorkState> { Ok(&self.work) } + fn note_firmware_consumer(&self) { self.consumer.set(true); } + fn attach_render_lease(&self, lease: RenderLease) -> Result { *self.lease.borrow_mut() = Some(lease); Ok(()) } + fn detach_render_lease(&self) -> Option { self.lease.borrow_mut().take() } +} +pub struct Packet { + command: g17::command::Validated, order: Order, completion: Arc, + producers: Vec, published: Cell, cancel_at: Cell, +} +impl Packet { + fn check_firmware_producers(&self) -> Result { + if self.producers.iter().any(|fence| fence.0.get() < 0) { Err(g17::dependency::PRODUCER_FAILED) } else { Ok(()) } + } + fn check_dependencies(&self) -> Result { self.check_firmware_producers() } + fn cancel_requested(&self) -> bool { now() >= self.cancel_at.get() } + fn is_published(&self) -> bool { self.published.get() } +} +fn packet(status: &Arc, order: Order, command: g17::command::Validated, producers: Vec) -> Arc { + Arc::new(Packet { + command, order, producers, published: Cell::new(false), cancel_at: Cell::new(u64::MAX), + completion: Arc::new(Completion { + status: status.clone(), fence: CompletionFence::default(), consumer: Cell::new(false), + work: WorkState { returns: Availability::new("work") }, lease: RefCell::new(None), + }), + }) +} + +pub struct Flags; +pub const GFP_KERNEL: Flags = Flags; +pub struct KVec(Vec); +impl KVec { fn push(&mut self, value: T, _: Flags) -> Result { self.0.push(value); Ok(()) } } +impl std::ops::Deref for KVec { type Target = Vec; fn deref(&self) -> &Vec { &self.0 } } +impl std::ops::DerefMut for KVec { fn deref_mut(&mut self) -> &mut Vec { &mut self.0 } } +#[derive(Clone, Copy)] +pub struct Ticket { kick: u64 } +pub struct Active { packet: Arc, ticket: Option } +/// One compute queue of the render's owner. +pub struct Queue { + owner: Option, active: VecDeque, replays: VecDeque>, + pending_failed: KVec<(u64, CompletionFence)>, quarantined: bool, spared_quarantine: bool, +} +impl Queue { + fn qid(&self) -> u8 { 28 } +''' + queue + r''' +} + +pub struct DeferredBatch { failed: Vec, finished: usize } +impl DeferredBatch { + fn new() -> Self { Self { failed: Vec::new(), finished: 0 } } + fn is_idle(&self) -> bool { self.failed.is_empty() } + fn finish(&mut self) { + assert!(!STATE_HELD.with(Cell::get), "fences signal off the device mutex"); + for fence in self.failed.drain(..) { fence.0.set(EIO); } + self.finished += 1; + } +} + +pub struct RenderLease(u8); +impl RenderLease { fn slot(&self) -> u8 { self.0 } } +pub struct Request; +impl Request { fn of(_: &Packet) -> Self { Self } } +pub struct Pool; +impl Pool { + fn try_acquire_render(&self, _: u64, _: u32, _: Request) -> Result> { Ok(None) } + fn spared_quarantined(&self, _: u64) -> bool { false } +} +pub struct Init; +pub struct Recovery; +impl Recovery { fn pending(&self) -> bool { false } } +pub struct Queues { admission: Pool, compute: Queue } +pub struct Firmware { recovery: Recovery, init: Init, queues: Queues } +pub struct Held<'a>(RefMut<'a, Option>>); +impl Drop for Held<'_> { fn drop(&mut self) { STATE_HELD.with(|held| held.set(false)); } } +impl std::ops::Deref for Held<'_> { type Target = Option>; fn deref(&self) -> &Self::Target { &self.0 } } +impl std::ops::DerefMut for Held<'_> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } +pub struct State(RefCell>>); +impl State { + fn lock(&self) -> Held<'_> { + let held = self.0.borrow_mut(); + STATE_HELD.with(|flag| flag.set(true)); + Held(held) + } +} +pub struct Lease; +impl Lease { + fn new() -> Self { LEASES.with(|leases| leases.set(leases.get() + 1)); Self } + fn is_current(&self) -> bool { true } +} +impl Drop for Lease { fn drop(&mut self) { LEASES.with(|leases| leases.set(leases.get() - 1)); } } +pub struct Gate; +impl Gate { + fn enter(&self, _interruptible: bool) -> Result { Ok(Lease::new()) } + fn snapshot(&self) -> u64 { 0 } + fn wait_closure(&self, _: u64, _: u64) -> Result { unreachable!("no recovery here") } +} +pub struct Shared { + preparations: Gate, state: State, crashed: AtomicBool, renders: Availability, progress: Availability, +} +impl Shared { fn queue_events(&self) { REQUESTED.with(|requested| requested.set(true)); } } +pub struct Context; +impl Context { fn is_current(&self) -> bool { true } } + +''' + clock + r''' + +/// What a publication attempt meets before its dependencies. +#[derive(Clone, Copy, PartialEq)] +enum Refusal { None, Busy, Batch } +/// The host work of one attempt: pair loan, preparation, discard. +const ATTEMPT_NS: u64 = 20_000; +pub struct Backend { + owner: u64, shared: Shared, context: Context, admission: Pool, direct_slot: AtomicU32, + refusal: Cell, kick: Cell>>, +} +impl Backend { + fn admission_open(&self) -> Result { Ok(()) } + fn render_pairs(&self, _: &Packet) -> u8 { 1 } + fn render_direct(&self, _: &Arc, _: u8, _: &mut DeferredBatch) -> Option { None } + fn acquire_render_with_ids(&self, _: &Arc, early: Option, _: bool) -> Result<(RenderLease, bool)> { + Ok((early.unwrap_or(RenderLease(1)), false)) + } + fn enter_preparation(&self, _: bool) -> Result { Ok(Lease::new()) } + fn ensure_render(&self, _: &Arc, _: u8, _: bool) -> Result { Ok(()) } + fn wait_render_capacity(&self, _: &mut Option, _: &mut WaitClock, _: bool) -> Result { unreachable!("no capacity wait here") } + /// One attempt: prepared off the device mutex, then refused or published under it. + fn prepare_render(&self, _slot: u8, packet: &Arc, deferred: &mut DeferredBatch, sleep: bool, + outer_wait: &mut Option<(Arc, u64)>) -> Result { + *outer_wait = None; + let lease = self.enter_preparation(sleep)?; + let attempts = ATTEMPTS.with(|attempts| { attempts.set(attempts.get() + 1); attempts.get() }); + assert!(attempts <= 2 * (BLOCKS.with(Cell::get) + 1), "a refused publication waits before it retries"); + advance_until(now() + ATTEMPT_NS, || false); + let mut state = self.shared.state.lock(); + let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; + match self.refusal.get() { + Refusal::None => {} + Refusal::Busy => return Err(EBUSY), + Refusal::Batch => { + deferred.failed.extend(packet.producers.iter().cloned()); + return Err(EAGAIN); + } + } + let queue = &firmware.queues.compute; + let dependency = queue.dependency(self.owner, packet.completion.status(), packet.order.wait_through[1], 0)?; + packet.check_firmware_producers()?; + assert!(packet.producers.iter().all(|fence| fence.0.get() != 0) || dependency.is_some(), + "published ahead of a dependency without a kick"); + self.kick.set(Some(dependency)); + packet.published.set(true); + Ok(()) + } +''' + host(backend) + r''' +} + +#[cfg(test)] +mod tests { + use super::*; + + const OWNER: u64 = 7; + const COMPUTE: u64 = 5; + /// The longest a replay stays parked: behind a live consumer, then for work-ring room. + const LONGEST_PARKED: u64 = CONSUMER_WAIT_NS + rt::WORK_RING_WAIT_NS - MS; + + struct Setup { backend: Rc, render: Arc, command: Arc } + + /// A compute command parked for replay, and a render waiting through `through`. + fn parked(through: u64) -> Setup { + NOW.with(|now| now.set(0)); + STEPS.with(|steps| steps.borrow_mut().clear()); + for count in [&BLOCKS, &ATTEMPTS, &LEASES] { count.with(|count| count.set(0)); } + for flag in [&REQUESTED, &STATE_HELD] { flag.with(|flag| flag.set(false)); } + let status = Arc::new(VmStatus); + let command = packet(&status, Order { sequence: COMPUTE, ..Order::default() }, + g17::command::Validated::Compute { visible_completion: true }, vec![]); + let render = packet(&status, Order { sequence: 1, wait_through: [None, Some(through)] }, + g17::command::Validated::Render, vec![command.completion.fence()]); + let compute = Queue { + owner: Some(OWNER), active: VecDeque::new(), replays: VecDeque::from([command.clone()]), + pending_failed: KVec(Vec::new()), quarantined: false, spared_quarantine: false, + }; + let backend = Rc::new(Backend { + owner: OWNER, context: Context, admission: Pool, direct_slot: AtomicU32::new(0), + refusal: Cell::new(Refusal::None), kick: Cell::new(None), + shared: Shared { + preparations: Gate, crashed: AtomicBool::new(false), + renders: Availability::new("renders"), progress: Availability::new("progress"), + state: State(RefCell::new(Some(Box::new(Firmware { + recovery: Recovery, init: Init, queues: Queues { admission: Pool, compute }, + })))), + }, + }); + Setup { backend, render, command } + } + + impl Setup { + /// The event pass at `when` republishes the parked command with kick 9. + fn republishes(&self, when: u64) { + let (backend, command) = (self.backend.clone(), self.command.clone()); + at(when, move || { + { + let mut state = backend.shared.state.lock(); + let queue = &mut state.as_deref_mut().unwrap().queues.compute; + assert!(Arc::ptr_eq(&queue.replays.pop_front().unwrap(), &command)); + queue.active.push_back(Active { packet: command, ticket: Some(Ticket { kick: 9 }) }); + } + backend.shared.progress.notify(); + }); + } + /// The event pass at `when` fails it; its fence signals `delay` later. + fn fails(&self, when: u64, delay: u64) { + let (backend, command) = (self.backend.clone(), self.command.clone()); + at(when, move || { + let mut state = backend.shared.state.lock(); + let queue = &mut state.as_deref_mut().unwrap().queues.compute; + queue.replays.pop_front().unwrap(); + queue.note_pending_failed(&command); + backend.shared.progress.notify(); + }); + let (backend, command) = (self.backend.clone(), self.command.clone()); + at(when + delay, move || { + command.completion.fence.0.set(-61); + backend.shared.progress.notify(); + }); + } + fn publish(&self, early: Option) -> Result { + self.backend.render_with_lease(&self.render, early, &mut DeferredBatch::new()) + } + fn blocks(&self) -> (usize, usize) { + (self.backend.shared.progress.blocks.get(), self.backend.shared.renders.blocks.get()) + } + } + + #[test] + fn a_parked_dependency_is_waited_for_and_its_replacement_kick_named() { + for when in [MS, CONSUMER_WAIT_NS + 4 * MS, LONGEST_PARKED] { + let setup = parked(COMPUTE); + setup.republishes(when); + assert_eq!(setup.publish(None), Ok(())); + assert!(setup.render.is_published()); + assert_eq!(setup.backend.kick.get(), + Some(KickDependency::new(28, KickTimestamp::new(9).unwrap()))); + assert!(setup.command.completion.consumer.get(), "the replayed command has a consumer"); + assert!(now() >= when && now() <= when + MS, "published {} ns after the replay", now() - when); + let (progress, renders) = setup.blocks(); + assert!(progress != 0 && renders == 0, "woken by the replay's notification"); + } + } + + #[test] + fn a_failed_dependency_fails_the_render_once_its_fence_signals() { + for delay in [0, 3 * MS, 45 * MS] { + let setup = parked(COMPUTE); + setup.fails(50 * MS, delay); + assert_eq!(setup.publish(None), Err(g17::dependency::PRODUCER_FAILED)); + assert!(!setup.render.is_published()); + let end = 50 * MS + delay; + assert!(now() >= end && now() <= end + MS, "failed {} ns after the signal", now() - end); + } + } + + #[test] + fn a_dependency_that_stays_parked_ends_at_one_deadline() { + let setup = parked(COMPUTE); + let bound = g17::preparation::QUEUE_WAIT_NS.min(recovery_wait_ns()); + assert!(bound > LONGEST_PARKED, "a replay ends before its consumer gives up"); + at(bound + 60 * MS, || panic!("the wait ends at its deadline")); + assert_eq!(setup.publish(None), Err(ETIMEDOUT)); + assert!(now() >= bound && now() <= bound + 20 * MS, "ended at {}", now()); + assert!(!setup.render.is_published()); + } + + #[test] + fn a_cancelled_render_stops_waiting() { + let setup = parked(COMPUTE); + setup.render.cancel_at.set(15 * MS); + at(60 * MS, || panic!("cancellation is seen within one slice")); + assert_eq!(setup.publish(None), Err(ECANCELED)); + assert!(now() <= 26 * MS); + } + + #[test] + fn the_submitting_ioctl_falls_back_without_waiting() { + let setup = parked(COMPUTE); + assert_eq!(setup.publish(Some(RenderLease(1))), Err(FALLBACK)); + assert_eq!((setup.blocks(), ATTEMPTS.with(Cell::get)), ((0, 0), 1)); + assert!(!REQUESTED.with(Cell::get)); + } + + #[test] + fn a_command_outside_the_frontier_or_of_another_owner_is_no_dependency() { + let setup = parked(COMPUTE - 1); + setup.command.completion.fence.0.set(1); + assert_eq!(setup.publish(None), Ok(())); + assert_eq!((setup.backend.kick.get(), ATTEMPTS.with(Cell::get)), (Some(None), 1)); + let setup = parked(COMPUTE); + setup.command.completion.fence.0.set(1); + setup.backend.shared.state.lock().as_deref_mut().unwrap().queues.compute.owner = Some(OWNER + 1); + assert_eq!(setup.publish(None), Ok(())); + assert_eq!((setup.backend.kick.get(), ATTEMPTS.with(Cell::get)), (Some(None), 1)); + } + + #[test] + fn a_busy_pair_keeps_its_own_bound_and_wake_up() { + let setup = parked(COMPUTE); + setup.backend.refusal.set(Refusal::Busy); + at(rt::WORK_RING_WAIT_NS + 60 * MS, || panic!("a busy pair ends at its deadline")); + assert_eq!(setup.publish(None), Err(ETIMEDOUT)); + assert!(now() >= rt::WORK_RING_WAIT_NS); + let (progress, renders) = setup.blocks(); + assert!(progress == 0 && renders != 0, "pair returns signal the render domain"); + } + + #[test] + fn queued_completions_are_signalled_before_the_wait() { + for early in [false, true] { + let setup = parked(COMPUTE); + setup.backend.refusal.set(Refusal::Batch); + let mut deferred = DeferredBatch::new(); + assert_eq!(setup.backend.render_with_lease(&setup.render, early.then_some(RenderLease(1)), &mut deferred), + Err(g17::dependency::PRODUCER_FAILED), "early {early}: the failed producer ends the retry"); + assert_eq!((deferred.finished, deferred.is_idle()), (1, true)); + assert_eq!((setup.blocks(), ATTEMPTS.with(Cell::get)), ((0, 0), 1), "early {early}"); + } + } +} +''' + + +WAIT = 'self.wait_compute_dependency(&mut parked, &mut progress, sleep, packet)?;' +# Each restores an old behaviour or drops one part of the rule. +MUTATIONS = { + # The old loop: EAGAIN without a recovery goes straight to the next attempt. + 'spin': [(' } else {\n ' + WAIT, + ' } else if !sleep {\n return Err(FALLBACK);'), + ('let mut progress = None;', 'let mut progress: Option = None;')], + 'renewed-clock': [(WAIT, WAIT.replace('&mut parked', '&mut WaitClock::default()'))], + 'short-bound': [('self.wait_deadline(clock, crate::g17::preparation::QUEUE_WAIT_NS)?', + 'self.wait_deadline(clock, rt::WORK_RING_WAIT_NS)?')], + 'render-domain': [('self.wait_domain(&self.shared.progress, sample, deadline, packet)', + 'self.wait_domain(&self.shared.renders, sample, deadline, packet)')], + 'no-event-pass': [(' self.shared.queue_events();\n self.wait_domain(&self.shared.progress,', + ' self.wait_domain(&self.shared.progress,')], + 'ioctl-waits': [(' if !sleep {\n return Err(FALLBACK);\n }\n' + ' let deadline = self.wait_deadline(clock, crate::g17::preparation::QUEUE_WAIT_NS)?;', + ' let deadline = self.wait_deadline(clock, crate::g17::preparation::QUEUE_WAIT_NS)?;')], + 'busy-waits-here': [(' } else if error == EBUSY {\n', + ' } else if false {\n')], + # The refusal itself: a parked or not yet signalled failed command is no dependency. + 'parked-unseen': [('if self.replay_through(through)\n', 'if false\n')], + 'failed-unseen': [(' || self.pending_failed.iter().any(', ' || false && self.pending_failed.iter().any(')], + # The attempt's completions stay queued across the wait, or signal before dependencies are read. + 'batch-kept': [(' if !deferred.is_idle() {', ' if false {')], + 'batch-unchecked': [(' if sleep {\n packet.check_dependencies()?;\n' + ' } else {\n packet.check_firmware_producers()?;\n' + ' }\n', '')], +} + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split('\n', 1)[0]) + ap.add_argument('--mutation', choices=sorted(MUTATIONS)) + args = ap.parse_args() + code = fixture() + for old, new in MUTATIONS.get(args.mutation, []): + assert code.count(old) == 1, (args.mutation, code.count(old), old) + code = code.replace(old, new) + with tempfile.TemporaryDirectory(prefix='g17-render-parked-') as tmp: + path = Path(tmp) / 'parked.rs' + binary = path.with_suffix('') + path.write_text(code) + subprocess.run([os.environ.get('RUSTC', 'rustc'), '--edition=2021', '--test', str(path), + '-o', str(binary)], check=True) + # A killed mutant exits with the failed test's panic in its output. + result = subprocess.run([str(binary)], timeout=120) + if result.returncode: + raise SystemExit(result.returncode) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/g17-render-partial-order-tests.py b/tools/asahi/g17-render-partial-order-tests.py new file mode 100755 index 0000000000000..ad39815ffa1f2 --- /dev/null +++ b/tools/asahi/g17-render-partial-order-tests.py @@ -0,0 +1,217 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Which of a render's waits hold its tiling kick, per render pairs of a queue. + +Runs the production `render_barriers()` through the arguments `Pair::publish()` gives it +(`queue/render.rs`), with the production pair count (`pairs::select_board()`, +`pairs::per_owner()`), for a board of each cluster count and for one without an M5 board. + +`fragment_busy` drains only the fragment work of the pair a partial render runs on. A fragment +wait for a render of another pair therefore also holds the tiling kick. With several pairs per +queue a compute wait or a same-VM attachment overlap can stand for such a render, and they hold it +as well. With one pair per queue (A18 Pro, one- and two-cluster M5) they stay on the fragment kick, +so that tiling overlaps them, and without `fragment_busy` nothing is promoted. + +Each `--mutation` widens or drops one of these promotions and must fail. +""" +from pathlib import Path +import argparse +import os +import re +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] / 'drivers/gpu/drm/asahi' +G17 = ROOT / 'g17' + + +def item(source, signature, attributes=False): + """The item that starts at `signature`, through its closing brace.""" + assert source.count(signature) == 1, signature + start = source.index(signature) + if attributes: + while source[source.rfind('\n', 0, start - 1) + 1:start].strip().startswith('#['): + start = source.rfind('\n', 0, start - 1) + 1 + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def statement(source, pattern): + found = re.findall(r'^ *((?:pub\(crate\) )?' + pattern + r'[^;]*;)', source, re.M) + assert len(found) == 1, (pattern, found) + return found[0] + + +def fixture(): + render = (G17 / 'queue/render.rs').read_text() + pairs = (G17 / 'pairs.rs').read_text() + kick = (G17 / 'fw/kick.rs').read_text() + pairs_max = statement((ROOT / 'hw/t8140.rs').read_text(), 'const RENDER_PAIRS_MAX: usize =') + calls = re.findall(r'let mut barriers =\s+(render_barriers\([^;]*\));\n', item(render, 'pub(crate) fn publish(')) + assert len(calls) == 1 + call = calls[0] + kicks = '\n'.join([ + statement(kick, 'const QID_MAX: u8 ='), statement(kick, 'const KICK_TIMESTAMP_BITS: u32 ='), statement(kick, 'const KICK_TIMESTAMP_MASK: u64 ='), + '#[derive(Copy, Clone, Debug, PartialEq, Eq)]', statement(kick, r'struct KickTimestamp\(u64\)'), + 'impl KickTimestamp {', statement(kick, 'const ZERO: Self = Self\\(0\\)'), + statement(kick, 'const FIRST: Self ='), '}', + item(kick, 'pub(crate) struct KickDependency {', True), + item(kick, 'impl KickDependency {').replace('crate::g17::fw::kick::', '')]) + counts = '\n'.join([ + statement(pairs, 'const MULTI_PAIRS: u8 ='), statement(pairs, 'const COMPUTE_CHANNELS_MAX: usize ='), + statement(pairs, 'static PAIRS:'), statement(pairs, 'static COMPUTE_CHANNELS:'), + item(pairs, 'pub(crate) fn select_board('), item(pairs, 'pub(crate) fn per_owner(')]) + counts = counts.replace('crate::g17::fw::m5::initdata::Board', 'crate::Board') + return r''' +#![allow(warnings)] +mod hw { pub(crate) mod t8140 { pub(crate) mod queues { ''' + pairs_max + r''' } } } +pub struct Board { clusters: u32 } +impl Board { fn compute_channels(&self) -> u8 { 1 } } +mod g17 { + pub(crate) mod pairs { + use core::sync::atomic::{AtomicU8, Ordering::Relaxed}; + use crate::hw::t8140::queues::RENDER_PAIRS_MAX; +''' + counts + r''' + } + pub(crate) mod hazard { ''' + statement((G17 / 'hazard.rs').read_text(), 'const PUBLICATION_BARRIERS: usize =') + r''' } + pub(crate) mod fw { pub(crate) mod m5 { pub(crate) mod compute { + pub(crate) fn explicit_dependency(_: &crate::Board) -> u8 { 3 } + } } } +} +''' + kicks + '\n' + '#[derive(Copy, Clone)]\n' + item(render, 'pub(crate) struct RenderDependencies {') + '\n' + item( + render, 'impl RenderDependencies {') + '\n' + item(render, 'struct RenderBarriers {') + '\n' + item( + render, 'fn render_barriers(') + r''' + +struct Pass { fragment_barriers: bool, stage_prefixes: bool } +struct Variant { fragment_busy: bool } +struct Pair { variant: Variant, board: Option<&'static Board> } +impl Pair { + /// The barriers of a published render: `qids` are its pair's tiling and fragment queues. + fn publish(&self, pass: &Pass, dependencies: &RenderDependencies, own_tiling: KickDependency, + qids: [u8; 2]) -> RenderBarriers { + ''' + call + r''' + } +} + +const TILING: u8 = 4; +const FRAGMENT: u8 = 5; +/// The queues a wait can name: the pair's own fragment queue, another pair's, and compute. +const OTHER_FRAGMENT: u8 = 7; +const OTHER_OWNER: u8 = 9; +const COMPUTE: u8 = 12; +const FRAGMENT_COMPUTE: u8 = 13; +fn kick(qid: u8) -> KickDependency { KickDependency::new(qid, KickTimestamp::FIRST).unwrap() } + +/// The queue and class of every wait of the tiling kick, and the queues the fragment kick waits for. +fn waits(pair: &Pair, pass: &Pass, dependencies: &RenderDependencies) -> (Vec<(u8, u8)>, Vec) { + let barriers = pair.publish(pass, dependencies, kick(TILING), [TILING, FRAGMENT]); + assert_eq!(barriers.tiling_types[barriers.tiling_count], 1, "the implicit parent's class follows"); + ((0..barriers.tiling_count).map(|i| (barriers.tiling[i].qid(), barriers.tiling_types[i])).collect(), + barriers.fragment[..barriers.fragment_count].iter().map(|wait| wait.qid()).collect()) +} + +/// A render behind an earlier one of its own pair that also waits for compute: `compute` before +/// tiling, `fragment_compute` before its fragment work only. +fn indirect() -> RenderDependencies { + let mut waits = RenderDependencies::EMPTY; + waits.render[0] = kick(FRAGMENT); + waits.render_count = 1; + waits.compute[0] = kick(COMPUTE); + waits.compute_count = 1; + waits.fragment_compute[0] = kick(FRAGMENT_COMPUTE); + waits.fragment_compute_count = 1; + waits +} + +fn main() { + static BOARDS: [Board; 4] = [Board { clusters: 1 }, Board { clusters: 2 }, Board { clusters: 4 }, Board { clusters: 8 }]; + let staged = Pass { fragment_barriers: false, stage_prefixes: true }; + let barriered = Pass { fragment_barriers: true, stage_prefixes: false }; + // The A18 Pro has no M5 board: its count stays as it starts. + for board in std::iter::once(None).chain(BOARDS.iter().map(Some)) { + if let Some(board) = board { g17::pairs::select_board(board); } + let clusters = board.map(|board| board.clusters); + let several = clusters.is_some_and(|clusters| clusters >= 4); + assert_eq!(g17::pairs::per_owner() > 1, several, "{clusters:?} clusters"); + let class = if board.is_some() { 3 } else { 2 }; + let pair = Pair { variant: Variant { fragment_busy: true }, board }; + let undrained = Pair { variant: Variant { fragment_busy: false }, board }; + for pass in [&staged, &barriered] { + // A fragment-only compute wait. + let mut dependencies = indirect(); + let (tiling, fragment) = waits(&pair, pass, &dependencies); + assert_eq!(fragment, [TILING, FRAGMENT, FRAGMENT_COMPUTE], "the fragment kick keeps every wait"); + let mut expected = vec![(COMPUTE, class)]; + if several { expected.push((FRAGMENT_COMPUTE, class)); } + assert_eq!(tiling, expected, "fragment-only compute wait, {clusters:?} clusters"); + assert_eq!(waits(&undrained, pass, &dependencies).0, [(COMPUTE, class)]); + // Another queue's render overlaps its attachments. + dependencies.hazards[0] = kick(OTHER_OWNER); + dependencies.hazard_count = 1; + let (tiling, fragment) = waits(&pair, pass, &dependencies); + assert_eq!(fragment, [TILING, FRAGMENT, FRAGMENT_COMPUTE, OTHER_OWNER]); + if several { expected.push((OTHER_OWNER, 2)); } + assert_eq!(tiling, expected, "attachment overlap, {clusters:?} clusters"); + assert_eq!(waits(&undrained, pass, &dependencies).0, [(COMPUTE, class)]); + // A fragment wait that names a render of another pair: every count promotes it. + dependencies.render[1] = kick(OTHER_FRAGMENT); + dependencies.render_count = 2; + let (tiling, fragment) = waits(&pair, pass, &dependencies); + assert_eq!(fragment, [TILING, FRAGMENT, OTHER_FRAGMENT, FRAGMENT_COMPUTE, OTHER_OWNER]); + expected.insert(0, (OTHER_FRAGMENT, 2)); + assert_eq!(tiling, expected, "another pair's render, {clusters:?} clusters"); + assert_eq!(waits(&undrained, pass, &dependencies).0, [(COMPUTE, class)]); + } + } + println!("PASS g17-render-partial-order: one pair per queue tiles beside compute waits and attachment overlaps"); +} +''' + + +# name -> [(old, new)], each applied exactly once. +MUTATIONS = { + # One-pair queues are promoted as well, for both kinds of wait or for one. + 'every-count': [('ordered_partial && render_pairs > 1;', 'ordered_partial;')], + 'compute-every-count': [('several pairs.\n if ordered_indirect {', 'several pairs.\n if ordered_partial {')], + 'hazard-every-count': [(' fragment_count += 1;\n if ordered_indirect {', + ' fragment_count += 1;\n if ordered_partial {')], + 'count-ignored': [('crate::g17::pairs::per_owner(),', '2,')], + # A promotion two-pair queues need is gone. + 'no-count': [('ordered_partial && render_pairs > 1;', 'false;')], + 'compute-dropped': [('several pairs.\n if ordered_indirect {', 'several pairs.\n if false {')], + 'hazard-dropped': [(' fragment_count += 1;\n if ordered_indirect {', + ' fragment_count += 1;\n if false {')], + 'render-dropped': [('if ordered_partial && dependency.qid() != own_fragment_qid {', 'if false {')], + 'render-several-only': [('if ordered_partial && dependency.qid() != own_fragment_qid {', + 'if ordered_indirect && dependency.qid() != own_fragment_qid {')], + # The pair's own renders hold tiling, or boards whose firmware does not drain promote. + 'own-pair-promoted': [('if ordered_partial && dependency.qid() != own_fragment_qid {', 'if ordered_partial {')], + 'undrained-promoted': [(' self.variant.fragment_busy,', ' true,')], +} + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split('\n', 1)[0]) + ap.add_argument('--mutation', choices=sorted(MUTATIONS)) + args = ap.parse_args() + code = fixture() + for old, new in MUTATIONS.get(args.mutation, []): + assert code.count(old) == 1, (args.mutation, code.count(old), old) + code = code.replace(old, new) + with tempfile.TemporaryDirectory(prefix='g17-render-partial-') as tmp: + path = Path(tmp) / 'partial.rs' + binary = path.with_suffix('') + path.write_text(code) + subprocess.run([os.environ.get('RUSTC', 'rustc'), '--edition=2021', str(path), '-o', str(binary)], check=True) + # A killed mutant exits with the failed assertion in its output. + result = subprocess.run([str(binary)]) + if result.returncode: + raise SystemExit(result.returncode) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/g17-render-return-observe-tests.py b/tools/asahi/g17-render-return-observe-tests.py old mode 100755 new mode 100644 index fd893e12b7078..7be4eaa98f890 --- a/tools/asahi/g17-render-return-observe-tests.py +++ b/tools/asahi/g17-render-return-observe-tests.py @@ -10,6 +10,9 @@ - `retain_render_completions()`, `render_needs_rescan()`, `take_missed_event()`, `take_pair()` and `return_pair()` from drivers/gpu/drm/asahi/g17/runtime/render.rs; +- `entry_parked_through()`, `owner_parked_through()`, `owner_parked_other_through()` and + `replay_parked()` from runtime/render/replay.rs, with the pair's `replay_front()`, + `replay_through()` and `replay_frontier()` and `Order::contains()`; - `next_render_observation()`, `next_render_observation_in()`, `try_fast_observe_render()`, `observe_returned_render()` and `fast_observe_renders()` from runtime/render/observe.rs, with the production `FastRenderOutcome` and `completion_noted()`. @@ -31,7 +34,10 @@ recovery, takes the collector with `try_lock()`, finishes it after the device mutex and otherwise requests the event pass or, for a rescan, the poll; and that `runtime_event_turn()` ends in its first hold a pass whose render completions are owed to borrowers or that leaves - only a rescan, arming the poll for it. + only a rescan, arming the poll for it; +e. a pair with groups parked for replay is not lent for a preparation and stays visible to the + owner's later commands; the frontier recorded for a borrowed pair is the parked work other + slots' commands wait behind, until the pair returns. Each mutation restores the old behaviour or drops one part of the rule, and must fail an assertion of the compiled harness. @@ -107,6 +113,16 @@ def ordered_ok(source, *parts): 'rescan-no-poll': [('direct', 'FastRenderOutcome::Rescan => self.shared.queue_poll(),', 'FastRenderOutcome::Rescan => {}')], 'worker-rescan-slow-path': [('events', ' rescan = true;\n true\n', ' rescan = true;\n false\n')], + # (e) A pair with parked replays is lent, a borrowed pair's frontier is ignored, outlives the + # loan, or is not told apart by owner, or a command's own slot counts as a sibling. + 'lend-parked': [('render', ' if pair.replay_front().is_some() {\n return Err(EBUSY);\n }\n', '')], + 'borrowed-frontier-ignored': [('replay', 'borrowed_owner == owner && crate::g17::job::Order::contains(through, sequence)', 'false')], + 'borrowed-frontier-any-owner': [('replay', 'borrowed_owner == owner && ', '')], + 'borrowed-not-parked': [('replay', ' || entry.borrowed_replay.is_some()\n', '')], + 'return-keeps-frontier': [('render', ' entry.pair = pair.take();\n entry.borrowed_dependencies = None;\n entry.borrowed_replay = None;\n', + ' entry.pair = pair.take();\n entry.borrowed_dependencies = None;\n')], + 'own-slot-is-sibling': [('replay', ' .filter(|(index, _)| *index != slot)\n', '')], + 'tiling-frontier-ignored': [('replay', ' || Self::entry_parked_through(entry, owner, tiling_through)\n', '')], 'owed-slow-path': [('events', 'if render_clean && (compute_scan.is_some() || render_changed || masks != [0; 2]) {', 'if render_clean && (compute_scan.is_some() || render_changed) {')], } @@ -119,11 +135,14 @@ def build(mutation=None): 'direct': (G17 / 'runtime/render/direct.rs').read_text(), 'events': (G17 / 'runtime/events.rs').read_text(), 'queue': (G17 / 'queue/render.rs').read_text(), + 'replay': (G17 / 'runtime/render/replay.rs').read_text(), } + job = (G17 / 'job.rs').read_text() for name, old, new in MUTATIONS.get(mutation, []): assert files[name].count(old) == 1, (mutation, old) files[name] = files[name].replace(old, new) - render, observe, direct, events, queue = (files[k] for k in ('render', 'observe', 'direct', 'events', 'queue')) + render, observe, direct, events, queue, replay = ( + files[k] for k in ('render', 'observe', 'direct', 'events', 'queue', 'replay')) def host(code): return (code.replace('pub(in crate::g17::runtime) ', '').replace('pub(in crate::g17) ', '') @@ -132,6 +151,7 @@ def host(code): .replace('crate::g17::queue::render::completion_noted', 'completion_noted') .replace('crate::hw::t8140::queues::RENDER_SLOTS', 'RENDER_SLOTS') .replace('crate::g17::now_ns()', 'now_ns()').replace('kick::Id::qid', 'Id::qid') + .replace('crate::g17::job::Order', 'Order').replace('super::Entry', 'Entry') .replace('KBox', 'Box')) outcome = host(item(observe, 'pub(in crate::g17::runtime) enum FastRenderOutcome')) @@ -140,6 +160,15 @@ def host(code): ' fn entry(&self, slot: u8)', ' fn entry_mut(&mut self, slot: u8)', 'fn take_missed_event(', 'fn take_pair(&mut self, slot: u8', 'fn return_pair(&mut self, slot: u8', ])) + state_fns += host('\n'.join(item(replay, signature) for signature in [ + 'fn entry_parked_through(', 'pub(in crate::g17) fn owner_parked_through(', + 'pub(in crate::g17) fn owner_parked_other_through(', 'pub(in crate::g17) fn replay_parked(', + ])) + order_fns = host(item(job, 'pub(crate) fn contains(')) + parked_replay = item(queue, 'struct ParkedReplay {') + pair_fns = host('\n'.join(item(queue, signature) for signature in [ + 'pub(crate) fn replay_front(', 'pub(crate) fn replay_through(', 'pub(crate) fn replay_frontier(', + ])) registry_fns = host('\n'.join(item(render, signature) for signature in [ 'pub(in crate::g17) fn render_needs_rescan(', 'pub(in crate::g17) fn retain_render_completions(', ])) @@ -182,7 +211,8 @@ def host(code): } checks = '\n'.join(f' assert!({str(ok).lower()}, "structure: {name}");' for name, ok in structure.items()) return (TEMPLATE.replace('@@OUTCOME@@', outcome).replace('@@NOTED@@', noted).replace('@@STATE@@', state_fns) - .replace('@@REGISTRY@@', registry_fns).replace('@@FIRMWARE@@', firmware_fns) + .replace('@@ORDER@@', order_fns).replace('@@PAIR@@', pair_fns) + .replace('@@PARKED_REPLAY@@', parked_replay).replace('@@REGISTRY@@', registry_fns).replace('@@FIRMWARE@@', firmware_fns) .replace('@@STRUCTURE@@', checks)) @@ -209,7 +239,11 @@ def host(code): pub struct Id(u8); impl Id { fn qid(self) -> u8 { self.0 } } pub struct Context; -pub struct Packet { context: Arc, ordinal: u64 } +pub struct Order { sequence: u64 } +impl Order { +@@ORDER@@ +} +pub struct Packet { context: Arc, ordinal: u64, order: Order } pub struct VmStatus; #[derive(Clone, Copy)] pub struct Dependencies; @@ -234,16 +268,19 @@ def host(code): pub struct Observed { ordinal: u64 } pub struct Host; +@@PARKED_REPLAY@@ /// A render pair: its published commands in order and the fragment stamp the GPU writes. pub struct Pair { - slot: u8, qids: [u8; 2], owner: u64, active: VecDeque, retired: Vec, + slot: u8, qids: [u8; 2], owner: Option, active: VecDeque, retired: Vec, + replay: VecDeque, quarantined: bool, terminal: Option<(Arc, i32)>, fault_at: Option, } impl Pair { fn slot(&self) -> u8 { self.slot } fn qids(&self) -> [u8; 2] { self.qids } - fn owner(&self) -> Option { Some(self.owner) } - fn matches(&self, owner: u64, _: &Arc) -> Result { Ok(owner == self.owner) } + fn owner(&self) -> Option { self.owner } + fn matches(&self, owner: u64, _: &Arc) -> Result { Ok(self.owner == Some(owner)) } +@@PAIR@@ fn published_in_flight(&self) -> bool { !self.quarantined && !self.active.is_empty() } fn in_flight(&self) -> bool { !self.active.is_empty() } fn stamp_waiting(&self) -> bool { false } @@ -277,13 +314,13 @@ def host(code): struct Entry { reservation: Reservation, pair: Option>, preparing: Option>, borrowed_active: bool, borrowed_dependencies: Option, borrowed_switch: Option, + borrowed_replay: Option<(u64, u64)>, event_masks: [u64; 2], missed_event: bool, closed: bool, pending_error: Option<(Arc, i32)>, pending_timeout: bool, growing: bool, } -pub struct RenderState { entries: Vec>, replay: bool } +pub struct RenderState { entries: Vec> } impl RenderState { @@STATE@@ - fn replay_parked(&self) -> bool { self.replay } fn collect_retired(&mut self, _slot: usize) -> Result { Ok(()) } } pub struct Registry { render: RenderState } @@ -323,17 +360,18 @@ def host(code): const FRAGMENT_QID: u8 = 21; fn pair(slot: u8, qids: [u8; 2], ordinals: &[u64]) -> Box { - Box::new(Pair { slot, qids, owner: OWNER, active: ordinals.iter().copied().collect(), retired: Vec::new(), + Box::new(Pair { slot, qids, owner: Some(OWNER), active: ordinals.iter().copied().collect(), retired: Vec::new(), + replay: VecDeque::new(), quarantined: false, terminal: None, fault_at: None }) } fn entry(slot: u8, qids: [u8; 2], ordinals: &[u64]) -> Entry { Entry { reservation: Reservation { slot, ids: [Id(qids[0]), Id(qids[1])], owner: OWNER }, pair: Some(pair(slot, qids, ordinals)), preparing: None, borrowed_active: false, - borrowed_dependencies: None, borrowed_switch: None, event_masks: [0; 2], missed_event: false, + borrowed_dependencies: None, borrowed_replay: None, borrowed_switch: None, event_masks: [0; 2], missed_event: false, closed: false, pending_error: None, pending_timeout: false, growing: false } } fn firmware(entries: Vec>) -> Firmware { - Firmware { recovery: Recovery { pending: false }, queues: Registry { render: RenderState { entries, replay: false } }, + Firmware { recovery: Recovery { pending: false }, queues: Registry { render: RenderState { entries } }, init: Init { stamps: (0..128).map(|_| AtomicU32::new(0)).collect(), recovery_state: AtomicU32::new(0) }, primary: Primary { state: StateStub { shared: SharedStub { event_records: AtomicUsize::new(0) } } }, grow: false, settled: Vec::new() } @@ -350,7 +388,9 @@ def host(code): fn retired(batch: &mut DeferredBatch) -> Vec { batch.finish().into_iter().map(|d| match d { Deferred::Retired(o) => o, Deferred::Failed(o) => 1000 + o }).collect() } -fn packet(ordinal: u64) -> Arc { Arc::new(Packet { context: Arc::new(Context), ordinal }) } +fn packet(ordinal: u64) -> Arc { + Arc::new(Packet { context: Arc::new(Context), ordinal, order: Order { sequence: ordinal } }) +} /// The direct path's loan: the production take_pair(), a publication, the production return_pair(). fn lend(fw: &mut Firmware, slot: u8, ordinal: u64) -> Box { fw.queues.render.take_pair(slot, OWNER, &packet(ordinal)).unwrap() @@ -447,7 +487,7 @@ def host(code): 1 => e2.pending_timeout = true, 2 => e2.closed = true, 3 => e2.growing = true, - 4 => fw.queues.render.replay = true, + 4 => e2.pair.as_mut().unwrap().replay.push_back(ParkedReplay { packet: packet(1) }), 5 => fw.recovery.pending = true, _ => room = 1, } @@ -469,6 +509,47 @@ def host(code): assert_eq!(fw.settled, vec![1], "the terminal is settled, not dropped"); assert_eq!(retired(&mut collector), vec![1000, 1001]); + // (e) Groups 5 and 6 of slot 1 are parked for replay. + const OTHER: u64 = 4; + let mut fw = firmware(vec![None, Some(entry(1, qids, &[])), Some(entry(2, other, &[]))]); + for ordinal in [5, 6] { + fw.queues.render.entries[1].as_mut().unwrap().pair.as_mut().unwrap().replay.push_back(ParkedReplay { packet: packet(ordinal) }); + } + assert!(matches!(fw.queues.render.take_pair(1, OWNER, &packet(7)), Err(EBUSY)), + "a pair with parked replays is not lent"); + { + let e1 = fw.queues.render.entries[1].as_ref().unwrap(); + assert!(e1.pair.is_some() && e1.preparing.is_none() && e1.borrowed_dependencies.is_none() + && e1.borrowed_replay.is_none(), "a refused loan leaves the pair resident"); + } + let parked = |render: &RenderState| { + (render.replay_parked(), + [None, Some(4), Some(5), Some(9)].map(|through| render.owner_parked_through(OWNER, through)), + render.owner_parked_through(OTHER, Some(9)), + [(1, Some(9), None), (2, Some(9), None), (2, None, Some(9)), (2, Some(4), Some(4))].map( + |(slot, through, tiling)| render.owner_parked_other_through(OWNER, slot, through, tiling))) + }; + let expected = (true, [false, false, true, true], false, [false, true, true, false]); + assert_eq!(parked(&fw.queues.render), expected, "resident parked work precedes what waits through it"); + // Growth and rebinding borrow such a pair, recording its frontier first. + { + let e1 = fw.queues.render.entries[1].as_mut().unwrap(); + let pair = e1.pair.as_ref().unwrap(); + e1.borrowed_replay = pair.replay_frontier(); + assert_eq!(e1.borrowed_replay, Some((OWNER, 5))); + e1.preparing = Some(packet(7)); + } + let lent = fw.queues.render.entries[1].as_mut().unwrap().pair.take().unwrap(); + assert_eq!(parked(&fw.queues.render), expected, "a borrowed pair's parked work still precedes it"); + put_back(&mut fw, 1, lent); + assert_eq!(fw.queues.render.entries[1].as_ref().unwrap().borrowed_replay, None, + "the returned pair answers for itself"); + fw.queues.render.entries[1].as_mut().unwrap().pair.as_mut().unwrap().replay.clear(); + assert_eq!(parked(&fw.queues.render), (false, [false; 4], false, [false; 4])); + let lent = lend(&mut fw, 1, 8); + assert_eq!(fw.queues.render.entries[1].as_ref().unwrap().borrowed_replay, None); + put_back(&mut fw, 1, lent); + // (c) Three threads: a publisher lending and returning slot 1, the event worker, the GPU. const PASSES: u64 = 4000; let fw = Arc::new(Mutex::new(firmware(vec![None, Some(entry(1, qids, &[]))]))); diff --git a/tools/asahi/g17-unpublished-tests.py b/tools/asahi/g17-unpublished-tests.py index 5955fd2cbd500..898d6bef2a3c9 100644 --- a/tools/asahi/g17-unpublished-tests.py +++ b/tools/asahi/g17-unpublished-tests.py @@ -50,7 +50,7 @@ def fixture(): } channels.push(Backend{q:std::cell::RefCell::new(q),owner,context}); } - let packet=Arc::new(Packet{completion:Arc::new(Completion)}); + let packet=command(1); for b in &channels { assert_eq!(b.finish_publication(&packet,Err(ENOMEM),&mut DeferredBatch),Err(ENOMEM)); let q=b.q.borrow();assert!(q.reusable(),"failed open-owner first submit must return channel"); @@ -64,8 +64,8 @@ def fixture(): match guard { 0=>q.unpublished_binding=false, 1=>q.exit=Some(Exit{phase:Phase::Acknowledged}), - 2=>q.active.push(Active{packet:Arc::new(Packet{completion:Arc::new(Completion)}),ticket:None,observed:None,qos_pending:false,stamps_owed:false}).unwrap(), - 3=>q.replays.push(Arc::new(Packet{completion:Arc::new(Completion)})).unwrap(), + 2=>q.active.push(Active{packet:command(1),ticket:None,observed:None,qos_pending:false,stamps_owed:false}).unwrap(), + 3=>q.replays.push(command(1)).unwrap(), 4=>q.growing=true, 5=>q.quarantined=true, 6=>q.awaiting_witness=true, diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 1fccc3bfcaadd..64c40a28305cc 100644 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -409,7 +409,9 @@ def mutations(flag, names, base, expect=KILL): 'no-step-past', 'pop-owed', 'head-includes-owed', 'held-stamped-pops', 'crossed-behind-owed', 'owed-classified', 'rebind-check-entry', 'timeout-fails-retired', 'no-owed-poll', 'count-recordless', - 'count-owed-twice', 'forfeit-spared', 'forfeit-unclassified'), []), + 'count-owed-twice', 'forfeit-spared', 'forfeit-unclassified', + 'failed-unnoted', 'succeeded-noted', 'signalled-kept', + 'owner-keeps-failures'), []), 'g17-compute-deadline-tests.py': [([], PASS)], 'g17-compute-growth-deadline-tests.py': [([], PASS)], 'g17-render-template-tests.py': [([], PASS)] @@ -548,13 +550,28 @@ def mutations(flag, names, base, expect=KILL): 'render-timeout-decision-includes-owed', 'visit-contexts-includes-owed', 'pass-started-includes-owed', - 'running-owner-includes-owed'), []), + 'running-owner-includes-owed', + 'park-outside-render-lock', 'park-keeps-kick', + 'executed-outside-render-lock', 'executed-not-noted'), []), + 'g17-render-parked-dependency-tests.py': [([], PASS)] + + mutations('--mutation', ('spin', 'renewed-clock', 'short-bound', 'render-domain', + 'no-event-pass', 'ioctl-waits', 'busy-waits-here', + 'parked-unseen', 'failed-unseen', 'batch-kept', + 'batch-unchecked'), []), + 'g17-render-partial-order-tests.py': [([], PASS)] + + mutations('--mutation', ('every-count', 'compute-every-count', 'hazard-every-count', + 'count-ignored', 'no-count', 'compute-dropped', 'hazard-dropped', + 'render-dropped', 'render-several-only', 'own-pair-promoted', + 'undrained-promoted'), []), 'g17-render-return-observe-tests.py': [([], PASS)] + mutations('--mutation', ('rescan-owed', 'observe-all-slots', 'observe-ignores-gate', 'rescan-in-loop-bail', 'rescan-is-fallback', 'missed-dropped', 'observe-in-recovery', 'collector-blocks', 'finish-under-mutex', 'no-pass-requested', 'rescan-no-poll', 'worker-rescan-slow-path', - 'owed-slow-path'), []), + 'owed-slow-path', 'lend-parked', 'borrowed-frontier-ignored', + 'borrowed-frontier-any-owner', 'borrowed-not-parked', + 'return-keeps-frontier', 'own-slot-is-sibling', + 'tiling-frontier-ignored'), []), 'g17-rescan-poll-tests.py': [([], PASS)] + mutations('--mutation', ('starve-fast-pending', 'starve-slow-pending', 'jiffy-poll', 'skip-backpressure-poll', 'skip-sleep-cancel',