Skip to content

Apple drivers: bound firmware-sized work and fix teardown and restore lifetimes (admac, macsmc, aop_motion, aop_devmotion, aop_lpai, afk) - #2911

Closed
RyanTheTide wants to merge 6 commits into
integration/aurorafrom
hardening/apple-drivers-20261123
Closed

RyanTheTide wants to merge 6 commits into
integration/aurorafrom
hardening/apple-drivers-20261123

Conversation

@RyanTheTide

Copy link
Copy Markdown
Contributor

Six small robustness fixes in Apple SoC drivers, found by reading the code. Each commit carries a KUnit case that fails without its fix and passes with it.

Problem and change, per commit

  1. dmaengine: apple-admac: the saved slave config kept the client's peripheral_config pointer, and the restore after a system sleep read the realign frame size through it again. The AOP audio driver passes a pointer to a local variable, so that memory is long gone by then. The frame size is now taken once, the saved copy carries no pointer, and the restore only programs the registers.
  2. mfd: macsmc: the two completions the RTKit receive path completes were initialised only after RTKit init, wake and endpoint start. They are now set up with the mutex and the spinlock, before RTKit init.
  3. iio: aop_motion: the IIO device was freed when the driver data was dropped. That happens before the device-managed trigger and triggered buffer are released, and the buffer's release reads from the IIO device. This is a use after free on unbind and on any probe failure after buffer setup. The IIO device and its private data now belong to the platform device's resources, registered before the trigger and the buffer, so they are freed last.
  4. iio: aop_devmotion: the buffer scan is 32 bytes and the IIO core copies all 32, but only 24 were written. The tail is now an explicit zeroed field, as in the sibling drivers.
  5. ASoC: apple: aop_lpai:
    • the PCM's period limits are now computed with checked arithmetic, and a format with an empty or oversized minimum period is refused when it is read. Before, a division or overflow could panic at PCM open.
    • the T6041 host ring is bounded by twice the ALSA buffer limit before it is allocated. The firmware's own geometry is between one and two buffers.
  6. drm/apple: afk: compact service-call replies queued on the transmit workqueue had no limit. The payload bytes of replies queued and not yet sent are now counted per endpoint, and capped at AFK_COMPACT_MESSAGE_MAX, the largest single message. A call over that is dropped with a rate-limited warning before anything is allocated.

There are no new parameters and no chip, board or firmware gates. Every limit comes from an existing driver constant or the PCM's own buffer limit.

Testing

  • KUnit (arm64 qemu), integration/aurora 13e494a plus this series. All new cases pass in both groups:
    • C group (admac, macsmc, drm/apple parser): 52 run, 51 passed, 1 skipped (apple_g17_rx_util_min_test, needs CONFIG_UCLAMP_TASK).
    • Rust group (aop_motion, aop_devmotion, aop_lpai): 60 run, 59 passed, the same 1 skip.
  • A/B on the previous tip daa9e2d: for each commit, the fix hunks were reverted with the new test kept, and the new case failed:
    • admac_restore_keeps_the_frame_size
    • macsmc_early_message_test
    • iio_device_is_freed_with_the_device_resources
    • scan_is_written_in_full
    • a_format_without_a_valid_period_range_is_refused
    • the_ring_geometry_is_bounded_by_the_pcm_buffer
    • afk_compact_call_reply_budget_test
  • Build checks: W=1 shows no new warnings in the touched C files. checkpatch reports 0 errors and 0 warnings. Clippy and rustfmt show no new findings in the touched Rust files; the files' existing rustfmt drift is unchanged.

Still to run

  • Hardware rows on the default cmdline:
    • aop_motion bind/unbind and an aop_devmotion buffered read on an M1 Pro or M2;
    • a low-power microphone open on T6041;
    • a DCP external display on a desktop 26.x Mac (for the afk change);
    • admac speaker-sense capture across a deep sleep on a board with realign_sense.
Reviewer detail
  • admac: admac_program_config() is the old register part of admac_device_config(). admac_device_config() sets realign_bytes once (the duplicate assignment is gone), then saves the config with peripheral_config = NULL and peripheral_size = 0. admac_restore_chan() calls admac_program_config() on the saved copy, so realign_bytes stays as the client set it.
  • macsmc: apple_smc_init_state() runs before the SRAM map and before either RTKit init variant. The KUnit case builds a zeroed apple_smc with a fake SRAM resource. It checks that both wait lists are initialised, then delivers a shared-buffer message through apple_smc_rtkit_recv_early().
  • aop_motion: the new IioAlloc owns the iio_dev, the Arc<State> in priv_ and the channel table (Spec). It is registered with devres::register() right after iio_device_alloc(); if that registration fails, the allocation is dropped and freed. Devres releases in reverse order: buffer, then trigger, then IioAlloc. MotionIio::drop only unregisters. MotionIio::new() now takes &Device<Bound>, so the KUnit test can run it on a faux device. The test checks that the private data is still alive when devres release begins and gone when it ends.
  • aop_devmotion: Scan::new() zeroes the tail. The test derives the scan size the way iio_compute_scan_bytes() does, compares it with size_of::<Scan>(), and checks that the bytes after the timestamp are zero over a 0xa5-filled slot.
  • aop_lpai: StreamFormat::period_bytes_min() returns None outside 1..=PERIOD_BYTES_MAX, and StreamFormat::new() refuses such a format. hw() uses the checked value. ring_geometry() folds the existing quantum checks together with the new RING_BYTES_MAX = 2 * BUFFER_BYTES_MAX bound. ring_step() is untouched.
  • afk:
    • afk_compact_reply_reserve() and afk_compact_reply_release() work under ep->lock.
    • A dropped call is not counted in sleep_jobs.
    • The worker releases the reply's bytes after a send whether it succeeded or failed. Teardown (destroy_workqueue(tx_wq)) drains through the worker, so the count returns to zero.
    • Any single valid call is always taken when nothing is queued.
    • The handlers in the tree (dptxport_*, panelav_sac_call_v2, ext26_aux_call) take short calls, far below the cap.

Assisted-by: LLM (Claude:Opus 5.5)

…inter

admac_device_config() saves the whole dma_slave_config so that a channel
can be set up again after a system sleep took its registers. The copy
includes peripheral_config, a pointer to memory the client only
guarantees for the duration of the call: the AOP audio driver passes the
address of a local variable. admac_restore_chan() then calls
admac_device_config() on the saved copy and reads the realign frame size
through that pointer again, long after the client returned.

Split the register programming out into admac_program_config(), which
the restore calls on the saved copy. admac_device_config() takes the
frame size from the client's config once (it was assigned twice) and
stores the copy with peripheral_config cleared, so a restore keeps the
frame size the client configured and never touches the client's memory.

Add a KUnit case that configures a capture channel, overwrites the
client's frame size, marks the channel lost and restores it.

Fixes: d9b438c ("arm64: apple: support coordinated suspend-to-RAM on T8140")
Signed-off-by: Ryan Murray <[email protected]>
apple_smc_probe() initialised init_done and cmd_done only after the
RTKit was initialised, woken and the SMC endpoint started. The receive
callback is live from the RTKit's initialisation on, and it completes
init_done for the first message on the SMC endpoint, so a message that
arrives before the probe got that far completes a completion that is
still all zeroes.

Initialise both completions together with the mutex and the spinlock,
before the RTKit is initialised, in a helper, apple_smc_init_state().

Add a KUnit case that takes the first message with only that state set
up.

Fixes: e038d98 ("mfd: Add Apple Silicon System Management Controller")
Signed-off-by: Ryan Murray <[email protected]>
The triggered buffer and the trigger of each sensor are resources of the
platform device, and the release of the triggered buffer reads the poll
function and the buffer out of the IIO device. The IIO device, though,
was freed when the driver's data was dropped, which the driver core does
before it releases the resources of the device, both on unbind and when
a probe fails after the buffer is set up. The buffer release then read
an IIO device that was already freed.

Hand the IIO device, its private data and the channel table it points to
to the resources of the platform device, right after the allocation and
before the trigger and the buffer are set up. Resources are released in
reverse order, so the buffer and the trigger now go first and the IIO
device last. Dropping the driver's data only unregisters the device.

MotionIio::new() takes the bound device instead of the platform device,
so that a KUnit test can run it on a faux device: the test checks that
the private data of the IIO device is still there when the release of
the device's resources begins and gone when it has ended.

Signed-off-by: Ryan Murray <[email protected]>
A scan is a quaternion and a timestamp: 24 bytes, which the 16-byte
alignment of the quaternion rounds up to 32. The IIO core computes the
same 32 bytes and copies them all into the buffer, but the last eight
were padding of the scan structure, which nothing wrote.

Make the tail a field and build the scan in one place that zeroes it, as
the accelerometer, gyroscope and temperature drivers already do for
their scans.

Add a KUnit test that derives the scan size from the channels as the IIO
core does, compares it with the structure, and checks that every byte
after the timestamp of a freshly built scan is zero.

Signed-off-by: Ryan Murray <[email protected]>
…format

The low-power microphone takes its stream format and, on T6041, its
ring geometry from properties of the AOP's audio service.

The PCM limits are computed from the rate: the shortest period is
PERIOD_MS_MIN of frames, and the most periods is the buffer limit divided
by it. A rate that gives no whole frame in that time made the shortest
period zero and the division one by zero, and a rate large enough
overflowed the product; both stop the kernel when the PCM is opened.
Compute the shortest period with checked arithmetic when the format is
read, and refuse a format whose shortest period is empty or longer than
the longest period the PCM offers. Such a format leaves the PCM out, as
the other unusable formats do.

The host ring was sized as frames times frame bytes with only a 4 GiB
limit, and was allocated before the binding. The ring only feeds the
ALSA buffer, so a ring of more than twice that buffer's limit serves no
stream the PCM can offer; the firmware's own geometry (four seconds of
its format) lies between one and two buffers. Refuse a larger ring
before anything is allocated, together with the report-interval checks
that were already there, in one helper.

Add KUnit cases for formats with and without a valid period range and
for ring geometries on both sides of the limit.

Signed-off-by: Ryan Murray <[email protected]>
Every compact service call from the firmware gets a reply buffer of the
call's size, which is queued on the endpoint's ordered transmit queue.
A reply can wait there for transmit ring space for up to five seconds
while the receive worker keeps taking calls, and nothing limits how many
replies, or how many bytes of them, are queued in the meantime. A
firmware that keeps calling while it does not drain its ring makes the
queue grow without bound.

Count the payload bytes of the replies that are queued and not yet sent,
under the endpoint lock, and take a call only while its reply fits.
The room is AFK_COMPACT_MESSAGE_MAX, the largest single message, which
is also what the receive side holds in assembly: one call of any valid
size is always taken when nothing is queued, and the short calls the
display services receive stay far below it. A call beyond that is
dropped with a rate-limited warning before its buffer is allocated and
before the service handler runs, so it is not counted as a pending job
either. The reply worker returns the room once the send has finished or
failed, which covers the queue flush at teardown as well.

Add a KUnit case that stalls the transmit queue, feeds calls until the
room is used up and checks that later calls are dropped until the queue
has drained.

Signed-off-by: Ryan Murray <[email protected]>
@RyanTheTide

Copy link
Copy Markdown
Contributor Author

Review at 4bbeec8.

All six fixes are real and correctly ordered. I checked the admac restore, the macsmc completion init, and the aop_motion devres order against device_unbind_cleanup(): drvdata is dropped before devres_release_all(), and iio_triggered_buffer_cleanup() reads indio_dev. Findings:

  1. afk.c:1196: a dropped compact call never gets a reply, which is the same firmware-visible failure as a failed send. With v27_sleep_transport the worker sets sleep_poisoned at afk.c:1157 when a send fails, but the drop path does not. Please poison there too, so a later coordinated sleep does not run against a firmware that still has a call outstanding.
  2. aop_lpai.rs:126/435: RING_BYTES_MAX (1 MiB) is only checked against one geometry, 16 kHz x 3 ch x 4 B x 4 s = 768000. Four channels at 16 kHz come to 1024000, just under the cap, and any 48 kHz ring would be refused, so the microphone would disappear. The T6041 ring path also runs on t6040 and t8132 (both carry t6041-aop-audio). Please print the live geometry on each, or tie the cap to the stream format instead of a fixed size.
  3. macsmc-test.c:415-418 asserts on swait internals (wait.task_list). completion_done() plus the receive call already prove the point, so please drop those two asserts.
  4. The six commits are independent and touch five subsystems. Please split them so each can land on its own rows: admac+aop_lpai (audio), macsmc, aop_motion+aop_devmotion (iio), afk (drm). afk carries the most behaviour risk.
  5. macsmc: no read, refusal or timeout semantics change. Only the init order moves, so no fan, power or thermal protection is affected.
  6. admac: MCA clients pass no peripheral_config, so they behave as before. For realign_sense boards (J813, J815, J714s) the restore used to read a dead stack slot and now keeps the frame size, which fixes V/I sense alignment after s2r.

Rows owed at this head (none posted): an s2r speaker-sense capture with V/I aligned on one realign_sense board, plus s2r MCA playback on J616s or M2; boot with SMC sensors/fans up on J616s and on one saved_enabled board (J714s or J813); aop_motion unbind/rebind with KASAN, plus a devmotion buffered read, on J616s, J713 and M1 Pro; an lpai microphone open with the ring geometry logged on J616s and J713; an external display with hotplug on J713 and on a desktop 26.x DCP.

@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.

Formal adversarial §1–§6 pre-PR checklist review at 4bbeec89c25598093770f7e9e0d6177c96f10892 (REQUEST_CHANGES — 2 code blockers in afk.c and aop_lpai.rs, 0 hardware rows run across 5 subsystems, and incomplete CI coverage).

Checklist Summary

  • §1 (No model gating): Blocked — aop_lpai.rs hardcodes RING_BYTES_MAX = 2 * BUFFER_BYTES_MAX (1 MiB) tuned to a single 16 kHz / 3-ch observation (Blocker #2).
  • §2 (Production-ready, no hacks): Blocked — afk.c drops compact calls without poisoning v27_sleep_transport (Blocker #1).
  • §3 (Safety): Mixed — apple-admac.c (admac_program_config split + clearing peripheral_config in saved copy), macsmc.c (initializing init_done/cmd_done before RTKit init), aop_motion.rs (IioAlloc devres ordering before trigger/buffer), and aop_devmotion.rs (explicit zeroed pad: u64 tail in Scan) are all sound on code inspection; afk.c and aop_lpai.rs have blockers below.
  • §4 (Clean-room & attribution): Pass — all 6 commits carry human author/committer (Ryan Murray <[email protected]>) and human Signed-off-by: only (zero AI trailers in commits); PR body includes Assisted-by:.
  • §5 (Evidence): Blocked — 0 hardware rows run across 5 subsystems (dmaengine, mfd, iio, ASoC, drm), and GitHub CI only reports host-tests (SUCCESS) with no kunit, rust-build, source, or DWC3/ATC checks recorded.
  • §6 (Naming): Pass.

Blockers

  1. §2 / §3 (drivers/gpu/drm/apple/afk.c:1196-1206): Dropping a compact service call leaves v27_sleep_transport unpoisoned:
    • In afk_compact_reply_worker() (afk.c:1155-1158), a failed compact reply send on v27_sleep_transport sets r->ep->sleep_poisoned = true under ep->lock so coordinated sleep does not proceed against firmware with an unanswered call.
    • In afk_recv_handle_compact_call(), both the new budget-exhaustion drop path (!afk_compact_reply_reserve()) and the kvzalloc() OOM path silently leave a firmware call unanswered without setting ep->sleep_poisoned = true when ep->dcp->v27_sleep_transport is enabled. Poison ep->sleep_poisoned under ep->lock on those drop paths too.
  2. §1 / §3 (sound/soc/apple/aop_lpai.rs:126, 435): Hardcoded RING_BYTES_MAX (1 MiB) risks breaking legitimate higher-rate / 4-channel t6041-aop-audio rings:
    • RING_BYTES_MAX = 2 * BUFFER_BYTES_MAX (1,048,576 B) is checked only against one geometry (16 kHz × 3 ch × 4 B × 4 s = 768,000 B). Four channels at 16 kHz is already 1,024,000 B, and any 48 kHz 4-second ring (e.g. 2,304,000 B for 3 ch) would be refused with -EIO, causing the low-power microphone to disappear.
    • The T6041 ring path also runs on t6040 and t8132 (t6041-aop-audio). Measure/log live ring geometries across all chips using this path, and tie the ring cap to the stream format's byte rate (e.g., max ring duration × byte rate with a generous upper safety ceiling) rather than a tight fixed 1 MiB cap.
  3. §5 (Owed hardware verification rows across 5 subsystems):
    • No on-hardware rows have been posted yet. Owed on the default command line (with 0 SELinux denials, 0 failed units, 0 new kernel errors):
      • admac: s2r speaker-sense capture with V/I alignment verified on a realign_sense board (J813/J815/J714s), plus s2r MCA playback on J616s or M2;
      • macsmc: boot with SMC sensors/fans up on J616s and a saved_enabled board (J714s or J813);
      • aop_motion + aop_devmotion: unbind/rebind (ideally under KASAN) + aop_devmotion buffered read on M1 Pro/M2/J616s/J713;
      • aop_lpai: low-power microphone open with live ring geometry logged on t6041-aop-audio boards (J616s, J713);
      • afk: external display + hotplug on J713 and a desktop 26.x DCP Mac.
    • Strongly recommend splitting this 6-commit bundle by subsystem (admac+aop_lpai, macsmc, aop_motion+aop_devmotion, afk) so low-risk fixes can land on their own rows without being blocked by afk / aop_lpai.

Non-blocking Notes

  • drivers/mfd/macsmc-test.c:415-418 asserts on swait internal fields (wait.task_list.next); completion_done() + apple_smc_rtkit_recv_early() already verifies completion initialization without coupling to wait-queue internals.
  • drivers/mfd/macsmc.c:679-686: smc->boot_stage = APPLE_SMC_BOOTING is still set after devm_apple_rtkit_init*(); moving it ahead of RTKit init (alongside apple_smc_init_state()) closes any remaining early-callback window.

Assisted-by: LLM (Gemini 4 Neon)

@RyanTheTide

Copy link
Copy Markdown
Contributor Author

Split by subsystem as both reviews asked, rebased on integration/aurora a7638d5, with the review points addressed:

Hardware rows (fleet82 + the series as a one-shot on M1 Pro, M2, J616s, J473, against the same rows on production) go on the new PRs. Closing this one as superseded.

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.

2 participants