From ac2ef807804de0b61257a565a1021cd13810f339 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Thu, 26 Nov 2026 05:19:35 -0500 Subject: [PATCH 1/2] media: apple: ave: bound the sessions kept for a power cycle beside a running one A session the firmware has seen keeps all its DMA buffers after it stops, on failed_sessions, until the last session ends and the coprocessor is proved to have lost power: neither an answered Close nor a Halt proves the engines stopped, and freeing after them corrupted memory on the Neo. While one session stays open, that power loss never comes, and the list had no bound. Starting and stopping another session beside the open one kept every stopped session's buffers, and each start allocated a new set, until DMA memory or the encoder's address space ran out. Count the encoder sessions on failed_sessions. Beside a running session, ave_session_attach() now refuses another with -EBUSY once AVE_MAX_SESSIONS of them wait, before the firmware is given anything, so the refused session is freed at once. Nothing is freed any earlier than before. The reap that follows the power loss resets the count. MCTF sessions hold only the device pool and are not counted. Add a case to the recovery host test that keeps one session open, starts and stops eight in the other slot through the production ave_session_attach(), and checks that what waits stays within AVE_MAX_SESSIONS. It then ends the last session and checks that the power loss gives everything back and admits a new session. run-recovery.py gains --ref to build an older driver against the same cases. The previous revision is registered as its negative control: there the stopped sessions grow past the bound. Signed-off-by: DjDeveloperr --- drivers/media/platform/apple/ave/ave-sess.c | 3 + drivers/media/platform/apple/ave/ave-v4l2.c | 13 +++ drivers/media/platform/apple/ave/ave.h | 2 + .../apple/ave/tests/recovery-boundary.h | 22 +++++ .../platform/apple/ave/tests/recovery-test.c | 92 ++++++++++++++++++- .../platform/apple/ave/tests/run-recovery.py | 36 +++++++- tools/asahi/run-host-tests.py | 8 +- 7 files changed, 169 insertions(+), 7 deletions(-) diff --git a/drivers/media/platform/apple/ave/ave-sess.c b/drivers/media/platform/apple/ave/ave-sess.c index 85e3fae75fab4..0a03fc917447b 100644 --- a/drivers/media/platform/apple/ave/ave-sess.c +++ b/drivers/media/platform/apple/ave/ave-sess.c @@ -950,6 +950,8 @@ void ave_sess_destroy(struct ave_ctx *ctx) sess->mctf_surf = NULL; kvfree(sess->mctf_lin); sess->mctf_lin = NULL; + if (!sess->mctf_borrowed) + ave->failed_count++; sess->failed_next = ave->failed_sessions; ave->failed_sessions = sess; } else { @@ -987,6 +989,7 @@ void ave_sess_reap(struct ave_dev *ave) kfree(sess); freed = true; } + ave->failed_count = 0; domain = freed ? iommu_get_domain_for_dev(ave->dev) : NULL; if (domain) iommu_flush_iotlb_all(domain); diff --git a/drivers/media/platform/apple/ave/ave-v4l2.c b/drivers/media/platform/apple/ave/ave-v4l2.c index 5d73737fe6624..893c5e1d3e68d 100644 --- a/drivers/media/platform/apple/ave/ave-v4l2.c +++ b/drivers/media/platform/apple/ave/ave-v4l2.c @@ -835,6 +835,19 @@ static int ave_session_attach(struct ave_ctx *ctx) dev_err(ave->dev, "already encoding %u streams\n", max_sessions); return -EBUSY; } + /* + * A session stopped beside a running one keeps its memory until the + * last session ends and the coprocessor loses power (ave_sess_reap()). + * Starting and stopping sessions next to one that stays open would + * keep all of it: once as many stopped sessions wait as the encoder + * runs at once, refuse another before the firmware is given anything. + */ + if (ave_session_count(ave) && ave->failed_count >= AVE_MAX_SESSIONS) { + dev_err_ratelimited(ave->dev, + "%u stopped sessions wait for the encoder to power off; not starting another\n", + ave->failed_count); + return -EBUSY; + } if (!ave_session_count(ave)) { ret = ave_fw_ensure_running(ave); if (ret) diff --git a/drivers/media/platform/apple/ave/ave.h b/drivers/media/platform/apple/ave/ave.h index 331c866381399..ac31248d22dcc 100644 --- a/drivers/media/platform/apple/ave/ave.h +++ b/drivers/media/platform/apple/ave/ave.h @@ -302,6 +302,8 @@ struct ave_dev { struct ave_recovery_history recovery; unsigned int recovery_count; struct ave_session *failed_sessions; + /* encoder sessions on failed_sessions (MCTF ones hold only the pool) */ + unsigned int failed_count; bool inject_wedge; /* debugfs: the last Start and first Process built, per codec */ diff --git a/drivers/media/platform/apple/ave/tests/recovery-boundary.h b/drivers/media/platform/apple/ave/tests/recovery-boundary.h index 3c4df20fb2463..842e6b20cba19 100644 --- a/drivers/media/platform/apple/ave/tests/recovery-boundary.h +++ b/drivers/media/platform/apple/ave/tests/recovery-boundary.h @@ -78,6 +78,7 @@ struct ave_dev { enum ave_fw_state fw_state; struct ave_ctx *sessions[AVE_MAX_SESSIONS]; struct ave_session *failed_sessions; + unsigned int failed_count; struct ave_recovery_history recovery; unsigned int recovery_count; bool inject_wedge, data_dirty; @@ -101,6 +102,27 @@ struct ave_dev { u32 mctf_pool_changed; }; +/* ave_session_attach(): the firmware is running; Open is answered. */ +int ave_cmd_start(struct ave_ctx *ctx); +static int ave_fw_ensure_running(struct ave_dev *ave) +{ + ave->fw_state = AVE_FW_RUNNING; + return 0; +} +static int ave_cmd_open(struct ave_ctx *ctx) +{ + ctx->sess->fw_open = true; + return 0; +} +static int ave_sess_mctf_borrow(struct ave_ctx *ctx) +{ + return 0; +} +static int ave_mctf_cmd_start(struct ave_ctx *ctx) +{ + return 0; +} + static void *test_ctrl_addr; static void ave_ipc_dump(struct ave_dev *ave, const char *why) {} static int halt_result, close_result; diff --git a/drivers/media/platform/apple/ave/tests/recovery-test.c b/drivers/media/platform/apple/ave/tests/recovery-test.c index b5fa981b30ca5..1d44884c17fe2 100644 --- a/drivers/media/platform/apple/ave/tests/recovery-test.c +++ b/drivers/media/platform/apple/ave/tests/recovery-test.c @@ -563,8 +563,97 @@ static void unconfirmed_close(void) free(ctx[1].sess); } +static unsigned int quarantined(void) +{ + unsigned int n = 0; + + for (struct ave_session *s = ave.failed_sessions; s; s = s->failed_next) + n++; + return n; +} + +/* + * One session stays open, so the coprocessor never powers off and every + * session stopped beside it stays quarantined. Starting and stopping + * another one in the free slot again and again must not keep all their + * memory: once AVE_MAX_SESSIONS stopped sessions wait for the power loss, + * attaching one more is refused before the firmware is given anything. + * Ending the last session and losing power gives all of it back. + */ +static void quarantine_churn(void) +{ + unsigned int started = 0, refused = 0; + int ret; + + init(); + owners(); + /* Session 1 stops; session 0 keeps encoding. */ + mutex_lock(&ave.hw_lock); + ave_session_close(&ctx[1], false); + mutex_unlock(&ave.hw_lock); + ctx[1].sess->hdr.cpu = NULL; + ave_sess_destroy(&ctx[1]); + assert(quarantined() == 1 && !halts); + + for (unsigned int i = 0; i < 8; i++) { + ctx[1].sess = calloc(1, sizeof(*ctx[1].sess)); + assert(ctx[1].sess); + ctx[1].sess->p.slots = 2; + ctx[1].sess->p.codec = AVE_CODEC_H264; + submit_ctx = &ctx[1]; + mutex_lock(&ave.hw_lock); + ret = ave_session_attach(&ctx[1]); + if (!ret) { + started++; + assert(ctx[1].sess->handed && ave.sessions[1] == &ctx[1]); + ave_session_close(&ctx[1], false); + } else { + refused++; + assert(ret == -EBUSY && !ctx[1].sess->handed && !ave.sessions[1]); + } + mutex_unlock(&ave.hw_lock); + ave_sess_destroy(&ctx[1]); + /* What waits for the power loss stays bounded. */ + assert(quarantined() <= AVE_MAX_SESSIONS); + } + assert(started == AVE_MAX_SESSIONS - 1 && refused == 8 - started); + assert(ave.failed_count == AVE_MAX_SESSIONS && !halts); + + /* The last session ends; once the power is gone, everything goes back. */ + mutex_lock(&ave.hw_lock); + ave_session_close(&ctx[0], false); + mutex_unlock(&ave.hw_lock); + assert(halts == 1); + ctx[0].sess->hdr.cpu = NULL; + ave_sess_destroy(&ctx[0]); + *(u32 *)((char *)coproc + regs.ctrl) = 0; + *(u32 *)((char *)coproc + regs.boot_arg) = 0; + stop_seen = power_seen = true; + mutex_lock(&ave.hw_lock); + assert(!ave_fw_prepare_restart(&ave)); + mutex_unlock(&ave.hw_lock); + assert(!ave.failed_sessions && !ave.failed_count); + + /* A new session is admitted again. */ + ctx[1].sess = calloc(1, sizeof(*ctx[1].sess)); + assert(ctx[1].sess); + ctx[1].sess->p.slots = 2; + ctx[1].sess->p.codec = AVE_CODEC_H264; + mutex_lock(&ave.hw_lock); + assert(!ave_session_attach(&ctx[1])); + ave_session_close(&ctx[1], false); + mutex_unlock(&ave.hw_lock); + ave_sess_destroy(&ctx[1]); + assert(ave.failed_count == 1); + mutex_lock(&ave.hw_lock); + assert(!ave_fw_prepare_restart(&ave)); + mutex_unlock(&ave.hw_lock); + assert(!ave.failed_sessions && !ave.failed_count); +} + int main(void) { + quarantine_churn(); session_lifetime(); unconfirmed_close(); unusable_witness(); @@ -580,6 +669,7 @@ int main(void) restore_data(); puts("ok: recovery ownership, queues, quarantine, reset proof, rate limit, " "PM rollback, DATA, IPC deadline and interrupt wait, MMAP/dma-buf release ordering, " - "session and MCTF pool lifetime, canary, unconfirmed Close, unusable witness"); + "session and MCTF pool lifetime, canary, unconfirmed Close, unusable witness, " + "bounded quarantine beside a running session"); return 0; } diff --git a/drivers/media/platform/apple/ave/tests/run-recovery.py b/drivers/media/platform/apple/ave/tests/run-recovery.py index da00c6ad1a351..110009911335e 100644 --- a/drivers/media/platform/apple/ave/tests/run-recovery.py +++ b/drivers/media/platform/apple/ave/tests/run-recovery.py @@ -1,6 +1,11 @@ #!/usr/bin/env python3 # SPDX-License-Identifier: GPL-2.0-only -"""Exercise production AVE recovery, PM and queue callbacks at a fake boundary.""" +"""Exercise production AVE recovery, PM and queue callbacks at a fake boundary. + +With --ref the driver sources of that revision are built instead (the +negative control); the boundary and the test cases stay this tree's. +""" +import argparse import os from pathlib import Path import re @@ -14,8 +19,29 @@ def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument('--ref', help='build the driver of this revision instead') + args = parser.parse_args() here = Path(__file__).resolve().parent - src = here.parent + tree = here.parent + + class Driver: + """The driver directory, or the same files at --ref.""" + + def __truediv__(self, name): + return File(name) + + class File: + def __init__(self, name): + self.name = name + + def read_text(self): + if not args.ref: + return (tree / self.name).read_text() + return subprocess.check_output(['git', '-C', str(tree), 'show', + f'{args.ref}:./{self.name}'], text=True) + + src = Driver() header = (src / 'ave.h').read_text() code = (here / 'shim.h').read_text() code += '\ntypedef uintptr_t phys_addr_t;\n' @@ -46,7 +72,8 @@ def main(): 'ave_fw_runtime_suspend', 'ave_fw_prepare_restart', 'ave_fw_restore_data'), 'ave-sess.c': ('ave_mctf_pool_crc', 'ave_mctf_pool_check', 'ave_mctf_pool_return', 'ave_sess_domain_unsafe', 'ave_sess_free_bufs', 'ave_sess_destroy', 'ave_sess_reap'), 'ave-v4l2.c': ('ave_return_bufs', 'ave_buf_queue', 'ave_session_index', - 'ave_session_count', 'ave_session_close', 'ave_session_free', + 'ave_session_count', 'ave_session_close', 'ave_session_attach', + 'ave_session_free', 'ave_session_end', 'ave_stop_streaming', 'ave_reset_drain', 'ave_job_ready', 'ave_job_fail', 'ave_poll_work'), 'ave-ipc.c': ('ave_ipc_pump',), @@ -67,7 +94,8 @@ def main(): '-Wno-unused-function', '-fsanitize=address,undefined', '-fno-omit-frame-pointer', str(path / 'test.c'), '-o', str(path / 'test')], check=True) - subprocess.run([str(path / 'test')], check=True) + # A failed check aborts the test: report it as this script's status. + sys.exit(subprocess.run([str(path / 'test')]).returncode) if __name__ == '__main__': diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index a3c33382e0fb1..4bc32e7806864 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -479,6 +479,9 @@ def mutations(flag, names, base, expect=KILL): # recovery code built against host boundaries. ('ave-host', AVE_TESTS, ['python3', '-I', '-B', 'run.py', '--build', '{out}']), ('ave-recovery', AVE_TESTS, ['python3', '-I', '-B', 'run-recovery.py']), + # This revision keeps every session stopped beside a running one. + ('ave-recovery-old', AVE_TESTS, ['python3', '-I', '-B', 'run-recovery.py', + '--ref', '255761f1d55f8dcf3e2c24d17095439237ad6f72'], KILL), ('ave-input', AVE_TESTS, ['python3', '-I', '-B', 'run-input.py']), ('ave-ipc', AVE_TESTS, ['python3', '-I', '-B', 'run-ipc.py']), ] @@ -516,11 +519,12 @@ def jobs(work, conf, dtc): sys.exit(2) result = [] # The suites take longest, so start them first. - for name, cwd, cmd in SUITES: + for name, cwd, cmd, *expect in SUITES: d = work / name # Only ASan catches an unbounded legacy reply copy, so keep it on. env = {'AFKV2_SANITIZERS': '1', 'HOSTCC': name.rsplit('-', 1)[1]} if name.startswith('apple-afkv2') else {} - result.append((name, [a.replace('{out}', str(d / 'out')) for a in cmd], cwd, PASS, d, env)) + result.append((name, [a.replace('{out}', str(d / 'out')) for a in cmd], cwd, + expect[0] if expect else PASS, d, env)) for name, runs in ASAHI_TESTS.items(): for index, (args, expect) in enumerate(runs): label = name.removesuffix('.py') + ('' if not args or args == out() or args == out('--output') From 73509b814f71edf5c288729aad5508acd7a45903 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Thu, 26 Nov 2026 05:37:45 -0500 Subject: [PATCH 2/2] media: apple: ave: bound stopped sessions when the firmware gives no reset proof When the firmware does not arm the reset witness (witness_unusable), ave_sess_reap() keeps every stopped session for the whole boot, since nothing proves the engines stopped. The limit from the previous commit applied only beside a running session, so sessions started one at a time, each halting the firmware when it stopped, still piled up without bound. In that state, refuse a new session once AVE_MAX_SESSIONS stopped sessions wait, whether or not another runs, and say so once. The encoder then stops taking sessions for the rest of that boot instead of holding more memory it can never give back. Add a recovery host case that starts and stops sessions one at a time with no reset proof. The first AVE_MAX_SESSIONS run, the rest are refused before the firmware sees them, and what waits stays within the bound. At the previous commit, the list grows past it. Signed-off-by: DjDeveloperr --- drivers/media/platform/apple/ave/ave-v4l2.c | 8 +++ .../platform/apple/ave/tests/recovery-test.c | 49 ++++++++++++++++++- 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/drivers/media/platform/apple/ave/ave-v4l2.c b/drivers/media/platform/apple/ave/ave-v4l2.c index 893c5e1d3e68d..93e13a961d8cb 100644 --- a/drivers/media/platform/apple/ave/ave-v4l2.c +++ b/drivers/media/platform/apple/ave/ave-v4l2.c @@ -841,7 +841,15 @@ static int ave_session_attach(struct ave_ctx *ctx) * Starting and stopping sessions next to one that stays open would * keep all of it: once as many stopped sessions wait as the encoder * runs at once, refuse another before the firmware is given anything. + * Without a reset proof (witness_unusable) the reap never frees them + * this boot, so then the limit holds with no session running too. */ + if (ave->witness_unusable && ave->failed_count >= AVE_MAX_SESSIONS) { + dev_warn_once(ave->dev, + "%u stopped sessions wait for a reset proof this firmware does not give; not starting more\n", + ave->failed_count); + return -EBUSY; + } if (ave_session_count(ave) && ave->failed_count >= AVE_MAX_SESSIONS) { dev_err_ratelimited(ave->dev, "%u stopped sessions wait for the encoder to power off; not starting another\n", diff --git a/drivers/media/platform/apple/ave/tests/recovery-test.c b/drivers/media/platform/apple/ave/tests/recovery-test.c index 1d44884c17fe2..0bc628b695a8a 100644 --- a/drivers/media/platform/apple/ave/tests/recovery-test.c +++ b/drivers/media/platform/apple/ave/tests/recovery-test.c @@ -651,9 +651,56 @@ static void quarantine_churn(void) assert(!ave.failed_sessions && !ave.failed_count); } +/* + * Without a reset proof the reap keeps every stopped session for the whole + * boot, so sessions started one at a time would pile up with none running + * beside them. There the limit holds with no session running too. + */ +static void quarantine_no_witness(void) +{ + unsigned int started = 0, refused = 0; + int ret; + + init(); + ave.fw_state = AVE_FW_HALTED; + ave.witness_unusable = true; + for (unsigned int i = 0; i < 8; i++) { + ctx[0].sess = calloc(1, sizeof(*ctx[0].sess)); + assert(ctx[0].sess); + ctx[0].sess->p.slots = 2; + ctx[0].sess->p.codec = AVE_CODEC_H264; + submit_ctx = &ctx[0]; + mutex_lock(&ave.hw_lock); + /* The restart's reap has no proof and keeps the list. */ + ave_sess_reap(&ave); + ret = ave_session_attach(&ctx[0]); + if (!ret) { + started++; + ave_session_close(&ctx[0], false); /* the last one: halt */ + } else { + refused++; + assert(ret == -EBUSY && !ctx[0].sess->handed && !ave.sessions[0]); + } + mutex_unlock(&ave.hw_lock); + ave_sess_destroy(&ctx[0]); + assert(quarantined() <= AVE_MAX_SESSIONS && !ave_session_count(&ave)); + } + assert(started == AVE_MAX_SESSIONS && refused == 8 - started); + assert(ave.failed_count == AVE_MAX_SESSIONS && halts == AVE_MAX_SESSIONS); + + /* Test cleanup only: a proof this firmware never gives. */ + ave.witness_unusable = false; + stop_seen = power_seen = true; + mutex_lock(&ave.hw_lock); + ave_sess_reap(&ave); + mutex_unlock(&ave.hw_lock); + assert(!ave.failed_sessions && !ave.failed_count); +} + int main(void) { quarantine_churn(); + quarantine_no_witness(); session_lifetime(); unconfirmed_close(); unusable_witness(); @@ -670,6 +717,6 @@ int main(void) puts("ok: recovery ownership, queues, quarantine, reset proof, rate limit, " "PM rollback, DATA, IPC deadline and interrupt wait, MMAP/dma-buf release ordering, " "session and MCTF pool lifetime, canary, unconfirmed Close, unusable witness, " - "bounded quarantine beside a running session"); + "bounded quarantine beside a running session and without a reset proof"); return 0; }