diff --git a/Documentation/devicetree/bindings/power/apple,pmc.yaml b/Documentation/devicetree/bindings/power/apple,pmc.yaml index bd8d9972e1533..6c4d228e46fad 100644 --- a/Documentation/devicetree/bindings/power/apple,pmc.yaml +++ b/Documentation/devicetree/bindings/power/apple,pmc.yaml @@ -270,6 +270,40 @@ patternProperties: The SMC, whose package power reading the low-power platform profile holds the CPU clusters to. + apple,gpu-busy-memory-states: + $ref: /schemas/types.yaml#/definitions/uint32-matrix + description: + The DCS state (first row) and fabric state (second row) for GPU work + the GPU driver reports, by the busy share it reports, below each of + the three apple,gpu-busy-permille shares and at or above the last. + A non-zero top DCS state enables the busy-share ladder; without + these properties, reported GPU work gets the compatible's default + floor. + minItems: 2 + maxItems: 2 + items: + minItems: 4 + maxItems: 4 + items: + maximum: 15 + + apple,gpu-busy-permille: + $ref: /schemas/types.yaml#/definitions/uint32-array + description: + The GPU busy shares, in permille of the time the GPU spends + executing, from which reported GPU work gets the second, third and + top column of apple,gpu-busy-memory-states. + minItems: 3 + maxItems: 3 + items: + maximum: 1000 + + dependentRequired: + apple,gpu-busy-memory-states: + - apple,gpu-busy-permille + apple,gpu-busy-permille: + - apple,gpu-busy-memory-states + required: - compatible - reg diff --git a/arch/arm64/boot/dts/apple/t6041.dtsi b/arch/arm64/boot/dts/apple/t6041.dtsi index 23720e5e53b6b..dd165c4b15176 100644 --- a/arch/arm64/boot/dts/apple/t6041.dtsi +++ b/arch/arm64/boot/dts/apple/t6041.dtsi @@ -341,8 +341,20 @@ apple,static-voters = <1 3>; }; +/* + * The GPU's memory states by the busy share the GPU driver reports, measured + * on a J616c: DCS 1, 2, 4 or 5 and fabric 0, 0, 0 or 3, split at 160, 500 + * and 800 permille, and the top column with no share reported. The top + * column matches apple_clpc_hw_t6041's DCS 5 / fabric 3 floor (full memory + * bandwidth), so busy GPU work keeps it; light work such as scrolling a + * browser gets the lower columns. With a 3 GB/s copy: DCS 0 / fabric 0 + * 5.46 W at 309 ns DRAM latency, DCS 3 6.22 W at 166 ns, DCS 4 6.92 W at + * 114 ns, DCS 5 7.04 W at 113 ns. + */ &clpc { compatible = "apple,t6041-max-clpc", "apple,t6041-clpc"; + apple,gpu-busy-memory-states = <1 2 4 5>, <0 0 0 3>; + apple,gpu-busy-permille = <160 500 800>; }; / { diff --git a/drivers/gpu/drm/asahi/g17/clpc.c b/drivers/gpu/drm/asahi/g17/clpc.c index 58adaba19910f..bfe26e5d91c14 100644 --- a/drivers/gpu/drm/asahi/g17/clpc.c +++ b/drivers/gpu/drm/asahi/g17/clpc.c @@ -10,6 +10,12 @@ void asahi_clpc_gpu_set_active(struct apple_clpc_gpu *gpu, bool active) { apple_clpc_gpu_set_active(gpu, active); } + +void asahi_clpc_gpu_set_busy(struct apple_clpc_gpu *gpu, unsigned int permille) +{ + apple_clpc_gpu_set_busy(gpu, permille); +} + void asahi_clpc_gpu_put(struct apple_clpc_gpu *gpu) { apple_clpc_gpu_put(gpu); diff --git a/drivers/gpu/drm/asahi/g17/clpc.h b/drivers/gpu/drm/asahi/g17/clpc.h index 372820ade7eff..6b16d5e8d5801 100644 --- a/drivers/gpu/drm/asahi/g17/clpc.h +++ b/drivers/gpu/drm/asahi/g17/clpc.h @@ -5,5 +5,6 @@ struct device; struct apple_clpc_gpu; int asahi_clpc_gpu_get(void *dev, struct apple_clpc_gpu **out); void asahi_clpc_gpu_set_active(struct apple_clpc_gpu *gpu, bool active); +void asahi_clpc_gpu_set_busy(struct apple_clpc_gpu *gpu, unsigned int permille); void asahi_clpc_gpu_put(struct apple_clpc_gpu *gpu); #endif diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index d43b2b3aa69b9..fe960caa74f3d 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -1076,12 +1076,14 @@ impl Firmware { } power::IdleAction::Recheck(delay) => Some(delay), }; - Ok( - match (effort, self.idle_hold(now_ns, in_flight || submitted)) { - (Some(a), Some(b)) => Some(a.min(b)), - (a, b) => a.or(b), - }, - ) + let busy_recheck = if in_flight { + self.port.report_busy(now_ns); + self.port.busy_recheck_delay(now_ns) + } else { + None + }; + let hold = self.idle_hold(now_ns, in_flight || submitted); + Ok([effort, hold, busy_recheck].into_iter().flatten().min()) } /// Drives the idle hold (see power::Hold); returns the delay in ns for its next check. A diff --git a/drivers/gpu/drm/asahi/g17/port.rs b/drivers/gpu/drm/asahi/g17/port.rs index f9bd31f13bc7d..2a535f81429c8 100644 --- a/drivers/gpu/drm/asahi/g17/port.rs +++ b/drivers/gpu/drm/asahi/g17/port.rs @@ -116,6 +116,13 @@ pub(super) struct Port { /// Full firmware effort is applied; cleared before an idle clear rechecks `submissions`. effort_full: AtomicBool, demand: super::power::Demand, + /// Serializes busy-share window accounting and CLPC busy updates. + #[pin] + busy: SpinLock, + /// Mirrored from `busy` and `qos` for a lock-free fast path in `note_gpu_activity()`. + busy_window_start: AtomicU64, + busy_below_top: AtomicBool, + oldest_in_flight_any: AtomicU64, statistics_epoch: AtomicU64, last_submission_ns: AtomicU64, submissions: AtomicU64, @@ -174,6 +181,10 @@ impl Port { publications: AtomicU64::new(0), effort_full: AtomicBool::new(false), demand, + busy <- new_spinlock!(super::power::BusyShare::new(), "g17::Port::busy"), + busy_window_start: AtomicU64::new(0), + busy_below_top: AtomicBool::new(false), + oldest_in_flight_any: AtomicU64::new(0), statistics_epoch: AtomicU64::new(0), last_submission_ns: AtomicU64::new(0), submissions: AtomicU64::new(0), @@ -427,10 +438,14 @@ impl Port { policy: Policy, ) -> Result { let view = self.qos_view()?; - let publication = self - .qos - .lock() - .publish(&view, owner, scheduler, policy, qos::clock)?; + let publication = { + let mut qos = self.qos.lock(); + let publication = + qos.publish(&view, owner, scheduler, policy, qos::clock, super::now_ns())?; + self.oldest_in_flight_any + .store(qos.oldest_in_flight_any(), Ordering::Relaxed); + publication + }; self.rx_update(); Ok(publication) } @@ -443,17 +458,31 @@ impl Port { policy: Policy, ) -> Result<[qos::Publication; 2]> { let view = self.qos_view()?; - let publications = - self.qos - .lock() - .publish_owners(&view, owners, scheduler, policy, qos::clock)?; + let publications = { + let mut qos = self.qos.lock(); + let publications = qos.publish_owners( + &view, + owners, + scheduler, + policy, + qos::clock, + super::now_ns(), + )?; + self.oldest_in_flight_any + .store(qos.oldest_in_flight_any(), Ordering::Relaxed); + publications + }; self.rx_update(); Ok(publications) } pub(super) fn qos_cancel(&self, publication: qos::Publication) -> Result { let view = self.qos_view()?; - self.qos.lock().cancel(&view, publication) + let mut qos = self.qos.lock(); + qos.cancel(&view, publication)?; + self.oldest_in_flight_any + .store(qos.oldest_in_flight_any(), Ordering::Relaxed); + Ok(()) } /// Clears the QoS table rows of released QoS IDs (`QosIds::forget_released`); returns @@ -468,7 +497,12 @@ impl Port { pub(super) fn qos_complete(&self, owners: &[qos::Owner]) -> Result { let view = self.qos_view()?; - self.qos.lock().complete(&view, owners)?; + { + let mut qos = self.qos.lock(); + qos.complete(&view, owners, super::now_ns())?; + self.oldest_in_flight_any + .store(qos.oldest_in_flight_any(), Ordering::Relaxed); + } self.rx_update(); Ok(()) } @@ -538,7 +572,15 @@ impl Port { pub(super) fn set_effort_full(&self, full: bool) { self.effort_full.store(full, Ordering::SeqCst); - self.demand.set_active(full); + if full { + self.demand.set_active(true); + } else { + let mut busy = self.busy.lock(); + self.demand.set_active(false); + busy.clear_active(); + self.busy_window_start.store(0, Ordering::Relaxed); + self.busy_below_top.store(false, Ordering::Relaxed); + } } /// The next statistics drain and reader discard what the decoder holds. @@ -550,6 +592,54 @@ impl Port { self.statistics_epoch.load(Ordering::Acquire) } + /// Reports the busiest GPU engine's share of the last window (including unretired + /// in-flight commands) to CLPC once a window elapses or an in-flight command + /// saturates its engine. Lock-free on the common in-window path. + pub(super) fn report_busy(&self, now_ns: u64) { + if !self.demand.has_provider() { + return; + } + let start = self.busy_window_start.load(Ordering::Relaxed); + let window_due = + start == 0 || now_ns.saturating_sub(start) >= super::power::BUSY_WINDOW_NS; + let long_due = !window_due + && self.busy_below_top.load(Ordering::Relaxed) + && { + let oldest = self.oldest_in_flight_any.load(Ordering::Relaxed); + oldest != 0 + && now_ns.saturating_sub(oldest) >= super::power::BUSY_LONG_COMMAND_NS + }; + if !window_due && !long_due { + return; + } + // Read retired time (Acquire) before qos (lock Acquire): retirement calls + // qos_complete() before usage::Client::add() Release-adds ENGINE_NS, so we + // never observe both the retired time and the old in-flight timestamp. + let retired = crate::usage::ENGINE_NS + .each_ref() + .map(|ns| ns.load(Ordering::Acquire)); + let oldest = self.qos.lock().oldest_in_flight(); + let now_ns = super::now_ns().max(now_ns); + let mut busy = self.busy.lock(); + if let Some(permille) = busy.sample(now_ns, retired, oldest) { + self.demand.set_busy(permille); + } + self.busy_window_start + .store(busy.window_start().map_or(0, |s| s.max(1)), Ordering::Relaxed); + self.busy_below_top + .store(busy.below_top(), Ordering::Relaxed); + } + + /// Wake delay (ns) for `idle_check` while a solo long command is running below + /// the top CLPC busy column, or `None` when already at top or idle. + pub(super) fn busy_recheck_delay(&self, now_ns: u64) -> Option { + if !self.demand.has_provider() || !self.busy_below_top.load(Ordering::Relaxed) { + return None; + } + let oldest = self.oldest_in_flight_any.load(Ordering::Relaxed); + super::power::BusyShare::recheck_delay_for(now_ns, oldest) + } + pub(super) fn note_gpu_activity(&self) { // Observe gating before activity can wake the cores. A lockless // publisher cannot clear the decoder under the device mutex; this @@ -561,9 +651,10 @@ impl Port { { self.statistics_epoch.fetch_add(1, Ordering::Release); } - self.last_submission_ns - .store(super::now_ns(), Ordering::Relaxed); + let now_ns = super::now_ns(); + self.last_submission_ns.store(now_ns, Ordering::Relaxed); self.demand.set_active(true); + self.report_busy(now_ns); } pub(super) fn write_power(&self, f: &mut kernel::fmt::Formatter<'_>) -> kernel::fmt::Result { diff --git a/drivers/gpu/drm/asahi/g17/power.rs b/drivers/gpu/drm/asahi/g17/power.rs index 8ae6e5d1808eb..cf1fe38cbea5e 100644 --- a/drivers/gpu/drm/asahi/g17/power.rs +++ b/drivers/gpu/drm/asahi/g17/power.rs @@ -420,6 +420,141 @@ pub(super) fn release(control: &mut C) -> kernel::error::Result { result } +/// Busy-share window: long enough to span frames, short enough to follow a burst. +pub(super) const BUSY_WINDOW_NS: u64 = 200_000_000; +/// A longer gap between reports with no long command in flight was idle: start over +/// rather than average it in. +pub(super) const BUSY_WINDOW_MAX_NS: u64 = 2_000_000_000; +/// An unretired command that has been running continuously for this long saturates +/// its engine and immediately lifts the busy share to 1000 permille, without waiting +/// for it to retire or for the current window to end. +pub(super) const BUSY_LONG_COMMAND_NS: u64 = 50_000_000; + +/// Per-window busiest GPU engine share (0..=1000 permille), combining retired stage +/// execution time with unretired in-flight command time. +/// +/// The vertex, fragment and compute engines run in parallel, so their summed time is +/// not a share of the window: taking the busiest engine's share avoids double-counting +/// across engines. For each engine, `retired_ns + in_flight_age` is differenced across +/// window boundaries so a command spanning a boundary counts in the window it runs in +/// and is never double-counted when it later retires. Any engine with an unretired +/// command older than [`BUSY_LONG_COMMAND_NS`] lifts immediately to 1000 permille so +/// long compute or render work running beside a light compositor never sits at a low +/// memory floor waiting for retirement. In-flight age counts from publication, so time +/// a command waits in its queue or on dependencies, and a render's vertex and fragment +/// stages retiring together, err toward a higher share, which is the safe direction. +pub(super) struct BusyShare { + start_ns: Option, + retired_ns: [u64; crate::usage::NUM_ENGINES], + in_flight_ns: [u64; crate::usage::NUM_ENGINES], + below_top: bool, +} + +impl BusyShare { + pub(super) const fn new() -> Self { + Self { + start_ns: None, + retired_ns: [0; crate::usage::NUM_ENGINES], + in_flight_ns: [0; crate::usage::NUM_ENGINES], + below_top: false, + } + } + + /// CLPC cleared GPU activity (forgetting its last share so a new burst starts + /// at the top column). Only called once the GPU is idle: restart the window so + /// the first report of the next burst re-baselines instead of closing a window + /// diluted by the idle gap, which would drop the burst off the top column. + pub(super) fn clear_active(&mut self) { + self.start_ns = None; + self.in_flight_ns = [0; crate::usage::NUM_ENGINES]; + self.below_top = false; + } + + pub(super) fn below_top(&self) -> bool { + self.below_top + } + + pub(super) fn window_start(&self) -> Option { + self.start_ns + } + + pub(super) fn is_long_in_flight( + now_ns: u64, + oldest_in_flight: [u64; crate::usage::NUM_ENGINES], + ) -> bool { + oldest_in_flight + .iter() + .any(|&since| since != 0 && now_ns.saturating_sub(since) >= BUSY_LONG_COMMAND_NS) + } + + /// Delay (ns) until an in-flight command reaches [`BUSY_LONG_COMMAND_NS`], at + /// least 1 ms. Retirement runs its own event pass, so this never delays idle + /// teardown. + pub(super) fn recheck_delay_for(now_ns: u64, oldest: u64) -> Option { + if oldest == 0 { + return None; + } + let age = now_ns.saturating_sub(oldest); + Some(BUSY_LONG_COMMAND_NS.saturating_sub(age).max(1_000_000)) + } + + pub(super) fn sample( + &mut self, + now_ns: u64, + retired_ns: [u64; crate::usage::NUM_ENGINES], + oldest_in_flight: [u64; crate::usage::NUM_ENGINES], + ) -> Option { + let long_in_flight = Self::is_long_in_flight(now_ns, oldest_in_flight); + let Some(start) = self.start_ns else { + self.start_ns = Some(now_ns); + self.retired_ns = retired_ns; + for (slot, &since) in self.in_flight_ns.iter_mut().zip(oldest_in_flight.iter()) { + *slot = if since != 0 { + now_ns.saturating_sub(since) + } else { + 0 + }; + } + return None; + }; + let elapsed = now_ns.saturating_sub(start); + if elapsed < BUSY_WINDOW_NS { + if self.below_top && long_in_flight { + self.below_top = false; + return Some(1000); + } + return None; + } + let mut busiest = 0u64; + for i in 0..crate::usage::NUM_ENGINES { + let now = retired_ns[i]; + let delta = now.saturating_sub(self.retired_ns[i]); + self.retired_ns[i] = now; + let since = oldest_in_flight[i]; + let age = if since != 0 { + now_ns.saturating_sub(since) + } else { + 0 + }; + let prev_age = self.in_flight_ns[i]; + self.in_flight_ns[i] = age; + let busy = delta.saturating_add(age).saturating_sub(prev_age); + busiest = busiest.max(busy); + } + self.start_ns = Some(now_ns); + if elapsed > BUSY_WINDOW_MAX_NS && !long_in_flight { + return None; + } + let permille = if long_in_flight { + 1000 + } else { + (busiest.saturating_mul(1000) / elapsed).min(1000) as u32 + }; + self.below_top = permille < 1000; + Some(permille) + } +} + #[cfg_attr(not(test), kernel::macros::kunit_tests(asahi_g17_idle_hold))] mod tests { use super::*; @@ -576,12 +711,150 @@ mod tests { hold.asserted(); assert_eq!(hold.step(1, false, 2, FIRMWARE_IDLE_OFF_MS), HoldAction::Release); } + + #[test] + fn long_in_flight_command_lifts_beside_light_submitter() { + const NS_MS: u64 = 1_000_000; + let mut share = BusyShare::new(); + // Establish light compositor baseline: ~50 permille (10 ms in 200 ms). + assert_eq!(share.sample(1000 * NS_MS, [0, 0, 0], [0, 0, 0]), None); + assert_eq!( + share.sample(1200 * NS_MS, [2 * NS_MS, 10 * NS_MS, 0], [0, 0, 0]), + Some(50) + ); + assert!(share.below_top()); + // A 500 ms compute job starts at t=1250 ms; compositor submits at t=1410 ms. + assert_eq!( + share.sample( + 1410 * NS_MS, + [4 * NS_MS, 20 * NS_MS, 0], + [0, 0, 1250 * NS_MS], + ), + Some(1000) + ); + assert!(!share.below_top()); + // Still running across the next window at t=1610 ms: stays at 1000. + assert_eq!( + share.sample( + 1610 * NS_MS, + [6 * NS_MS, 30 * NS_MS, 0], + [0, 0, 1250 * NS_MS], + ), + Some(1000) + ); + // Retires at t=1750 ms (+500 ms retired); only the 140 ms in [1610, 1750] counts. + assert_eq!( + share.sample(1810 * NS_MS, [8 * NS_MS, 40 * NS_MS, 500 * NS_MS], [0, 0, 0]), + Some(700) + ); + // Next window returns cleanly to the light compositor share. + assert_eq!( + share.sample(2010 * NS_MS, [10 * NS_MS, 50 * NS_MS, 500 * NS_MS], [0, 0, 0]), + Some(50) + ); + } + + #[test] + fn late_long_command_lifts_mid_window_without_double_counting() { + const NS_MS: u64 = 1_000_000; + let mut share = BusyShare::new(); + assert_eq!(share.sample(1000 * NS_MS, [0, 0, 0], [0, 0, 0]), None); + assert_eq!(share.sample(1200 * NS_MS, [0, 10 * NS_MS, 0], [0, 0, 0]), Some(50)); + // Long compute starts at t=1390 ms; window closes at t=1410 ms (only 20 ms old). + assert_eq!( + share.sample(1410 * NS_MS, [0, 20 * NS_MS, 0], [0, 0, 1390 * NS_MS]), + Some(95) + ); + assert!(share.below_top()); + // At t=1440 ms (50 ms old, mid-window), early lift reports 1000 immediately. + assert_eq!( + share.sample(1440 * NS_MS, [0, 22 * NS_MS, 0], [0, 0, 1390 * NS_MS]), + Some(1000) + ); + assert!(!share.below_top()); + // Second mid-window submit does not spam CLPC. + assert_eq!( + share.sample(1460 * NS_MS, [0, 23 * NS_MS, 0], [0, 0, 1390 * NS_MS]), + None + ); + // Retires at t=1490 ms (+100 ms retired); window [1410, 1610] credits exact 80 ms. + assert_eq!( + share.sample(1610 * NS_MS, [0, 30 * NS_MS, 100 * NS_MS], [0, 0, 0]), + Some(400) + ); + } + + #[test] + fn straddling_short_command_and_long_gaps_behave_cleanly() { + const NS_MS: u64 = 1_000_000; + let mut share = BusyShare::new(); + assert_eq!(share.sample(1000 * NS_MS, [0, 0, 0], [0, 0, 0]), None); + // 40 ms command [1170, 1210] straddles boundary 1200: 30 ms in first, 10 ms in second. + assert_eq!( + share.sample(1200 * NS_MS, [0, 0, 0], [0, 0, 1170 * NS_MS]), + Some(150) + ); + assert_eq!( + share.sample(1400 * NS_MS, [0, 0, 40 * NS_MS], [0, 0, 0]), + Some(50) + ); + // Multi-engine takes busiest engine rather than summing parallel engines. + assert_eq!( + share.sample(1600 * NS_MS, [0, 120 * NS_MS, 150 * NS_MS], [0, 0, 0]), + Some(600) + ); + // >2 s idle gap with a freshly-started command (age 0) restarts without reporting. + assert_eq!( + share.sample(5000 * NS_MS, [0, 120 * NS_MS, 150 * NS_MS], [0, 0, 5000 * NS_MS]), + None + ); + // >2 s active command still reports 1000. + assert_eq!( + share.sample(8000 * NS_MS, [0, 120 * NS_MS, 150 * NS_MS], [0, 0, 5000 * NS_MS]), + Some(1000) + ); + // Recheck delay wakes once at the long-command age (at least 1 ms), None when idle. + assert_eq!(BusyShare::recheck_delay_for(1010 * NS_MS, 0), None); + assert_eq!( + BusyShare::recheck_delay_for(1010 * NS_MS, 1000 * NS_MS), + Some(40 * NS_MS) + ); + assert_eq!( + BusyShare::recheck_delay_for(1045 * NS_MS, 1000 * NS_MS), + Some(5 * NS_MS) + ); + assert_eq!( + BusyShare::recheck_delay_for(1100 * NS_MS, 1000 * NS_MS), + Some(NS_MS) + ); + } + + #[test] + fn new_burst_after_idle_restarts_the_window() { + const NS_MS: u64 = 1_000_000; + let mut share = BusyShare::new(); + // Steady 600 permille fragment work. + assert_eq!(share.sample(900 * NS_MS, [0, 0, 0], [0, 0, 0]), None); + assert_eq!(share.sample(1100 * NS_MS, [0, 120 * NS_MS, 0], [0, 0, 0]), Some(600)); + assert_eq!(share.sample(1300 * NS_MS, [0, 240 * NS_MS, 0], [0, 0, 0]), Some(600)); + // Work continues to 1400 ms, then the GPU idles and CLPC clears its share. + share.clear_active(); + assert!(!share.below_top()); + // First submission after a 600 ms idle gap: closing [1300, 2000] would report + // a diluted 85 permille (60 ms in 700 ms); it re-baselines instead. + assert_eq!(share.sample(2000 * NS_MS, [0, 300 * NS_MS, 0], [0, 0, 0]), None); + assert!(!share.below_top()); + // No report until a fresh 200 ms window of the new burst completes. + assert_eq!(share.sample(2190 * NS_MS, [0, 414 * NS_MS, 0], [0, 0, 0]), None); + assert_eq!(share.sample(2200 * NS_MS, [0, 420 * NS_MS, 0], [0, 0, 0]), Some(600)); + } } unsafe extern "C" { fn asahi_clpc_gpu_get(dev: *mut core::ffi::c_void, out: *mut *mut core::ffi::c_void) -> core::ffi::c_int; fn asahi_clpc_gpu_set_active(gpu: *mut core::ffi::c_void, active: bool); fn asahi_clpc_gpu_put(gpu: *mut core::ffi::c_void); + fn asahi_clpc_gpu_set_busy(gpu: *mut core::ffi::c_void, permille: core::ffi::c_uint); } /// DT-selected memory-demand provider. Its independent allocation outlives a @@ -605,10 +878,19 @@ impl Demand { } } + pub(super) fn has_provider(&self) -> bool { + !self.0.is_null() + } + pub(super) fn set_active(&self, active: bool) { // SAFETY: the retained reference is live; NULL denotes no DT provider. unsafe { asahi_clpc_gpu_set_active(self.0, active) }; } + + pub(super) fn set_busy(&self, permille: u32) { + // SAFETY: the retained reference is live; NULL denotes no DT provider. + unsafe { asahi_clpc_gpu_set_busy(self.0, permille.min(1000) as core::ffi::c_uint) }; + } } impl Drop for Demand { diff --git a/drivers/gpu/drm/asahi/g17/qos.rs b/drivers/gpu/drm/asahi/g17/qos.rs index 5adccb14b5cad..36a20a5e02d8f 100644 --- a/drivers/gpu/drm/asahi/g17/qos.rs +++ b/drivers/gpu/drm/asahi/g17/qos.rs @@ -6,7 +6,10 @@ //! precedes submitted counters; retiring a final owner clears only its two row //! bytes. Cancellation balances host references without rewinding shared counts. -use super::fw::{qos as fw, queue::Policy}; +use super::fw::{ + qos as fw, + queue::{DataMaster, Policy}, +}; use crate::hw::t8140::qos as cfg; use core::{ mem::offset_of, @@ -14,6 +17,13 @@ use core::{ }; use kernel::prelude::*; +const _: () = { + assert!(fw::QUEUES <= 128); + assert!(DataMaster::Tiling as usize == crate::usage::Engine::Vertex as usize); + assert!(DataMaster::Fragment as usize == crate::usage::Engine::Fragment as usize); + assert!(DataMaster::Compute as usize == crate::usage::Engine::Compute as usize); +}; + /// Atomic views retain the allocation borrow and never borrow firmware words /// as ordinary mutable memory. The arrays are disjoint apart from the explicit /// data-master time/count indexing in `times_and_counts`. @@ -87,6 +97,11 @@ pub(crate) struct Accounting { in_flight: [u32; fw::QUEUES], dm_in_flight: [u64; fw::DATA_MASTERS], dm_by_qid: [u8; fw::QUEUES], + /// Bitmask of QIDs with `in_flight[qid] > 0`. + active_qids: u128, + /// Monotonic start timestamp (ns) of each active QID's oldest unretired command, + /// advanced when a command completes with more work still in flight on that QID. + qid_since_ns: [u64; fw::QUEUES], /// The table's rows and counts as last stored, indexed as in [`View`]. Only the host /// writes them, so a publication counts on from these instead of reading them back. rows: [[u8; 8]; fw::QUEUES], @@ -101,6 +116,8 @@ impl Accounting { in_flight: [0; fw::QUEUES], dm_in_flight: [0; fw::DATA_MASTERS], dm_by_qid: [0; fw::QUEUES], + active_qids: 0, + qid_since_ns: [0; fw::QUEUES], rows: [[0; 8]; fw::QUEUES], queue_submitted: [0; fw::QUEUES], owner_submitted: [0; fw::QUEUES], @@ -119,8 +136,9 @@ impl Accounting { scheduler: u64, policy: Policy, clock: impl FnOnce() -> (u64, u64), + now_ns: u64, ) -> Result { - let [publication] = self.publish_owners(view, [owner], scheduler, policy, clock)?; + let [publication] = self.publish_owners(view, [owner], scheduler, policy, clock, now_ns)?; Ok(publication) } @@ -136,6 +154,7 @@ impl Accounting { scheduler: u64, policy: Policy, clock: impl FnOnce() -> (u64, u64), + now_ns: u64, ) -> Result<[Publication; N]> { if scheduler == 0 { return Err(EINVAL); @@ -219,6 +238,10 @@ impl Accounting { let mut record = rows[index]; record[0] = owner.qos; record[1] = class; + if self.in_flight[qid] == 0 { + self.qid_since_ns[qid] = now_ns.max(1); + self.active_qids |= 1u128 << qid; + } self.in_flight[qid] += 1; self.dm_in_flight[dm] += 1; self.dm_by_qid[qid] = owner.data_master; @@ -243,7 +266,7 @@ impl Accounting { { return Err(EIO); } - self.complete(view, &[ticket.owner]) + self.complete_inner(view, &[ticket.owner], 0, true) } /// Clears the scheduler and share rows of the QoS IDs in `ids`, which no context holds: a @@ -271,7 +294,17 @@ impl Accounting { /// Preflights the entire set before clearing any final row. QID membership, /// scheduler mappings and monotonically increasing counts remain intact. - pub(crate) fn complete(&mut self, view: &View<'_>, owners: &[Owner]) -> Result { + pub(crate) fn complete(&mut self, view: &View<'_>, owners: &[Owner], now_ns: u64) -> Result { + self.complete_inner(view, owners, now_ns, false) + } + + fn complete_inner( + &mut self, + view: &View<'_>, + owners: &[Owner], + now_ns: u64, + cancelled: bool, + ) -> Result { let mut completed = [0u64; fw::DATA_MASTERS]; for (index, owner) in owners.iter().copied().enumerate() { let (qid, _, dm) = owner.indices()?; @@ -300,7 +333,14 @@ impl Accounting { } } for owner in owners { - self.in_flight[usize::from(owner.qid)] -= 1; + let qid = usize::from(owner.qid); + self.in_flight[qid] -= 1; + if self.in_flight[qid] == 0 { + self.qid_since_ns[qid] = 0; + self.active_qids &= !(1u128 << qid); + } else if !cancelled { + self.qid_since_ns[qid] = now_ns.max(1); + } } for (dm, count) in completed.iter().enumerate() { self.dm_in_flight[dm] -= count; @@ -308,6 +348,32 @@ impl Accounting { fence(Ordering::SeqCst); Ok(()) } + + /// Oldest unretired command timestamp (monotonic ns) per engine + /// (vertex, fragment, compute), or 0 when that engine has none in flight. + pub(crate) fn oldest_in_flight(&self) -> [u64; crate::usage::NUM_ENGINES] { + let mut oldest = [0u64; crate::usage::NUM_ENGINES]; + let mut mask = self.active_qids; + while mask != 0 { + let qid = mask.trailing_zeros() as usize; + mask &= mask - 1; + let dm = usize::from(self.dm_by_qid[qid]); + let since = self.qid_since_ns[qid]; + if dm < oldest.len() && since != 0 && (oldest[dm] == 0 || since < oldest[dm]) { + oldest[dm] = since; + } + } + oldest + } + + /// Oldest unretired command timestamp across all engines, or 0 if idle. + pub(crate) fn oldest_in_flight_any(&self) -> u64 { + self.oldest_in_flight() + .into_iter() + .filter(|&since| since != 0) + .min() + .unwrap_or(0) + } } /// Firmware accounting uses a 24 MHz domain independent of host timer speed. diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index 810ba87367875..8a4cc26470333 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -1598,6 +1598,7 @@ impl compute::Host for ComputeHost<'_> { } fn note_submission(&mut self) -> Result { self.shared.note_submitter(); + self.port.note_gpu_activity(); self.shared.note_gpu_activity(); self.effort.submit(); self.effort.note_waiters(super::now_ns(), super::fence::waiters()); diff --git a/drivers/gpu/drm/asahi/usage.rs b/drivers/gpu/drm/asahi/usage.rs index aa817d2d41768..f25b367ea8101 100644 --- a/drivers/gpu/drm/asahi/usage.rs +++ b/drivers/gpu/drm/asahi/usage.rs @@ -11,6 +11,16 @@ use core::sync::atomic::{AtomicU64, Ordering}; +/// Number of GPU engines tracked in [`Engine`]: vertex, fragment and compute. +pub(crate) const NUM_ENGINES: usize = 3; + +/// Engine time charged across all clients per [`Engine`], in ns, for the GPU busy share. +/// +/// Overlapping work from multiple clients on the same engine adds up here; consumers clamp +/// the resulting busy share to 1000 permille, which safely errs toward the higher floor. +pub(crate) static ENGINE_NS: [AtomicU64; NUM_ENGINES] = + [const { AtomicU64::new(0) }; NUM_ENGINES]; + #[derive(Clone, Copy)] pub(crate) enum Engine { Vertex, @@ -20,13 +30,13 @@ pub(crate) enum Engine { /// One ledger per DRM file, shared by all of its queues and VMs. pub(crate) struct Client { - ns: [AtomicU64; 3], + ns: [AtomicU64; NUM_ENGINES], } impl Client { pub(crate) const fn new() -> Self { Self { - ns: [const { AtomicU64::new(0) }; 3], + ns: [const { AtomicU64::new(0) }; NUM_ENGINES], } } @@ -38,6 +48,9 @@ impl Client { return; } let ns = ticks_to_ns(end - start, frequency_hz); + // Release orders retirement's earlier qos_complete() before any reader + // that Acquire-loads ENGINE_NS and then reads qos.oldest_in_flight(). + ENGINE_NS[engine as usize].fetch_add(ns, Ordering::Release); let counter = &self.ns[engine as usize]; let mut old = counter.load(Ordering::Relaxed); loop { @@ -54,7 +67,7 @@ impl Client { } /// Vertex, fragment and compute, in ns. No cross-engine atomic snapshot is promised. - pub(crate) fn snapshot(&self) -> [u64; 3] { + pub(crate) fn snapshot(&self) -> [u64; NUM_ENGINES] { self.ns.each_ref().map(|ns| ns.load(Ordering::Relaxed)) } } @@ -75,14 +88,14 @@ const DISCONTINUITY_S: u64 = 60; /// still add up, one union each. pub(crate) struct Lane

{ client: P, - covered: [AtomicU64; 3], + covered: [AtomicU64; NUM_ENGINES], } impl> Lane

{ pub(crate) fn new(client: P) -> Self { Self { client, - covered: [const { AtomicU64::new(0) }; 3], + covered: [const { AtomicU64::new(0) }; NUM_ENGINES], } } diff --git a/drivers/soc/apple/clpc.c b/drivers/soc/apple/clpc.c index c06f00e508bde..8ec5471fc735a 100644 --- a/drivers/soc/apple/clpc.c +++ b/drivers/soc/apple/clpc.c @@ -77,6 +77,9 @@ enum apple_clpc_rail { #define APPLE_CLPC_REASON_HOLD BIT(4) #define APPLE_CLPC_REASON_ANE BIT(5) +/* A lower GPU busy level must last this long; a higher one applies at once. */ +#define APPLE_CLPC_GPU_DOWN_MS 400 + /** * struct apple_clpc_hw - per-SoC CLPC parameters * @rail: PMC rail of the DCS and of the fabric @@ -101,7 +104,19 @@ enum apple_clpc_rail { * measured on; SoCs sharing this CLPC without it get no cluster floor * @gpu_input: the GPU driver reports its work in flight through * apple_clpc_gpu_get(); while there is some, both rails go to the top - * of @map + * of @map (or @gpu where higher), or to @gpu_busy if enabled from the DT + * @gpu_busy: state of each rail for reported GPU work below @gpu_busy_mid, + * @gpu_busy_high and @gpu_busy_top and at or above it, from the node's + * apple,gpu-busy-memory-states and apple,gpu-busy-permille properties; + * a non-zero top DCS state enables the busy-share ladder, otherwise + * reported GPU work falls back to the top of @map (or @gpu where higher) + * @gpu_busy_mid: GPU busy share in permille (apple_clpc_gpu_set_busy()) + * from which reported GPU work gets the second column of @gpu_busy + * @gpu_busy_high: busy share from which it gets the third column + * @gpu_busy_top: busy share from which it gets the top column, as does a + * GPU that reports no share. The share is the busiest engine's time spent + * executing at whatever clock the GPU runs, not bandwidth: a scrolling + * browser reads a few percent, CS2 at 120 fps ~480-620 permille. * @idle_on_time: sample every period even with no vote held, instead of * from a deferrable timer * @low_power_khz: CPU frequency ceiling of the low-power platform profile, @@ -123,6 +138,10 @@ struct apple_clpc_hw { unsigned int pmp_agent; unsigned int gpu_dense; bool gpu_input; + u8 gpu_busy[APPLE_CLPC_RAILS][APPLE_CLPC_LEVELS]; + unsigned int gpu_busy_mid; + unsigned int gpu_busy_high; + unsigned int gpu_busy_top; u8 ane[APPLE_CLPC_RAILS]; unsigned int ane_cluster; unsigned int ane_cluster_khz; @@ -157,6 +176,11 @@ struct apple_clpc_gpu { bool active; u64 updated_ns; u64 sequence; + /* Busy share of the last window in permille, if the GPU reports one */ + unsigned int busy; + bool busy_valid; + unsigned int level; + unsigned long level_since; struct delayed_work *wake; }; @@ -266,12 +290,35 @@ void apple_clpc_gpu_set_active(struct apple_clpc_gpu *gpu, bool active) if (active && !gpu->active && gpu->wake) mod_delayed_work(system_freezable_power_efficient_wq, gpu->wake, 0); gpu->active = active; + /* A new burst after idle starts from the top, not from an old share. */ + if (!active) + gpu->busy_valid = false; gpu->updated_ns = ktime_get_mono_fast_ns(); gpu->sequence++; spin_unlock_irqrestore(&gpu->lock, flags); } EXPORT_SYMBOL_GPL(apple_clpc_gpu_set_active); +/** + * apple_clpc_gpu_set_busy() - Report the GPU busy share of the last window + * @gpu: the GPU input, from apple_clpc_gpu_get() + * @permille: share of the window the GPU spent executing work, 0..1000 + * + * Scales the floor that reported GPU work gets, see &struct apple_clpc_hw.gpu_busy. + */ +void apple_clpc_gpu_set_busy(struct apple_clpc_gpu *gpu, unsigned int permille) +{ + unsigned long flags; + + if (!gpu) + return; + spin_lock_irqsave(&gpu->lock, flags); + gpu->busy = min(permille, 1000U); + gpu->busy_valid = true; + spin_unlock_irqrestore(&gpu->lock, flags); +} +EXPORT_SYMBOL_GPL(apple_clpc_gpu_set_busy); + void apple_clpc_gpu_put(struct apple_clpc_gpu *gpu) { if (gpu) { @@ -340,6 +387,36 @@ int apple_clpc_gpu_get(struct device *dev, struct apple_clpc_gpu **out) } EXPORT_SYMBOL_GPL(apple_clpc_gpu_get); +/* + * The column of @hw->gpu_busy for reported GPU work, from its busy share. + * Called once per CLPC sample: a higher column applies at once, a lower one + * at the first sample at least APPLE_CLPC_GPU_DOWN_MS after the last one + * that asked for the current column or a higher one. + */ +static unsigned int apple_clpc_gpu_level(const struct apple_clpc_hw *hw, + struct apple_clpc_gpu *gpu) +{ + unsigned long flags; + unsigned int level; + + spin_lock_irqsave(&gpu->lock, flags); + if (!gpu->busy_valid || gpu->busy >= hw->gpu_busy_top) + level = APPLE_CLPC_LEVELS - 1; + else if (gpu->busy >= hw->gpu_busy_high) + level = 2; + else + level = gpu->busy >= hw->gpu_busy_mid ? 1 : 0; + if (level >= gpu->level || + time_after_eq(jiffies, gpu->level_since + + msecs_to_jiffies(APPLE_CLPC_GPU_DOWN_MS))) { + gpu->level = level; + gpu->level_since = jiffies; + } + level = gpu->level; + spin_unlock_irqrestore(&gpu->lock, flags); + return level; +} + static bool apple_clpc_gpu_active(struct apple_clpc_gpu *gpu, u64 *updated, u64 *sequence) { unsigned long flags; @@ -724,22 +801,30 @@ static void apple_clpc_gpu_floor_count(struct apple_clpc *clpc, bool released) /* * The GPU driver's input, where it drives demand instead of the GFX power - * state: every rail at the top of @map, or at @gpu where that is higher, - * while the driver reports work. + * state: while the driver reports work, every rail at @gpu_busy for the + * reported busy share when @gpu_busy has a non-zero top DCS state, or at the + * top of @map (or @gpu where that is higher) otherwise. */ static bool apple_clpc_gpu_input_demand(const struct apple_clpc_hw *hw, struct apple_clpc_gpu *gpu, unsigned int *demand) { + bool has_busy = hw->gpu_busy[APPLE_CLPC_DCS][APPLE_CLPC_LEVELS - 1]; u64 updated, sequence; - unsigned int rail; + unsigned int level = 0, rail; if (!gpu || hw->gpu_demand || !apple_clpc_gpu_active(gpu, &updated, &sequence)) return false; - for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) - demand[rail] = max(demand[rail], - max(hw->map[rail][APPLE_CLPC_LEVELS - 1], hw->gpu[rail])); + if (has_busy) + level = apple_clpc_gpu_level(hw, gpu); + for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) { + unsigned int state = has_busy ? hw->gpu_busy[rail][level] : + max(hw->map[rail][APPLE_CLPC_LEVELS - 1], + hw->gpu[rail]); + + demand[rail] = max(demand[rail], state); + } return true; } @@ -1033,9 +1118,25 @@ static int apple_clpc_status_show(struct seq_file *s, void *unused) READ_ONCE(clpc->last_floor), READ_ONCE(clpc->last_reason), READ_ONCE(clpc->last_vote_ns)); if (clpc->gpu) { + struct apple_clpc_gpu *gpu = clpc->gpu; + unsigned int busy, level; + unsigned long flags; u64 updated, sequence; - bool active = apple_clpc_gpu_active(clpc->gpu, &updated, &sequence); - + bool active = apple_clpc_gpu_active(gpu, &updated, &sequence); + bool busy_valid; + + /* Show the level the last sample chose; reading must not move it. */ + spin_lock_irqsave(&gpu->lock, flags); + busy = gpu->busy; + busy_valid = gpu->busy_valid; + level = gpu->level; + spin_unlock_irqrestore(&gpu->lock, flags); + if (clpc->hw->gpu_busy[APPLE_CLPC_DCS][APPLE_CLPC_LEVELS - 1]) + seq_printf(s, "host_gpu busy: %u permille (%s) level %u\n", + busy, busy_valid ? "reported" : "none", level); + else + seq_printf(s, "host_gpu busy: %u permille (%s)\n", + busy, busy_valid ? "reported" : "none"); seq_printf(s, "host_gpu: active %u request_ns %llu sequence %llu\n", active, updated, sequence); } @@ -1354,6 +1455,115 @@ static const struct platform_profile_ops apple_clpc_profile_ops = { .profile_set = apple_clpc_profile_set, }; +/* + * Fills @hw->gpu_busy from a DT matrix: APPLE_CLPC_RAILS rows of + * APPLE_CLPC_LEVELS states, each bounded by the compatible table's rail + * maximum (and the 4-bit PMC state field). + */ +static int apple_clpc_dt_map(struct apple_clpc_hw *hw, const u32 *cells, int n) +{ + u8 states[APPLE_CLPC_RAILS][APPLE_CLPC_LEVELS]; + unsigned int rail, level; + + if (n != APPLE_CLPC_RAILS * APPLE_CLPC_LEVELS) + return -EINVAL; + for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) { + u32 top = max(hw->map[rail][APPLE_CLPC_LEVELS - 1], + hw->gpu[rail]); + + for (level = 0; level < APPLE_CLPC_LEVELS; level++) { + u32 state = cells[rail * APPLE_CLPC_LEVELS + level]; + + if (state > top || state > 15) + return -EINVAL; + states[rail][level] = state; + } + } + memcpy(hw->gpu_busy, states, sizeof(states)); + return 0; +} + +/* The busy shares from which reported GPU work gets the 2nd, 3rd and top column. */ +static int apple_clpc_dt_busy(struct apple_clpc_hw *hw, const u32 *cells, int n) +{ + if (n != 3 || cells[0] > cells[1] || cells[1] > cells[2] || cells[2] > 1000) + return -EINVAL; + hw->gpu_busy_mid = cells[0]; + hw->gpu_busy_high = cells[1]; + hw->gpu_busy_top = cells[2]; + return 0; +} + +/* + * Applies parsed DT GPU busy-share cells onto a copy of @soc. Any error in + * either property warns and leaves @soc unchanged so a malformed optional + * ladder never aborts CLPC probe. + */ +static bool apple_clpc_dt_apply(struct device *dev, + const struct apple_clpc_hw *soc, + struct apple_clpc_hw *out, + const u32 *states, int n_states, + const u32 *busy, int n_busy) +{ + int err; + + *out = *soc; + err = n_states < 0 ? n_states : apple_clpc_dt_map(out, states, n_states); + if (!err) + err = n_busy < 0 ? n_busy : apple_clpc_dt_busy(out, busy, n_busy); + if (err) { + dev_warn(dev, + "ignoring invalid GPU busy-share states in the device tree (%d)\n", + err); + *out = *soc; + return false; + } + return true; +} + +/* Reads up to @max cells of @name; returns how many, or an error. */ +static int apple_clpc_dt_cells(struct device_node *np, const char *name, + u32 *cells, int max) +{ + int n = of_property_count_u32_elems(np, name); + + if (n < 0) + return n; + if (n > max) + return -EOVERFLOW; + return of_property_read_u32_array(np, name, cells, n) ?: n; +} + +/* + * The compatible's table, with the GPU busy-share memory states the node + * gives (apple,pmc.yaml). Without those properties, or if they are malformed, + * the compatible's own table applies unchanged. + */ +static const struct apple_clpc_hw *apple_clpc_dt_hw(struct device *dev, + const struct apple_clpc_hw *soc) +{ + u32 states[APPLE_CLPC_RAILS * APPLE_CLPC_LEVELS]; + u32 busy[3]; + struct device_node *np = dev->of_node; + struct apple_clpc_hw copy, *hw; + int n_states, n_busy; + + if (!of_property_present(np, "apple,gpu-busy-memory-states") && + !of_property_present(np, "apple,gpu-busy-permille")) + return soc; + n_states = apple_clpc_dt_cells(np, "apple,gpu-busy-memory-states", + states, ARRAY_SIZE(states)); + n_busy = apple_clpc_dt_cells(np, "apple,gpu-busy-permille", + busy, ARRAY_SIZE(busy)); + if (!apple_clpc_dt_apply(dev, soc, ©, states, n_states, + busy, n_busy)) + return soc; + hw = devm_kmemdup(dev, ©, sizeof(copy), GFP_KERNEL); + if (!hw) + return ERR_PTR(-ENOMEM); + return hw; +} + static int apple_clpc_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; @@ -1368,7 +1578,9 @@ static int apple_clpc_probe(struct platform_device *pdev) clpc->dev = dev; clpc->pmc = dev->parent; - clpc->hw = of_device_get_match_data(dev); + clpc->hw = apple_clpc_dt_hw(dev, of_device_get_match_data(dev)); + if (IS_ERR(clpc->hw)) + return PTR_ERR(clpc->hw); /* T6040 firmware keeps GFX powered for its whole lifetime. A separate * host publication/idle input, not that supplier state, drives demand; * the T8132 and M5 (T8142) GPU drivers report through the same input. diff --git a/include/linux/soc/apple/clpc.h b/include/linux/soc/apple/clpc.h index 0a4c4f439ac56..5f83b2aedc609 100644 --- a/include/linux/soc/apple/clpc.h +++ b/include/linux/soc/apple/clpc.h @@ -12,6 +12,7 @@ struct apple_clpc_ane; #if IS_REACHABLE(CONFIG_APPLE_CLPC) int apple_clpc_gpu_get(struct device *dev, struct apple_clpc_gpu **out); void apple_clpc_gpu_set_active(struct apple_clpc_gpu *gpu, bool active); +void apple_clpc_gpu_set_busy(struct apple_clpc_gpu *gpu, unsigned int permille); void apple_clpc_gpu_put(struct apple_clpc_gpu *gpu); /* Optional, single-publisher input: success with NULL means no provider. */ int apple_clpc_ane_get(struct device *dev, struct apple_clpc_ane **out); @@ -24,6 +25,7 @@ static inline int apple_clpc_gpu_get(struct device *dev, struct apple_clpc_gpu * return device_property_present(dev, "apple,clpc") ? -ENODEV : 0; } static inline void apple_clpc_gpu_set_active(struct apple_clpc_gpu *gpu, bool active) {} +static inline void apple_clpc_gpu_set_busy(struct apple_clpc_gpu *gpu, unsigned int permille) {} static inline void apple_clpc_gpu_put(struct apple_clpc_gpu *gpu) {} /* ANE remains usable when the optional floor provider is not reachable. */ diff --git a/tools/asahi/clpc-gpu-demand-tests.py b/tools/asahi/clpc-gpu-demand-tests.py index a4db3f838738e..278794f1fc3b9 100644 --- a/tools/asahi/clpc-gpu-demand-tests.py +++ b/tools/asahi/clpc-gpu-demand-tests.py @@ -20,17 +20,217 @@ def item(text, signature): return text[start:end] +def test_g17_busy_share(): + """Compile and run production g17 BusyShare (power.rs) with negative controls. + + Returns the (t_ms, permille) reports emitted for the long-command-beside- + light-compositor scenario, and the (t_ms, permille or -1 for no report) + samples of a new burst after idle, so the C CLPC harness drives + apple_clpc_sample() with them end-to-end. + """ + power = (ROOT / 'drivers/gpu/drm/asahi/g17/power.rs').read_text() + consts = '\n'.join( + re.search(r'^pub\(super\) const ' + name + r': u64 = [^\n]+$', power, re.M).group(0) + for name in ('BUSY_WINDOW_NS', 'BUSY_WINDOW_MAX_NS', 'BUSY_LONG_COMMAND_NS')) + struct_def = item(power, 'pub(super) struct BusyShare {') + impl_def = item(power, 'impl BusyShare {') + prod = f'{consts}\n{struct_def}\n{impl_def}\n' + + harness = r''' +#![allow(dead_code)] +mod usage { + pub const NUM_ENGINES: usize = 3; +} +mod power { +''' + prod + r''' +} +use power::{BusyShare, BUSY_LONG_COMMAND_NS}; + +fn main() { + const MS: u64 = 1_000_000; + // Scenario 1: long 500 ms compute job running next to a light compositor. + // Light compositor runs 10 ms per 200 ms window (50 permille -> level 0). + let mut s = BusyShare::new(); + assert_eq!(s.sample(1000 * MS, [0, 0, 0], [0, 0, 0]), None); + let r0 = s.sample(1200 * MS, [2 * MS, 10 * MS, 0], [0, 0, 0]).unwrap(); + assert_eq!(r0, 50); + assert!(s.below_top()); + // Compute job (500 ms) starts at t=1650 ms (after CLPC has dropped to level 0 + // following its 400 ms down-step hold); compositor submits at t=1810 ms (210 ms + // after a 1600 ms window start). Must immediately report 1000 while still running. + let r1 = s.sample(1400 * MS, [4 * MS, 20 * MS, 0], [0, 0, 0]).unwrap(); + assert_eq!(r1, 50); + let r2 = s.sample(1600 * MS, [6 * MS, 30 * MS, 0], [0, 0, 0]).unwrap(); + assert_eq!(r2, 50); + let r3 = s.sample(1810 * MS, [8 * MS, 40 * MS, 0], [0, 0, 1650 * MS]).unwrap(); + assert_eq!(r3, 1000, "long in-flight compute next to light compositor must lift to 1000"); + assert!(!s.below_top()); + // Still running across the next 200 ms window at t=2010 ms: holds 1000. + let r4 = s.sample(2010 * MS, [10 * MS, 50 * MS, 0], [0, 0, 1650 * MS]).unwrap(); + assert_eq!(r4, 1000); + // Job retires at t=2150 ms (+500 ms retired). At t=2210 ms only the 140 ms in + // [2010, 2150] counts (700 permille), proving zero double-counting. + let r5 = s.sample(2210 * MS, [12 * MS, 60 * MS, 500 * MS], [0, 0, 0]).unwrap(); + assert_eq!(r5, 700, "post-retirement window must not double-count prior in-flight time"); + // Next window returns cleanly to compositor's 50 permille. + let r6 = s.sample(2410 * MS, [14 * MS, 70 * MS, 500 * MS], [0, 0, 0]).unwrap(); + assert_eq!(r6, 50); + + // Scenario 2: long command starting late in a window lifts mid-window at 50 ms. + let mut late = BusyShare::new(); + assert_eq!(late.sample(1000 * MS, [0, 0, 0], [0, 0, 0]), None); + assert_eq!(late.sample(1200 * MS, [0, 10 * MS, 0], [0, 0, 0]), Some(50)); + assert_eq!(late.sample(1410 * MS, [0, 20 * MS, 0], [0, 0, 1390 * MS]), Some(95)); + assert!(late.below_top()); + assert_eq!(late.sample(1440 * MS, [0, 22 * MS, 0], [0, 0, 1390 * MS]), Some(1000)); + assert!(!late.below_top()); + assert_eq!(late.sample(1460 * MS, [0, 23 * MS, 0], [0, 0, 1390 * MS]), None); + assert_eq!(late.sample(1610 * MS, [0, 30 * MS, 100 * MS], [0, 0, 0]), Some(400)); + + // Scenario 3: solo long command driven by recheck_delay_for reaches 1000 and stops. + let mut solo = BusyShare::new(); + assert_eq!(solo.sample(1000 * MS, [0, 0, 0], [0, 0, 0]), None); + assert_eq!(solo.sample(1200 * MS, [0, 10 * MS, 0], [0, 0, 0]), Some(50)); + let mut t = 1222 * MS; + let start = 1210 * MS; + let mut lifted = false; + let mut rechecks = 0; + for _ in 0..8 { + if let Some(p) = solo.sample(t, [0, 10 * MS, 0], [0, 0, start]) { + assert_eq!(p, 1000); + lifted = true; + break; + } + let delay = BusyShare::recheck_delay_for(t, start).unwrap(); + assert!(delay <= BUSY_LONG_COMMAND_NS); + t += delay; + rechecks += 1; + } + // One wake-up at the long-command age, not a train of short ones. + assert!(lifted && !solo.below_top() && t == start + BUSY_LONG_COMMAND_NS && rechecks == 1); + + // Scenario 4: short straddling command (no double count), multi-engine max, >2 s gaps. + let mut misc = BusyShare::new(); + assert_eq!(misc.sample(1000 * MS, [0, 0, 0], [0, 0, 0]), None); + assert_eq!(misc.sample(1200 * MS, [0, 0, 0], [0, 0, 1170 * MS]), Some(150)); + assert_eq!(misc.sample(1400 * MS, [0, 0, 40 * MS], [0, 0, 0]), Some(50)); + assert_eq!(misc.sample(1600 * MS, [0, 120 * MS, 150 * MS], [0, 0, 0]), Some(600)); + assert_eq!(misc.sample(5000 * MS, [0, 120 * MS, 150 * MS], [0, 0, 5000 * MS]), None); + assert_eq!(misc.sample(8000 * MS, [0, 120 * MS, 150 * MS], [0, 0, 5000 * MS]), Some(1000)); + + // Scenario 5: steady 600 permille work until 1400 ms, idle (CLPC cleared), then a + // new burst at 2000 ms. Closing [1300, 2000] would report a diluted 85 permille + // (60 ms in 700 ms); the first submission re-baselines instead and nothing is + // reported until a fresh 200 ms window of the new burst completes. + let mut burst = BusyShare::new(); + assert_eq!(burst.sample(900 * MS, [0, 0, 0], [0, 0, 0]), None); + let mut idle_events = Vec::new(); + for (t, frag) in [(1100, 120), (1300, 240)] { + let p = burst.sample(t * MS, [0, frag * MS, 0], [0, 0, 0]); + assert_eq!(p, Some(600)); + idle_events.push((t, p)); + } + burst.clear_active(); + assert!(!burst.below_top()); + for (t, frag) in [(2000, 300), (2048, 328), (2100, 360), (2148, 388), (2196, 417), (2200, 420)] { + let p = burst.sample(t * MS, [0, frag * MS, 0], [0, 0, 0]); + assert_eq!(p, if t < 2200 { None } else { Some(600) }, + "new burst after idle must not report a window diluted by the idle gap"); + idle_events.push((t, p)); + } + assert!(burst.below_top()); + + println!("EVENTS:1200={r0},1400={r1},1600={r2},1810={r3},2010={r4},2210={r5},2410={r6}"); + let idle: Vec = + idle_events.iter().map(|(t, p)| format!("{t}={}", p.map_or(-1, i64::from))).collect(); + println!("IDLE:{}", idle.join(",")); +} +''' + rustc = os.environ.get('RUSTC', 'rustc') + events = idle_events = None + with tempfile.TemporaryDirectory(prefix='asahi-g17-busy-') as tmp: + root = Path(tmp) + for name, text in [ + ('fixed', harness), + ('g17-ignore-in-flight', + harness.replace('let long_in_flight = Self::is_long_in_flight(now_ns, oldest_in_flight);', + 'let _ = oldest_in_flight; let oldest_in_flight = [0; crate::usage::NUM_ENGINES];\n' + ' let long_in_flight = Self::is_long_in_flight(now_ns, oldest_in_flight);')), + ('g17-double-count-in-flight', + harness.replace('let busy = delta.saturating_add(age).saturating_sub(prev_age);', + 'let _ = prev_age; let busy = delta.saturating_add(age);')), + ('g17-no-early-lift', + harness.replace('if self.below_top && long_in_flight {', + 'if false && self.below_top && long_in_flight {')), + ('g17-long-idle-reports', + harness.replace('if elapsed > BUSY_WINDOW_MAX_NS && !long_in_flight {', + 'if false && elapsed > BUSY_WINDOW_MAX_NS && !long_in_flight {')), + ('g17-idle-keeps-window', + harness.replace('self.start_ns = None;\n self.in_flight_ns = [0; crate::usage::NUM_ENGINES];\n' + ' self.below_top = false;', + 'self.below_top = false;')), + ]: + assert name == 'fixed' or text != harness, 'stale mutation: ' + name + src = root / (name + '.rs') + src.write_text(text) + binary = src.with_suffix('') + subprocess.run([rustc, '--edition=2021', '-Dwarnings', str(src), '-o', str(binary)], + check=True) + run = subprocess.run([str(binary)], capture_output=True, text=True) + if name == 'fixed': + assert run.returncode == 0, run.stderr + lines = run.stdout.strip().splitlines() + assert len(lines) == 2 and lines[0].startswith('EVENTS:') \ + and lines[1].startswith('IDLE:'), lines + events = [tuple(int(x) for x in pair.split('=')) + for pair in lines[0].removeprefix('EVENTS:').split(',')] + idle_events = [tuple(int(x) for x in pair.split('=')) + for pair in lines[1].removeprefix('IDLE:').split(',')] + print('PASS: g17 BusyShare (in-flight long command, early lift, solo recheck, ' + 'non-double-counting, new burst after idle)') + else: + assert run.returncode != 0, name + print('PASS negative control:', name) + return events, idle_events + + def main(): + g17_events, g17_idle_events = test_g17_busy_share() source = (ROOT / 'drivers/soc/apple/clpc.c').read_text() header = (ROOT / 'include/linux/soc/apple/pmc.h').read_text() rail_shift = re.search(r'^#define APPLE_PMC_RAIL_SHIFT\(rail\).*$', header, re.M).group(0) dense_samples = re.search(r'^#define APPLE_CLPC_GPU_DENSE_SAMPLES\s.*$', source, re.M).group(0) reasons = '\n'.join(re.findall(r'^#define APPLE_CLPC_REASON_\w+\s.*$', source, re.M)) + gpu_down = re.search(r'^#define APPLE_CLPC_GPU_DOWN_MS\s.*$', source, re.M).group(0) types = '\n'.join(item(source, s) + ';' for s in [ 'struct apple_clpc_hw {', 'struct apple_clpc_vote {']) tables = '\n'.join(item(source, 'static const struct apple_clpc_hw ' + n + ' =') + ';' for n in ['apple_clpc_hw_t8132', 'apple_clpc_hw_t8140', - 'apple_clpc_hw_t6040', 'apple_clpc_hw_t6041']) + 'apple_clpc_hw_t6040', 'apple_clpc_hw_t6041', + 'apple_clpc_hw_t6050']) + # When t6041.dtsi supplies the GPU busy-share properties, parse and test them directly; + # otherwise exercise the DT parsers and ladder against the reference values. + dts = (ROOT / 'arch/arm64/boot/dts/apple/t6041.dtsi').read_text() + clpc_node = item(dts, '&clpc {') + + def cells(name): + match = re.search(r'\s' + re.escape(name) + r'\s*=\s*([^;]*);', clpc_node) + if not match: + return None + return [int(x, 0) for x in re.findall(r'0x[0-9a-fA-F]+|\d+', match.group(1))] + + dt_states = cells('apple,gpu-busy-memory-states') + dt_busy = cells('apple,gpu-busy-permille') + assert (dt_states is None) == (dt_busy is None) + gpu_states = dt_states or [1, 2, 4, 5, 0, 0, 0, 3] + gpu_busy = dt_busy or [160, 500, 800] + t6041_dt = ( + 'static const u32 t6041_gpu_states[] = {' + ', '.join(str(x) for x in gpu_states) + '};\n' + 'static const u32 t6041_gpu_busy[] = {' + ', '.join(str(x) for x in gpu_busy) + '};\n' + 'static const struct { unsigned long ms; unsigned int permille; } g17_long_events[] = {' + + ', '.join(f'{{{t}, {p}}}' for t, p in g17_events) + '};\n' + 'static const struct { unsigned long ms; int permille; } g17_idle_events[] = {' + + ', '.join(f'{{{t}, {p}}}' for t, p in g17_idle_events) + '};\n') methods = '\n'.join(item(source, s) for s in [ 'static unsigned int apple_clpc_vote(', 'static u32 apple_clpc_floor(', 'static bool apple_clpc_gpu_streaming(', @@ -38,6 +238,10 @@ def main(): 'static bool apple_clpc_gpu_dense(', 'static bool apple_clpc_gpu_limited(', 'static void apple_clpc_gpu_floor_count(', + 'static unsigned int apple_clpc_gpu_level(', + 'static int apple_clpc_dt_map(', + 'static int apple_clpc_dt_busy(', + 'static bool apple_clpc_dt_apply(', 'static bool apple_clpc_gpu_input_demand(', 'static bool apple_clpc_ane_input_demand(', 'static void apple_clpc_ane_cluster(', @@ -47,16 +251,19 @@ def main(): #include #include #include +#include #include typedef uint8_t u8; typedef uint32_t u32; typedef uint64_t u64; +struct device; #define APPLE_CLPC_LEVELS 4 #define APPLE_CLPC_HOLD_MS 32 #define APPLE_CLPC_SAMPLE_MS 4 #define APPLE_CLPC_GPU_BACKOFF_MS 100 #define HZ 1000 #define max(a,b) ((a) > (b) ? (a) : (b)) +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) #define GENMASK(h,l) (((1u << ((h)-(l)+1))-1) << (l)) #define BIT(n) (1u << (n)) #define APPLE_PMC_RAIL_SHIFT(r) ((r)*8) @@ -64,11 +271,15 @@ def main(): #define time_after(a,b) ((long)((a)-(b)) > 0) #define time_before(a,b) ((long)((a)-(b)) < 0) #define msecs_to_jiffies(ms) (ms) -static int warned; +static int warned, dt_warned; #define dev_warn_once(d, ...) ((void)(d), warned++) +#define dev_warn(d, ...) ((void)(d), dt_warned++) enum apple_clpc_rail { APPLE_CLPC_DCS, APPLE_CLPC_SOC, APPLE_CLPC_RAILS }; ''' + types + r''' -struct apple_clpc_gpu { bool active; u64 sequence; }; +struct apple_clpc_gpu { + int lock; bool active; u64 sequence; + unsigned int busy; bool busy_valid; unsigned int level; unsigned long level_since; +}; struct apple_clpc_ane { int lock; bool active, pending; }; #define spin_lock_irqsave(l, f) ((void)(l), (f) = 0) #define spin_unlock_irqrestore(l, f) ((void)(l), (void)(f)) @@ -135,7 +346,83 @@ def main(): static void apple_clpc_queue(struct apple_clpc *c, bool idle) { (void)c; queued_idle=idle; } #define READ_ONCE(x) (x) static void apple_clpc_profile_limit(struct apple_clpc *c) { (void)c; } -''' + dense_samples + '\n' + reasons + '\n' + tables + '\n' + methods + r''' +''' + dense_samples + '\n' + reasons + '\n' + gpu_down + '\n' + tables + '\n' + methods + '\n' + t6041_dt + r''' +// Apply DT GPU busy-share properties through the driver's parsers: the CPU map +// stays untouched, valid GPU states/thresholds populate the ladder, states +// above the compatible table's rail maximum are rejected, and any malformed +// optional ladder warns and falls back to the compatible's static table. +static struct apple_clpc_hw t6041_dt_hw; +static void t6041_from_dt(void) { + static const u8 cpu[2][4] = {{5, 5, 5, 5}, {3, 3, 3, 3}}, gpu[2][4] = {{1, 2, 4, 5}, {0, 0, 0, 3}}; + struct apple_clpc_hw out, bad = apple_clpc_hw_t6040; + u32 over_4bit[8] = {1, 2, 4, 5, 0, 0, 0, 16}; + u32 t6041_over_dcs[8] = {1, 2, 4, 7, 0, 0, 0, 3}; + u32 t6041_over_dcs6[8] = {1, 2, 4, 6, 0, 0, 0, 3}; + u32 t6041_over_soc[8] = {1, 2, 4, 5, 0, 0, 0, 4}; + u32 t6050_ok[8] = {1, 2, 4, 6, 0, 0, 0, 2}; + u32 t6050_over_dcs[8] = {1, 2, 4, 7, 0, 0, 0, 2}; + u32 t6050_over_soc[8] = {1, 2, 4, 6, 0, 0, 0, 3}; + u32 busy[3] = {500, 160, 800}; + + dt_warned = 0; + assert(apple_clpc_dt_apply(NULL, &apple_clpc_hw_t6041, &t6041_dt_hw, + t6041_gpu_states, ARRAY_SIZE(t6041_gpu_states), + t6041_gpu_busy, ARRAY_SIZE(t6041_gpu_busy))); + assert(dt_warned == 0); + for (int r = 0; r < 2; r++) + for (int l = 0; l < 4; l++) + assert(t6041_dt_hw.map[r][l] == cpu[r][l] && t6041_dt_hw.gpu_busy[r][l] == gpu[r][l]); + + // Direct parser bounds: 4-bit max, rail-specific compatible max, counts, thresholds. + assert(apple_clpc_dt_map(&bad, over_4bit, 8) == -EINVAL); + assert(apple_clpc_dt_map(&bad, over_4bit, 7) == -EINVAL); + assert(apple_clpc_dt_map(&bad, t6041_gpu_states, 8) == -EINVAL); // fabric 3 > T6040 max 2 + bad = apple_clpc_hw_t6041; + assert(apple_clpc_dt_map(&bad, t6041_over_dcs, 8) == -EINVAL); // DCS 7 > T6041 max 5 + assert(apple_clpc_dt_map(&bad, t6041_over_dcs6, 8) == -EINVAL); // DCS 6 > T6041 max 5 + assert(apple_clpc_dt_map(&bad, t6041_over_soc, 8) == -EINVAL); // fabric 4 > T6041 max 3 + // T6050 rail max uses max(map[rail][top], gpu[rail]): DCS 6 from gpu[DCS], fabric 2. + assert(apple_clpc_dt_apply(NULL, &apple_clpc_hw_t6050, &out, + t6050_ok, 8, t6041_gpu_busy, 3)); + assert(dt_warned == 0 && out.gpu_busy[APPLE_CLPC_DCS][3] == 6); + assert(!apple_clpc_dt_apply(NULL, &apple_clpc_hw_t6050, &out, + t6050_over_dcs, 8, t6041_gpu_busy, 3)); + assert(dt_warned == 1 && !memcmp(&out, &apple_clpc_hw_t6050, sizeof(out))); + assert(!apple_clpc_dt_apply(NULL, &apple_clpc_hw_t6050, &out, + t6050_over_soc, 8, t6041_gpu_busy, 3)); + assert(dt_warned == 2 && !memcmp(&out, &apple_clpc_hw_t6050, sizeof(out))); + + // Malformed optional DT properties warn and fall back to the static soc table unchanged. + assert(!apple_clpc_dt_apply(NULL, &apple_clpc_hw_t6041, &out, + t6041_over_dcs, 8, t6041_gpu_busy, 3)); + assert(dt_warned == 3 && !memcmp(&out, &apple_clpc_hw_t6041, sizeof(out))); + assert(!apple_clpc_dt_apply(NULL, &apple_clpc_hw_t6041, &out, + t6041_over_soc, 8, t6041_gpu_busy, 3)); + assert(dt_warned == 4 && !memcmp(&out, &apple_clpc_hw_t6041, sizeof(out))); + // Valid states paired with bad permille or missing partner must not leave partial ladder. + assert(!apple_clpc_dt_apply(NULL, &apple_clpc_hw_t6041, &out, + t6041_gpu_states, 8, busy, 3)); + assert(dt_warned == 5 && !memcmp(&out, &apple_clpc_hw_t6041, sizeof(out))); + assert(!apple_clpc_dt_apply(NULL, &apple_clpc_hw_t6041, &out, + t6041_gpu_states, 8, NULL, -EINVAL)); + assert(dt_warned == 6 && !memcmp(&out, &apple_clpc_hw_t6041, sizeof(out))); + assert(!apple_clpc_dt_apply(NULL, &apple_clpc_hw_t6041, &out, + NULL, -EINVAL, t6041_gpu_busy, 3)); + assert(dt_warned == 7 && !memcmp(&out, &apple_clpc_hw_t6041, sizeof(out))); + // Falling back keeps the compatible's full GPU floor even when a low busy share arrives. + { + struct apple_clpc_gpu g = {.active = true, .busy_valid = true, .busy = 100}; + struct apple_clpc c = {.hw = &out, .agent = 1, .mask = 3, .gpu = &g}; + read_error = vote_error = 0; pmgr_status = 0xf0; pmp_floor = 0; jiffies = 2900; published = ~0u; + apple_clpc_sample(&c); + assert(published == 0x35 && c.last_reason == 2); + } + + assert(apple_clpc_dt_busy(&bad, busy, 3) == -EINVAL); + busy[0] = 160; busy[1] = 500; busy[2] = 1001; + assert(apple_clpc_dt_busy(&bad, busy, 3) == -EINVAL); + assert(apple_clpc_dt_busy(&bad, busy, 2) == -EINVAL); +} // T8140 ANE work holds its DRAM and fabric states while it runs, a request // shorter than one sample is still seen once, and the hold then expires. static void check_t8140_ane(void) { @@ -172,6 +459,145 @@ def main(): ane.active=true; jiffies=2040; apple_clpc_sample(&c); assert(qos_adds==1 && qos_min==3756000); } +// DT GPU busy-share ladder: DCS 1, 2, 4 or 5 and fabric 0, 0, 0 or 3, split at +// 160, 500 and 800 permille. A higher level applies at once, a lower one at the +// first sample at least 400 ms after the last one that asked for the current +// level or more. A table without a non-zero top DCS state falls back to @map. +static void check_t6041_busy(void) { + struct apple_clpc_gpu gpu={0}; + struct apple_clpc c={.hw=&t6041_dt_hw,.agent=1,.mask=3,.gpu=&gpu}; + struct apple_clpc_hw no_top = t6041_dt_hw; + assert(c.hw->gpu_busy_mid==160 && c.hw->gpu_busy_high==500 && c.hw->gpu_busy_top==800); + read_error=vote_error=0; pmgr_status=0xf0; pmp_floor=0; published=~0u; + // No share reported: the top of the ladder, as before the busy share. + gpu.active=true; jiffies=3000; apple_clpc_sample(&c); + assert(published==0x35 && c.last_reason==2 && gpu.level==3); + gpu.active=false; jiffies=3100; apple_clpc_sample(&c); assert(published==0); + // Below gpu_busy_mid: the lowest GPU state (after a long idle, at once). + gpu.active=true; gpu.busy_valid=true; gpu.busy=100; jiffies=3500; + apple_clpc_sample(&c); assert(published==0x01 && c.last_reason==2 && gpu.level==0); + // Between the thresholds, going up: each level applies at the next sample. + gpu.busy=160; jiffies=3504; apple_clpc_sample(&c); assert(published==0x02 && gpu.level==1); + gpu.busy=499; jiffies=3508; apple_clpc_sample(&c); assert(published==0x02 && gpu.level==1); + gpu.busy=500; jiffies=3512; apple_clpc_sample(&c); assert(published==0x04 && gpu.level==2); + gpu.busy=799; jiffies=3516; apple_clpc_sample(&c); assert(published==0x04 && gpu.level==2); + gpu.busy=800; jiffies=3520; apple_clpc_sample(&c); assert(published==0x35 && gpu.level==3); + // Going down waits 400 ms from the last sample at the top. + gpu.busy=100; + for (jiffies=3524; jiffies<3920; jiffies+=4) { + apple_clpc_sample(&c); assert(published==0x35 && gpu.level==3); + } + jiffies=3919; apple_clpc_sample(&c); assert(published==0x35 && gpu.level==3); + // At 400 ms the DCS drops at once; the fabric state keeps HOLD_MS. + jiffies=3920; apple_clpc_sample(&c); assert(published==0x31 && gpu.level==0); + jiffies=3952; apple_clpc_sample(&c); assert(published==0x01 && c.last_reason==2); + // A sample that asks for the current level again restarts the 400 ms. + gpu.busy=600; jiffies=4000; apple_clpc_sample(&c); assert(published==0x04 && gpu.level==2); + gpu.busy=100; jiffies=4200; apple_clpc_sample(&c); assert(gpu.level==2); + gpu.busy=550; jiffies=4300; apple_clpc_sample(&c); assert(gpu.level==2); + gpu.busy=100; jiffies=4699; apple_clpc_sample(&c); assert(published==0x04 && gpu.level==2); + jiffies=4700; apple_clpc_sample(&c); assert(published==0x01 && gpu.level==0); + gpu.active=false; jiffies=4800; apple_clpc_sample(&c); assert(published==0 && queued_idle); + // Without a non-zero top DCS state, even a low reported share keeps the map top. + no_top.gpu_busy[APPLE_CLPC_DCS][APPLE_CLPC_LEVELS - 1] = 0; + c.hw = &no_top; gpu.active=true; gpu.busy_valid=true; gpu.busy=100; jiffies=4900; + apple_clpc_sample(&c); assert(published==0x35 && c.last_reason==2); + // Same for a static table with no DT properties at all. + c.hw = &apple_clpc_hw_t6041; jiffies=4904; + apple_clpc_sample(&c); assert(published==0x35 && c.last_reason==2); + gpu.active=false; jiffies=5000; apple_clpc_sample(&c); assert(published==0 && queued_idle); +} + +// End-to-end: feed g17 BusyShare's actual reports for a 500 ms compute job +// running beside a light compositor into CLPC's T6041 ladder. CLPC drops to +// DCS 1 / fabric 0 during light compositing, lifts IMMEDIATELY to DCS 5 / +// fabric 3 (0x35) at t=1810 ms while the compute job is still in flight, holds +// 0x35 while it runs, and drops back to 0x01 after it finishes + 400 ms hold. +static void check_t6041_long_in_flight(void) { + struct apple_clpc_gpu gpu = {0}; + struct apple_clpc c = {.hw = &t6041_dt_hw, .agent = 1, .mask = 3, .gpu = &gpu}; + read_error = vote_error = 0; pmgr_status = 0xf0; pmp_floor = 0; published = ~0u; + gpu.active = true; + // Initial burst starts at top (no share yet). + jiffies = 1000; apple_clpc_sample(&c); + assert(published == 0x35 && gpu.level == 3); + // Light compositor windows (1200, 1400, 1600 ms -> 50 permille) drop to DCS 1 / fabric 0. + assert(ARRAY_SIZE(g17_long_events) == 7); + for (size_t i = 0; i < 3; i++) { + gpu.busy = g17_long_events[i].permille; gpu.busy_valid = true; + jiffies = g17_long_events[i].ms; apple_clpc_sample(&c); + } + // After 400 ms down-step hold + 32 ms fabric hold, CLPC is at DCS 1 / fabric 0. + jiffies = 1640; apple_clpc_sample(&c); + assert(published == 0x01 && gpu.level == 0); + // At t=1810 ms (160 ms into the 500 ms compute job, still in flight!), BusyShare + // reports 1000 permille and CLPC lifts IMMEDIATELY to DCS 5 / fabric 3. + gpu.busy = g17_long_events[3].permille; gpu.busy_valid = true; + jiffies = g17_long_events[3].ms; apple_clpc_sample(&c); + assert(published == 0x35 && gpu.level == 3); + // Still running at t=2010 ms: stays at DCS 5 / fabric 3. + gpu.busy = g17_long_events[4].permille; gpu.busy_valid = true; + jiffies = g17_long_events[4].ms; apple_clpc_sample(&c); + assert(published == 0x35 && gpu.level == 3); + // Retires at t=2150 ms; window at t=2210 ms reports exact 700 (still in 400 ms hold). + gpu.busy = g17_long_events[5].permille; gpu.busy_valid = true; + for (jiffies = g17_long_events[5].ms; jiffies < g17_long_events[6].ms; jiffies += 4) { + apple_clpc_sample(&c); + assert(published == 0x35 && gpu.level == 3); + } + // Next light window at t=2410 ms (400 ms after last top request at 2010 ms): + // DCS drops immediately to 1, fabric keeps HOLD_MS (32 ms) from the 2406 ms sample. + gpu.busy = g17_long_events[6].permille; gpu.busy_valid = true; + jiffies = g17_long_events[6].ms; apple_clpc_sample(&c); + assert(published == 0x31 && gpu.level == 0); + jiffies = g17_long_events[6].ms + APPLE_CLPC_HOLD_MS; apple_clpc_sample(&c); + assert(published == 0x01 && gpu.level == 0); +} + +// End-to-end: g17 BusyShare's samples (-1: no report) for steady 600 permille +// work, an idle gap in which the GPU clears its activity (apple_clpc_gpu_set_active +// false also clears busy_valid), and a new burst 600 ms later. The new burst starts +// at the top (0x35) and stays there until a fresh 200 ms window reports; the +// diluted 85 permille a stale window would report drops it to 0x01 at once. +static void check_t6041_idle_burst(void) { + struct apple_clpc_gpu gpu = {0}; + struct apple_clpc c = {.hw = &t6041_dt_hw, .agent = 1, .mask = 3, .gpu = &gpu}; + size_t i = 0, n = ARRAY_SIZE(g17_idle_events); + read_error = vote_error = 0; pmgr_status = 0xf0; pmp_floor = 0; published = ~0u; + assert(n == 8 && g17_idle_events[0].ms == 1100 && g17_idle_events[2].ms == 2000); + gpu.active = true; jiffies = 900; apple_clpc_sample(&c); + assert(published == 0x35 && gpu.level == 3); + for (; i < 2; i++) { + assert(g17_idle_events[i].permille == 600); + gpu.busy = g17_idle_events[i].permille; gpu.busy_valid = true; + jiffies = g17_idle_events[i].ms; apple_clpc_sample(&c); + } + assert(gpu.level == 2); + // Idle: the GPU clears its activity and CLPC forgets the share. + gpu.active = false; gpu.busy_valid = false; + for (jiffies = 1416; jiffies < 2000; jiffies += 4) + apple_clpc_sample(&c); + assert(published == 0); + gpu.active = true; + for (jiffies = 2000; jiffies <= 2200; jiffies += 4) { + if (i < n && g17_idle_events[i].ms == jiffies) { + if (g17_idle_events[i].permille >= 0) { + gpu.busy = g17_idle_events[i].permille; gpu.busy_valid = true; + } + i++; + } + assert(gpu.busy_valid == (jiffies >= 2200)); + apple_clpc_sample(&c); + assert(published == 0x35 && gpu.level == 3); + } + assert(i == n); + // The stale window's diluted share would have dropped the new burst at once. + gpu.active = false; gpu.busy_valid = false; jiffies = 2400; apple_clpc_sample(&c); + gpu.active = true; gpu.busy = 85; gpu.busy_valid = true; jiffies = 3000; + apple_clpc_sample(&c); assert(published == 0x01 && gpu.level == 0); + gpu.active = false; jiffies = 3100; apple_clpc_sample(&c); assert(published == 0); +} + // T8132's G16 firmware keeps graphics powered while the GPU idles: the // M5/F3 floor follows the work the GPU driver reports, as on T6040. static void check_t8132(void) { @@ -190,10 +616,10 @@ def main(): // T6041 (M4 Max) votes DCS 5 / fabric 3 for CPU and host GPU demand without a // streak, samples on time while idle, preserves T6041's DCS 5 / fabric 2 ANE // floor, and carries the 2808 MHz Low Power ceiling. -static void check_t6041(void) { +static void check_t6041(const struct apple_clpc_hw *hw) { struct apple_clpc_gpu gpu={0}; struct apple_clpc_ane ane={0}; - struct apple_clpc c={.hw=&apple_clpc_hw_t6041,.agent=1,.mask=3,.gpu=&gpu,.ane=&ane}; + struct apple_clpc c={.hw=hw,.agent=1,.mask=3,.gpu=&gpu,.ane=&ane}; c.ane_states[APPLE_CLPC_DCS]=c.hw->ane[APPLE_CLPC_DCS]; c.ane_states[APPLE_CLPC_SOC]=c.hw->ane[APPLE_CLPC_SOC]; assert(!c.hw->gpu_demand && c.hw->gpu_input && c.hw->sustain==0 && c.hw->idle_on_time); @@ -299,14 +725,19 @@ def main(): assert(published==0x12 && c.last_reason==1); c.clusters[0].request[0]=c.clusters[0].request[1]=0; jiffies=264; apple_clpc_sample(&c); assert(published==0); + t6041_from_dt(); + check_t6041_busy(); + check_t6041_long_in_flight(); + check_t6041_idle_burst(); check_t8132(); - check_t6041(); + check_t6041(&apple_clpc_hw_t6041); + check_t6041(&t6041_dt_hw); check_read_error(); check_t8140(); check_t8140_dense(); check_t8140_ane(); check_t6040_ane(); - puts("PASS: T6040, T6041 and T8132 host demand; T8140/T604x ANE, streaming, dense work, read errors and PMP backoff; idle release"); + puts("PASS: T6040, T6041 and T8132 host demand; DT GPU busy share and down-step hold; T8140/T604x ANE, streaming, dense work, read errors and PMP backoff; idle release"); } ''' code = code.replace('#define APPLE_PMC_RAIL_SHIFT(r) ((r)*8)', rail_shift) @@ -331,7 +762,22 @@ def main(): ('omit-pmp-backoff', code.replace('bool released = apple_clpc_gpu_limited(clpc, now);', 'bool released = (apple_clpc_gpu_limited(clpc, now), false);')), ('release-too-early', code.replace('msecs_to_jiffies(APPLE_CLPC_HOLD_MS)', '0')), + ('gpu-down-at-once', code.replace('msecs_to_jiffies(APPLE_CLPC_GPU_DOWN_MS)', '0')), + ('gpu-busy-ignored', code.replace('if (!gpu->busy_valid || gpu->busy >= hw->gpu_busy_top)', + 'if (true || gpu->busy >= hw->gpu_busy_top)')), + ('gpu-no-share-uses-table', code.replace('if (!gpu->busy_valid || gpu->busy >= hw->gpu_busy_top)', + 'if (gpu->busy >= hw->gpu_busy_top)')), + ('gpu-busy-without-dt', code.replace('bool has_busy = hw->gpu_busy[APPLE_CLPC_DCS][APPLE_CLPC_LEVELS - 1];', + 'bool has_busy = true;')), ('retain-at-idle', code.replace('vote->state = 0;', '')), + ('dt-state-unchecked', code.replace('if (state > top || state > 15)', 'if ((void)top, false)')), + ('dt-rail-bound-unchecked', code.replace('if (state > top || state > 15)', 'if ((void)top, state > 15)')), + ('dt-gpu-rail-max-ignored', code.replace('max(hw->map[rail][APPLE_CLPC_LEVELS - 1],\n\t\t\t hw->gpu[rail])', + 'hw->map[rail][APPLE_CLPC_LEVELS - 1]')), + ('dt-fallback-keeps-partial', code.replace('\t\t*out = *soc;\n\t\treturn false;', '\t\treturn false;')), + ('dt-fallback-silent', code.replace('dev_warn(dev,\n\t\t\t "ignoring invalid GPU busy-share states in the device tree (%d)\\n",\n\t\t\t err);', + '(void)dev; (void)err;')), + ('dt-busy-unordered', code.replace('cells[0] > cells[1] || ', '')), ]: # A mutation that no longer matches the driver tests nothing. assert name == 'fixed' or text != code, 'stale mutation: ' + name