From 54bad83f2aaa9a4c03ef84083bf67b1608d1f5b6 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Fri, 27 Nov 2026 10:19:28 -0500 Subject: [PATCH 1/3] soc: apple: clpc: add apple_clpc_gpu_clear_busy() Prepare to decouple clearing CLPC's cached GPU busy share from brief inactivity clears in apple_clpc_gpu_set_active(gpu, false). Export apple_clpc_gpu_clear_busy() so GPU drivers can explicitly forget their reported busy share after genuine idle, and call it from apple_clpc_gpu_put() on teardown. Signed-off-by: Erik Bourget --- drivers/soc/apple/clpc.c | 20 ++++++++++++++++++++ include/linux/soc/apple/clpc.h | 2 ++ 2 files changed, 22 insertions(+) diff --git a/drivers/soc/apple/clpc.c b/drivers/soc/apple/clpc.c index a04d546d1e3b6..b29e9b68fa08c 100644 --- a/drivers/soc/apple/clpc.c +++ b/drivers/soc/apple/clpc.c @@ -333,10 +333,30 @@ void apple_clpc_gpu_set_busy(struct apple_clpc_gpu *gpu, unsigned int permille) } EXPORT_SYMBOL_GPL(apple_clpc_gpu_set_busy); +/** + * apple_clpc_gpu_clear_busy() - Forget the GPU busy share after genuine idle + * @gpu: the GPU input, from apple_clpc_gpu_get() + * + * Returns reported GPU work to the top column of &struct apple_clpc_hw.gpu_busy + * until the driver reports a fresh window via apple_clpc_gpu_set_busy(). + */ +void apple_clpc_gpu_clear_busy(struct apple_clpc_gpu *gpu) +{ + unsigned long flags; + + if (!gpu) + return; + spin_lock_irqsave(&gpu->lock, flags); + gpu->busy_valid = false; + spin_unlock_irqrestore(&gpu->lock, flags); +} +EXPORT_SYMBOL_GPL(apple_clpc_gpu_clear_busy); + void apple_clpc_gpu_put(struct apple_clpc_gpu *gpu) { if (gpu) { apple_clpc_gpu_set_active(gpu, false); + apple_clpc_gpu_clear_busy(gpu); kref_put(&gpu->ref, apple_clpc_gpu_free); } } diff --git a/include/linux/soc/apple/clpc.h b/include/linux/soc/apple/clpc.h index 5f83b2aedc609..25c9d10fd791a 100644 --- a/include/linux/soc/apple/clpc.h +++ b/include/linux/soc/apple/clpc.h @@ -13,6 +13,7 @@ struct apple_clpc_ane; 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_clear_busy(struct apple_clpc_gpu *gpu); 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); @@ -26,6 +27,7 @@ static inline int apple_clpc_gpu_get(struct device *dev, struct apple_clpc_gpu * } 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_clear_busy(struct apple_clpc_gpu *gpu) {} static inline void apple_clpc_gpu_put(struct apple_clpc_gpu *gpu) {} /* ANE remains usable when the optional floor provider is not reachable. */ From 883f0567e5d68db27dc203f20cb36dc89eac3587 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Fri, 27 Nov 2026 10:19:28 -0500 Subject: [PATCH 2/3] drm/asahi: g17: preserve CLPC busy-share window across brief idle gaps When Effort::idle() expires after IDLE_HOLD_NS (16 ms), Port::set_effort_full(false) unconditionally reset BusyShare and left paced 24-30 fps workloads (33-42 ms period) unable to complete a 200 ms BusyShare window before the next frame arrived inside CLPC's 32 ms rail hold. Record inactivity via BusyShare::note_inactive() and only reset the window and call apple_clpc_gpu_clear_busy() when activity resumes after at least BUSY_IDLE_RESET_NS (100 ms) of inactivity, as well as unconditionally on firmware teardown and system resume (since CLOCK_MONOTONIC does not advance across suspend). Brief inter-frame gaps preserve the 200 ms window so low-fps paced streams settle to the lower CLPC column, while genuine idle gaps still re-baseline and start new bursts at the top column. Add KUnit coverage in g17/power.rs. Signed-off-by: Erik Bourget --- drivers/gpu/drm/asahi/g17/clpc.c | 5 ++ drivers/gpu/drm/asahi/g17/clpc.h | 1 + drivers/gpu/drm/asahi/g17/mod.rs | 2 +- drivers/gpu/drm/asahi/g17/port.rs | 47 ++++++++++++++-- drivers/gpu/drm/asahi/g17/power.rs | 86 ++++++++++++++++++++++++++++-- drivers/gpu/drm/asahi/g17/sleep.rs | 1 + 6 files changed, 134 insertions(+), 8 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/clpc.c b/drivers/gpu/drm/asahi/g17/clpc.c index bfe26e5d91c14..7d14fb23963a0 100644 --- a/drivers/gpu/drm/asahi/g17/clpc.c +++ b/drivers/gpu/drm/asahi/g17/clpc.c @@ -16,6 +16,11 @@ 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_clear_busy(struct apple_clpc_gpu *gpu) +{ + apple_clpc_gpu_clear_busy(gpu); +} + 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 6b16d5e8d5801..6c76355e38411 100644 --- a/drivers/gpu/drm/asahi/g17/clpc.h +++ b/drivers/gpu/drm/asahi/g17/clpc.h @@ -6,5 +6,6 @@ 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_clear_busy(struct apple_clpc_gpu *gpu); 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 f30bdc97d0b47..cfcff28e6cb98 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -845,7 +845,7 @@ impl Drop for Firmware { secondary.stop(); } self.primary.stop(); - self.port.set_effort_full(false); + self.port.clear_effort_and_busy(); self.primary.state.shared.set_full_effort_published(false); self.pool.stop_after_firmware(); // RTKit destruction releases the mailbox power references. Clear the bridge while diff --git a/drivers/gpu/drm/asahi/g17/port.rs b/drivers/gpu/drm/asahi/g17/port.rs index 7083cf028a403..1246b7d6e03c9 100644 --- a/drivers/gpu/drm/asahi/g17/port.rs +++ b/drivers/gpu/drm/asahi/g17/port.rs @@ -141,6 +141,7 @@ pub(super) struct Port { /// Mirrored from `busy` and `qos` for a lock-free fast path in `note_gpu_activity()`. busy_window_start: AtomicU64, busy_below_top: AtomicBool, + busy_inactive_since: AtomicU64, oldest_in_flight_any: AtomicU64, statistics_epoch: AtomicU64, last_submission_ns: AtomicU64, @@ -236,6 +237,7 @@ impl Port { busy <- new_spinlock!(super::power::BusyShare::new(), "g17::Port::busy"), busy_window_start: AtomicU64::new(0), busy_below_top: AtomicBool::new(false), + busy_inactive_since: AtomicU64::new(0), oldest_in_flight_any: AtomicU64::new(0), statistics_epoch: AtomicU64::new(0), last_submission_ns: AtomicU64::new(0), @@ -937,19 +939,50 @@ impl Port { self.submissions.load(Ordering::SeqCst) } + fn resume_busy_if_inactive(&self, now_ns: u64) { + if self.busy_inactive_since.load(Ordering::Acquire) == 0 { + return; + } + let now_ns = super::now_ns().max(now_ns); + let mut busy = self.busy.lock(); + if busy.resume(now_ns) { + self.demand.clear_busy(); + self.busy_window_start.store(0, Ordering::Relaxed); + self.busy_below_top.store(false, Ordering::Relaxed); + } + self.busy_inactive_since.store(0, Ordering::Release); + } + pub(super) fn set_effort_full(&self, full: bool) { self.effort_full.store(full, Ordering::SeqCst); if full { + self.resume_busy_if_inactive(super::now_ns()); self.demand.set_active(true); } else { + let now = super::now_ns(); 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); + if self.demand.has_provider() { + busy.note_inactive(now); + self.busy_inactive_since.store( + busy.inactive_since().map_or(0, |s| s.max(1)), + Ordering::Release, + ); + } } } + pub(super) fn clear_effort_and_busy(&self) { + self.effort_full.store(false, Ordering::SeqCst); + let mut busy = self.busy.lock(); + self.demand.set_active(false); + self.demand.clear_busy(); + busy.clear_active(); + self.busy_window_start.store(0, Ordering::Relaxed); + self.busy_below_top.store(false, Ordering::Relaxed); + self.busy_inactive_since.store(0, Ordering::Release); + } + /// The next statistics drain and reader discard what the decoder holds. pub(super) fn statistics_epoch_bump(&self) { self.statistics_epoch.fetch_add(1, Ordering::Release); @@ -988,6 +1021,12 @@ impl Port { let oldest = self.qos.lock().oldest_in_flight(); let now_ns = super::now_ns().max(now_ns); let mut busy = self.busy.lock(); + if busy.inactive_since().is_some() { + if busy.resume(now_ns) { + self.demand.clear_busy(); + } + self.busy_inactive_since.store(0, Ordering::Release); + } if let Some(permille) = busy.sample(now_ns, retired, oldest) { self.demand.set_busy(permille); } @@ -1012,6 +1051,7 @@ impl Port { let mut busy = self.busy.lock(); if let Some(permille) = busy.lift_saturated(now_ns, retired, oldest) { self.demand.set_busy(permille); + self.busy_inactive_since.store(0, Ordering::Release); } self.busy_window_start .store(busy.window_start().map_or(0, |s| s.max(1)), Ordering::Relaxed); @@ -1051,6 +1091,7 @@ impl Port { self.statistics_epoch.fetch_add(1, Ordering::Release); } self.last_submission_ns.store(now, Ordering::Relaxed); + self.resume_busy_if_inactive(now); self.demand.set_active(true); self.report_busy(now); } diff --git a/drivers/gpu/drm/asahi/g17/power.rs b/drivers/gpu/drm/asahi/g17/power.rs index c4e1125a6dbd9..c9f8180e86a29 100644 --- a/drivers/gpu/drm/asahi/g17/power.rs +++ b/drivers/gpu/drm/asahi/g17/power.rs @@ -471,6 +471,11 @@ 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; +/// Inactive gap (after [`IDLE_HOLD_NS`] ends effort) long enough to forget the prior +/// busy share so a new burst starts at the top CLPC column. Short enough to avoid +/// diluting new bursts after real idle, yet longer than inter-frame gaps of paced +/// low-fps workloads (e.g. 24-30 fps video or VRR, 25-42 ms). +pub(super) const BUSY_IDLE_RESET_NS: u64 = 100_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. @@ -491,6 +496,7 @@ pub(super) const BUSY_LONG_COMMAND_NS: u64 = 50_000_000; /// stages retiring together, err toward a higher share, which is the safe direction. pub(super) struct BusyShare { start_ns: Option, + inactive_since: Option, retired_ns: [u64; crate::usage::NUM_ENGINES], in_flight_ns: [u64; crate::usage::NUM_ENGINES], below_top: bool, @@ -500,22 +506,49 @@ impl BusyShare { pub(super) const fn new() -> Self { Self { start_ns: None, + inactive_since: 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. + /// Unconditionally resets the window and forgets any prior busy share (for + /// genuine idle expiry or teardown). pub(super) fn clear_active(&mut self) { self.start_ns = None; + self.inactive_since = None; self.in_flight_ns = [0; crate::usage::NUM_ENGINES]; self.below_top = false; } + /// Marks the GPU inactive after [`IDLE_HOLD_NS`] expires without wiping the + /// measurement window yet. Paced 24-30 fps streams resume well inside + /// [`BUSY_IDLE_RESET_NS`] and keep their window; longer idle gaps clear on + /// [`Self::resume`]. Idempotent while already inactive. + pub(super) fn note_inactive(&mut self, now_ns: u64) { + self.inactive_since.get_or_insert(now_ns); + } + + pub(super) fn inactive_since(&self) -> Option { + self.inactive_since + } + + /// Resumes activity at `now_ns` after [`Self::note_inactive`]. Returns `true` + /// when the inactive gap reached [`BUSY_IDLE_RESET_NS`] and the window was + /// cleared so the caller clears CLPC's cached share before reactivating. + pub(super) fn resume(&mut self, now_ns: u64) -> bool { + let Some(since) = self.inactive_since.take() else { + return false; + }; + if now_ns.saturating_sub(since) >= BUSY_IDLE_RESET_NS { + self.clear_active(); + true + } else { + false + } + } + pub(super) fn below_top(&self) -> bool { self.below_top } @@ -534,6 +567,7 @@ impl BusyShare { if !self.below_top { return None; } + self.inactive_since = None; 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()) { @@ -577,6 +611,7 @@ impl BusyShare { retired_ns: [u64; crate::usage::NUM_ENGINES], oldest_in_flight: [u64; crate::usage::NUM_ENGINES], ) -> Option { + let _ = self.resume(now_ns); 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); @@ -956,6 +991,43 @@ mod tests { assert!(share.below_top()); } + #[test] + fn paced_low_fps_preserves_window_across_effort_clears() { + const NS_MS: u64 = 1_000_000; + let mut share = BusyShare::new(); + let mut retired = 0u64; + let mut reported = None; + + // 24 fps light video/compositor (~42 ms period, 0.5 ms fragment work/frame): + // Effort::idle fires 16 ms after each frame, leaving a ~26 ms inactive gap + // (< BUSY_IDLE_RESET_NS). The 200 ms window must survive and close cleanly. + for frame in 0..8u64 { + let t = 1000 * NS_MS + frame * 42 * NS_MS; + assert!(!share.resume(t)); + if let Some(p) = share.sample(t, [0, retired, 0], [0, 0, 0]) { + reported = Some((frame, p)); + } + retired += 500_000; + // Idempotent note_inactive (Effort::idle calls set_effort_full(false) twice). + share.note_inactive(t + 16 * NS_MS); + share.note_inactive(t + 20 * NS_MS); + assert_eq!(share.inactive_since(), Some(t + 16 * NS_MS)); + } + // Frame 5 is at t = 1210 ms (210 ms elapsed, 2.5 ms retired -> 11 permille). + assert_eq!(reported, Some((5, 11))); + assert!(share.below_top()); + + // A genuine idle gap (>= BUSY_IDLE_RESET_NS) clears the window so the next + // burst starts fresh at the top CLPC column instead of diluting the window. + let last_inactive = 1000 * NS_MS + 7 * 42 * NS_MS + 16 * NS_MS; + let next_burst = last_inactive + BUSY_IDLE_RESET_NS; + assert!(share.resume(next_burst)); + assert!(!share.below_top()); + assert_eq!(share.window_start(), None); + assert_eq!(share.sample(next_burst, [0, retired, 0], [0, 0, 0]), None); + assert_eq!(share.window_start(), Some(next_burst)); + } + #[test] fn compute_waiters_lift_immediately_and_expire_while_streaming() { const NS_MS: u64 = 1_000_000; @@ -990,6 +1062,7 @@ unsafe extern "C" { 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); + fn asahi_clpc_gpu_clear_busy(gpu: *mut core::ffi::c_void); } /// DT-selected memory-demand provider. Its independent allocation outlives a @@ -1026,6 +1099,11 @@ impl Demand { // 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) }; } + + pub(super) fn clear_busy(&self) { + // SAFETY: the retained reference is live; NULL denotes no DT provider. + unsafe { asahi_clpc_gpu_clear_busy(self.0) }; + } } impl Drop for Demand { diff --git a/drivers/gpu/drm/asahi/g17/sleep.rs b/drivers/gpu/drm/asahi/g17/sleep.rs index a88a881c5de66..85718a7e3d442 100644 --- a/drivers/gpu/drm/asahi/g17/sleep.rs +++ b/drivers/gpu/drm/asahi/g17/sleep.rs @@ -562,6 +562,7 @@ impl Shared { } firmware.rings.invalidate_statistics(); firmware.port.statistics_epoch_bump(); + firmware.port.clear_effort_and_busy(); } result } From 206e5628ffd4e294c1fba1c6f7805ed122d1686c Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Fri, 27 Nov 2026 10:19:28 -0500 Subject: [PATCH 3/3] soc: apple: clpc: keep GPU busy share across brief inactivity Now that the sole apple_clpc_gpu_set_busy() consumer (drm/asahi g17) explicitly calls apple_clpc_gpu_clear_busy() after genuine idle gaps, system resume, and teardown, stop wiping gpu->busy_valid on every apple_clpc_gpu_set_active(gpu, false) call. Previously, paced 24-30 fps workloads (33-42 ms frame period) triggered g17's 16 ms effort clear between every frame while CLPC still held its rail vote for APPLE_CLPC_HOLD_MS (32 ms), wiping busy_valid and resetting the 400 ms down-step timer on every frame so DCS and fabric stayed pinned at the top column continuously. Add a KUnit test in clpc.c covering preservation across brief inactivity and explicit clear, and extend tools/asahi/clpc-gpu-demand-tests.py with end-to-end 24 fps paced coverage and negative controls. Signed-off-by: Erik Bourget --- drivers/soc/apple/clpc.c | 52 ++++++++++- tools/asahi/clpc-gpu-demand-tests.py | 124 ++++++++++++++++++++------- 2 files changed, 144 insertions(+), 32 deletions(-) diff --git a/drivers/soc/apple/clpc.c b/drivers/soc/apple/clpc.c index b29e9b68fa08c..ba235e845e07c 100644 --- a/drivers/soc/apple/clpc.c +++ b/drivers/soc/apple/clpc.c @@ -304,9 +304,6 @@ 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); @@ -2872,11 +2869,60 @@ static void apple_clpc_floor_test(struct kunit *test) KUNIT_EXPECT_EQ(test, apple_clpc_floor(clpc, state), 0xf00u); } +static void apple_clpc_gpu_busy_clear_test(struct kunit *test) +{ + struct apple_clpc_hw hw = apple_clpc_hw_t6041; + struct apple_clpc_gpu *gpu = kzalloc_obj(*gpu); + unsigned int demand[APPLE_CLPC_RAILS] = {}; + + KUNIT_ASSERT_NOT_NULL(test, gpu); + kref_init(&gpu->ref); + spin_lock_init(&gpu->lock); + hw.gpu_busy[APPLE_CLPC_DCS][0] = 1; + hw.gpu_busy[APPLE_CLPC_DCS][1] = 2; + hw.gpu_busy[APPLE_CLPC_DCS][2] = 4; + hw.gpu_busy[APPLE_CLPC_DCS][3] = 5; + hw.gpu_busy[APPLE_CLPC_SOC][3] = 3; + hw.gpu_busy_mid = 160; + hw.gpu_busy_high = 500; + hw.gpu_busy_top = 800; + + /* Brief inactivity preserves the reported busy share across paced frames. */ + apple_clpc_gpu_set_active(gpu, true); + apple_clpc_gpu_set_busy(gpu, 15); + gpu->level = 0; + gpu->level_since = jiffies - msecs_to_jiffies(APPLE_CLPC_GPU_DOWN_MS); + apple_clpc_gpu_set_active(gpu, false); + KUNIT_EXPECT_TRUE(test, gpu->busy_valid); + KUNIT_EXPECT_EQ(test, gpu->busy, 15u); + apple_clpc_gpu_set_active(gpu, true); + KUNIT_EXPECT_TRUE(test, apple_clpc_gpu_input_demand(&hw, gpu, demand)); + KUNIT_EXPECT_EQ(test, demand[APPLE_CLPC_DCS], 1u); + KUNIT_EXPECT_EQ(test, demand[APPLE_CLPC_SOC], 0u); + + /* Explicit clear_busy returns the next burst to the top column at once. */ + apple_clpc_gpu_clear_busy(gpu); + KUNIT_EXPECT_FALSE(test, gpu->busy_valid); + memset(demand, 0, sizeof(demand)); + KUNIT_EXPECT_TRUE(test, apple_clpc_gpu_input_demand(&hw, gpu, demand)); + KUNIT_EXPECT_EQ(test, demand[APPLE_CLPC_DCS], 5u); + KUNIT_EXPECT_EQ(test, demand[APPLE_CLPC_SOC], 3u); + + /* Releasing the consumer clears both activity and busy_valid. */ + kref_get(&gpu->ref); + apple_clpc_gpu_set_busy(gpu, 15); + apple_clpc_gpu_put(gpu); + KUNIT_EXPECT_FALSE(test, gpu->active); + KUNIT_EXPECT_FALSE(test, gpu->busy_valid); + kref_put(&gpu->ref, apple_clpc_gpu_free); +} + static struct kunit_case apple_clpc_policy_cases[] = { KUNIT_CASE(apple_clpc_step_khz_test), KUNIT_CASE(apple_clpc_steps_first_test), KUNIT_CASE(apple_clpc_vote_test), KUNIT_CASE(apple_clpc_floor_test), + KUNIT_CASE(apple_clpc_gpu_busy_clear_test), {} }; static struct kunit_suite apple_clpc_policy_suite = { diff --git a/tools/asahi/clpc-gpu-demand-tests.py b/tools/asahi/clpc-gpu-demand-tests.py index cb8acb4e4faa6..73f7fbdcbb6d7 100644 --- a/tools/asahi/clpc-gpu-demand-tests.py +++ b/tools/asahi/clpc-gpu-demand-tests.py @@ -31,7 +31,7 @@ def test_g17_busy_share(): 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')) + for name in ('BUSY_WINDOW_NS', 'BUSY_WINDOW_MAX_NS', 'BUSY_IDLE_RESET_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' @@ -118,10 +118,10 @@ def test_g17_busy_share(): 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. + // Scenario 5: steady 600 permille work until 1400 ms, genuine idle (>= BUSY_IDLE_RESET_NS), + // then a new burst at 2000 ms. Closing [1300, 2000] would report a diluted 85 permille + // (60 ms in 700 ms); resume() clears the window so 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(); @@ -130,7 +130,8 @@ def test_g17_busy_share(): assert_eq!(p, Some(600)); idle_events.push((t, p)); } - burst.clear_active(); + burst.note_inactive(1416 * MS); + assert!(burst.resume(2000 * MS)); 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]); @@ -140,14 +141,34 @@ def test_g17_busy_share(): } assert!(burst.below_top()); + // Scenario 6: paced 24 fps light work (42 ms period, 0.5 ms GPU/frame). Effort::idle + // fires 16 ms after each frame, leaving a 26 ms inactive gap (< BUSY_IDLE_RESET_NS). + // BusyShare must preserve its 200 ms window across those brief clears and report ~11 permille. + let mut paced = BusyShare::new(); + let mut paced_events = Vec::new(); + let mut frag_ns = 0u64; + for frame in 0..18u64 { + let t_ms = 1000 + frame * 42; + assert!(!paced.resume(t_ms * MS), "brief inter-frame gap must not reset BusyShare"); + let p = paced.sample(t_ms * MS, [0, frag_ns, 0], [0, 0, 0]); + paced_events.push((t_ms, p)); + frag_ns += 500_000; + paced.note_inactive((t_ms + 16) * MS); + } + assert!(paced.below_top(), "24 fps light frames must close their 200 ms window"); + assert!(paced_events.iter().any(|&(_, p)| p == Some(11))); + 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(",")); + let paced_out: Vec = + paced_events.iter().map(|(t, p)| format!("{t}={}", p.map_or(-1, i64::from))).collect(); + println!("PACED:{}", paced_out.join(",")); } ''' rustc = os.environ.get('RUSTC', 'rustc') - events = idle_events = None + events = idle_events = paced_events = None with tempfile.TemporaryDirectory(prefix='asahi-g17-busy-') as tmp: root = Path(tmp) for name, text in [ @@ -166,9 +187,11 @@ def test_g17_busy_share(): 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;')), + harness.replace('if now_ns.saturating_sub(since) >= BUSY_IDLE_RESET_NS {', + 'if false && now_ns.saturating_sub(since) >= BUSY_IDLE_RESET_NS {')), + ('g17-brief-idle-resets-window', + harness.replace('if now_ns.saturating_sub(since) >= BUSY_IDLE_RESET_NS {', + 'if true || now_ns.saturating_sub(since) >= BUSY_IDLE_RESET_NS {')), ]: assert name == 'fixed' or text != harness, 'stale mutation: ' + name src = root / (name + '.rs') @@ -180,22 +203,25 @@ def test_g17_busy_share(): 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 + assert len(lines) == 3 and lines[0].startswith('EVENTS:') \ + and lines[1].startswith('IDLE:') \ + and lines[2].startswith('PACED:'), 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(',')] + paced_events = [tuple(int(x) for x in pair.split('=')) + for pair in lines[2].removeprefix('PACED:').split(',')] print('PASS: g17 BusyShare (in-flight long command, early lift, solo recheck, ' - 'non-double-counting, new burst after idle)') + 'non-double-counting, new burst after idle, 24 fps brief idle)') else: assert run.returncode != 0, name print('PASS negative control:', name) - return events, idle_events + return events, idle_events, paced_events def main(): - g17_events, g17_idle_events = test_g17_busy_share() + g17_events, g17_idle_events, g17_paced_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) @@ -230,8 +256,13 @@ def cells(name): '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') + + ', '.join(f'{{{t}, {p}}}' for t, p in g17_idle_events) + '};\n' + 'static const struct { unsigned long ms; int permille; } g17_paced_events[] = {' + + ', '.join(f'{{{t}, {p}}}' for t, p in g17_paced_events) + '};\n') methods = '\n'.join(item(source, s) for s in [ + 'void apple_clpc_gpu_set_active(', + 'void apple_clpc_gpu_set_busy(', + 'void apple_clpc_gpu_clear_busy(', 'static unsigned int apple_clpc_vote(', 'static u32 apple_clpc_floor(', 'static bool apple_clpc_gpu_streaming(', 'static bool apple_clpc_gpu_dense_step(', @@ -263,6 +294,7 @@ def cells(name): #define APPLE_CLPC_GPU_BACKOFF_MS 100 #define HZ 1000 #define max(a,b) ((a) > (b) ? (a) : (b)) +#define min(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)) @@ -271,14 +303,17 @@ def cells(name): #define time_after(a,b) ((long)((a)-(b)) > 0) #define time_before(a,b) ((long)((a)-(b)) < 0) #define msecs_to_jiffies(ms) (ms) +#define system_freezable_power_efficient_wq NULL +static void mod_delayed_work(void *wq, void *w, unsigned long d) { (void)wq; (void)w; (void)d; } 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 { - int lock; bool active; u64 sequence; + int lock; bool active; u64 updated_ns; u64 sequence; unsigned int busy; bool busy_valid; unsigned int level; unsigned long level_since; + void *wake; }; struct apple_clpc_ane { int lock; bool active, pending; }; #define spin_lock_irqsave(l, f) ((void)(l), (f) = 0) @@ -576,8 +611,8 @@ def cells(name): } // 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 +// work, a genuine idle gap in which the GPU clears its activity and busy share +// (via apple_clpc_gpu_clear_busy), 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) { @@ -594,17 +629,17 @@ def cells(name): 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; + // Idle: after genuine idle (>= BUSY_IDLE_RESET_NS), g17 clears both activity and busy. + apple_clpc_gpu_set_active(&gpu, false); + apple_clpc_gpu_clear_busy(&gpu); for (jiffies = 1416; jiffies < 2000; jiffies += 4) apple_clpc_sample(&c); assert(published == 0); - gpu.active = true; + apple_clpc_gpu_set_active(&gpu, 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; - } + if (g17_idle_events[i].permille >= 0) + apple_clpc_gpu_set_busy(&gpu, g17_idle_events[i].permille); i++; } assert(gpu.busy_valid == (jiffies >= 2200)); @@ -613,10 +648,38 @@ def cells(name): } 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); + apple_clpc_gpu_set_active(&gpu, false); apple_clpc_gpu_clear_busy(&gpu); + jiffies = 2400; apple_clpc_sample(&c); + apple_clpc_gpu_set_active(&gpu, true); apple_clpc_gpu_set_busy(&gpu, 85); + jiffies = 3000; apple_clpc_sample(&c); assert(published == 0x01 && gpu.level == 0); + apple_clpc_gpu_set_active(&gpu, false); jiffies = 3100; apple_clpc_sample(&c); assert(published == 0); +} + +// End-to-end: paced 24 fps light work (42 ms period). Every frame clears activity +// after 16 ms (Effort::idle) and resumes 26 ms later (inside CLPC's 32 ms vote +// hold). Keeping busy_valid across set_active(false) lets g17's 200 ms window +// drop CLPC from 0x35 (level 3) to 0x01 (level 0) after APPLE_CLPC_GPU_DOWN_MS. +static void check_t6041_paced_24fps(void) { + struct apple_clpc_gpu gpu = {0}; + struct apple_clpc c = {.hw = &t6041_dt_hw, .has_pmc = true, .agent = 1, .mask = 3, .gpu = &gpu}; + size_t n = ARRAY_SIZE(g17_paced_events); + read_error = vote_error = 0; pmgr_status = 0xf0; pmp_floor = 0; published = ~0u; + assert(n == 18 && g17_paced_events[0].ms == 1000); + for (size_t i = 0; i < n; i++) { + unsigned long start = g17_paced_events[i].ms; + unsigned long end = (i + 1 < n) ? g17_paced_events[i + 1].ms : start + 42; + apple_clpc_gpu_set_active(&gpu, true); + if (g17_paced_events[i].permille >= 0) + apple_clpc_gpu_set_busy(&gpu, g17_paced_events[i].permille); + for (jiffies = start; jiffies < end; jiffies += 4) { + if (jiffies >= start + 16) + apple_clpc_gpu_set_active(&gpu, false); + apple_clpc_sample(&c); + } + } + // By frame 17 (~1714..1756 ms), 200 ms window + 400 ms down-step + 32 ms fabric hold + // have all elapsed: floor must have dropped to DCS 1 / fabric 0 (0x01). + assert(gpu.busy_valid && gpu.level == 0 && published == 0x01); } // T8132's G16 firmware keeps graphics powered while the GPU idles: the @@ -767,6 +830,7 @@ def cells(name): check_t6041_busy(); check_t6041_long_in_flight(); check_t6041_idle_burst(); + check_t6041_paced_24fps(); check_t8132(); check_t6041(&apple_clpc_hw_t6041); check_t6041(&t6041_dt_hw); @@ -807,6 +871,8 @@ def cells(name): '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)')), + ('clpc-set-active-clears-busy', code.replace('\tgpu->active = active;\n', + '\tgpu->active = active;\n\tif (!active)\n\t\tgpu->busy_valid = false;\n')), ('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;', '')),