Skip to content

media: apple: avd: runtime and system PM for the frame queue - #707

Closed
RyanTheTide wants to merge 4 commits into
avd/rewrite-corefrom
avd/power-idle
Closed

RyanTheTide wants to merge 4 commits into
avd/rewrite-corefrom
avd/power-idle

Conversation

@RyanTheTide

@RyanTheTide RyanTheTide commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

The frame queue needs to keep power until every slot is FREE and context drains have finished. This adds a common runtime/system PM path, wires both backend suspend/resume ops, drains deferred driver DMA releases before firmware boot, and kicks the queue only after successful boot. Apple resume reuses its boot verification/load/link/ready sequence; the existing firmware generation invalidates old session state. The autosuspend delay remains 100 ms, explicitly [C] pending the capture.

The host mailbox IRQ starts disabled, is enabled only after successful firmware boot, and is synchronized/disabled before the power domain can turn off. Queue hooks retain the frame PM reference through slot release, wake system-drain waiters, and protect streamoff register accesses with a PM reference. System sleep pauses m2m scheduling, drains accepted work, forces suspend, resumes firmware, and restarts scheduling. Teardown drains before reset/cleanup and flushes deferred releases while suppliers are powered.

Open-firmware resume reloads ITCM on every boot, enables the mailbox, writes RUN_CTRL bit 0, and polls FLAG0_SET == 1 at 10 us intervals for up to 10 ms. Suspend writes RUN_CTRL bits 1..3, clears FLAG0, and masks mailbox interrupts. The common boot dispatcher also rewrites PIODMA+0x24 = SRAM physical address >> 4 whenever the DT declares that transport, including recovery boots. Recovery closes the host IRQ, stops firmware, resets the block, attaches/detaches an empty IOMMU paging domain, verifies restoration of the original domain, and then reboots. Core invalidates old slots before reopening the IRQ. A running stream never falls back to another command ABI.

Integration requirements: PIODMA needs both decode and DMA IOMMU streams restored by the supplier; the T6040 DT currently lacks stream 1, and legacy T6000/T8112 DTs lack the named PIODMA aperture. Those DT changes and the DART provider support needed for empty-domain recovery belong to their separate lanes. This driver maps only declared resources and does not synthesize missing apertures or stream IDs. Firmware WFI and FULL-bit not-full interrupts remain firmware integration work; no unverified interrupt mask is enabled here.

Ten PM KUnit cases cover all-slot/drain suspend gating, deferred releases, boot-failure rollback, reserved-only replay through the real queue worker, repeated ITCM/PIODMA boot setup, and recovery guards/failure handling.

Validation: git diff --check passes. Checkpatch reports 0 errors and 0 warnings with its generic FILE_PATH_CHANGES notice excluded. The lead test shell and retained-session Python pass syntax checks. Buildbox arm64 LLVM W=1 CONFIG_WERROR=y, QEMU KUnit, and host-test runs have been requested but have not executed; build capacity is currently unavailable. No target hardware was requested or measured by this worker.

Source: 0eaf5955fb6e2ea01d12e18435c07eec1e9cec99, based on avd/rewrite-core at a116172.

The base branch still marks the Borage transport facts unverified. This PM change does not invent the missing ITCM/link/reply register offsets or claim measured retention, bus-idle timing, or power savings. Keep this draft until the lead qualifies both available backends.

Lead power qualification (run through a controller request with the exact device identity and policy approval; no direct target transport): install the built kernel and separately supplied firmware using the normal bootguard-protected workflow. Use the same hashed sample set before and after this series. Keep raw logs on the lab machine; publish only sanitized outcomes and aggregate watts.

Run the following commands inside the approved target execution. They open video only and send decoded output to a null sink.

set -euo pipefail
SAMPLES=/tmp/avd-samples
RESULTS=$(mktemp -d /tmp/avd-pm-results.XXXXXX)
AVD=
for d in /sys/bus/platform/drivers/avd/*; do
    [ -d "$d/power" ] || continue
    AVD=$(readlink -f "$d")
    break
done
test -n "$AVD"
old_control=$(cat "$AVD/power/control")
old_sleep=$(sed -n 's/.*\[\([^]]*\)\].*/\1/p' /sys/power/mem_sleep)
restore() {
    if [ -n "${decode_pid:-}" ]; then
        kill -INT "$decode_pid" 2>/dev/null || true
        wait "$decode_pid" 2>/dev/null || true
    fi
    printf '%s\n' "$old_control" > "$AVD/power/control"
    printf '%s\n' "$old_sleep" > /sys/power/mem_sleep
}
trap restore EXIT
printf auto > "$AVD/power/control"
uname -r > "$RESULTS/kernel.txt"
cat "$AVD/power/autosuspend_delay_ms" > "$RESULTS/autosuspend-ms.txt"
(cd "$SAMPLES" && sha256sum -c SHA256SUMS) > "$RESULTS/samples.txt"

decode() {
    local codec=$1 parser decoder
    case "$codec" in
        h264) parser=h264parse; decoder=v4l2slh264dec ;;
        hevc) parser=h265parse; decoder=v4l2slh265dec ;;
        vp9) parser=vp9parse; decoder=v4l2slvp9dec ;;
        av1) parser=av1parse; decoder=v4l2slav1dec ;;
    esac
    timeout 90 gst-launch-1.0 -q filesrc location="$SAMPLES/$codec-4k.mp4" \
        ! qtdemux ! "$parser" ! "$decoder" ! fakesink sync=false
}

# Warm once, then verify runtime suspend and successful decode after each idle.
# Run every codec currently advertised by the tested backend; record unsupported
# codecs explicitly rather than substituting a software decoder.
for codec in h264 hevc vp9 av1; do
    if ! decode "$codec" > "$RESULTS/$codec-warm.log" 2>&1; then
        printf '%s warm decode unsupported/failed; see log\n' "$codec"
        continue
    fi
    for idle in 2 10 120; do
        sleep "$idle"
        cat "$AVD/power/runtime_status" "$AVD/power/runtime_suspended_time" \
            > "$RESULTS/$codec-idle-$idle.pm"
        decode "$codec" > "$RESULTS/$codec-after-$idle.log" 2>&1
    done
done

# Keep one decoder session open through all three idle gaps (PyGObject/Gst).
# A pad probe pauses compressed input before it reaches the decoder.
export AVD SAMPLES
python3 - <<'PYSESSION' > "$RESULTS/retained-session.log" 2>&1
import os, subprocess, time
import gi
gi.require_version("Gst", "1.0")
from gi.repository import Gst
Gst.init(None)
sample = os.path.join(os.environ["SAMPLES"], "h264-4k.mp4")
frames = int(subprocess.check_output([
    "ffprobe", "-v", "error", "-select_streams", "v:0", "-count_frames",
    "-show_entries", "stream=nb_read_frames", "-of", "csv=p=0", sample], text=True))
assert frames >= 8
pipeline = Gst.parse_launch(
    'filesrc name=input ! qtdemux ! h264parse ! video/x-h264,alignment=au '
    '! identity name=gap ! v4l2slh264dec ! fakesink sync=false')
pipeline.get_by_name("input").set_property("location", sample)
positions = {frames // 4: 2, frames // 2: 10, 3 * frames // 4: 120}
count = [0]
failures = []
seen = []
def pause_input(pad, info):
    count[0] += 1
    delay = positions.get(count[0])
    if delay:
        time.sleep(delay)
        status = open(os.path.join(os.environ["AVD"], "power/runtime_status")).read().strip()
        print("open-session idle", delay, "seconds:", status, flush=True)
        seen.append(delay)
        if status != "suspended":
            failures.append((delay, status))
    return Gst.PadProbeReturn.OK
pipeline.get_by_name("gap").get_static_pad("src").add_probe(
    Gst.PadProbeType.BUFFER, pause_input)
pipeline.set_state(Gst.State.PLAYING)
try:
    msg = pipeline.get_bus().timed_pop_filtered(
        240 * Gst.SECOND, Gst.MessageType.EOS | Gst.MessageType.ERROR)
    assert msg is not None, "decode did not finish after idle gaps"
    assert msg.type == Gst.MessageType.EOS, str(msg.parse_error())
    assert seen == [2, 10, 120], seen
    assert not failures, failures
    assert count[0] > max(positions), count
finally:
    pipeline.set_state(Gst.State.NULL)
PYSESSION

# s2idle while a paced decode owns its open queues: it must drain, sleep, wake,
# and finish. The RTC provides the wake; retain the bootguard fallback.
printf s2idle > /sys/power/mem_sleep
gst-launch-1.0 -q filesrc location="$SAMPLES/h264-4k.mp4" \
    ! qtdemux ! h264parse ! identity sleep-time=33333 \
    ! v4l2slh264dec ! fakesink sync=false > "$RESULTS/s2idle-decode.log" 2>&1 &
decode_pid=$!
sleep 0.2
rtcwake -m mem -s 15 > "$RESULTS/s2idle-wake.log" 2>&1
wait "$decode_pid"
decode_pid=
decode h264 > "$RESULTS/after-s2idle.log" 2>&1

# Cache an elementary stream before power sampling. No audio is decoded.
ffmpeg -v error -i "$SAMPLES/h264-4k.mp4" -map 0:v:0 -c copy \
    -bsf:v h264_mp4toannexb -f h264 "$RESULTS/power.h264"
PSTR=
for label in /sys/class/hwmon/hwmon*/power*_label; do
    [ -f "$label" ] || continue
    case "$(cat "$label")" in
        *PSTR*|*"Total System"*|*"System Total"*) PSTR=${label%_label}_input; break ;;
    esac
done
test -r "$PSTR"
sample_power() {
    local phase=$1
    for n in $(seq 1 30); do
        awk -v n="$n" '{printf "%d,%.6f\n", n, $1/1000000}' "$PSTR"
        sleep 1
    done > "$RESULTS/$phase-watts.csv"
}
sleep 2
sample_power idle
python3 - "$RESULTS/power.h264" <<'PY' | \
    gst-launch-1.0 -q fdsrc ! h264parse ! v4l2slh264dec ! fakesink sync=false \
        > "$RESULTS/power-decode.log" 2>&1 &
import sys
payload = open(sys.argv[1], 'rb').read()
try:
    while True:
        sys.stdout.buffer.write(payload)
        sys.stdout.buffer.flush()
except BrokenPipeError:
    pass
PY
decode_pid=$!
sleep 2
sample_power decoding
kill -INT "$decode_pid"
wait "$decode_pid" || true
decode_pid=
for phase in idle decoding; do
    awk -F, '{s+=$2; n++} END {printf "%s mean_PSTR_W=%.6f samples=%d\n", FILENAME,s/n,n}' \
        "$RESULTS/$phase-watts.csv"
done
dmesg > "$RESULTS/kernel.log"
printf 'Local evidence: %s\n' "$RESULTS"

Pass criteria: each supported codec decodes after 2/10/120 seconds; runtime status reaches suspended between bursts; the paced decode survives s2idle; no AVD timeout, DART fault, lockdep warning or failed unmap; no retained mapping after closed-stream teardown. Repeat the idle/decode watts sample three times on the baseline and this kernel, with identical boot/display/network conditions, and report median idle watts, decoding watts, and their difference. Do not change the 100 ms delay until the idle-timer capture settles it.

Keep power through slot retirement and context drains, restore firmware before retrying reserved frames, and defer DMA releases while the DART is inactive. Re-enable a retained Apple MCPU image before mailbox link setup, without uploading it again. Pause and drain the queue for system sleep and final teardown.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
Request the mailbox IRQ without automatic enable, open it only after successful firmware boot, and synchronize and close it after backend suspend. Close the host IRQ on teardown even if the final PM transition fails.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
Map only DT-declared PIODMA and SRAM resources and replay the shifted SRAM base before every open CM3 boot. Keep reset, empty-domain attach/detach and firmware reboot ordered; refuse to reboot if the DMA domain cannot be restored. Keep host IRQs closed until old slots are invalidated. Add synthetic-RAM boot replay and recovery-gating KUnit coverage. Queued PIODMA use still requires the DT to describe the DMA stream as well as decode.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
Replay PIODMA setup in the common boot dispatcher so queued open transports inherit it even with their own mailbox boot implementation. Keep firmware generation handling and initial-only backend fallback in the same dispatcher, and test the real open boot path through it.

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

Copy link
Copy Markdown
Contributor Author

Closing as merged in content: head 0eaf595 is an ancestor of integration/aurora 43c790f (it came in through merge e2e4736 'Merge branch avd/power-idle into avd/rewrite-integ'), so nothing in this PR is left to land. Deleting the head branch avd/power-idle (tip still 0eaf595, no open PR uses it as a base). Overnight merge train, 11-07.

@RyanTheTide RyanTheTide closed this Nov 7, 2026
@RyanTheTide
RyanTheTide deleted the avd/power-idle branch November 7, 2026 11:03
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.

1 participant