Skip to content

iio: aop_motion: calibrate once per boot and idle-stop direct reads - #2910

Merged
RyanTheTide merged 1 commit into
aurora-silicon:integration/aurorafrom
AxxzyWasTaken:fix/aop-motion-cal-storm
Nov 23, 2026
Merged

RyanTheTide merged 1 commit into
aurora-silicon:integration/aurorafrom
AxxzyWasTaken:fix/aop-motion-cal-storm

Conversation

@AxxzyWasTaken

@AxxzyWasTaken AxxzyWasTaken commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Commit 9538a1d2111f ("iio: aop_motion: run the reports only while someone reads them") stopped the AOP accelerometer and gyroscope reports when idle, which saved ~100 AP wakeups/s on an idle desktop. However, its direct-read path (State::read_now()) calls Control::start() and Control::stop() around every individual sysfs axis read (in_accel_{x,y,z}_raw / in_anglvel_{x,y,z}_raw), and Control::start() unconditionally re-sends all three calibration packets (properties 75, 76, 77) before writing PROP_INTERVAL = 20_000.

On T6041 (M4 Max, J616C, 7.3.0-j616c-ia34), opening a web page that polls the Generic Sensor API in Chromium (x.com in helium-browser) polls X/Y/Z sysfs continuously at ~25-60 Hz:

  • Each axis read triggers a full start()/stop() cycle (~73 cycles/s, ~365 EPIC RPCs/s).
  • On every start(), properties 75 and 76 return 0xe00002c7 (STATUS_UNSUPPORTED) while property 77 returns 0 (re-accepted every time), logging 2 of 3 calibration packets kept from an earlier start 1,241 times in 17 seconds.
  • After 17 seconds, the AOP firmware crashes (apple_aop 510c10000.aop: RTKit: co-processor has crashed, mailbox history 100% endpoint 0x24, task rtk_ep_work), permanently freezing ALS and breaking speaker endpoint 34 for the rest of the boot.

Root Cause

  1. Unconditional calibration re-writes: The AOP keeps a service's calibration across normal start/stop cycles and across s2idle (where the AOP core does nothing). Re-sending all three calibration packets on every start() repeatedly triggers property 77 handling and spams dmesg.
  2. Per-axis start/stop thrashing: Direct IIO sysfs reads fetch X, Y, and Z via three separate read_raw() calls. Starting and stopping PROP_INTERVAL inside each individual read_now() turns a single 3-axis read into 3 start/stop cycles, and turns browser polling into hundreds of EPIC RPCs/sec.

Fix

Preserves 9538a1d2111f's 0 Hz idle AOP goal while eliminating both the calibration re-write storm and per-axis start/stop thrashing (incorporating review feedback from @RyanTheTide):

  1. Calibrate once at probe; conservative reset across firmware sleep / hibernation / restore:
    • Track Stream::calibrated under Control::stream. Probe runs probe_init() (calibrate once, verify interval, stop to 0 Hz). Subsequent starts (buffer enable, direct read, s2idle PM_POST_SUSPEND) only write PROP_INTERVAL = 20_000.
    • In pm_event(), handle PM_SUSPEND_PREPARE | PM_HIBERNATION_PREPARE | PM_RESTORE_PREPARE by parking, PM_POST_SUSPEND with reset_cal = pm_suspend_via_firmware(), and PM_POST_HIBERNATION | PM_POST_RESTORE with reset_cal = true. On s2idle (!pm_suspend_via_firmware()), the AOP core does nothing so calibration stays valid; across firmware suspend, hibernation, and restore, calibrated and active are reset conservatively so calibration is sent once on the next start (firmwares that kept it answer packets 75/76 with STATUS_UNSUPPORTED benignly once).
    • Downgrade the "N of 3 calibration packets kept from an earlier start" message from dev_info! to dev_dbg!.
  2. Short idle auto-stop window for direct reads (DIRECT_IDLE_MS = 2_000) + failed-start backoff:
    • A direct read_now() without an enabled buffer starts reports if idle, waits up to FIRST_SAMPLE_MS for the first fresh sample, sets direct_until = now + 2s, and schedules a DelayedWork item (Control::idle_work) on system_dfl_wq.
    • Back-to-back X/Y/Z reads and continuous direct polling reuse the running 50 Hz stream and extend direct_until with zero EPIC RPCs and zero timer churn.
    • When idle_work fires, it checks remaining time via Stream::check_idle(); if more reads extended the deadline it re-arms for the remaining delta, otherwise it clears direct_until and stops reports (PROP_INTERVAL = 0), returning the AOP to 0 Hz.
    • If a direct-read start fails, Stream::failed_until remembers (deadline, error) for DIRECT_IDLE_MS and Stream::check_backoff() returns that error without calling the service again until the deadline passes (bounding failing-service traffic and refused() logs to at most once per DIRECT_IDLE_MS). Enabling a buffer, system sleep transitions, and shutdown() clear the backoff.
    • Only clear s.active = false in sync_locked() after stop_reports() succeeds; set_parked(false, true) clears both calibrated and active.
    • Enabling a buffer smoothly takes over an active direct stream and clears direct_until; disabling the buffer stops immediately.
    • PM_SUSPEND_PREPARE / PM_HIBERNATION_PREPARE / PM_RESTORE_PREPARE stop reports under the mutex, release the mutex, and call cancel_delayed_work_sync() (reclaiming any pending Arc reference); unbind() and probe() failure after iio.register() unregister pm and call shutdown() with disable_delayed_work_sync() before teardown.
  3. Host selftest & docs: Extended tools/testing/selftests/drivers/apple/aop-motion.py to compile and test the production Stream<T>, SyncAction, and IdleStep state machine (single calibration, direct-stream reuse, idle expiry/re-arm, buffer handoff, suspend vs hibernation calibration policy, failed-start backoff, and failed-stop / reset_cal handling), and updated Documentation/iio/aop-sensors.rst.

Hardware A/B Results (credit: @RyanTheTide)

Measured via runtime module swap against stock fleet kernels (kit 20261123-aop-motion2):

J616s (M4 Pro, T6040, 7.3.0-aurora-fleet81)

Arm Workload Duration Reads/s per sensor Read p50 AOP mbox IRQ/s (median) Calib-kept lines Errors AOP crash
stock sysfs accel+gyro 60 Hz 120 s accel 95, gyro 20 accel 12 ms, gyro 50 ms 714 13,758 (115/s) 0 no
stock Chromium 157 headless 180 s page: acc 31/s, gyr 6.6/s - 716 20,510 (114/s) 0 no
patched (axb1) sysfs accel+gyro 60 Hz 300 s 180 + 180 (full rate) <0.1 ms 107 0 0 no
patched (axb1) Chromium 157 headless 600 s page: acc 49/s, gyr 49/s - 107 0 0 no
patched + backoff (bo1) sysfs / Chromium 90 s / 120 s same as above <0.1 ms 107 / 107 0 0 no
  • Idle (nobody reading): 7 IRQ/s on every arm; post-load 0-2 s 76/s (motion hold), 3-13 s back to 7/s.
  • bufmix (60 Hz direct reads across 6 buffer enable/disable cycles): 0 direct-read errors, buffer ~1.2 kB/s accel, idle 7/s after.
  • unbindhold (rmmod inside the 2 s hold x3): 8-16 ms, 0 WARN/BUG/refcount lines, reloads cleanly.
  • s2idle 15 s x2 per arm: OK, direct reads immediately after resume OK, idle 7/s after; ALS, LAS, als-temp, and both AOP mics unchanged.

M1 Pro (T6000, 7.3.0-aurora-fleet82)

Arm Workload Duration Reads/s per sensor Read p50 AOP mbox IRQ/s (median) Errors
stock sysfs accel+gyro 60 Hz 120 s accel 99, gyro 20 accel 10.6 ms, gyro 49 ms 737 0
stock Chromium headless 180 s page: acc 33/s, gyr 8/s - 740 0
patched (f82axb1) sysfs accel+gyro 60 Hz 300 s 180 + 180 0.1 ms 103 0
patched (f82axb1) Chromium headless 300 s page: acc 49/s, gyr 49/s - 104 0
  • Idle 3/s both arms; after load 0-2 s 79/s, 3-13 s 3/s; s2idle x2 OK; bufmix 0 errors; unbindhold x3 18-22 ms, 0 WARN. (Pre-existing gap on stock too: M1 Pro accel and gyro read 0 0 0.)

M4 Max (J616C, T6041, 7.3.0-j616c-aopfix at 65ddaa0adccc)

  • Probe & idle: accel.1.auto + gyro.2.auto bound, 0 failed units; idle AOP mailbox IRQ 3.6 recv/s (0.0 send/s).
  • Direct sysfs + 2 s idle-stop: 102.5 recv/s during hold, returns cleanly to 3.6 recv/s.
  • 90.5 s 60 Hz direct sysfs soak (poll.py): 16,209 accel + 16,203 gyro reads, 0 errors, 103 recv/s median, 0 AOP crashes, 0 calib-kept spam.
  • 60 s headless Chromium Generic Sensor soak (--headless=new --mute-audio): 3,520 devicemotion, 2,910 accel, 2,910 gyro, err: [], 0 AOP crashes.
  • unbind/bind inside 2 s hold (3x accel.1.auto): 0–1 ms, 0 warnings; 2x rtcwake -d /dev/rtc1 -m freeze -s 10: 2/2 PASS, immediate post-resume reads; sibling als/las live, 0 AVC denials.

Local Verification

  • python3 tools/testing/selftests/drivers/apple/aop-motion.py: 10/10 tests pass (-Dwarnings)
  • python3 tools/testing/selftests/drivers/apple/aop-las.py and tools/asahi/aop-*.py: all pass
  • rustfmt --check --edition 2021 drivers/iio/common/aop_sensors/aop_motion.rs: clean (0 diffs)
  • scripts/checkpatch.pl --strict --git HEAD~1..HEAD: 0 errors, 0 warnings, 0 checks
  • make ARCH=arm64 LLVM=1 W=1 KBUILD_MODPOST_WARN=1 O=... drivers/iio/common/aop_sensors/aop_motion.ko: clean compile and link (0 warnings, 0 errors; KBUILD_MODPOST_WARN=1 only because vmlinux.o was not built in the isolated objdir)

Fixes: 9538a1d ("iio: aop_motion: run the reports only while someone reads them")
Suggested-by: Ryan Murray [email protected]

Assisted-by: LLM (Anthropic:Claude Opus 5.5, Google:Gemini 4 Neon)

Commit 9538a1d ("iio: aop_motion: run the reports only while
someone reads them") stopped the AOP accelerometer and gyroscope reports
when nobody reads them, saving ~100 AP wakeups/s on an idle desktop.
However, its direct-read path calls Control::start() and Control::stop()
around every individual sysfs axis read, and start() unconditionally
resends all three calibration packets (properties 75, 76 and 77) before
setting the report interval.

On T6041 (M4 Max, J616C), Chromium polling the raw X/Y/Z sysfs channels
at 25-60 Hz drives ~73 start/stop cycles/s (~365 EPIC RPCs/s). On every
start, properties 75 and 76 return kIOReturnUnsupported (0xe00002c7)
while property 77 is re-accepted, logging "2 of 3 calibration packets
kept from an earlier start" over 1,200 times in 17 seconds until the AOP
firmware crashes on endpoint 0x24, wedging ALS and audio for the rest of
the boot.

Keep the 0 Hz idle behaviour while eliminating both the calibration
rewrite storm and per-axis start/stop thrashing:

- Track calibration state in Stream so the three calibration packets are
  sent once at probe, and subsequent starts for buffers, direct reads
  and s2idle resume only write PROP_INTERVAL. On s2idle
  (!pm_suspend_via_firmware()), the AOP core does nothing so calibration
  stays valid. Across firmware suspend (pm_suspend_via_firmware()),
  hibernation and restore (PM_POST_HIBERNATION / PM_POST_RESTORE), clear
  calibrated and active conservatively so calibration is sent once on
  the next start (on firmwares that kept it, packets 75/76 return
  STATUS_UNSUPPORTED benignly once). Downgrade the kept-packets log
  message from dev_info! to dev_dbg!.
- Hold direct-read reports active for a 2 s idle window via a
  DelayedWork item on system_dfl_wq. Back-to-back X/Y/Z reads and
  polling callers share the running 50 Hz stream and extend the deadline
  with no extra EPIC calls, while quiet periods return the AOP to
  interval 0.
- Back off direct reads for DIRECT_IDLE_MS after a failed start so a
  polling client cannot hammer a failing service or spam refused() logs;
  buffer enable, sleep transitions and shutdown clear the backoff.
- Only clear active after stop_reports() succeeds, and park on
  PM_RESTORE_PREPARE alongside suspend/hibernation prepare. Cancel and
  join the idle work synchronously with the stream mutex dropped on
  sleep prepare (cancel_delayed_work_sync) and permanently disable it on
  unbind or a failed iio.register() in probe (disable_delayed_work_sync),
  reclaiming any pending Arc reference cleanly.
- Extend the host selftest in
  tools/testing/selftests/drivers/apple/aop-motion.py to cover the
  production Stream state machine (including failed-start backoff and
  failed-stop / reset_cal handling) and update
  Documentation/iio/aop-sensors.rst.

Fixes: 9538a1d ("iio: aop_motion: run the reports only while someone reads them")
Suggested-by: Ryan Murray <[email protected]>
Signed-off-by: AxxzyWasTaken <[email protected]>
@AxxzyWasTaken

Copy link
Copy Markdown
Contributor Author

J616C (MacBook Pro 16" M4 Max, T6041) exact-head hardware soak at 65ddaa0adccc (7.3.0-j616c-aopfix, 99-aurora-no-aop-motion.conf removed):

Test Result
Probe & IIO registration aop_motion bound to accel.1.auto (iio:device2) + gyro.2.auto (iio:device3); 0 failed units
Idle AOP mailbox IRQ (510608000) 3.6 recv/s, 0.0 send/s (10 s window)
Direct sysfs read + 2 s idle-stop Accel (-348, 617, -64978), Gyro (12000, 0, 8000); 102.5 recv/s during 2 s hold → back to 3.6 recv/s idle
60 Hz direct sysfs polling soak (poll.py, 90.5 s) 16,209 accel + 16,203 gyro reads, 0 errors, 103 recv/s median, 0 AOP crashes → back to 3.6 recv/s
Headless Chromium Generic Sensor (--headless=new --mute-audio, 60 s) 3,520 devicemotion, 2,910 accel, 2,910 gyro, err: [], 0 AOP crashes → back to 3.6 recv/s
Driver unbind/bind inside 2 s direct-read hold (3× accel.1.auto) 0 ms / 1 ms / 1 ms, post-rebind reads -386 / -340 / -378, 0 crashes / warnings
2-cycle rtcwake -d /dev/rtc1 -m freeze -s 10 2/2 PASS (rc=0), post-resume accel/gyro immediately readable (-329/-389, 24000/12000), back to 3.6 recv/s
Sibling AOP sensors & health aop-sensors-als (3915.48) & aop-sensors-las (43) live; 0 AOP crashes, 0 Too many inflight, 0 calib-kept spam, 0 AVC denials

Moving out of Draft — ready for review. (Also checked upcoming #2936 KUnit overlap in aop_motion.rs: ready to rebase Stream::new() + idle_work into #2936's KUnit test if #2936 lands first.)

Assisted-by: LLM (Google:Gemini 4 Neon)

@AxxzyWasTaken
AxxzyWasTaken marked this pull request as ready for review November 23, 2026 05:20

@DjDeveloperr DjDeveloperr left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Full adversarial review of 65ddaa0adcccd3d635eae59ec704279b39242392 against pre-pr-checklist.md (§1–§6): APPROVE.

Code, Concurrency & Safety Audit (§1–§4, §6) — clean

  • §1 No model gating: Zero chip, SoC, board, or firmware-version gates. Uses standard kernel pm_suspend_via_firmware() to distinguish s2idle (AOP stays up, calibration preserved) from firmware suspend/hibernation/restore (conservatively clears both calibrated and active). Validated across 3 Mac families (T6041 M4 Max, T6040 M4 Pro, T6000 M1 Pro).
  • §2 Production-ready, no hacks: Works on the default kernel command line with no module parameters or race-workaround sleeps. DIRECT_IDLE_MS = 2_000 cleanly coalesces multi-axis sysfs reads and polling clients onto the running 50 Hz stream while returning the AOP to 0 Hz when idle; Stream::failed_until caps failing-service retries and refused() log spam to at most once per idle window.
  • §3 Safety, locking & lifecycle:
    • Calibration packets continue to come solely from device tree properties (apple,range-intrinsic-cal, apple,nominal-extrinsic-cal, apple,range-extrinsic-cal).
    • Deadlock / lock ordering: Both set_parked(true, _) and shutdown() set s.parked = true and s.direct_until = None under stream.lock(), release the mutex, and only then call stop_idle_sync(), preventing AB-BA deadlock with Control::run() and preventing any racing read_now() or Control::run() from re-arming idle_work.
    • Unbind / probe teardown: Both unbind() and the iio.register() error path in probe() unregister PmHook (synchronizing against in-flight pm_event callbacks) before calling control.shutdown(), which uses disable_delayed_work_sync to cancel, drain, and permanently block requeues.
    • Rust unsafe & Arc refcounting: stop_idle_sync() extracts bindings::delayed_work from the pinned DelayedWork<Control> inside Arc<Control> and reclaims exactly one Arc via Arc::from_raw(Arc::as_ptr(self)) iff cancel_delayed_work_sync / disable_delayed_work_sync reports a pending item was cancelled (matching kernel/workqueue.c __cancel_work_sync semantics and aop_devmotion.rs::disable_poll). Instant<Monotonic> subtraction + Delta::as_millis_ceil() handles positive, zero, and negative deltas without overflow or off-by-one errors; bindings::pm_suspend_via_firmware() compiles cleanly with and without CONFIG_SUSPEND.
    • State fidelity: s.active is cleared only after stop_reports() succeeds, and set_parked(false, true) resets both calibrated and active.
    • Tests & docs: Host selftest in tools/testing/selftests/drivers/apple/aop-motion.py compiles and verifies the production Stream<T> / SyncAction / IdleStep state machine (including backoff and failed-stop/reset_cal paths), and Documentation/iio/aop-sensors.rst matches the code.
  • §4 Clean-room & attribution / §6 Naming: Single commit 65ddaa0adcccd3d635eae59ec704279b39242392 with human author/committer (AxxzyWasTaken) and human Signed-off-by: only, zero AI trailers in commits; PR body carries Assisted-by:; naming is clean.

§5 Evidence & CI — satisfied

  • CI: Host tests / host-tests SUCCESS on 65ddaa0adcccd3d635eae59ec704279b39242392; MERGEABLE (CLEAN), non-draft.
  • J616C (M4 Max, T6041, exact head 65ddaa0adccc, 7.3.0-j616c-aopfix): accel.1.auto + gyro.2.auto bound, idle 3.6 recv/s (0.0 send/s), 2 s direct-read idle-stop returns to 3.6 recv/s, 90.5 s 60 Hz sysfs soak (16,209 accel + 16,203 gyro reads, 0 errors, 103 recv/s median), 60 s headless Chromium Generic Sensor soak (3,520 devicemotion, 2,910 accel/gyro, err: []), 3× unbind/bind inside the 2 s hold (0–1 ms, 0 warnings), 2× rtcwake -m freeze -s 10 (2/2 PASS, immediate post-resume reads), sibling als/las live, 0 AOP crashes, 0 calib-kept spam, 0 failed units, 0 AVC denials.
  • J616s (M4 Pro, T6040) & M1 Pro (T6000) A/B (@RyanTheTide): AOP mailbox IRQ/s reduced from ~714–740/s (with 114–115/s calib-kept spam) to ~103–107/s (0 spam), 300–600 s soaks, bufmix, unbindhold ×3, and s2idle ×2 all clean.

(Non-blocking notes: (1) the PR body still has a stale Draft placeholder line for J616C soak that can be refreshed from the comment; (2) when rebasing alongside #2936, #2936's new iio_aop_motion KUnit test will need Stream::new() + idle_work <- new_delayed_work!(...) in its Control initializer — already noted by the author.)

Assisted-by: LLM (Gemini 4 Neon)

@RyanTheTide

Copy link
Copy Markdown
Contributor

Merge-train review at 65ddaa0 (non-author pass): no blockers.

I read the whole aop_motion.rs change at this head and tried to break the lifecycle and the state machine. I found nothing that blocks a merge. The change selects nothing by chip, board or firmware version. The calibration still comes only from the DT properties, and it works on the default cmdline with no parameters. The 2 s direct-read hold works like an autosuspend delay: it is a policy timing, not a safety value. The J616C row at this exact head covers the runtime change, together with the J616s and M1 Pro A/B rows.

Lifecycle and locking
  • idle_work refcount: schedule_idle() drops the Arc that a refused enqueue returns, so re-arming while the work is already pending does not leak. stop_idle_sync() gives back exactly one Arc when cancel or disable reports that a pending item was removed. That is the same pattern as aop_devmotion.
  • Park, unbind and run(): set_parked(true) and shutdown() clear direct_until under the stream lock and cancel only after they drop it. run() takes the same lock and returns early once direct_until is None, so the cancel cannot deadlock against a running callback, and the callback cannot re-arm after a park. After disable_delayed_work_sync() a late schedule_idle() is refused, and its Arc is dropped.
  • Unbind order: pm hook, then shutdown(), then listener. A direct read that races with the teardown, before the IIO device is gone, gets -EBUSY from the parked check before it can schedule anything. If iio.register() fails, the probe error path unregisters the pm hook and calls shutdown(). PmHook::unregister() is idempotent (xchg), so its Drop does no harm.
  • read_now() still holds the stream mutex across the first-sample wait of up to 200 ms. That predates this PR. run() just waits on the mutex.
  • active is cleared only after stop_reports() succeeds. If a stop fails at park, a later s2idle resume (reset_cal = false) retries the stop. pm_suspend_via_firmware() is the generic PM core flag and is false on every s2idle-only Mac.
Selftest and mutants (tools/testing/selftests/drivers/apple/aop-motion.py, run at this head)

10/10 pass. I applied each mutant to the driver source one at a time and reran:

  • calibrate: true (calibrate on every start): 3 cases fail.
  • backoff remaining_ms <= 0 -> < 0: 1 fails.
  • want() ignoring direct_until: 3 fail.
  • check_idle expiring at >= 0 instead of > 0: 1 fails.
  • check_idle without the parked half of if self.parked || self.buffer_on: all pass. In production this branch cannot be reached, because a park always clears direct_until under the lock. So this is a defensive branch the tests don't cover. Nit.
Notes, not blocking
  • Older AOP firmware (M1 Pro and M2 run a 2023 build) composes each calibration write onto the current matrix. With this PR, a cold boot reads correctly (-1.00 g on the M1 Pro, per the AOP-MOTION3 rows). A driver rebind still compounds, because calibrated resets with the new bind. That predates this PR and is much milder than before. iio: aop_motion: fix the M1/M2 accelerometer and gyroscope, and idle-window aop_devmotion (stacked on #2910) #2927 (stacked on this one) handles it through the calibration-state property.
  • If the AOP restarts after an RTKit crash, calibrated stays true and the next start sends no calibration. Today a crashed AOP does not come back on its own, so this is only worth a comment for whenever recovery exists.
  • The reset_cal path after a firmware suspend or hibernation has no hardware row. No Mac in the lab enters firmware suspend, so I'm noting it, not asking for a row.
  • CI here is host-tests only: no Rust build check runs on this path. The exact-head J616C kernel and the W=1 module build in the PR body cover compilation.

Assisted-by: LLM (Claude:Opus 5.5)

@RyanTheTide
RyanTheTide merged commit 5129ba7 into aurora-silicon:integration/aurora Nov 23, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants