From fff2d23562f4d93ec7995b5caee47306316f89df Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Fri, 27 Nov 2026 02:29:46 -0500 Subject: [PATCH 1/5] iio: aop_temp: run board temperature reports on demand with idle stop The AOP temperature driver starts 1 Hz fake-HID reports at probe and keeps them streaming until system sleep or unbind, waking the application processor once a second even when nothing reads in_temp_input or enables its kfifo buffer. Follow the on-demand idle-stop pattern used by aop_motion: - Calibrate once per AOP boot (and conservatively again after firmware suspend, hibernation, or restore) and stop reports at probe after verifying calibration, start, and stop. Retain continuous mode if the firmware refuses PROP_INTERVAL = 0, and unwind transient errors. - Track firmware run state as Stopped, Running, or Unknown so any unacknowledged start or stop reasserts the target interval on the next transition and arms a 5 s stop retry whenever an idle on-demand stream is left Unknown or Running (including after unpark). - Invalidate cached samples before starting reports from Stopped or Unknown on direct reads, buffer enable, and sleep resume. - Wire iio_buffer_setup_ops (postenable / predisable) to the kfifo buffer, gating iio_push_to_buffers() under a spinlock that drains in-flight pushes in predisable before IIO detaches the buffer list while keeping direct-read sample caching active. - Track in-flight direct_readers so concurrent reads wait for the first report and buffer transitions cannot stop a stream under an active direct read; hold reports warm for 5 s via DelayedWork and back off after failed starts. - Free the IIO device via devres registered before the kfifo buffer, and tear down IIO, PM, delayed work, and listener in Drop as well as unbind so probe rollback after iio.register() cannot leak work. - Add a host regression test (aop-temp.py) and register it in run-host-tests.py. Signed-off-by: Erik Bourget --- drivers/iio/common/aop_sensors/aop_temp.rs | 704 ++++++++++++++++-- tools/asahi/run-host-tests.py | 2 +- .../testing/selftests/drivers/apple/Makefile | 5 +- .../selftests/drivers/apple/aop-temp.py | 174 +++++ 4 files changed, 813 insertions(+), 72 deletions(-) create mode 100755 tools/testing/selftests/drivers/apple/aop-temp.py diff --git a/drivers/iio/common/aop_sensors/aop_temp.rs b/drivers/iio/common/aop_sensors/aop_temp.rs index af4ba06224e52..f24bd055d7f0c 100644 --- a/drivers/iio/common/aop_sensors/aop_temp.rs +++ b/drivers/iio/common/aop_sensors/aop_temp.rs @@ -5,7 +5,12 @@ //! The `als-temp` service on current laptops is a board-temperature sensor. //! Its fake-HID report carries a signed Q16.16 Celsius value and an AOP //! timestamp. Calibration data, when supplied by the bootloader, is sent -//! unchanged before reports are enabled. +//! once per AOP boot before reports are enabled. +//! +//! When the service accepts clearing its report interval, reports run only +//! while someone reads them: while a buffer is enabled, or until direct reads +//! go quiet for a short idle window. With nobody reading, the reports stay off +//! so the AOP does not wake the application processor once a second at idle. //! //! The AOP core creates a device for the service whenever the firmware //! announces it, and the driver binds to that device by name. A device tree @@ -19,16 +24,18 @@ use core::{ use kernel::{ bindings, c_str, - device::{self, Core}, - driver, new_spinlock, of, platform, + device::{self, Bound, Core}, + devres, driver, new_delayed_work, new_mutex, new_spinlock, of, platform, prelude::*, soc::apple::aop::{EPICService, FakehidListener, FakehidRegistration, AOP}, sync::{ aref::ARef, atomic::{Atomic, Relaxed}, - Arc, SpinLock, + Arc, Mutex, SpinLock, }, + time::{self, delay::fsleep, Delta, Instant, Monotonic}, types::{ForeignOwnable, Opaque}, + workqueue::{self, impl_has_delayed_work, DelayedWork, Work, WorkItem}, ThisModule, }; @@ -36,6 +43,11 @@ const SUBTYPE_SET_PROPERTY: u16 = 4; const PROP_INTERVAL: u32 = 0; const PROP_CALIBRATION_STATE: u32 = 61; const INTERVAL_US: u32 = 1_000_000; +/// How long a direct read waits for the first 1 Hz report of a fresh start. +const FIRST_SAMPLE_MS: i64 = 1_500; +const FIRST_SAMPLE_POLL_MS: i64 = 20; +/// How long reports stay on after the last direct read without a buffer. +const DIRECT_IDLE_MS: i64 = 5_000; const STATUS_UNSUPPORTED: u32 = 0xe000_02c7; const REPORT_LEN: usize = 14; const TEMP_OFFSET: usize = 2; @@ -77,11 +89,140 @@ fn decode_millicelsius(report: &[u8]) -> Option { Some(((i64::from(raw) * 1000) / 65_536) as i32) } +/// What a stream state change requires from the service. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum SyncAction { + None, + /// Enable reports; send calibration packets first when `calibrate` is true. + Start { + calibrate: bool, + }, + Stop, +} + +/// Outcome of checking the direct-read idle deadline. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum IdleStep { + /// No direct-read hold to expire. + Ignore, + /// More reads extended the deadline; re-arm the work for this many ms. + RearmMs(u32), + /// The deadline passed; stop the reports if nothing else wants them. + Expire, +} + +/// Observed firmware reporting state. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum RunState { + Stopped, + Running, + /// A start or stop write was not acknowledged; the next transition + /// reasserts the desired interval in either direction. + Unknown, +} + +/// Who wants the reports of the service and whether calibration has already +/// been sent in this AOP boot. +struct Stream { + /// Calibration has been sent in this AOP boot. + calibrated: bool, + /// Service accepted `PROP_INTERVAL = 0` at probe so reports can idle-stop. + /// When false, reports stay running continuously except across sleep/unbind. + on_demand: bool, + /// A buffer is enabled. + buffer_on: bool, + /// Number of direct reads currently waiting for a sample. + direct_readers: u32, + /// Reports are held on for recent direct reads until this deadline. + direct_until: Option, + /// A start for a direct read failed with this error; direct reads return + /// it without another try until this deadline. + failed_until: Option<(T, Error)>, + /// Set across system sleep and after unbind: no reports. + parked: bool, + /// Current knowledge of whether firmware reports are running. + run_state: RunState, +} + +impl Stream { + const fn new() -> Self { + Self { + calibrated: false, + on_demand: false, + buffer_on: false, + direct_readers: 0, + direct_until: None, + failed_until: None, + parked: false, + run_state: RunState::Stopped, + } + } + + fn want(&self) -> bool { + if self.parked { + return false; + } + !self.on_demand || self.buffer_on || self.direct_readers > 0 || self.direct_until.is_some() + } + + fn next_action(&self) -> SyncAction { + match (self.want(), self.run_state) { + (true, RunState::Stopped | RunState::Unknown) => SyncAction::Start { + calibrate: !self.calibrated, + }, + (false, RunState::Running | RunState::Unknown) => SyncAction::Stop, + _ => SyncAction::None, + } + } + + /// Evaluates the direct-read idle deadline given the milliseconds left + /// until it expires (`<= 0` once expired). + fn check_idle(&mut self, remaining_ms: i64) -> IdleStep { + if self.direct_until.is_none() { + return IdleStep::Ignore; + } + if !self.on_demand || self.parked || self.buffer_on { + self.direct_until = None; + return IdleStep::Ignore; + } + if self.direct_readers > 0 { + return IdleStep::RearmMs(DIRECT_IDLE_MS as u32); + } + if remaining_ms > 0 { + IdleStep::RearmMs(remaining_ms.clamp(1, DIRECT_IDLE_MS) as u32) + } else { + self.direct_until = None; + IdleStep::Expire + } + } + + /// Returns the error of a failed start for as long as direct reads back + /// off from it, given the milliseconds left until they may try again + /// (`<= 0` once they may). + fn check_backoff(&mut self, remaining_ms: i64) -> Option { + if remaining_ms <= 0 { + self.failed_until = None; + } + self.failed_until.as_ref().map(|(_, e)| *e) + } +} + +#[pin_data] struct Control { dev: ARef, aop: Arc, service: EPICService, packets: KVec<(u32, KVec)>, + /// Serializes starting and stopping the reports. + #[pin] + stream: Mutex>>, + /// Stops direct-read reports once reads go quiet. + #[pin] + idle_work: DelayedWork, +} + +impl_has_delayed_work! { + impl HasDelayedWork for Control { self.idle_work } } impl Control { @@ -113,15 +254,17 @@ impl Control { "no temperature calibration from the bootloader; using sensor defaults\n" ); } - Ok(Arc::new( - Self { + Arc::pin_init( + pin_init!(Self { dev: dev.into(), aop, service, packets, - }, + stream <- new_mutex!(Stream::new()), + idle_work <- new_delayed_work!("Control::idle_work"), + }), GFP_KERNEL, - )?) + ) } fn write(&self, prop: u32, value: &[u8]) -> Result { @@ -133,7 +276,7 @@ impl Control { .epic_call(&self.service, SUBTYPE_SET_PROPERTY, &msg) } - fn start(&self) -> Result { + fn calibrate(&self) -> Result { for (prop, packet) in &self.packets { let status = self.write(*prop, packet)?; if status != 0 && status != STATUS_UNSUPPORTED { @@ -156,6 +299,10 @@ impl Control { ); return Err(EIO); } + Ok(()) + } + + fn start_reports(&self) -> Result { let status = self.write(PROP_INTERVAL, &INTERVAL_US.to_le_bytes())?; if status != 0 { dev_err!(self.dev, "interval refused: status {:#x}\n", status); @@ -164,7 +311,7 @@ impl Control { Ok(()) } - fn stop(&self) -> Result { + fn stop_reports(&self) -> Result { let status = self.write(PROP_INTERVAL, &0u32.to_le_bytes())?; if status != 0 { dev_err!(self.dev, "stop refused: status {:#x}\n", status); @@ -172,6 +319,230 @@ impl Control { } Ok(()) } + + /// Checks once at probe that the service accepts calibration and the + /// report interval, then stops reports for on-demand operation. If the + /// firmware explicitly refuses `PROP_INTERVAL = 0`, retain continuous + /// mode rather than dropping a working sensor. + fn probe_init(&self) -> Result { + let mut s = self.stream.lock(); + self.calibrate()?; + s.calibrated = true; + match self.write(PROP_INTERVAL, &INTERVAL_US.to_le_bytes()) { + Ok(0) => { + s.run_state = RunState::Running; + } + Ok(status) => { + dev_err!(self.dev, "interval refused: status {:#x}\n", status); + return Err(EIO); + } + Err(e) => { + // An unacknowledged start may still have taken effect in + // firmware; mark unknown so shutdown and best-effort rollback + // attempt to stop it. + s.run_state = RunState::Unknown; + if let Ok(0) = self.write(PROP_INTERVAL, &0u32.to_le_bytes()) { + s.run_state = RunState::Stopped; + } + return Err(e); + } + } + match self.write(PROP_INTERVAL, &0u32.to_le_bytes()) { + Ok(0) => { + s.run_state = RunState::Stopped; + s.on_demand = true; + Ok(()) + } + Ok(status) => { + dev_info!( + self.dev, + "idle stop refused (status {:#x}); keeping continuous reports\n", + status + ); + s.on_demand = false; + Ok(()) + } + Err(e) => { + // Transient transport error after start: attempt best-effort stop. + s.run_state = RunState::Unknown; + if let Ok(0) = self.write(PROP_INTERVAL, &0u32.to_le_bytes()) { + s.run_state = RunState::Stopped; + } + Err(e) + } + } + } + + /// Starts or stops the reports to match their users. The caller holds the + /// stream lock. `before_start` runs right before enabling reports so any + /// cached sample from an earlier run is invalidated before new reports + /// arrive. + fn sync_locked( + &self, + s: &mut Stream>, + before_start: impl FnOnce(), + ) -> Result { + match s.next_action() { + SyncAction::Start { calibrate } => { + if calibrate { + self.calibrate()?; + s.calibrated = true; + } + before_start(); + match self.start_reports() { + Ok(()) => { + s.run_state = RunState::Running; + Ok(()) + } + Err(e) => { + s.run_state = RunState::Unknown; + Err(e) + } + } + } + SyncAction::Stop => match self.stop_reports() { + Ok(()) => { + s.run_state = RunState::Stopped; + Ok(()) + } + Err(e) => { + s.run_state = RunState::Unknown; + Err(e) + } + }, + SyncAction::None => Ok(()), + } + } + + /// Arms a rate-limited idle-stop retry whenever an unacknowledged start or + /// stop leaves an idle on-demand stream potentially running. + fn arm_stop_retry_locked(&self, s: &mut Stream>) -> bool { + if s.on_demand && !s.want() && s.run_state != RunState::Stopped { + s.direct_until = Some(Instant::::now() + Delta::from_millis(DIRECT_IDLE_MS)); + true + } else { + false + } + } + + fn schedule_idle(self: &Arc, delay_ms: u32) { + let _ = + workqueue::system_dfl().enqueue_delayed(self.clone(), time::msecs_to_jiffies(delay_ms)); + } + + fn stop_idle_sync(self: &Arc, disable: bool) { + // SAFETY: `idle_work` is initialized and pinned in this `Arc`. Both + // helpers cancel pending work and join a running callback; the disable + // variant also prevents any later requeue. + let cancelled = unsafe { + let work = Work::raw_get(DelayedWork::raw_as_work(ptr::addr_of!(self.idle_work))); + let delayed = kernel::container_of!(work, bindings::delayed_work, work); + if disable { + bindings::disable_delayed_work_sync(delayed) + } else { + bindings::cancel_delayed_work_sync(delayed) + } + }; + if cancelled { + // SAFETY: A cancelled pending callback owned exactly one `Arc` + // transferred by `enqueue_delayed`. + drop(unsafe { Arc::from_raw(Arc::as_ptr(self)) }); + } + } + + fn set_buffer(self: &Arc, on: bool, before_start: impl FnOnce()) -> Result { + let (ret, retry) = { + let mut s = self.stream.lock(); + s.buffer_on = on; + if on { + s.direct_until = None; + s.failed_until = None; + } + let ret = self.sync_locked(&mut s, before_start); + if on && ret.is_err() { + // The IIO core does not call predisable after a failed enable. + s.buffer_on = false; + } + let retry = ret.is_err() && self.arm_stop_retry_locked(&mut s); + (ret, retry) + }; + if retry { + self.schedule_idle(DIRECT_IDLE_MS as u32); + } + ret + } + + fn set_parked( + self: &Arc, + parked: bool, + reset_cal: bool, + before_start: impl FnOnce(), + ) -> Result { + let (ret, retry) = { + let mut s = self.stream.lock(); + s.parked = parked; + s.failed_until = None; + if parked { + s.direct_until = None; + } else if reset_cal { + s.calibrated = false; + s.run_state = RunState::Stopped; + } + let ret = self.sync_locked(&mut s, before_start); + let retry = !parked && ret.is_err() && self.arm_stop_retry_locked(&mut s); + (ret, retry) + }; + if parked { + self.stop_idle_sync(false); + } else if retry { + self.schedule_idle(DIRECT_IDLE_MS as u32); + } + ret + } + + fn shutdown(self: &Arc) -> Result { + let ret = { + let mut s = self.stream.lock(); + s.parked = true; + s.direct_until = None; + s.failed_until = None; + self.sync_locked(&mut s, || {}) + }; + self.stop_idle_sync(true); + ret + } +} + +impl WorkItem for Control { + type Pointer = Arc; + + fn run(this: Arc) { + let retry = { + let mut s = this.stream.lock(); + let Some(deadline) = s.direct_until else { + return; + }; + let remaining_ms = (deadline - Instant::::now()).as_millis_ceil(); + match s.check_idle(remaining_ms) { + IdleStep::Ignore => None, + IdleStep::RearmMs(delay_ms) => Some(delay_ms), + IdleStep::Expire => match this.sync_locked(&mut s, || {}) { + Ok(()) => None, + Err(e) => { + dev_warn!(this.dev, "reports not stopped after idle: {:?}\n", e); + if this.arm_stop_retry_locked(&mut s) { + Some(DIRECT_IDLE_MS as u32) + } else { + None + } + } + }, + } + }; + if let Some(delay_ms) = retry { + this.schedule_idle(delay_ms); + } + } } #[derive(Clone, Copy, Default)] @@ -190,8 +561,97 @@ struct Scan { #[pin_data] struct State { iio: IioPtr, + control: Arc, #[pin] sample: SpinLock, + /// Gates `iio_push_to_buffers()` and synchronously drains in-flight pushes + /// during `buffer_predisable` before the IIO core detaches the buffer list. + #[pin] + push_enabled: SpinLock, +} + +/// Keeps `direct_readers` accounted for across `read_now()`, and arms the +/// idle-stop deadline once the reader finishes. +struct DirectReadGuard<'a>(&'a Arc); + +impl Drop for DirectReadGuard<'_> { + fn drop(&mut self) { + let schedule = { + let mut s = self.0.stream.lock(); + s.direct_readers = s.direct_readers.saturating_sub(1); + if s.on_demand && !s.parked && !s.buffer_on { + s.direct_until = + Some(Instant::::now() + Delta::from_millis(DIRECT_IDLE_MS)); + true + } else { + false + } + }; + if schedule { + self.0.schedule_idle(DIRECT_IDLE_MS as u32); + } + } +} + +impl State { + /// Returns the latest temperature sample. Without a buffer the reports are + /// started on demand and kept running until direct reads go quiet for + /// `DIRECT_IDLE_MS`. + fn read_now(&self) -> Result { + let guard = { + let mut s = self.control.stream.lock(); + if !s.on_demand { + drop(s); + let sample = *self.sample.lock(); + return if sample.valid { + Ok(sample.millicelsius) + } else { + Err(ENODATA) + }; + } + if s.parked { + return Err(EBUSY); + } + if let Some((until, _)) = s.failed_until { + let remaining_ms = (until - Instant::::now()).as_millis_ceil(); + if let Some(e) = s.check_backoff(remaining_ms) { + return Err(e); + } + } + s.direct_readers += 1; + if let Err(e) = self + .control + .sync_locked(&mut s, || self.sample.lock().valid = false) + { + s.direct_readers = s.direct_readers.saturating_sub(1); + let until = Instant::::now() + Delta::from_millis(DIRECT_IDLE_MS); + s.failed_until = Some((until, e)); + let retry = self.control.arm_stop_retry_locked(&mut s); + drop(s); + if retry { + self.control.schedule_idle(DIRECT_IDLE_MS as u32); + } + return Err(e); + } + DirectReadGuard(&self.control) + }; + + let mut waited = 0; + while waited < FIRST_SAMPLE_MS && !self.sample.lock().valid { + if self.control.stream.lock().parked { + return Err(EBUSY); + } + fsleep(Delta::from_millis(FIRST_SAMPLE_POLL_MS)); + waited += FIRST_SAMPLE_POLL_MS; + } + let sample = *self.sample.lock(); + drop(guard); + if sample.valid { + Ok(sample.millicelsius) + } else { + Err(ENODATA) + } + } } struct IioPtr(*mut bindings::iio_dev); @@ -208,15 +668,20 @@ impl FakehidListener for State { millicelsius, valid: true, }; - // SAFETY: The listener is removed before the IIO device is freed. - let timestamp = unsafe { bindings::iio_get_time_ns(self.iio.0) }; - let scan = Scan { - millicelsius, - pad: 0, - timestamp, - }; - // SAFETY: The scan layout matches the only available scan mask. - unsafe { bindings::iio_push_to_buffers(self.iio.0, ptr::from_ref(&scan).cast()) }; + let push = self.push_enabled.lock(); + if *push { + // SAFETY: The buffer is enabled and `buffer_predisable` clears + // `push_enabled` under this lock before the IIO core removes the + // buffer from the active list. + let timestamp = unsafe { bindings::iio_get_time_ns(self.iio.0) }; + let scan = Scan { + millicelsius, + pad: 0, + timestamp, + }; + // SAFETY: The scan layout matches the only available scan mask. + unsafe { bindings::iio_push_to_buffers(self.iio.0, ptr::from_ref(&scan).cast()) }; + } Ok(()) } } @@ -238,7 +703,7 @@ unsafe extern "C" fn read_raw( if mask == bindings::BINDINGS_IIO_CHAN_INFO_SAMP_FREQ as isize { // SAFETY: The pointers are the caller's result variables. unsafe { - *val = 1; + *val = (1_000_000 / INTERVAL_US) as i32; *val2 = 0; } return bindings::IIO_VAL_INT as i32; @@ -246,19 +711,64 @@ unsafe extern "C" fn read_raw( if mask != bindings::BINDINGS_IIO_CHAN_INFO_PROCESSED as isize { return EINVAL.to_errno(); } - let sample = *state.sample.lock(); - if !sample.valid { - return ENODATA.to_errno(); - } + let millicelsius = match state.read_now() { + Ok(value) => value, + Err(e) => return e.to_errno(), + }; // SAFETY: The pointers are the caller's result variables. IIO temperature // processed values are in millidegrees Celsius. unsafe { - *val = sample.millicelsius; + *val = millicelsius; *val2 = 0; } bindings::IIO_VAL_INT as i32 } +/// Starts the reports for an enabled buffer. +/// +/// # Safety +/// +/// The IIO core calls it with a device registered by [`TempIio`]. +unsafe extern "C" fn buffer_postenable(indio_dev: *mut bindings::iio_dev) -> c_int { + // SAFETY: The private data is the `Arc` stored by `TempIio::new()`. + let state = unsafe { Arc::::borrow((*indio_dev).priv_.cast()) }; + match state + .control + .set_buffer(true, || state.sample.lock().valid = false) + { + Ok(()) => { + *state.push_enabled.lock() = true; + 0 + } + Err(e) => e.to_errno(), + } +} + +/// Stops the reports when the buffer is disabled. +/// +/// # Safety +/// +/// As [`buffer_postenable`]. +unsafe extern "C" fn buffer_predisable(indio_dev: *mut bindings::iio_dev) -> c_int { + // SAFETY: As in `buffer_postenable()`. + let state = unsafe { Arc::::borrow((*indio_dev).priv_.cast()) }; + // Synchronously drain any in-flight buffer push before IIO core detaches + // the buffer list, while keeping direct-read sample caching active. + *state.push_enabled.lock() = false; + match state.control.set_buffer(false, || {}) { + Ok(()) => 0, + Err(e) => e.to_errno(), + } +} + +static BUFFER_OPS: bindings::iio_buffer_setup_ops = bindings::iio_buffer_setup_ops { + preenable: None, + postenable: Some(buffer_postenable), + predisable: Some(buffer_predisable), + postdisable: None, + validate_scan_mask: None, +}; + fn temp_channel() -> bindings::iio_chan_spec { bindings::iio_chan_spec { type_: bindings::BINDINGS_IIO_TEMP, @@ -300,15 +810,36 @@ struct Spec { _p: PhantomPinned, } -struct TempIio { +/// Owns the IIO device and what it points to so it is released with the +/// platform device's resources, after the devres kfifo buffer is detached. +struct IioAlloc { dev: *mut bindings::iio_dev, _spec: Pin>, - registered: bool, +} + +impl Drop for IioAlloc { + fn drop(&mut self) { + // SAFETY: `self.dev` was allocated in `TempIio::new()` with an + // `Arc` as its private data. `TempIio` has unregistered it and + // resources registered after this one (the kfifo buffer) are released. + unsafe { + drop(Arc::::from_foreign((*self.dev).priv_.cast())); + bindings::iio_device_free(self.dev); + } + } +} + +// SAFETY: The IIO device may be freed from any thread, and the channel +// table is only read. +unsafe impl Send for IioAlloc {} + +struct TempIio { + dev: *mut bindings::iio_dev, + registered: Atomic, } impl TempIio { - fn new(pdev: &platform::Device>) -> Result<(Self, Arc)> { - let dev = pdev.as_ref(); + fn new(dev: &device::Device, control: Arc) -> Result<(Self, Arc)> { let spec = KBox::pin( Spec { channels: [temp_channel(), timestamp_channel()], @@ -328,7 +859,9 @@ impl TempIio { let state = match Arc::pin_init( pin_init!(State { iio: IioPtr(indio_dev), + control, sample <- new_spinlock!(Sample::default()), + push_enabled <- new_spinlock!(false), }), GFP_KERNEL, ) { @@ -349,56 +882,60 @@ impl TempIio { (*indio_dev).modes = bindings::INDIO_DIRECT_MODE as i32; (*indio_dev).available_scan_masks = SCAN_MASKS.as_ptr(); } + // Register the IIO allocation before the kfifo buffer so devres + // detaches the buffer before freeing `indio_dev`. + devres::register( + dev, + IioAlloc { + dev: indio_dev, + _spec: spec, + }, + GFP_KERNEL, + )?; // SAFETY: Both devices are valid and the buffer is device-managed. let ret = unsafe { bindings::devm_iio_kfifo_buffer_setup_ext( dev.as_raw(), indio_dev, - ptr::null(), + &BUFFER_OPS, ptr::null_mut(), ) }; if ret < 0 { - // SAFETY: The device is not registered; the private pointer is - // the foreign `Arc` installed above. - unsafe { - drop(Arc::::from_foreign((*indio_dev).priv_.cast())); - bindings::iio_device_free(indio_dev); - } return Err(Error::from_errno(ret)); } Ok(( Self { dev: indio_dev, - _spec: spec, - registered: false, + registered: Atomic::new(false), }, state, )) } - fn register(&mut self) -> Result { + fn register(&self) -> Result { let module = kernel::module::this_module::(); // SAFETY: The device is fully initialized and unregistered. let ret = unsafe { bindings::__iio_device_register(self.dev, module.as_ptr()) }; if ret < 0 { return Err(Error::from_errno(ret)); } - self.registered = true; + self.registered.store(true, Relaxed); Ok(()) } + + fn unregister(&self) { + if self.registered.xchg(false, Relaxed) { + // SAFETY: `self.dev` was registered by `register()`. It is freed + // with the platform device's resources, which outlive this. + unsafe { bindings::iio_device_unregister(self.dev) }; + } + } } impl Drop for TempIio { fn drop(&mut self) { - // SAFETY: The device and its private `Arc` were installed by `new()`. - unsafe { - if self.registered { - bindings::iio_device_unregister(self.dev); - } - drop(Arc::::from_foreign((*self.dev).priv_.cast())); - bindings::iio_device_free(self.dev); - } + self.unregister(); } } @@ -410,7 +947,7 @@ unsafe impl Sync for TempIio {} #[repr(C)] struct PmHook { nb: Opaque, - control: Arc, + state: Arc, registered: Atomic, } @@ -424,14 +961,25 @@ unsafe extern "C" fn pm_event( ) -> c_int { // SAFETY: `nb` is the first field of a registered, pinned `PmHook`. let hook = unsafe { &*nb.cast::() }; + let invalidate = || hook.state.sample.lock().valid = false; let ret = match action as u32 { - bindings::PM_SUSPEND_PREPARE | bindings::PM_HIBERNATION_PREPARE => hook.control.stop(), - bindings::PM_POST_SUSPEND | bindings::PM_POST_HIBERNATION => hook.control.start(), + bindings::PM_SUSPEND_PREPARE + | bindings::PM_HIBERNATION_PREPARE + | bindings::PM_RESTORE_PREPARE => hook.state.control.set_parked(true, false, || {}), + bindings::PM_POST_SUSPEND => { + // SAFETY: Reads the PM core's sleep-transition flag, which stays + // set until the next suspend entry. + let fw_sleep = unsafe { bindings::pm_suspend_via_firmware() }; + hook.state.control.set_parked(false, fw_sleep, invalidate) + } + bindings::PM_POST_HIBERNATION | bindings::PM_POST_RESTORE => { + hook.state.control.set_parked(false, true, invalidate) + } _ => return bindings::NOTIFY_DONE as c_int, }; if let Err(e) = ret { dev_warn!( - hook.control.dev, + hook.state.control.dev, "reports not switched for sleep: {:?}\n", e ); @@ -477,7 +1025,7 @@ unsafe impl Send for PmHook {} unsafe impl Sync for PmHook {} impl PmHook { - fn new(control: Arc) -> Result>> { + fn new(state: Arc) -> Result>> { let hook = KBox::pin( Self { nb: Opaque::new(bindings::notifier_block { @@ -485,7 +1033,7 @@ impl PmHook { next: ptr::null_mut(), priority: 0, }), - control, + state, registered: Atomic::new(false), }, GFP_KERNEL, @@ -514,10 +1062,28 @@ impl Drop for PmHook { } struct IIOAopTempDriver { + iio: TempIio, pm: Pin>, - listener: FakehidRegistration, control: Arc, - _iio: TempIio, + listener: FakehidRegistration, +} + +impl IIOAopTempDriver { + fn teardown(&self) { + // Unregister IIO first so no new read_raw or buffer callback can start, + // then unregister PM, stop reports and permanently drain delayed work, + // and finally remove the fake-HID listener. + self.iio.unregister(); + self.pm.unregister(); + let _ = self.control.shutdown(); + self.listener.unregister(); + } +} + +impl Drop for IIOAopTempDriver { + fn drop(&mut self) { + self.teardown(); + } } kernel::of_device_table!( @@ -547,26 +1113,26 @@ impl platform::Driver for IIOAopTempDriver { // SAFETY: The record lives as long as this child device. let service = unsafe { *service }; let control = Control::new(dev, aop.clone(), service)?; - let (mut iio, state) = TempIio::new(pdev)?; - let listener = FakehidRegistration::new(aop, service, state)?; - let pm = PmHook::new(control.clone())?; - control.start()?; - if let Err(e) = iio.register() { - let _ = control.stop(); + let (iio, state) = TempIio::new(dev, control.clone())?; + let listener = FakehidRegistration::new(aop, service, state.clone())?; + let pm = PmHook::new(state)?; + if let Err(e) = control.probe_init() { + pm.unregister(); + let _ = control.shutdown(); return Err(e); } - Ok(IIOAopTempDriver { + let drv = IIOAopTempDriver { + iio, pm, - listener, control, - _iio: iio, - }) + listener, + }; + drv.iio.register()?; + Ok(drv) } fn unbind(_dev: &platform::Device>, this: Pin<&Self>) { - this.pm.unregister(); - let _ = this.control.stop(); - this.listener.unregister(); + this.teardown(); } } diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index a20d283737988..5c908769504b5 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -498,7 +498,7 @@ def mutations(flag, names, base, expect=KILL): # tools/testing/selftests/drivers/apple: the host-runnable harnesses build the # production driver code against host mocks. The others drive real devices. -APPLE_TESTS = ['aop-las.py', 'aop-motion.py', 'atc-t8132-usb3.py', 'bcm4377-dma-window.py', +APPLE_TESTS = ['aop-las.py', 'aop-motion.py', 'aop-temp.py', 'atc-t8132-usb3.py', 'bcm4377-dma-window.py', 'bcm4377-radio-sids.py', 'bcm4377-rti-address.py', 'bcm4377-state-wait.py', 'centauri-t6050-probe.py', 'dart-s2idle-retention.py', 'dwc3-initial-role.py', 'macsmc-j713.py', 'pmgr-inherited.py', 'sn201202x-transport.py'] diff --git a/tools/testing/selftests/drivers/apple/Makefile b/tools/testing/selftests/drivers/apple/Makefile index 7c9bc673e2ec2..54236e8ee01d1 100644 --- a/tools/testing/selftests/drivers/apple/Makefile +++ b/tools/testing/selftests/drivers/apple/Makefile @@ -5,15 +5,16 @@ # dwc3-initial-role.py checks initial host-role admission before core reset. # sn201202x-transport.py checks the production SPMI selection and payload path. # bcm4377 tests exercise DMA ownership, context addresses and firmware handshakes. -# aop-las.py checks the production angle decoder and IIO callback on the host. +# aop-las.py checks the production angle decoder, IIO callback and stream state machine. # aop-motion.py checks the motion report decoder and calibration selector. +# aop-temp.py checks the temperature report decoder and on-demand stream state machine. # centauri-t6050-probe.py checks sibling probe serialization on the build host. # dart-s2idle-retention.py checks the DART resume quarantine against host mocks. # sep-ioctl-fuzz.py feeds malformed /dev/sep-key and /dev/sep-bio requests (root, no finger). TEST_PROGS := macsmc-j713.py atc-t8132-usb3.py pmgr-inherited.py dwc3-initial-role.py \ sn201202x-transport.py bcm4377-dma-window.py bcm4377-radio-sids.py \ bcm4377-state-wait.py bcm4377-rti-address.py aop-las.py \ - aop-motion.py centauri-t6050-probe.py dart-s2idle-retention.py \ + aop-motion.py aop-temp.py centauri-t6050-probe.py dart-s2idle-retention.py \ sep-ioctl-fuzz.py TEST_FILES := j813-peripherals.sh diff --git a/tools/testing/selftests/drivers/apple/aop-temp.py b/tools/testing/selftests/drivers/apple/aop-temp.py new file mode 100755 index 0000000000000..b9aabc02121df --- /dev/null +++ b/tools/testing/selftests/drivers/apple/aop-temp.py @@ -0,0 +1,174 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Run the production AOP temperature decoder, calibration selector, and stream state machine.""" +import os +from pathlib import Path +import shlex +import subprocess +import tempfile + + +def block(source, marker): + start = source.index(marker) + brace = source.index("{", start) + depth = 1 + end = brace + 1 + while depth: + depth += (source[end] == "{") - (source[end] == "}") + end += 1 + return source[start:end] + + +def const(source, name): + start = source.index(f"const {name}") + return source[start:source.index(";", start) + 1] + + +def main(): + root = Path(__file__).resolve().parents[5] + temp = (root / "drivers/iio/common/aop_sensors/aop_temp.rs").read_text() + parts = [ + "#[derive(Clone, Copy, Debug, PartialEq, Eq)]\nstruct Error(i32);", + const(temp, "REPORT_LEN"), + const(temp, "TEMP_OFFSET"), + const(temp, "DIRECT_IDLE_MS"), + block(temp, "fn le_u32("), + block(temp, "fn location0_packet("), + block(temp, "fn decode_millicelsius("), + block(temp, "#[derive(Clone, Copy, Debug, PartialEq, Eq)]\nenum SyncAction"), + block(temp, "#[derive(Clone, Copy, Debug, PartialEq, Eq)]\nenum IdleStep"), + block(temp, "#[derive(Clone, Copy, Debug, PartialEq, Eq)]\nenum RunState"), + block(temp, "struct Stream"), + block(temp, "impl Stream"), + r''' +fn report(q16_16: i32) -> Vec { + let mut r = vec![0u8; REPORT_LEN]; + r[TEMP_OFFSET..TEMP_OFFSET + 4].copy_from_slice(&(q16_16 as u32).to_le_bytes()); + r +} + +#[test] +fn decodes_signed_q16_16_celsius() { + assert_eq!(decode_millicelsius(&report(25 << 16)), Some(25_000)); + assert_eq!(decode_millicelsius(&report((30 << 16) + 32_768)), Some(30_500)); + assert_eq!(decode_millicelsius(&report(-(5 << 16))), Some(-5_000)); + assert_eq!(decode_millicelsius(&vec![0u8; REPORT_LEN - 1]), None); + assert_eq!(decode_millicelsius(&vec![0u8; REPORT_LEN + 1]), None); +} + +#[test] +fn selects_location0_calibration_packet() { + let mut c = vec![2, 0, 2, 1]; + c.extend_from_slice(&3u32.to_le_bytes()); + c.extend_from_slice(&2u32.to_le_bytes()); + c.extend_from_slice(&[0xaa, 0xbb]); + c.extend_from_slice(&0u32.to_le_bytes()); + c.extend_from_slice(&3u32.to_le_bytes()); + c.extend_from_slice(&[1, 2, 3]); + assert_eq!(location0_packet(&c), Some(&[1u8, 2, 3][..])); + assert_eq!(location0_packet(&c[..c.len() - 1]), None); +} + +#[test] +fn calibrates_once_and_idle_stops_direct_reads() { + let mut s = Stream::::new(); + // Before on_demand is enabled, continuous mode wants reports on. + assert_eq!(s.next_action(), SyncAction::Start { calibrate: true }); + + // Probe calibrates once and enables on-demand idle-stop. + s.calibrated = true; + s.on_demand = true; + assert_eq!(s.next_action(), SyncAction::None); + + // Direct read holds direct_readers while waiting, then sets direct_until. + s.direct_readers = 1; + assert_eq!(s.next_action(), SyncAction::Start { calibrate: false }); + s.run_state = RunState::Running; + assert_eq!(s.next_action(), SyncAction::None); + + // Buffer enable then disable during an in-flight direct read keeps stream alive. + s.buffer_on = true; + s.direct_until = None; + assert_eq!(s.next_action(), SyncAction::None); + s.buffer_on = false; + assert_eq!(s.next_action(), SyncAction::None); + + // Idle work firing while direct_readers > 0 rearms instead of stopping. + s.direct_until = Some(5_000); + assert_eq!(s.check_idle(0), IdleStep::RearmMs(DIRECT_IDLE_MS as u32)); + assert_eq!(s.next_action(), SyncAction::None); + + // Reader finishes and quiet passes the deadline -> stops stream. + s.direct_readers = 0; + assert_eq!(s.check_idle(3_000), IdleStep::RearmMs(3_000)); + assert_eq!(s.check_idle(0), IdleStep::Expire); + assert_eq!(s.next_action(), SyncAction::Stop); + s.run_state = RunState::Stopped; + assert_eq!(s.next_action(), SyncAction::None); + + // Unacknowledged stop leaves state Unknown: re-enabling buffer reasserts Start, + // while remaining idle reasserts Stop. + s.run_state = RunState::Unknown; + assert_eq!(s.next_action(), SyncAction::Stop); + s.buffer_on = true; + assert_eq!(s.next_action(), SyncAction::Start { calibrate: false }); +} + +#[test] +fn buffer_and_sleep_transitions() { + let mut s = Stream::::new(); + s.calibrated = true; + s.on_demand = true; + s.buffer_on = true; + assert_eq!(s.next_action(), SyncAction::Start { calibrate: false }); + s.run_state = RunState::Running; + + // Sleep parks active buffer stream. + s.parked = true; + s.direct_until = None; + assert_eq!(s.next_action(), SyncAction::Stop); + s.run_state = RunState::Stopped; + + // Firmware sleep clears calibration and run_state; resume re-calibrates and starts buffer. + s.parked = false; + s.calibrated = false; + s.run_state = RunState::Stopped; + assert_eq!(s.next_action(), SyncAction::Start { calibrate: true }); + s.calibrated = true; + s.run_state = RunState::Running; + + // Disabling buffer stops stream. + s.buffer_on = false; + assert_eq!(s.next_action(), SyncAction::Stop); + s.run_state = RunState::Stopped; + assert_eq!(s.next_action(), SyncAction::None); + + // Continuous fallback (stop refused at probe): stays on after wake without buffer. + s.on_demand = false; + assert_eq!(s.next_action(), SyncAction::Start { calibrate: false }); +} + +#[test] +fn backoff_caps_failed_direct_starts() { + let mut s = Stream::::new(); + s.failed_until = Some((5_000, Error(-5))); + assert_eq!(s.check_backoff(1_000), Some(Error(-5))); + assert_eq!(s.check_backoff(0), None); + assert!(s.failed_until.is_none()); +} +''', + ] + with tempfile.TemporaryDirectory(prefix="aop-temp-") as tmp: + source = Path(tmp) / "test.rs" + binary = Path(tmp) / "test" + source.write_text("\n".join(parts)) + subprocess.run( + shlex.split(os.environ.get("RUSTC", "rustc")) + + ["--edition=2021", "--test", "-Dwarnings", str(source), "-o", str(binary)], + check=True, + ) + subprocess.run([str(binary)], check=True) + + +if __name__ == "__main__": + main() From a54b081f186ff41148d55976ecb4488f6e65d65f Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Fri, 27 Nov 2026 02:29:46 -0500 Subject: [PATCH 2/5] iio: aop_las: stop lid angle reports at idle and start on demand The AOP lid angle firmware streams reports at its default interval (~1 Hz) from boot whether anyone reads in_angl_raw or not, generating continuous AOP mailbox interrupts on an idle desktop. When the service supports reading and clearing PROP_INTERVAL at probe and reports within 2 s, record its interval, stop reports immediately, and start them on demand for in_angl_raw reads (tracking in-flight direct_readers, RunState::{Stopped, Running, Unknown}, waiting interval + 500 ms for a cold sample, holding for a 5 s idle window, backing off after failed starts, and arming a 5 s stop retry whenever an unacknowledged start or stop leaves an idle stream potentially running). Reconcile ambiguous probe stop timeouts and unconditionally restore the pre-probe interval on unbind or probe rollback (clearing the saved interval only after an acknowledged write) so a subsequent rebind never inherits 0. On firmware suspend, hibernation, or restore, clear the interval again on wake while idle in case an AOP restart resumed default streaming. Services whose interval cannot be read or cleared, or exceeds 2 s, keep the passive cached-read and sleep-hook path. Extend aop-las.py to cover the on-demand stream state machine and update Documentation/iio/aop-sensors.rst. Signed-off-by: Erik Bourget --- Documentation/iio/aop-sensors.rst | 20 +- drivers/iio/common/aop_sensors/aop_las.rs | 847 ++++++++++++++++-- .../selftests/drivers/apple/aop-las.py | 61 +- 3 files changed, 854 insertions(+), 74 deletions(-) diff --git a/Documentation/iio/aop-sensors.rst b/Documentation/iio/aop-sensors.rst index 3dcdce2da440f..61356a4bb6a98 100644 --- a/Documentation/iio/aop-sensors.rst +++ b/Documentation/iio/aop-sensors.rst @@ -28,8 +28,11 @@ the first sample; a raw read before the first valid sample returns leave the last valid reading unchanged. Report 1 carries a 9-bit little-endian value following the report ID. -The remaining bits in the last byte are padding. Reads return the cached -unsolicited report, rather than issuing a synchronous HID feature request. +The remaining bits in the last byte are padding. When the service supports +reading and clearing its report interval, reports are stopped at probe and +started on demand for direct ``in_angl_raw`` reads, stopping again after an +idle window so the AOP does not wake the application processor at idle. Services +whose interval cannot be read or cleared fall back to passive cached reads. Accelerometer and gyroscope =========================== @@ -116,16 +119,21 @@ degrees Celsius at offset 2; the driver timestamps it on receipt. The bootloader may provide ``apple,temp-offset-calibration``, ``apple,absolute-temp-offset-cal``, ``apple,absolute-temp-offset-fcm-cal`` and ``apple,absolute-temp-offset-bcm-cal`` containers. Location-zero packets are -sent unchanged before the one-hertz interval. If none are present the driver -warns and selects the firmware's default calibration state; otherwise it -selects the calibrated state. A missing optional calibration therefore does -not hide an otherwise usable sensor. +sent once per AOP boot (and conservatively again after firmware sleep or +hibernation) before enabling the one-hertz interval. Reports stay off while +nobody reads them: enabling the kfifo buffer starts them and disabling it stops +them, while direct ``in_temp_input`` reads start them on demand and stop them +again once reads go quiet. If no calibration containers are present the driver +selects the firmware's default calibration state; otherwise it selects the +calibrated state. A missing optional calibration therefore does not hide an +otherwise usable sensor. Host regression tests require Python 3 and a Rust compiler:: tools/testing/selftests/drivers/apple/aop-las.py tools/testing/selftests/drivers/apple/aop-motion.py + tools/testing/selftests/drivers/apple/aop-temp.py The tests compile the production decoder and shared IIO read callback against host mocks. They cover all 16-bit payloads (including padding), diff --git a/drivers/iio/common/aop_sensors/aop_las.rs b/drivers/iio/common/aop_sensors/aop_las.rs index f8f23e5c0ca40..fd1fbf2a8b6a7 100644 --- a/drivers/iio/common/aop_sensors/aop_las.rs +++ b/drivers/iio/common/aop_sensors/aop_las.rs @@ -3,31 +3,51 @@ //! Apple AOP lid angle sensor driver //! //! Copyright (C) The Asahi Linux Contributors +//! +//! When the service supports reading and clearing its report interval (and +//! reports within `MAX_ONDEMAND_INTERVAL_US`), reports are stopped at probe +//! and run only while direct sysfs reads are active (with a short idle window +//! so polling callers share one stream). Services whose interval cannot be +//! queried or stopped, or whose period is longer than the on-demand bound, +//! keep the passive streaming behaviour and still stop across system sleep +//! when readable. use core::{ ffi::{c_int, c_void}, + marker::PhantomPinned, ptr, }; use kernel::{ bindings, c_str, - device::{self, Core}, - iio::common::aop_sensors::{AopSensorData, IIORegistration, MessageProcessor, MICRO}, - module_platform_driver, of, platform, + device::{self, Bound, Core}, + devres, + iio::common::aop_sensors::{MessageProcessor, MICRO}, + module_platform_driver, new_delayed_work, new_mutex, new_spinlock, of, platform, prelude::*, - soc::apple::aop::{EPICService, FakehidRegistration, AOP}, + soc::apple::aop::{EPICService, FakehidListener, FakehidRegistration, AOP}, sync::{ aref::ARef, atomic::{Atomic, Relaxed}, - Arc, + Arc, Mutex, SpinLock, }, - types::Opaque, + time::{self, delay::fsleep, Delta, Instant, Monotonic}, + types::{ForeignOwnable, Opaque}, + workqueue::{self, impl_has_delayed_work, DelayedWork, Work, WorkItem}, }; const SUBTYPE_SET_PROPERTY: u16 = 4; const SUBTYPE_GET_PROPERTY: u16 = 10; /// The report interval, microseconds; 0 stops the reports. const PROP_INTERVAL: u32 = 0; +/// Maximum firmware period (2 s) eligible for on-demand cold-start waits. +/// Slower services stay passive so direct reads never time out waiting for a +/// multi-second first report. +const MAX_ONDEMAND_INTERVAL_US: u32 = 2_000_000; +/// Polling cadence while waiting for the first report of a fresh start. +const FIRST_SAMPLE_POLL_MS: i64 = 20; +/// How long reports stay on after the last direct read. +const DIRECT_IDLE_MS: i64 = 5_000; /// Writes one u32 property; returns the service's status word. fn set_u32(aop: &dyn AOP, svc: &EPICService, prop: u32, value: u32) -> Result { @@ -47,30 +67,399 @@ fn get_u32(aop: &dyn AOP, svc: &EPICService, prop: u32) -> Result> { if status != 0 || value.len() < 4 { return Ok(None); } - Ok(Some(u32::from_le_bytes([value[0], value[1], value[2], value[3]]))) + Ok(Some(u32::from_le_bytes([ + value[0], value[1], value[2], value[3], + ]))) } -/// Stops the lid angle reports around system sleep and restores them after. -/// -/// The firmware streams the angle at its own interval whether anyone reads -/// it or not, and the AOP mailbox interrupt stays enabled in -/// suspend-to-idle: every report ends the CPUs' idle period. On the J815 a -/// 4 h lid-closed s2idle left the freeze loop 14478 times, once every -/// 0.999 s, with as many AOP mailbox interrupts, after the light sensor -/// already stopped its reports for sleep. Lid open and close come from the -/// SMC, not from this sensor, so a sleeping system still wakes on the lid. -/// -/// The interval the firmware runs at is read when the system sleeps and -/// written back when it wakes; a service that does not answer the read is -/// left alone. Only suspend is handled, as for the light sensor. +/// How long a direct read waits for the first sample after starting `interval_us`. +fn first_sample_wait_ms(interval_us: u32) -> i64 { + i64::from(interval_us.div_ceil(1_000)) + 500 +} + +/// What a stream state change requires from the service. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum SyncAction { + None, + Start(u32), + Stop, +} + +/// Outcome of checking the direct-read idle deadline. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum IdleStep { + /// No direct-read hold to expire. + Ignore, + /// More reads extended the deadline; re-arm the work for this many ms. + RearmMs(u32), + /// The deadline passed; stop the reports if nothing else wants them. + Expire, +} + +/// Observed firmware reporting state. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum RunState { + Stopped, + Running, + /// A start or stop write was not acknowledged; the next transition + /// reasserts the desired interval in either direction. + Unknown, +} + +/// On-demand stream state for lid angle reports. +struct Stream { + /// Firmware's default interval when on-demand gating is supported (`None` + /// when the service cannot be queried/stopped or is slower than + /// `MAX_ONDEMAND_INTERVAL_US`, leaving passive streaming). + interval_us: Option, + /// Pre-probe firmware interval to restore on unbind or probe rollback + /// whenever probe attempted to clear `PROP_INTERVAL`, preserved until + /// restoration is confirmed. + restore_interval: Option, + /// Number of direct reads currently waiting for a sample. + direct_readers: u32, + /// Reports are held on for recent direct reads until this deadline. + direct_until: Option, + /// A start for a direct read failed with this error; direct reads return + /// it without another try until this deadline. + failed_until: Option<(T, Error)>, + /// Set across system sleep and after unbind: no reports. + parked: bool, + /// Current knowledge of whether firmware reports are running. + run_state: RunState, +} + +impl Stream { + const fn new() -> Self { + Self { + interval_us: None, + restore_interval: None, + direct_readers: 0, + direct_until: None, + failed_until: None, + parked: false, + run_state: RunState::Stopped, + } + } + + fn want(&self) -> bool { + self.interval_us.is_some() + && !self.parked + && (self.direct_readers > 0 || self.direct_until.is_some()) + } + + fn next_action(&self) -> SyncAction { + let Some(interval) = self.interval_us else { + return SyncAction::None; + }; + match (self.want(), self.run_state) { + (true, RunState::Stopped | RunState::Unknown) => SyncAction::Start(interval), + (false, RunState::Running | RunState::Unknown) => SyncAction::Stop, + _ => SyncAction::None, + } + } + + fn check_idle(&mut self, remaining_ms: i64) -> IdleStep { + if self.direct_until.is_none() { + return IdleStep::Ignore; + } + if self.parked || self.interval_us.is_none() { + self.direct_until = None; + return IdleStep::Ignore; + } + if self.direct_readers > 0 { + return IdleStep::RearmMs(DIRECT_IDLE_MS as u32); + } + if remaining_ms > 0 { + IdleStep::RearmMs(remaining_ms.clamp(1, DIRECT_IDLE_MS) as u32) + } else { + self.direct_until = None; + IdleStep::Expire + } + } + + fn check_backoff(&mut self, remaining_ms: i64) -> Option { + if remaining_ms <= 0 { + self.failed_until = None; + } + self.failed_until.as_ref().map(|(_, e)| *e) + } +} + +#[pin_data] +struct Control { + dev: ARef, + aop: Arc, + service: EPICService, + #[pin] + stream: Mutex>>, + #[pin] + idle_work: DelayedWork, +} + +impl_has_delayed_work! { + impl HasDelayedWork for Control { self.idle_work } +} + +impl Control { + fn new(dev: &device::Device, aop: Arc, service: EPICService) -> Result> { + Arc::pin_init( + pin_init!(Self { + dev: dev.into(), + aop, + service, + stream <- new_mutex!(Stream::new()), + idle_work <- new_delayed_work!("Control::idle_work"), + }), + GFP_KERNEL, + ) + } + + fn set_interval(&self, interval: u32) -> Result { + match set_u32(self.aop.as_ref(), &self.service, PROP_INTERVAL, interval)? { + 0 => Ok(()), + status => { + dev_err!( + self.dev, + "interval {} us refused: status {:#x}\n", + interval, + status + ); + Err(EIO) + } + } + } + + /// Queries the firmware's reporting interval and stops idle streaming when + /// the service reports within `MAX_ONDEMAND_INTERVAL_US` and accepts + /// `PROP_INTERVAL = 0`. + fn probe_init(&self) { + let mut s = self.stream.lock(); + match get_u32(self.aop.as_ref(), &self.service, PROP_INTERVAL) { + Ok(Some(interval)) if interval > 0 && interval <= MAX_ONDEMAND_INTERVAL_US => { + match set_u32(self.aop.as_ref(), &self.service, PROP_INTERVAL, 0) { + Ok(0) => { + s.interval_us = Some(interval); + s.restore_interval = Some(interval); + s.run_state = RunState::Stopped; + dev_dbg!( + self.dev, + "reports idle-stopped (interval {} us)\n", + interval + ); + } + Ok(status) => dev_info!( + self.dev, + "idle stop refused (status {:#x}); leaving reports on\n", + status + ), + Err(e) => { + // The stop write may have taken effect before the reply + // timed out. Reconcile the live interval and preserve + // the original period so unbind/rebind never inherits 0. + match get_u32(self.aop.as_ref(), &self.service, PROP_INTERVAL) { + Ok(Some(0)) => { + s.interval_us = Some(interval); + s.restore_interval = Some(interval); + s.run_state = RunState::Stopped; + dev_dbg!( + self.dev, + "idle stop timed out ({:?}) but interval is 0; using on-demand mode\n", + e + ); + } + Ok(Some(cur)) if cur > 0 => dev_warn!( + self.dev, + "idle stop failed ({:?}); interval still {} us, leaving passive\n", + e, + cur + ), + _ => { + dev_warn!( + self.dev, + "idle stop ambiguous ({:?}); restoring {} us and leaving passive\n", + e, + interval + ); + match set_u32( + self.aop.as_ref(), + &self.service, + PROP_INTERVAL, + interval, + ) { + Ok(0) => {} + _ => { + s.restore_interval = Some(interval); + s.run_state = RunState::Unknown; + } + } + } + } + } + } + } + Ok(Some(interval)) if interval > MAX_ONDEMAND_INTERVAL_US => dev_dbg!( + self.dev, + "interval {} us exceeds on-demand bound; leaving reports passive\n", + interval + ), + Ok(Some(_)) => dev_dbg!(self.dev, "interval is already 0 at probe\n"), + Ok(None) => dev_dbg!(self.dev, "interval not readable; leaving reports passive\n"), + Err(e) => dev_warn!(self.dev, "interval read failed at probe: {:?}\n", e), + } + } + + fn sync_locked(&self, s: &mut Stream>) -> Result { + match s.next_action() { + SyncAction::Start(interval) => match self.set_interval(interval) { + Ok(()) => { + s.run_state = RunState::Running; + Ok(()) + } + Err(e) => { + s.run_state = RunState::Unknown; + Err(e) + } + }, + SyncAction::Stop => match self.set_interval(0) { + Ok(()) => { + s.run_state = RunState::Stopped; + Ok(()) + } + Err(e) => { + s.run_state = RunState::Unknown; + Err(e) + } + }, + SyncAction::None => Ok(()), + } + } + + /// Arms a rate-limited idle-stop retry whenever an unacknowledged start or + /// stop leaves an idle on-demand stream potentially running. + fn arm_stop_retry_locked(&self, s: &mut Stream>) -> bool { + if s.interval_us.is_some() && !s.want() && s.run_state != RunState::Stopped { + s.direct_until = Some(Instant::::now() + Delta::from_millis(DIRECT_IDLE_MS)); + true + } else { + false + } + } + + fn schedule_idle(self: &Arc, delay_ms: u32) { + let _ = + workqueue::system_dfl().enqueue_delayed(self.clone(), time::msecs_to_jiffies(delay_ms)); + } + + fn stop_idle_sync(self: &Arc, disable: bool) { + // SAFETY: `idle_work` is initialized and pinned in this `Arc`. Both + // helpers cancel pending work and join a running callback; the disable + // variant also prevents any later requeue. + let cancelled = unsafe { + let work = Work::raw_get(DelayedWork::raw_as_work(ptr::addr_of!(self.idle_work))); + let delayed = kernel::container_of!(work, bindings::delayed_work, work); + if disable { + bindings::disable_delayed_work_sync(delayed) + } else { + bindings::cancel_delayed_work_sync(delayed) + } + }; + if cancelled { + // SAFETY: A cancelled pending callback owned exactly one `Arc` + // transferred by `enqueue_delayed`. + drop(unsafe { Arc::from_raw(Arc::as_ptr(self)) }); + } + } + + fn set_parked(self: &Arc, parked: bool, fw_reset: bool) -> Result { + let (ret, retry) = { + let mut s = self.stream.lock(); + if s.interval_us.is_none() { + return Ok(()); + } + s.parked = parked; + s.failed_until = None; + if parked { + s.direct_until = None; + } else if fw_reset { + // Firmware sleep or hibernation may restart the AOP with its + // default streaming interval; stop it again while nobody reads. + s.run_state = RunState::Unknown; + } + let ret = self.sync_locked(&mut s); + let retry = !parked && ret.is_err() && self.arm_stop_retry_locked(&mut s); + (ret, retry) + }; + if parked { + self.stop_idle_sync(false); + } else if retry { + self.schedule_idle(DIRECT_IDLE_MS as u32); + } + ret + } + + /// Permanently drains delayed work and unconditionally restores the + /// pre-probe firmware interval so a subsequent rebind observes the + /// hardware's period even after an unacknowledged idle stop. The saved + /// interval is cleared only once restoration succeeds so a second teardown + /// pass (for example `Drop` after `unbind`) can retry transient failures. + fn shutdown(self: &Arc) -> Result { + self.stop_idle_sync(true); + let mut s = self.stream.lock(); + s.parked = true; + s.direct_until = None; + s.failed_until = None; + if let Some(interval) = s.restore_interval { + self.set_interval(interval)?; + s.run_state = RunState::Running; + s.restore_interval = None; + s.interval_us = None; + } + Ok(()) + } +} + +impl WorkItem for Control { + type Pointer = Arc; + + fn run(this: Arc) { + let retry = { + let mut s = this.stream.lock(); + let Some(deadline) = s.direct_until else { + return; + }; + let remaining_ms = (deadline - Instant::::now()).as_millis_ceil(); + match s.check_idle(remaining_ms) { + IdleStep::Ignore => None, + IdleStep::RearmMs(delay_ms) => Some(delay_ms), + IdleStep::Expire => match this.sync_locked(&mut s) { + Ok(()) => None, + Err(e) => { + dev_warn!(this.dev, "reports not stopped after idle: {:?}\n", e); + if this.arm_stop_retry_locked(&mut s) { + Some(DIRECT_IDLE_MS as u32) + } else { + None + } + } + }, + } + }; + if let Some(delay_ms) = retry { + this.schedule_idle(delay_ms); + } + } +} + +/// Stops any active lid angle reports around system sleep and keeps them off +/// after wake while nobody reads them. #[repr(C)] struct PmHook { /// First, so that the callback finds the hook from it. nb: Opaque, - dev: ARef, - aop: Arc, - service: EPICService, - /// The interval to restore after the sleep; 0 when nothing was stopped. + control: Arc, + /// Fallback interval to restore after sleep when on-demand mode is not + /// active; 0 when nothing was stopped on the fallback path. saved: Atomic, registered: Atomic, } @@ -79,7 +468,7 @@ struct PmHook { /// /// # Safety /// -/// `nb` is the notifier block of a registered [`PmHook`]. +/// `nb` is the first field of a registered [`PmHook`]. unsafe extern "C" fn pm_event( nb: *mut bindings::notifier_block, action: usize, @@ -87,36 +476,69 @@ unsafe extern "C" fn pm_event( ) -> c_int { // SAFETY: `nb` is the first field of a registered `PmHook`. let hook = unsafe { &*nb.cast::() }; - let aop = hook.aop.as_ref(); + let on_demand = hook.control.stream.lock().interval_us.is_some(); + if on_demand { + let ret = match action as u32 { + bindings::PM_SUSPEND_PREPARE + | bindings::PM_HIBERNATION_PREPARE + | bindings::PM_RESTORE_PREPARE => hook.control.set_parked(true, false), + bindings::PM_POST_SUSPEND => { + // SAFETY: Reads the PM core's sleep-transition flag. + let fw_sleep = unsafe { bindings::pm_suspend_via_firmware() }; + hook.control.set_parked(false, fw_sleep) + } + bindings::PM_POST_HIBERNATION | bindings::PM_POST_RESTORE => { + hook.control.set_parked(false, true) + } + _ => return bindings::NOTIFY_DONE as c_int, + }; + if let Err(e) = ret { + dev_warn!( + hook.control.dev, + "reports not switched for sleep: {:?}\n", + e + ); + } + return bindings::NOTIFY_OK as c_int; + } + + let aop = hook.control.aop.as_ref(); match action as u32 { - bindings::PM_SUSPEND_PREPARE => match get_u32(aop, &hook.service, PROP_INTERVAL) { + bindings::PM_SUSPEND_PREPARE => match get_u32(aop, &hook.control.service, PROP_INTERVAL) { Ok(Some(0)) => {} - Ok(Some(interval)) => match set_u32(aop, &hook.service, PROP_INTERVAL, 0) { + Ok(Some(interval)) => match set_u32(aop, &hook.control.service, PROP_INTERVAL, 0) { Ok(status) => { hook.saved.store(interval, Relaxed); dev_info!( - hook.dev, + hook.control.dev, "reports off for sleep (interval {} us): status {:#x}\n", interval, status ); } - Err(e) => dev_warn!(hook.dev, "reports not stopped for sleep: {:?}\n", e), + Err(e) => dev_warn!(hook.control.dev, "reports not stopped for sleep: {:?}\n", e), }, - Ok(None) => dev_info!(hook.dev, "interval not readable: reports left on for sleep\n"), - Err(e) => dev_warn!(hook.dev, "interval read failed: {:?}\n", e), + Ok(None) => dev_info!( + hook.control.dev, + "interval not readable: reports left on for sleep\n" + ), + Err(e) => dev_warn!(hook.control.dev, "interval read failed: {:?}\n", e), }, bindings::PM_POST_SUSPEND => { let interval = hook.saved.xchg(0, Relaxed); if interval != 0 { - match set_u32(aop, &hook.service, PROP_INTERVAL, interval) { + match set_u32(aop, &hook.control.service, PROP_INTERVAL, interval) { Ok(status) => dev_info!( - hook.dev, + hook.control.dev, "reports back after sleep (interval {} us): status {:#x}\n", interval, status ), - Err(e) => dev_warn!(hook.dev, "reports not restarted after sleep: {:?}\n", e), + Err(e) => dev_warn!( + hook.control.dev, + "reports not restarted after sleep: {:?}\n", + e + ), } } } @@ -166,11 +588,7 @@ unsafe impl Send for PmHook {} unsafe impl Sync for PmHook {} impl PmHook { - fn new( - dev: &device::Device, - aop: Arc, - service: EPICService, - ) -> Result>> { + fn new(control: Arc) -> Result>> { let hook = KBox::pin( Self { nb: Opaque::new(bindings::notifier_block { @@ -178,9 +596,7 @@ impl PmHook { next: ptr::null_mut(), priority: 0, }), - dev: dev.into(), - aop, - service, + control, saved: Atomic::new(0), registered: Atomic::new(false), }, @@ -234,12 +650,317 @@ impl MessageProcessor for MsgProc { } } +#[derive(Clone, Copy, Default)] +struct Sample { + angle: i32, + valid: bool, +} + +#[pin_data] +struct State { + control: Arc, + #[pin] + sample: SpinLock, +} + +impl FakehidListener for State { + fn process_fakehid_report(&self, data: &[u8]) -> Result<()> { + if let Some(micro) = MsgProc.process(data) { + *self.sample.lock() = Sample { + angle: (micro / MICRO) as i32, + valid: true, + }; + } + Ok(()) + } +} + +/// Keeps `direct_readers` accounted for across `read_now()`, and arms the +/// idle-stop deadline once the reader finishes. +struct DirectReadGuard<'a>(&'a Arc); + +impl Drop for DirectReadGuard<'_> { + fn drop(&mut self) { + let schedule = { + let mut s = self.0.stream.lock(); + s.direct_readers = s.direct_readers.saturating_sub(1); + if s.interval_us.is_some() && !s.parked { + s.direct_until = + Some(Instant::::now() + Delta::from_millis(DIRECT_IDLE_MS)); + true + } else { + false + } + }; + if schedule { + self.0.schedule_idle(DIRECT_IDLE_MS as u32); + } + } +} + +impl State { + fn read_now(&self) -> Result { + let (max_wait, guard) = { + let mut s = self.control.stream.lock(); + let Some(interval) = s.interval_us else { + drop(s); + let sample = *self.sample.lock(); + return if sample.valid { + Ok(sample.angle) + } else { + Err(ENODATA) + }; + }; + if s.parked { + return Err(EBUSY); + } + if let Some((until, _)) = s.failed_until { + let remaining_ms = (until - Instant::::now()).as_millis_ceil(); + if let Some(e) = s.check_backoff(remaining_ms) { + return Err(e); + } + } + if s.run_state != RunState::Running { + // A sample from an earlier start may be stale. + self.sample.lock().valid = false; + } + s.direct_readers += 1; + if let Err(e) = self.control.sync_locked(&mut s) { + s.direct_readers = s.direct_readers.saturating_sub(1); + let until = Instant::::now() + Delta::from_millis(DIRECT_IDLE_MS); + s.failed_until = Some((until, e)); + let retry = self.control.arm_stop_retry_locked(&mut s); + drop(s); + if retry { + self.control.schedule_idle(DIRECT_IDLE_MS as u32); + } + return Err(e); + } + ( + first_sample_wait_ms(interval), + DirectReadGuard(&self.control), + ) + }; + + let mut waited = 0; + while waited < max_wait && !self.sample.lock().valid { + if self.control.stream.lock().parked { + return Err(EBUSY); + } + fsleep(Delta::from_millis(FIRST_SAMPLE_POLL_MS)); + waited += FIRST_SAMPLE_POLL_MS; + } + let sample = *self.sample.lock(); + drop(guard); + if sample.valid { + Ok(sample.angle) + } else { + Err(ENODATA) + } + } +} + +/// # Safety +/// +/// The IIO core supplies the registered device and output pointers. +unsafe extern "C" fn las_read_raw( + indio_dev: *mut bindings::iio_dev, + chan: *const bindings::iio_chan_spec, + val: *mut i32, + val2: *mut i32, + mask: isize, +) -> i32 { + // SAFETY: `priv_` is the `Arc` installed by `LasIio::new()`. + let state = unsafe { Arc::::borrow((*indio_dev).priv_.cast()) }; + // SAFETY: `chan` is the registered channel spec. + if unsafe { (*chan).type_ != bindings::BINDINGS_IIO_ANGL || (*chan).address != 0 } { + return EINVAL.to_errno(); + } + if mask == bindings::BINDINGS_IIO_CHAN_INFO_SCALE as isize { + let Some((int, frac)) = MsgProc.scale() else { + return EINVAL.to_errno(); + }; + // SAFETY: The pointers are the caller's result variables. + unsafe { + *val = int; + *val2 = frac; + } + return bindings::IIO_VAL_INT_PLUS_NANO as i32; + } + if mask != bindings::BINDINGS_IIO_CHAN_INFO_RAW as isize { + return EINVAL.to_errno(); + } + let angle = match state.read_now() { + Ok(angle) => angle, + Err(e) => return e.to_errno(), + }; + // SAFETY: The pointers are the caller's result variables. + unsafe { + *val = angle; + *val2 = 0; + } + bindings::IIO_VAL_INT as i32 +} + +struct Spec { + channels: [bindings::iio_chan_spec; 1], + info: bindings::iio_info, + _p: PhantomPinned, +} + +struct IioAlloc { + dev: *mut bindings::iio_dev, + _spec: Pin>, +} + +impl Drop for IioAlloc { + fn drop(&mut self) { + // SAFETY: `self.dev` was allocated in `LasIio::new()` with an + // `Arc` as its private data and has been unregistered. + unsafe { + drop(Arc::::from_foreign((*self.dev).priv_.cast())); + bindings::iio_device_free(self.dev); + } + } +} + +// SAFETY: The IIO device may be freed from any thread, and the channel +// table is only read. +unsafe impl Send for IioAlloc {} + +struct LasIio { + dev: *mut bindings::iio_dev, + registered: Atomic, +} + +impl LasIio { + fn new(dev: &device::Device, control: Arc) -> Result<(Self, Arc)> { + let info_mask = (1usize << bindings::BINDINGS_IIO_CHAN_INFO_RAW) + | (1usize << bindings::BINDINGS_IIO_CHAN_INFO_SCALE); + let spec = KBox::pin( + Spec { + channels: [bindings::iio_chan_spec { + type_: bindings::BINDINGS_IIO_ANGL, + address: 0, + __bindgen_anon_1: bindings::iio_chan_spec__bindgen_ty_1 { + scan_type: bindings::iio_scan_type { + __bindgen_anon_1: bindings::iio_scan_type__bindgen_ty_1 { + format: b'u' as _, + }, + realbits: 32, + storagebits: 32, + ..Default::default() + }, + }, + info_mask_separate: info_mask, + ..Default::default() + }], + info: bindings::iio_info { + read_raw: Some(las_read_raw), + ..Default::default() + }, + _p: PhantomPinned, + }, + GFP_KERNEL, + )?; + // SAFETY: `dev` is valid. + let indio_dev = unsafe { bindings::iio_device_alloc(dev.as_raw(), 0) }; + if indio_dev.is_null() { + return Err(ENOMEM); + } + let state = match Arc::pin_init( + pin_init!(State { + control, + sample <- new_spinlock!(Sample::default()), + }), + GFP_KERNEL, + ) { + Ok(state) => state, + Err(e) => { + // SAFETY: Allocated above and not registered. + unsafe { bindings::iio_device_free(indio_dev) }; + return Err(e); + } + }; + // SAFETY: The IIO device is unregistered and `spec` is pinned. + unsafe { + (*indio_dev).priv_ = state.clone().into_foreign().cast(); + (*indio_dev).name = c"aop-sensors-las".as_char_ptr(); + (*indio_dev).channels = spec.channels.as_ptr(); + (*indio_dev).num_channels = spec.channels.len() as i32; + (*indio_dev).info = &spec.info; + } + devres::register( + dev, + IioAlloc { + dev: indio_dev, + _spec: spec, + }, + GFP_KERNEL, + )?; + Ok(( + Self { + dev: indio_dev, + registered: Atomic::new(false), + }, + state, + )) + } + + fn register(&self) -> Result { + let module = kernel::module::this_module::(); + // SAFETY: The device is fully initialized and unregistered. + let ret = unsafe { bindings::__iio_device_register(self.dev, module.as_ptr()) }; + if ret < 0 { + return Err(Error::from_errno(ret)); + } + self.registered.store(true, Relaxed); + Ok(()) + } + + fn unregister(&self) { + if self.registered.xchg(false, Relaxed) { + // SAFETY: `self.dev` was registered by `register()` and is freed + // with the platform device's resources. + unsafe { bindings::iio_device_unregister(self.dev) }; + } + } +} + +impl Drop for LasIio { + fn drop(&mut self) { + self.unregister(); + } +} + +// SAFETY: The IIO core serializes registration and removal. +unsafe impl Send for LasIio {} +// SAFETY: As above. +unsafe impl Sync for LasIio {} + struct IIOAopLasDriver { - /// Fields are declared in teardown order: sleep handling first, then the - /// subscription, which ends before the IIO device goes. + iio: LasIio, pm: Pin>, + control: Arc, listener: FakehidRegistration, - _iio: IIORegistration, +} + +impl IIOAopLasDriver { + fn teardown(&self) { + // Unregister IIO first so no new read_raw can start, then unregister + // PM, drain delayed work and restore the pre-probe firmware interval, + // and finally remove the fake-HID listener. + self.iio.unregister(); + self.pm.unregister(); + let _ = self.control.shutdown(); + self.listener.unregister(); + } +} + +impl Drop for IIOAopLasDriver { + fn drop(&mut self) { + self.teardown(); + } } kernel::of_device_table!( @@ -259,7 +980,7 @@ impl platform::Driver for IIOAopLasDriver { _info: Option<&'bound ()>, ) -> impl PinInit, Error> + 'bound { let dev = pdev.as_ref(); - // SAFETY: This driver binds only to the service devices the AOP core + // SAFETY: This binds only to the service devices the AOP core // registers, and `pdev` is being probed. let adata = unsafe { ::from_child(dev) }?; // SAFETY: `dev` is a valid device; the AOP core attached its service @@ -268,32 +989,26 @@ impl platform::Driver for IIOAopLasDriver { if service.is_null() { return Err(ENODEV); } - // SAFETY: The record lives as long as the device it is attached to. + // SAFETY: The record lives as long as this child device. let service = unsafe { *service }; - let ty = bindings::BINDINGS_IIO_ANGL; - let data = AopSensorData::new(dev.into(), ty, MsgProc)?; - let listener = FakehidRegistration::new(adata.clone(), service, data.clone())?; - let info_mask = (1 << bindings::BINDINGS_IIO_CHAN_INFO_RAW) - | (1 << bindings::BINDINGS_IIO_CHAN_INFO_SCALE); - let iio = IIORegistration::::new( - data, - c"aop-sensors-las", - ty, - info_mask, - kernel::module::this_module::(), - )?; - let pm = PmHook::new(dev, adata, service)?; - Ok(IIOAopLasDriver { + let control = Control::new(dev, adata.clone(), service)?; + let (iio, state) = LasIio::new(dev, control.clone())?; + let listener = FakehidRegistration::new(adata, service, state)?; + let pm = PmHook::new(control.clone())?; + control.probe_init(); + let drv = IIOAopLasDriver { + iio, pm, + control, listener, - _iio: iio, - }) + }; + drv.iio.register()?; + Ok(drv) } fn unbind(_dev: &platform::Device>, this: Pin<&Self>) { - this.pm.unregister(); - this.listener.unregister(); + this.teardown(); } } diff --git a/tools/testing/selftests/drivers/apple/aop-las.py b/tools/testing/selftests/drivers/apple/aop-las.py index e1ffd7db3cfea..88e8c40c6e7e9 100755 --- a/tools/testing/selftests/drivers/apple/aop-las.py +++ b/tools/testing/selftests/drivers/apple/aop-las.py @@ -19,6 +19,11 @@ def block(source, marker): return source[start:end] +def const(source, name): + start = source.index(f"const {name}") + return source[start:source.index(";", start) + 1] + + def main(): root = Path(__file__).resolve().parents[5] common = (root / "rust/kernel/iio/common/aop_sensors.rs").read_text() @@ -28,7 +33,7 @@ def main(): use std::sync::atomic::Ordering::{Acquire, Relaxed, Release}; const MICRO: u64 = 1_000_000; const MAX_MICRO: u64 = i32::MAX as u64 * MICRO + MICRO - 1; -#[derive(Debug)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] struct Error(i32); impl Error { fn to_errno(&self) -> i32 { self.0 } } const EINVAL: Error = Error(-22); @@ -64,7 +69,14 @@ def main(): ty: [u32; N], value: [Atomic; N], valid: [Atomic; N], msg_proc: T, } struct MsgProc; -''', block(common, "pub trait MessageProcessor"), +''', const(las, "DIRECT_IDLE_MS"), + block(las, "fn first_sample_wait_ms("), + block(las, "#[derive(Clone, Copy, Debug, PartialEq, Eq)]\nenum SyncAction"), + block(las, "#[derive(Clone, Copy, Debug, PartialEq, Eq)]\nenum IdleStep"), + block(las, "#[derive(Clone, Copy, Debug, PartialEq, Eq)]\nenum RunState"), + block(las, "struct Stream"), + block(las, "impl Stream"), + block(common, "pub trait MessageProcessor"), block(las, "impl MessageProcessor for MsgProc"), block(common, "impl FakehidListener"), block(common, 'unsafe extern "C" fn aop_read_raw'), r''' @@ -142,6 +154,51 @@ def main(): assert_eq!(read(&data, BINDINGS_IIO_CHAN_INFO_SCALE).0, -22); assert_eq!(read(&data, 999).0, -22); } +#[test] +fn on_demand_stream_lifecycle_and_passive_fallback() { + assert_eq!(first_sample_wait_ms(100_000), 600); + assert_eq!(first_sample_wait_ms(1_000_000), 1_500); + assert_eq!(first_sample_wait_ms(2_000_000), 2_500); + + // Passive fallback (interval unreadable): never emits start/stop actions. + let mut passive = Stream::::new(); + passive.direct_until = Some(5_000); + assert_eq!(passive.next_action(), SyncAction::None); + assert_eq!(passive.check_idle(0), IdleStep::Ignore); + + // On-demand lifecycle: idle off -> in-flight read starts -> idle rearms while reading -> expires -> stops. + let mut s = Stream::::new(); + s.interval_us = Some(1_000_000); + s.restore_interval = Some(1_000_000); + assert_eq!(s.restore_interval, Some(1_000_000)); + assert_eq!(s.next_action(), SyncAction::None); + s.direct_readers = 1; + assert_eq!(s.next_action(), SyncAction::Start(1_000_000)); + s.run_state = RunState::Running; + s.direct_until = Some(5_000); + assert_eq!(s.check_idle(0), IdleStep::RearmMs(DIRECT_IDLE_MS as u32)); + s.direct_readers = 0; + assert_eq!(s.check_idle(2_000), IdleStep::RearmMs(2_000)); + assert_eq!(s.check_idle(0), IdleStep::Expire); + assert_eq!(s.next_action(), SyncAction::Stop); + s.run_state = RunState::Stopped; + assert_eq!(s.next_action(), SyncAction::None); + + // Firmware reset on wake or unacknowledged stop marks Unknown: + // idle reasserts Stop, while a new reader reasserts Start. + s.parked = false; + s.run_state = RunState::Unknown; + assert_eq!(s.next_action(), SyncAction::Stop); + s.direct_readers = 1; + assert_eq!(s.next_action(), SyncAction::Start(1_000_000)); + s.direct_readers = 0; + s.run_state = RunState::Stopped; + + // Failed start backoff. + s.failed_until = Some((5_000, Error(-5))); + assert_eq!(s.check_backoff(500), Some(Error(-5))); + assert_eq!(s.check_backoff(0), None); +} '''] with tempfile.TemporaryDirectory(prefix="aop-las-") as tmp: source = Path(tmp) / "test.rs" From cf2c1f844ddb4cc4036d88bee4d8a719b364a24f Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Fri, 27 Nov 2026 13:04:31 -0500 Subject: [PATCH 3/5] iio: aop_las: keep ambiguous probe stop-restore failure recoverable When the probe stop write times out, readback fails, and the fallback restore of the pre-probe interval also fails, firmware may have already applied interval 0. Leaving interval_us unset put read_now() on the passive cache path, where it never restarted reports and only teardown retried restoring restore_interval. Extract Stream::{probe_with, sync_with, shutdown_with} over an IntervalIo trait, set interval_us = Some(interval) alongside restore_interval and RunState::Unknown when both readback and restore fail, and arm the idle stop retry so either the next direct read restarts reports or the idle timer reconciles the stopped state. Extend aop-las.py with a mock IntervalIo test covering an applied stop with a lost reply, failed readback, and failed/refused first restore followed by direct-read and idle-retry recovery. Signed-off-by: Erik Bourget --- drivers/iio/common/aop_sensors/aop_las.rs | 323 +++++++++++------- .../selftests/drivers/apple/aop-las.py | 161 ++++++++- 2 files changed, 361 insertions(+), 123 deletions(-) diff --git a/drivers/iio/common/aop_sensors/aop_las.rs b/drivers/iio/common/aop_sensors/aop_las.rs index fd1fbf2a8b6a7..4c30d05939d1c 100644 --- a/drivers/iio/common/aop_sensors/aop_las.rs +++ b/drivers/iio/common/aop_sensors/aop_las.rs @@ -106,6 +106,28 @@ enum RunState { Unknown, } +/// Firmware property transport needed by stream lifecycle transitions. +trait IntervalIo { + fn get_interval(&self) -> Result>; + fn set_interval_status(&self, interval: u32) -> Result; + fn set_interval(&self, interval: u32) -> Result; +} + +/// Outcome of [`Stream::probe_with`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum ProbeEvent { + IdleStopped(u32), + StopRefused(u32), + StopTimedOutStopped(Error), + StopFailedStillRunning(Error, u32), + StopAmbiguousRestored(Error, u32), + StopAmbiguousRecoverable(Error, u32), + ExceedsBound(u32), + AlreadyZero, + NotReadable, + ReadFailed(Error), +} + /// On-demand stream state for lid angle reports. struct Stream { /// Firmware's default interval when on-demand gating is supported (`None` @@ -184,6 +206,109 @@ impl Stream { } self.failed_until.as_ref().map(|(_, e)| *e) } + + /// Arms a rate-limited idle-stop retry whenever an unacknowledged start or + /// stop leaves an idle on-demand stream potentially running. + fn arm_stop_retry(&mut self, deadline: T) -> bool { + if self.interval_us.is_some() && !self.want() && self.run_state != RunState::Stopped { + self.direct_until = Some(deadline); + true + } else { + false + } + } + + fn sync_with(&mut self, io: &dyn IntervalIo) -> Result { + match self.next_action() { + SyncAction::Start(interval) => match io.set_interval(interval) { + Ok(()) => { + self.run_state = RunState::Running; + Ok(()) + } + Err(e) => { + self.run_state = RunState::Unknown; + Err(e) + } + }, + SyncAction::Stop => match io.set_interval(0) { + Ok(()) => { + self.run_state = RunState::Stopped; + Ok(()) + } + Err(e) => { + self.run_state = RunState::Unknown; + Err(e) + } + }, + SyncAction::None => Ok(()), + } + } + + /// Queries the firmware's reporting interval and stops idle streaming when + /// the service reports within `MAX_ONDEMAND_INTERVAL_US` and accepts + /// `PROP_INTERVAL = 0`. + fn probe_with(&mut self, io: &dyn IntervalIo, retry_deadline: T) -> (ProbeEvent, bool) { + match io.get_interval() { + Ok(Some(interval)) if interval > 0 && interval <= MAX_ONDEMAND_INTERVAL_US => { + match io.set_interval_status(0) { + Ok(0) => { + self.interval_us = Some(interval); + self.restore_interval = Some(interval); + self.run_state = RunState::Stopped; + (ProbeEvent::IdleStopped(interval), false) + } + Ok(status) => (ProbeEvent::StopRefused(status), false), + Err(e) => match io.get_interval() { + // The stop write may have taken effect before the reply + // timed out. Reconcile the live interval and preserve + // the original period so unbind/rebind never inherits 0. + Ok(Some(0)) => { + self.interval_us = Some(interval); + self.restore_interval = Some(interval); + self.run_state = RunState::Stopped; + (ProbeEvent::StopTimedOutStopped(e), false) + } + Ok(Some(cur)) if cur > 0 => { + (ProbeEvent::StopFailedStillRunning(e, cur), false) + } + _ => match io.set_interval_status(interval) { + Ok(0) => (ProbeEvent::StopAmbiguousRestored(e, interval), false), + _ => { + // Both readback and passive restoration failed; + // keep on-demand mode from Unknown so direct + // reads restart reports and idle retry stops + // them instead of stranding passive ENODATA. + self.interval_us = Some(interval); + self.restore_interval = Some(interval); + self.run_state = RunState::Unknown; + let retry = self.arm_stop_retry(retry_deadline); + (ProbeEvent::StopAmbiguousRecoverable(e, interval), retry) + } + }, + }, + } + } + Ok(Some(interval)) if interval > MAX_ONDEMAND_INTERVAL_US => { + (ProbeEvent::ExceedsBound(interval), false) + } + Ok(Some(_)) => (ProbeEvent::AlreadyZero, false), + Ok(None) => (ProbeEvent::NotReadable, false), + Err(e) => (ProbeEvent::ReadFailed(e), false), + } + } + + fn shutdown_with(&mut self, io: &dyn IntervalIo) -> Result { + self.parked = true; + self.direct_until = None; + self.failed_until = None; + if let Some(interval) = self.restore_interval { + io.set_interval(interval)?; + self.run_state = RunState::Running; + self.restore_interval = None; + self.interval_us = None; + } + Ok(()) + } } #[pin_data] @@ -201,22 +326,17 @@ impl_has_delayed_work! { impl HasDelayedWork for Control { self.idle_work } } -impl Control { - fn new(dev: &device::Device, aop: Arc, service: EPICService) -> Result> { - Arc::pin_init( - pin_init!(Self { - dev: dev.into(), - aop, - service, - stream <- new_mutex!(Stream::new()), - idle_work <- new_delayed_work!("Control::idle_work"), - }), - GFP_KERNEL, - ) +impl IntervalIo for Control { + fn get_interval(&self) -> Result> { + get_u32(self.aop.as_ref(), &self.service, PROP_INTERVAL) + } + + fn set_interval_status(&self, interval: u32) -> Result { + set_u32(self.aop.as_ref(), &self.service, PROP_INTERVAL, interval) } fn set_interval(&self, interval: u32) -> Result { - match set_u32(self.aop.as_ref(), &self.service, PROP_INTERVAL, interval)? { + match self.set_interval_status(interval)? { 0 => Ok(()), status => { dev_err!( @@ -229,121 +349,91 @@ impl Control { } } } +} + +impl Control { + fn new(dev: &device::Device, aop: Arc, service: EPICService) -> Result> { + Arc::pin_init( + pin_init!(Self { + dev: dev.into(), + aop, + service, + stream <- new_mutex!(Stream::new()), + idle_work <- new_delayed_work!("Control::idle_work"), + }), + GFP_KERNEL, + ) + } /// Queries the firmware's reporting interval and stops idle streaming when /// the service reports within `MAX_ONDEMAND_INTERVAL_US` and accepts /// `PROP_INTERVAL = 0`. - fn probe_init(&self) { - let mut s = self.stream.lock(); - match get_u32(self.aop.as_ref(), &self.service, PROP_INTERVAL) { - Ok(Some(interval)) if interval > 0 && interval <= MAX_ONDEMAND_INTERVAL_US => { - match set_u32(self.aop.as_ref(), &self.service, PROP_INTERVAL, 0) { - Ok(0) => { - s.interval_us = Some(interval); - s.restore_interval = Some(interval); - s.run_state = RunState::Stopped; - dev_dbg!( - self.dev, - "reports idle-stopped (interval {} us)\n", - interval - ); - } - Ok(status) => dev_info!( - self.dev, - "idle stop refused (status {:#x}); leaving reports on\n", - status - ), - Err(e) => { - // The stop write may have taken effect before the reply - // timed out. Reconcile the live interval and preserve - // the original period so unbind/rebind never inherits 0. - match get_u32(self.aop.as_ref(), &self.service, PROP_INTERVAL) { - Ok(Some(0)) => { - s.interval_us = Some(interval); - s.restore_interval = Some(interval); - s.run_state = RunState::Stopped; - dev_dbg!( - self.dev, - "idle stop timed out ({:?}) but interval is 0; using on-demand mode\n", - e - ); - } - Ok(Some(cur)) if cur > 0 => dev_warn!( - self.dev, - "idle stop failed ({:?}); interval still {} us, leaving passive\n", - e, - cur - ), - _ => { - dev_warn!( - self.dev, - "idle stop ambiguous ({:?}); restoring {} us and leaving passive\n", - e, - interval - ); - match set_u32( - self.aop.as_ref(), - &self.service, - PROP_INTERVAL, - interval, - ) { - Ok(0) => {} - _ => { - s.restore_interval = Some(interval); - s.run_state = RunState::Unknown; - } - } - } - } - } - } - } - Ok(Some(interval)) if interval > MAX_ONDEMAND_INTERVAL_US => dev_dbg!( + fn probe_init(self: &Arc) { + let (event, retry) = { + let mut s = self.stream.lock(); + let retry_deadline = Instant::::now() + Delta::from_millis(DIRECT_IDLE_MS); + s.probe_with(self.as_ref(), retry_deadline) + }; + match event { + ProbeEvent::IdleStopped(interval) => dev_dbg!( + self.dev, + "reports idle-stopped (interval {} us)\n", + interval + ), + ProbeEvent::StopRefused(status) => dev_info!( + self.dev, + "idle stop refused (status {:#x}); leaving reports on\n", + status + ), + ProbeEvent::StopTimedOutStopped(e) => dev_dbg!( + self.dev, + "idle stop timed out ({:?}) but interval is 0; using on-demand mode\n", + e + ), + ProbeEvent::StopFailedStillRunning(e, cur) => dev_warn!( + self.dev, + "idle stop failed ({:?}); interval still {} us, leaving passive\n", + e, + cur + ), + ProbeEvent::StopAmbiguousRestored(e, interval) => dev_warn!( + self.dev, + "idle stop ambiguous ({:?}); restored {} us, leaving passive\n", + e, + interval + ), + ProbeEvent::StopAmbiguousRecoverable(e, interval) => dev_warn!( + self.dev, + "idle stop ambiguous ({:?}) and restore of {} us failed; keeping on-demand mode from unknown state\n", + e, + interval + ), + ProbeEvent::ExceedsBound(interval) => dev_dbg!( self.dev, "interval {} us exceeds on-demand bound; leaving reports passive\n", interval ), - Ok(Some(_)) => dev_dbg!(self.dev, "interval is already 0 at probe\n"), - Ok(None) => dev_dbg!(self.dev, "interval not readable; leaving reports passive\n"), - Err(e) => dev_warn!(self.dev, "interval read failed at probe: {:?}\n", e), + ProbeEvent::AlreadyZero => dev_dbg!(self.dev, "interval is already 0 at probe\n"), + ProbeEvent::NotReadable => { + dev_dbg!(self.dev, "interval not readable; leaving reports passive\n") + } + ProbeEvent::ReadFailed(e) => { + dev_warn!(self.dev, "interval read failed at probe: {:?}\n", e) + } + } + if retry { + self.schedule_idle(DIRECT_IDLE_MS as u32); } } fn sync_locked(&self, s: &mut Stream>) -> Result { - match s.next_action() { - SyncAction::Start(interval) => match self.set_interval(interval) { - Ok(()) => { - s.run_state = RunState::Running; - Ok(()) - } - Err(e) => { - s.run_state = RunState::Unknown; - Err(e) - } - }, - SyncAction::Stop => match self.set_interval(0) { - Ok(()) => { - s.run_state = RunState::Stopped; - Ok(()) - } - Err(e) => { - s.run_state = RunState::Unknown; - Err(e) - } - }, - SyncAction::None => Ok(()), - } + s.sync_with(self) } /// Arms a rate-limited idle-stop retry whenever an unacknowledged start or /// stop leaves an idle on-demand stream potentially running. fn arm_stop_retry_locked(&self, s: &mut Stream>) -> bool { - if s.interval_us.is_some() && !s.want() && s.run_state != RunState::Stopped { - s.direct_until = Some(Instant::::now() + Delta::from_millis(DIRECT_IDLE_MS)); - true - } else { - false - } + s.arm_stop_retry(Instant::::now() + Delta::from_millis(DIRECT_IDLE_MS)) } fn schedule_idle(self: &Arc, delay_ms: u32) { @@ -406,16 +496,7 @@ impl Control { fn shutdown(self: &Arc) -> Result { self.stop_idle_sync(true); let mut s = self.stream.lock(); - s.parked = true; - s.direct_until = None; - s.failed_until = None; - if let Some(interval) = s.restore_interval { - self.set_interval(interval)?; - s.run_state = RunState::Running; - s.restore_interval = None; - s.interval_us = None; - } - Ok(()) + s.shutdown_with(self.as_ref()) } } diff --git a/tools/testing/selftests/drivers/apple/aop-las.py b/tools/testing/selftests/drivers/apple/aop-las.py index 88e8c40c6e7e9..aefccb4a325f2 100755 --- a/tools/testing/selftests/drivers/apple/aop-las.py +++ b/tools/testing/selftests/drivers/apple/aop-las.py @@ -38,7 +38,9 @@ def main(): impl Error { fn to_errno(&self) -> i32 { self.0 } } const EINVAL: Error = Error(-22); const ENODATA: Error = Error(-61); -type Result = std::result::Result; +const EIO: Error = Error(-5); +const ETIMEDOUT: Error = Error(-110); +type Result = std::result::Result; mod bindings { pub const BINDINGS_IIO_CHAN_INFO_RAW: u32 = 0; pub const BINDINGS_IIO_CHAN_INFO_PROCESSED: u32 = 1; @@ -69,11 +71,14 @@ def main(): ty: [u32; N], value: [Atomic; N], valid: [Atomic; N], msg_proc: T, } struct MsgProc; -''', const(las, "DIRECT_IDLE_MS"), +''', const(las, "MAX_ONDEMAND_INTERVAL_US"), + const(las, "DIRECT_IDLE_MS"), block(las, "fn first_sample_wait_ms("), block(las, "#[derive(Clone, Copy, Debug, PartialEq, Eq)]\nenum SyncAction"), block(las, "#[derive(Clone, Copy, Debug, PartialEq, Eq)]\nenum IdleStep"), block(las, "#[derive(Clone, Copy, Debug, PartialEq, Eq)]\nenum RunState"), + block(las, "trait IntervalIo"), + block(las, "#[derive(Clone, Copy, Debug, PartialEq, Eq)]\nenum ProbeEvent"), block(las, "struct Stream"), block(las, "impl Stream"), block(common, "pub trait MessageProcessor"), @@ -199,6 +204,158 @@ def main(): assert_eq!(s.check_backoff(500), Some(Error(-5))); assert_eq!(s.check_backoff(0), None); } + +struct MockAop { + fw_interval: std::cell::Cell, + reads: std::cell::RefCell>>>, + writes: std::cell::RefCell)>>, + write_log: std::cell::RefCell>, +} + +impl MockAop { + fn new( + initial: u32, + reads: Vec>>, + writes: Vec<(bool, Result)>, + ) -> Self { + Self { + fw_interval: std::cell::Cell::new(initial), + reads: std::cell::RefCell::new(reads.into()), + writes: std::cell::RefCell::new(writes.into()), + write_log: std::cell::RefCell::new(Vec::new()), + } + } +} + +impl IntervalIo for MockAop { + fn get_interval(&self) -> Result> { + if let Some(res) = self.reads.borrow_mut().pop_front() { + return res; + } + Ok(Some(self.fw_interval.get())) + } + + fn set_interval_status(&self, interval: u32) -> Result { + self.write_log.borrow_mut().push(interval); + if let Some((apply, res)) = self.writes.borrow_mut().pop_front() { + if apply { + self.fw_interval.set(interval); + } + return res; + } + self.fw_interval.set(interval); + Ok(0) + } + + fn set_interval(&self, interval: u32) -> Result { + match self.set_interval_status(interval)? { + 0 => Ok(()), + _ => Err(EIO), + } + } +} + +#[test] +fn probe_applied_stop_failed_readback_and_failed_restore_recovers_on_read() { + // 1) Probe reads 1_000_000 us. + // 2) Stop write applies 0 in firmware, but its reply times out. + // 3) Readback also times out. + // 4) First restore write fails (timeout). + let aop = MockAop::new( + 1_000_000, + vec![Ok(Some(1_000_000)), Err(ETIMEDOUT)], + vec![(true, Err(ETIMEDOUT)), (false, Err(ETIMEDOUT))], + ); + let mut s = Stream::::new(); + let (event, retry) = s.probe_with(&aop, 5_000); + assert_eq!(event, ProbeEvent::StopAmbiguousRecoverable(ETIMEDOUT, 1_000_000)); + assert!(retry); + assert_eq!(s.interval_us, Some(1_000_000)); + assert_eq!(s.restore_interval, Some(1_000_000)); + assert_eq!(s.run_state, RunState::Unknown); + assert_eq!(aop.fw_interval.get(), 0); + assert_eq!(s.direct_until, Some(5_000)); + + // A direct read must NOT stay passive; it restarts firmware reports and + // transitions cleanly to Running -> Stopped -> restored on shutdown. + s.direct_readers = 1; + assert_eq!(s.sync_with(&aop), Ok(())); + assert_eq!(s.run_state, RunState::Running); + assert_eq!(aop.fw_interval.get(), 1_000_000); + + s.direct_readers = 0; + s.direct_until = Some(10_000); + assert_eq!(s.check_idle(0), IdleStep::Expire); + assert_eq!(s.sync_with(&aop), Ok(())); + assert_eq!(s.run_state, RunState::Stopped); + assert_eq!(aop.fw_interval.get(), 0); + + assert_eq!(s.shutdown_with(&aop), Ok(())); + assert_eq!(aop.fw_interval.get(), 1_000_000); + assert_eq!(s.restore_interval, None); + assert_eq!(s.interval_us, None); +} + +#[test] +fn probe_applied_stop_failed_readback_and_refused_restore_recovers_on_idle_retry() { + let aop = MockAop::new( + 1_000_000, + vec![Ok(Some(1_000_000)), Ok(None)], + vec![(true, Err(ETIMEDOUT)), (false, Ok(0xe000_02bc))], + ); + let mut s = Stream::::new(); + let (event, retry) = s.probe_with(&aop, 5_000); + assert_eq!(event, ProbeEvent::StopAmbiguousRecoverable(ETIMEDOUT, 1_000_000)); + assert!(retry); + assert_eq!(s.interval_us, Some(1_000_000)); + assert_eq!(s.run_state, RunState::Unknown); + assert_eq!(aop.fw_interval.get(), 0); + + // Without any direct read, the armed idle retry reasserts Stop. + assert_eq!(s.check_idle(0), IdleStep::Expire); + assert_eq!(s.sync_with(&aop), Ok(())); + assert_eq!(s.run_state, RunState::Stopped); + assert_eq!(aop.fw_interval.get(), 0); + + // A later direct read starts reports again and shutdown restores 1_000_000. + s.direct_readers = 1; + assert_eq!(s.sync_with(&aop), Ok(())); + assert_eq!(aop.fw_interval.get(), 1_000_000); + s.direct_readers = 0; + assert_eq!(s.shutdown_with(&aop), Ok(())); + assert_eq!(aop.fw_interval.get(), 1_000_000); +} + +#[test] +fn probe_reconciliation_variants() { + // Timed-out stop that did apply 0, confirmed by readback -> on-demand Stopped. + let aop = MockAop::new( + 1_000_000, + vec![Ok(Some(1_000_000)), Ok(Some(0))], + vec![(true, Err(ETIMEDOUT))], + ); + let mut s = Stream::::new(); + let (event, retry) = s.probe_with(&aop, 5_000); + assert_eq!(event, ProbeEvent::StopTimedOutStopped(ETIMEDOUT)); + assert!(!retry); + assert_eq!(s.interval_us, Some(1_000_000)); + assert_eq!(s.restore_interval, Some(1_000_000)); + assert_eq!(s.run_state, RunState::Stopped); + + // Ambiguous stop/readback where first restore succeeds -> passive, untouched on shutdown. + let aop2 = MockAop::new( + 1_000_000, + vec![Ok(Some(1_000_000)), Err(ETIMEDOUT)], + vec![(true, Err(ETIMEDOUT)), (true, Ok(0))], + ); + let mut s2 = Stream::::new(); + let (event2, retry2) = s2.probe_with(&aop2, 5_000); + assert_eq!(event2, ProbeEvent::StopAmbiguousRestored(ETIMEDOUT, 1_000_000)); + assert!(!retry2); + assert_eq!(s2.interval_us, None); + assert_eq!(s2.restore_interval, None); + assert_eq!(aop2.fw_interval.get(), 1_000_000); +} '''] with tempfile.TemporaryDirectory(prefix="aop-las-") as tmp: source = Path(tmp) / "test.rs" From c8cde22e54ca7ad17a8156bcb224217182f2a321 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 1 Dec 2026 02:28:46 -0500 Subject: [PATCH 4/5] iio: aop_temp: preserve Unknown state across firmware-sleep wake When pm_suspend_via_firmware() is true on wake (including pm_test=devices runs when deep suspend is selected, which never enter firmware sleep), Control::set_parked() previously reset s.run_state to RunState::Stopped. If the suspend stop failed and left RunState::Unknown, an idle stream then appeared stopped on wake without sending PROP_INTERVAL = 0 or arming an idle stop retry, allowing reports to keep streaming. Extract TempIo and Stream::{arm_stop_retry, sync_with, set_parked_with} and mark RunState::Unknown alongside calibrated = false on reset_cal wakes, matching aop_las. Idle wakes then reconcile by issuing stop_reports() (and arming the 5 s retry if that write fails), while active buffers and continuous-mode fallback recalibrate and start reports. Extend aop-temp.py with a MockTempIo harness covering unacknowledged suspend stops across deep-suspend and s2idle wakes, idle-retry recovery, and firmware-sleep recalibration. Signed-off-by: Erik Bourget --- drivers/iio/common/aop_sensors/aop_temp.rs | 225 +++++++++++------- .../selftests/drivers/apple/aop-temp.py | 192 +++++++++++++-- 2 files changed, 308 insertions(+), 109 deletions(-) diff --git a/drivers/iio/common/aop_sensors/aop_temp.rs b/drivers/iio/common/aop_sensors/aop_temp.rs index f24bd055d7f0c..e2d74b4b98d69 100644 --- a/drivers/iio/common/aop_sensors/aop_temp.rs +++ b/drivers/iio/common/aop_sensors/aop_temp.rs @@ -121,6 +121,13 @@ enum RunState { Unknown, } +/// Firmware property transport needed by stream lifecycle transitions. +trait TempIo { + fn calibrate(&self) -> Result; + fn start_reports(&self) -> Result; + fn stop_reports(&self) -> Result; +} + /// Who wants the reports of the service and whether calibration has already /// been sent in this AOP boot. struct Stream { @@ -205,6 +212,77 @@ impl Stream { } self.failed_until.as_ref().map(|(_, e)| *e) } + + /// Arms a rate-limited idle-stop retry whenever an unacknowledged start or + /// stop leaves an idle on-demand stream potentially running. + fn arm_stop_retry(&mut self, deadline: T) -> bool { + if self.on_demand && !self.want() && self.run_state != RunState::Stopped { + self.direct_until = Some(deadline); + true + } else { + false + } + } + + /// Starts or stops the reports to match their users. `before_start` runs + /// right before enabling reports so any cached sample from an earlier run is + /// invalidated before new reports arrive. + fn sync_with(&mut self, io: &dyn TempIo, before_start: impl FnOnce()) -> Result { + match self.next_action() { + SyncAction::Start { calibrate } => { + if calibrate { + io.calibrate()?; + self.calibrated = true; + } + before_start(); + match io.start_reports() { + Ok(()) => { + self.run_state = RunState::Running; + Ok(()) + } + Err(e) => { + self.run_state = RunState::Unknown; + Err(e) + } + } + } + SyncAction::Stop => match io.stop_reports() { + Ok(()) => { + self.run_state = RunState::Stopped; + Ok(()) + } + Err(e) => { + self.run_state = RunState::Unknown; + Err(e) + } + }, + SyncAction::None => Ok(()), + } + } + + /// Parks reports across system sleep and reconciles stream state on wake. + fn set_parked_with( + &mut self, + io: &dyn TempIo, + parked: bool, + reset_cal: bool, + retry_deadline: T, + before_start: impl FnOnce(), + ) -> (Result, bool) { + self.parked = parked; + self.failed_until = None; + if parked { + self.direct_until = None; + } else if reset_cal { + // Firmware sleep or hibernation may restart the AOP or leave an + // unacknowledged suspend stop live; recalibrate and reconcile on wake. + self.calibrated = false; + self.run_state = RunState::Unknown; + } + let ret = self.sync_with(io, before_start); + let retry = !parked && ret.is_err() && self.arm_stop_retry(retry_deadline); + (ret, retry) + } } #[pin_data] @@ -225,6 +303,52 @@ impl_has_delayed_work! { impl HasDelayedWork for Control { self.idle_work } } +impl TempIo for Control { + fn calibrate(&self) -> Result { + for (prop, packet) in &self.packets { + let status = self.write(*prop, packet)?; + if status != 0 && status != STATUS_UNSUPPORTED { + dev_err!( + self.dev, + "calibration property {} refused: status {:#x}\n", + prop, + status + ); + return Err(EIO); + } + } + let calibration_state = if self.packets.is_empty() { 1u32 } else { 2u32 }; + let status = self.write(PROP_CALIBRATION_STATE, &calibration_state.to_le_bytes())?; + if status != 0 { + dev_err!( + self.dev, + "calibration state refused: status {:#x}\n", + status + ); + return Err(EIO); + } + Ok(()) + } + + fn start_reports(&self) -> Result { + let status = self.write(PROP_INTERVAL, &INTERVAL_US.to_le_bytes())?; + if status != 0 { + dev_err!(self.dev, "interval refused: status {:#x}\n", status); + return Err(EIO); + } + Ok(()) + } + + fn stop_reports(&self) -> Result { + let status = self.write(PROP_INTERVAL, &0u32.to_le_bytes())?; + if status != 0 { + dev_err!(self.dev, "stop refused: status {:#x}\n", status); + return Err(EIO); + } + Ok(()) + } +} + impl Control { fn new(dev: &device::Device, aop: Arc, service: EPICService) -> Result> { let mut packets = KVec::new(); @@ -276,50 +400,6 @@ impl Control { .epic_call(&self.service, SUBTYPE_SET_PROPERTY, &msg) } - fn calibrate(&self) -> Result { - for (prop, packet) in &self.packets { - let status = self.write(*prop, packet)?; - if status != 0 && status != STATUS_UNSUPPORTED { - dev_err!( - self.dev, - "calibration property {} refused: status {:#x}\n", - prop, - status - ); - return Err(EIO); - } - } - let calibration_state = if self.packets.is_empty() { 1u32 } else { 2u32 }; - let status = self.write(PROP_CALIBRATION_STATE, &calibration_state.to_le_bytes())?; - if status != 0 { - dev_err!( - self.dev, - "calibration state refused: status {:#x}\n", - status - ); - return Err(EIO); - } - Ok(()) - } - - fn start_reports(&self) -> Result { - let status = self.write(PROP_INTERVAL, &INTERVAL_US.to_le_bytes())?; - if status != 0 { - dev_err!(self.dev, "interval refused: status {:#x}\n", status); - return Err(EIO); - } - Ok(()) - } - - fn stop_reports(&self) -> Result { - let status = self.write(PROP_INTERVAL, &0u32.to_le_bytes())?; - if status != 0 { - dev_err!(self.dev, "stop refused: status {:#x}\n", status); - return Err(EIO); - } - Ok(()) - } - /// Checks once at probe that the service accepts calibration and the /// report interval, then stops reports for on-demand operation. If the /// firmware explicitly refuses `PROP_INTERVAL = 0`, retain continuous @@ -382,47 +462,13 @@ impl Control { s: &mut Stream>, before_start: impl FnOnce(), ) -> Result { - match s.next_action() { - SyncAction::Start { calibrate } => { - if calibrate { - self.calibrate()?; - s.calibrated = true; - } - before_start(); - match self.start_reports() { - Ok(()) => { - s.run_state = RunState::Running; - Ok(()) - } - Err(e) => { - s.run_state = RunState::Unknown; - Err(e) - } - } - } - SyncAction::Stop => match self.stop_reports() { - Ok(()) => { - s.run_state = RunState::Stopped; - Ok(()) - } - Err(e) => { - s.run_state = RunState::Unknown; - Err(e) - } - }, - SyncAction::None => Ok(()), - } + s.sync_with(self, before_start) } /// Arms a rate-limited idle-stop retry whenever an unacknowledged start or /// stop leaves an idle on-demand stream potentially running. fn arm_stop_retry_locked(&self, s: &mut Stream>) -> bool { - if s.on_demand && !s.want() && s.run_state != RunState::Stopped { - s.direct_until = Some(Instant::::now() + Delta::from_millis(DIRECT_IDLE_MS)); - true - } else { - false - } + s.arm_stop_retry(Instant::::now() + Delta::from_millis(DIRECT_IDLE_MS)) } fn schedule_idle(self: &Arc, delay_ms: u32) { @@ -480,17 +526,14 @@ impl Control { ) -> Result { let (ret, retry) = { let mut s = self.stream.lock(); - s.parked = parked; - s.failed_until = None; - if parked { - s.direct_until = None; - } else if reset_cal { - s.calibrated = false; - s.run_state = RunState::Stopped; - } - let ret = self.sync_locked(&mut s, before_start); - let retry = !parked && ret.is_err() && self.arm_stop_retry_locked(&mut s); - (ret, retry) + let retry_deadline = Instant::::now() + Delta::from_millis(DIRECT_IDLE_MS); + s.set_parked_with( + self.as_ref(), + parked, + reset_cal, + retry_deadline, + before_start, + ) }; if parked { self.stop_idle_sync(false); diff --git a/tools/testing/selftests/drivers/apple/aop-temp.py b/tools/testing/selftests/drivers/apple/aop-temp.py index b9aabc02121df..fbbb590fa3ed7 100755 --- a/tools/testing/selftests/drivers/apple/aop-temp.py +++ b/tools/testing/selftests/drivers/apple/aop-temp.py @@ -29,6 +29,8 @@ def main(): temp = (root / "drivers/iio/common/aop_sensors/aop_temp.rs").read_text() parts = [ "#[derive(Clone, Copy, Debug, PartialEq, Eq)]\nstruct Error(i32);", + "type Result = std::result::Result;", + "const ETIMEDOUT: Error = Error(-110);", const(temp, "REPORT_LEN"), const(temp, "TEMP_OFFSET"), const(temp, "DIRECT_IDLE_MS"), @@ -38,9 +40,59 @@ def main(): block(temp, "#[derive(Clone, Copy, Debug, PartialEq, Eq)]\nenum SyncAction"), block(temp, "#[derive(Clone, Copy, Debug, PartialEq, Eq)]\nenum IdleStep"), block(temp, "#[derive(Clone, Copy, Debug, PartialEq, Eq)]\nenum RunState"), + block(temp, "trait TempIo"), block(temp, "struct Stream"), block(temp, "impl Stream"), r''' +use std::cell::RefCell; +use std::collections::VecDeque; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Op { + Calibrate, + Start, + Stop, +} + +struct MockTempIo { + ops: RefCell>, + cal_results: RefCell>, + start_results: RefCell>, + stop_results: RefCell>, +} + +impl MockTempIo { + fn new() -> Self { + Self { + ops: RefCell::new(Vec::new()), + cal_results: RefCell::new(VecDeque::new()), + start_results: RefCell::new(VecDeque::new()), + stop_results: RefCell::new(VecDeque::new()), + } + } + + fn take_ops(&self) -> Vec { + std::mem::take(&mut *self.ops.borrow_mut()) + } +} + +impl TempIo for MockTempIo { + fn calibrate(&self) -> Result { + self.ops.borrow_mut().push(Op::Calibrate); + self.cal_results.borrow_mut().pop_front().unwrap_or(Ok(())) + } + + fn start_reports(&self) -> Result { + self.ops.borrow_mut().push(Op::Start); + self.start_results.borrow_mut().pop_front().unwrap_or(Ok(())) + } + + fn stop_reports(&self) -> Result { + self.ops.borrow_mut().push(Op::Stop); + self.stop_results.borrow_mut().pop_front().unwrap_or(Ok(())) + } +} + fn report(q16_16: i32) -> Vec { let mut r = vec![0u8; REPORT_LEN]; r[TEMP_OFFSET..TEMP_OFFSET + 4].copy_from_slice(&(q16_16 as u32).to_le_bytes()); @@ -116,36 +168,140 @@ def main(): #[test] fn buffer_and_sleep_transitions() { + let io = MockTempIo::new(); let mut s = Stream::::new(); s.calibrated = true; s.on_demand = true; s.buffer_on = true; - assert_eq!(s.next_action(), SyncAction::Start { calibrate: false }); - s.run_state = RunState::Running; + let mut invalidated = 0; + assert_eq!(s.sync_with(&io, || invalidated += 1), Ok(())); + assert_eq!(invalidated, 1); + assert_eq!(io.take_ops(), vec![Op::Start]); + assert_eq!(s.run_state, RunState::Running); // Sleep parks active buffer stream. - s.parked = true; - s.direct_until = None; - assert_eq!(s.next_action(), SyncAction::Stop); - s.run_state = RunState::Stopped; + let (res, retry) = s.set_parked_with(&io, true, false, 5_000, || {}); + assert_eq!((res, retry), (Ok(()), false)); + assert_eq!(io.take_ops(), vec![Op::Stop]); + assert_eq!(s.run_state, RunState::Stopped); - // Firmware sleep clears calibration and run_state; resume re-calibrates and starts buffer. - s.parked = false; - s.calibrated = false; - s.run_state = RunState::Stopped; - assert_eq!(s.next_action(), SyncAction::Start { calibrate: true }); - s.calibrated = true; - s.run_state = RunState::Running; + // Firmware sleep clears calibration and reconciles via Unknown; resume re-calibrates and starts buffer. + let (res, retry) = s.set_parked_with(&io, false, true, 5_000, || invalidated += 1); + assert_eq!((res, retry), (Ok(()), false)); + assert_eq!(invalidated, 2); + assert_eq!(io.take_ops(), vec![Op::Calibrate, Op::Start]); + assert!(s.calibrated); + assert_eq!(s.run_state, RunState::Running); // Disabling buffer stops stream. s.buffer_on = false; - assert_eq!(s.next_action(), SyncAction::Stop); - s.run_state = RunState::Stopped; - assert_eq!(s.next_action(), SyncAction::None); + assert_eq!(s.sync_with(&io, || {}), Ok(())); + assert_eq!(io.take_ops(), vec![Op::Stop]); + assert_eq!(s.run_state, RunState::Stopped); + + // Idle firmware-sleep wake reconciles with Stop in case an AOP reset resumed default streaming. + let (res, retry) = s.set_parked_with(&io, true, false, 10_000, || {}); + assert_eq!((res, retry), (Ok(()), false)); + assert!(io.take_ops().is_empty()); + let (res, retry) = s.set_parked_with(&io, false, true, 10_000, || {}); + assert_eq!((res, retry), (Ok(()), false)); + assert_eq!(io.take_ops(), vec![Op::Stop]); + assert!(!s.calibrated); + assert_eq!(s.run_state, RunState::Stopped); - // Continuous fallback (stop refused at probe): stays on after wake without buffer. + // Continuous fallback (stop refused at probe): stays on and re-calibrates after firmware sleep. s.on_demand = false; - assert_eq!(s.next_action(), SyncAction::Start { calibrate: false }); + s.calibrated = true; + assert_eq!(s.sync_with(&io, || {}), Ok(())); + assert_eq!(io.take_ops(), vec![Op::Start]); + assert_eq!(s.run_state, RunState::Running); + let (res, retry) = s.set_parked_with(&io, true, false, 15_000, || {}); + assert_eq!((res, retry), (Ok(()), false)); + assert_eq!(io.take_ops(), vec![Op::Stop]); + let (res, retry) = s.set_parked_with(&io, false, true, 15_000, || invalidated += 1); + assert_eq!((res, retry), (Ok(()), false)); + assert_eq!(invalidated, 3); + assert_eq!(io.take_ops(), vec![Op::Calibrate, Op::Start]); + assert!(s.calibrated); + assert_eq!(s.run_state, RunState::Running); +} + +#[test] +fn failed_suspend_stop_reconciles_on_wake_including_fw_sleep_and_retries() { + let io = MockTempIo::new(); + let mut s = Stream::::new(); + s.calibrated = true; + s.on_demand = true; + s.direct_until = Some(5_000); + assert_eq!(s.sync_with(&io, || {}), Ok(())); + io.take_ops(); + + // Unacknowledged suspend stop leaves RunState::Unknown, then deep-suspend wake + // (reset_cal = true, e.g. pm_test=devices or firmware sleep) preserves Unknown and + // reconciles by issuing Stop rather than assuming Stopped. + io.stop_results.borrow_mut().push_back(Err(ETIMEDOUT)); + let (res, retry) = s.set_parked_with(&io, true, false, 5_000, || {}); + assert_eq!((res, retry), (Err(ETIMEDOUT), false)); + assert_eq!(s.run_state, RunState::Unknown); + assert_eq!(s.direct_until, None); + assert_eq!(io.take_ops(), vec![Op::Stop]); + + let (res, retry) = s.set_parked_with(&io, false, true, 10_000, || {}); + assert_eq!((res, retry), (Ok(()), false)); + assert_eq!(io.take_ops(), vec![Op::Stop]); + assert_eq!(s.run_state, RunState::Stopped); + assert!(!s.calibrated); + + // Next direct read recalibrates before starting reports. + s.direct_readers = 1; + let mut invalidated = 0; + assert_eq!(s.sync_with(&io, || invalidated += 1), Ok(())); + assert_eq!(invalidated, 1); + assert_eq!(io.take_ops(), vec![Op::Calibrate, Op::Start]); + assert!(s.calibrated); + assert_eq!(s.run_state, RunState::Running); + + // If both suspend stop and deep-suspend wake stop fail, wake arms the 5 s idle retry + // and the expired idle timer finishes stopping the stream. + s.direct_readers = 0; + s.direct_until = Some(15_000); + io.stop_results + .borrow_mut() + .extend([Err(ETIMEDOUT), Err(ETIMEDOUT)]); + let (res, retry) = s.set_parked_with(&io, true, false, 15_000, || {}); + assert_eq!((res, retry), (Err(ETIMEDOUT), false)); + assert_eq!(s.run_state, RunState::Unknown); + assert_eq!(io.take_ops(), vec![Op::Stop]); + + let (res, retry) = s.set_parked_with(&io, false, true, 20_000, || {}); + assert_eq!((res, retry), (Err(ETIMEDOUT), true)); + assert_eq!(s.run_state, RunState::Unknown); + assert_eq!(s.direct_until, Some(20_000)); + assert!(!s.calibrated); + assert_eq!(io.take_ops(), vec![Op::Stop]); + + assert_eq!(s.check_idle(0), IdleStep::Expire); + assert_eq!(s.sync_with(&io, || {}), Ok(())); + assert_eq!(io.take_ops(), vec![Op::Stop]); + assert_eq!(s.run_state, RunState::Stopped); + + // s2idle wake (reset_cal = false) after an unacknowledged suspend stop also + // reconciles Stop while preserving calibration. + s.calibrated = true; + s.direct_until = Some(25_000); + assert_eq!(s.sync_with(&io, || {}), Ok(())); + io.take_ops(); + io.stop_results.borrow_mut().push_back(Err(ETIMEDOUT)); + let (res, retry) = s.set_parked_with(&io, true, false, 25_000, || {}); + assert_eq!((res, retry), (Err(ETIMEDOUT), false)); + assert_eq!(s.run_state, RunState::Unknown); + io.take_ops(); + + let (res, retry) = s.set_parked_with(&io, false, false, 30_000, || {}); + assert_eq!((res, retry), (Ok(()), false)); + assert_eq!(io.take_ops(), vec![Op::Stop]); + assert_eq!(s.run_state, RunState::Stopped); + assert!(s.calibrated); } #[test] From 793075bd411e0216b66ed4019ce107891904731b Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Tue, 1 Dec 2026 13:40:46 -0500 Subject: [PATCH 5/5] iio: aop_temp: accept a confirmed idle-stop retry at probe If the first idle-stop request times out after calibration and start, the retry can still confirm that reports have stopped. Enter on-demand mode in that case instead of failing probe with the original timeout. Exercise the production probe method with acknowledged and unacknowledged retries in the host selftest. Signed-off-by: DjDeveloperr --- drivers/iio/common/aop_sensors/aop_temp.rs | 4 +- .../selftests/drivers/apple/aop-temp.py | 59 +++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/drivers/iio/common/aop_sensors/aop_temp.rs b/drivers/iio/common/aop_sensors/aop_temp.rs index e2d74b4b98d69..06d129b401334 100644 --- a/drivers/iio/common/aop_sensors/aop_temp.rs +++ b/drivers/iio/common/aop_sensors/aop_temp.rs @@ -443,10 +443,12 @@ impl Control { Ok(()) } Err(e) => { - // Transient transport error after start: attempt best-effort stop. + // A confirmed retry is safe to treat as the initial stop. s.run_state = RunState::Unknown; if let Ok(0) = self.write(PROP_INTERVAL, &0u32.to_le_bytes()) { s.run_state = RunState::Stopped; + s.on_demand = true; + return Ok(()); } Err(e) } diff --git a/tools/testing/selftests/drivers/apple/aop-temp.py b/tools/testing/selftests/drivers/apple/aop-temp.py index fbbb590fa3ed7..d03f41215775d 100755 --- a/tools/testing/selftests/drivers/apple/aop-temp.py +++ b/tools/testing/selftests/drivers/apple/aop-temp.py @@ -27,13 +27,22 @@ def const(source, name): def main(): root = Path(__file__).resolve().parents[5] temp = (root / "drivers/iio/common/aop_sensors/aop_temp.rs").read_text() + probe_init = ( + block(temp, "fn probe_init(") + .replace("self.stream.lock()", "self.stream.borrow_mut()") + .replace("dev_err!", "probe_log!") + .replace("dev_info!", "probe_log!") + ) parts = [ "#[derive(Clone, Copy, Debug, PartialEq, Eq)]\nstruct Error(i32);", "type Result = std::result::Result;", "const ETIMEDOUT: Error = Error(-110);", + "const EIO: Error = Error(-5);", const(temp, "REPORT_LEN"), const(temp, "TEMP_OFFSET"), const(temp, "DIRECT_IDLE_MS"), + const(temp, "PROP_INTERVAL"), + const(temp, "INTERVAL_US"), block(temp, "fn le_u32("), block(temp, "fn location0_packet("), block(temp, "fn decode_millicelsius("), @@ -47,6 +56,55 @@ def main(): use std::cell::RefCell; use std::collections::VecDeque; +macro_rules! probe_log { + ($dev:expr, $($args:tt)*) => {{ + let _ = (&$dev, format_args!($($args)*)); + }}; +} + +struct ProbeControl { + dev: (), + stream: RefCell>, + interval_writes: RefCell)>>, +} + +impl ProbeControl { + fn calibrate(&self) -> Result { + Ok(()) + } + + fn write(&self, prop: u32, value: &[u8]) -> Result { + let (interval, result) = self.interval_writes.borrow_mut().pop_front().unwrap(); + assert_eq!(prop, PROP_INTERVAL); + assert_eq!(value, &interval.to_le_bytes()); + result + } +} + +#[test] +fn probe_retries_unacknowledged_idle_stop() { + for (retry, result, state, on_demand) in [ + (Ok(0), Ok(()), RunState::Stopped, true), + (Err(EIO), Err(ETIMEDOUT), RunState::Unknown, false), + ] { + let control = ProbeControl { + dev: (), + stream: RefCell::new(Stream::new()), + interval_writes: RefCell::new(VecDeque::from([ + (INTERVAL_US, Ok(0)), + (0, Err(ETIMEDOUT)), + (0, retry), + ])), + }; + assert_eq!(control.probe_init(), result); + let stream = control.stream.borrow(); + assert!(stream.calibrated); + assert_eq!(stream.run_state, state); + assert_eq!(stream.on_demand, on_demand); + assert!(control.interval_writes.borrow().is_empty()); + } +} + #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Op { Calibrate, @@ -313,6 +371,7 @@ def main(): assert!(s.failed_until.is_none()); } ''', + f"impl ProbeControl {{\n{probe_init}\n}}", ] with tempfile.TemporaryDirectory(prefix="aop-temp-") as tmp: source = Path(tmp) / "test.rs"