From 184c074eb6dae58bcc01bf259064b962ff09272b Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Tue, 17 Nov 2026 09:37:33 -0500 Subject: [PATCH 01/19] build: expose headless Stage 1 option for J613 proxy host Signed-off-by: Satya Benson --- Makefile | 6 ++++++ tests/python/test_no_display_build.py | 22 ++++++++++++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 tests/python/test_no_display_build.py diff --git a/Makefile b/Makefile index de04715d2..beff1846b 100644 --- a/Makefile +++ b/Makefile @@ -102,6 +102,12 @@ ifeq ($(BRINGUP),1) CFG += BRINGUP endif +# Proxy-only Stage 1 images can run headless. This selects display.c's existing +# NO_DISPLAY path without changing the default or any installed boot image. +ifeq ($(NO_DISPLAY),1) +CFG += NO_DISPLAY +endif + ifeq ($(CHAINLOADING),1) CFG += CHAINLOADING CARGO_FLAGS += --features chainload diff --git a/tests/python/test_no_display_build.py b/tests/python/test_no_display_build.py new file mode 100644 index 000000000..2fe9ba973 --- /dev/null +++ b/tests/python/test_no_display_build.py @@ -0,0 +1,22 @@ +# SPDX-License-Identifier: GPL-2.0-only +"""The proxy-only Stage 1 can select Aura's existing headless display path.""" + +from pathlib import Path +import subprocess + + +ROOT = Path(__file__).resolve().parents[2] + + +def build_cfg(no_display: str) -> str: + subprocess.run( + ["gmake", "-s", "build-cfg", f"NO_DISPLAY={no_display}"], + cwd=ROOT, + check=True, + ) + return (ROOT / "build" / "build_cfg.h").read_text() + + +def test_no_display_is_explicit_and_defaults_off(): + assert "#define NO_DISPLAY" not in build_cfg("0") + assert "#define NO_DISPLAY" in build_cfg("1") From fa27578b71bf2c45e50ee4457e66015e0409592c Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Wed, 11 Nov 2026 16:55:40 -0500 Subject: [PATCH 02/19] Prepare fail-closed T8122 stock-SPTM profile and resident ANE capture Signed-off-by: Satya Benson --- proxyclient/aura/profiles/j613-25G83.json | 122 ++++++++++++++++++++++ proxyclient/aura/sptm_j613.py | 18 ++++ proxyclient/tools/run_guest_sptm.py | 19 +++- src/sptm_virt.c | 6 +- src/sptm_virt.h | 1 + src/sptm_virt_gpu.c | 57 +++++++++- tests/python/test_sptm_j613.py | 22 ++++ 7 files changed, 242 insertions(+), 3 deletions(-) create mode 100644 proxyclient/aura/profiles/j613-25G83.json create mode 100644 proxyclient/aura/sptm_j613.py create mode 100644 tests/python/test_sptm_j613.py diff --git a/proxyclient/aura/profiles/j613-25G83.json b/proxyclient/aura/profiles/j613-25G83.json new file mode 100644 index 000000000..c2cc6cf3f --- /dev/null +++ b/proxyclient/aura/profiles/j613-25G83.json @@ -0,0 +1,122 @@ +{ + "mode": "A", + "board": "J613", + "soc": "T8122", + "build": "25G83", + "source_adt_sha256": "e2c8cb7f1ebbe3849ce14d0c6d83838cae6c1dc17d8df2c4cffe616508b1f0f1", + "max_events": 250000, + "read": true, + "write": true, + "values": true, + "trace_mode": "SYNC", + "commit_allowed": false, + "resources": [ + { + "path": "/arm-io/ane", + "index": 0, + "base": "0x311400000", + "size": "0x6c000" + }, + { + "path": "/arm-io/ane", + "index": 1, + "base": "0x311050000", + "size": "0x4000" + }, + { + "path": "/arm-io/ane", + "index": 2, + "base": "0x310000000", + "size": "0x2000000" + }, + { + "path": "/arm-io/ane", + "index": 3, + "base": "0x2d0700000", + "size": "0x18000" + }, + { + "path": "/arm-io/ane", + "index": 4, + "base": "0x2d0724000", + "size": "0x4000" + }, + { + "path": "/arm-io/dart-ane", + "index": 0, + "base": "0x311800000", + "size": "0x4000" + }, + { + "path": "/arm-io/dart-ane", + "index": 1, + "base": "0x311810000", + "size": "0x4000" + }, + { + "path": "/arm-io/dart-ane", + "index": 2, + "base": "0x311820000", + "size": "0x4000" + }, + { + "path": "/arm-io/dart-ane", + "index": 3, + "base": "0x311804000", + "size": "0x4000" + }, + { + "path": "/arm-io/aic", + "index": 0, + "base": "0x2d1000000", + "size": "0x184000" + } + ], + "windows": [ + { + "base": "0x292468000", + "size": "0x4", + "end_exclusive": "0x292468004" + }, + { + "base": "0x2a5468000", + "size": "0x4", + "end_exclusive": "0x2a5468004" + }, + { + "base": "0x2d0700000", + "size": "0x18000", + "end_exclusive": "0x2d0718000" + }, + { + "base": "0x2d0724000", + "size": "0x4000", + "end_exclusive": "0x2d0728000" + }, + { + "base": "0x2d1000000", + "size": "0x184000", + "end_exclusive": "0x2d1184000" + }, + { + "base": "0x310000000", + "size": "0x2000000", + "end_exclusive": "0x312000000" + } + ], + "patch_export": { + "image_sha256": null, + "uuid": null, + "groups": { + "APSTS poll": null, + "CTRR check": null, + "CTRR reset-path check": null, + "ctXr lock check": null, + "AMCC CTRR match": null + }, + "ctrr_stash_off": null, + "ctxr_ctl": null, + "sptm_va_maps": null, + "reviewed": false + } +} diff --git a/proxyclient/aura/sptm_j613.py b/proxyclient/aura/sptm_j613.py new file mode 100644 index 000000000..d02440522 --- /dev/null +++ b/proxyclient/aura/sptm_j613.py @@ -0,0 +1,18 @@ +# SPDX-License-Identifier: MIT +"""Experimental T8122 profile. No J700 patch fallback; no Apple image reads on import.""" +import json +from pathlib import Path +PROFILE = json.loads((Path(__file__).parent / 'profiles/j613-25G83.json').read_text()) +# Export must bind image SHA256/UUID and provide checked sites and GL constants. +PATCH_EXPORT = None + +def capability(mmfr2, gxf): + return ((mmfr2 >> 24) & 15) >= 2 and gxf + +def validate_resources(get_reg): + for r in PROFILE['resources']: + if 'index' in r and tuple(get_reg(r['path'], r['index'])) != (int(r['base'], 0), int(r['size'], 0)): + raise ValueError('ADT drift: ' + str(r)) + +def patch_plan(image, entry_off): + raise ValueError('J613 dirty-room patch/GL export absent; guest entry disabled') diff --git a/proxyclient/tools/run_guest_sptm.py b/proxyclient/tools/run_guest_sptm.py index da7d407f2..a71915884 100755 --- a/proxyclient/tools/run_guest_sptm.py +++ b/proxyclient/tools/run_guest_sptm.py @@ -112,6 +112,7 @@ "AURA_S2R_DROP_USB": 1 << 4, "AURA_XNU_BT": 1 << 5, "AURA_GPU_TRACE": 1 << 6, + "AURA_J613_TRACE": 1 << 11, "AURA_SAMPLE": 1 << 7, "AURA_S2R_MEM": 1 << 8, # bit 9 is reserved for AURA_AURACTL in the feat/auractl runner @@ -845,6 +846,21 @@ def main(): # SPTM's managed window, as aura computed it: above aura and everything iBoot left low, # below aura's carve-out. + chip = u.adt["/chosen"].chip_id + if chip == 0x8122: + from aura import sptm_j613 + sptm_j613.validate_resources(lambda path, idx: u.adt[path].get_reg(idx)) + if not env_on("AURA_J613_TRACE"): + raise SystemExit("T8122 requires experimental AURA_J613_TRACE=1") + if any(env_on(k) for k in CONFIG_FLAGS if k != "AURA_J613_TRACE"): + raise SystemExit("J613: other trace/sleep modes are not qualified") + # Deliberately before reading images or placing anything on the target. + try: + sptm_j613.patch_plan(None, None) + except ValueError as e: + raise SystemExit(str(e)) + elif env_on("AURA_J613_TRACE"): + raise SystemExit("AURA_J613_TRACE requires T8122") scratch = u.malloc(0x40) if p.call(sym["sptm_virt_place"], scratch) != 0: raise SystemExit("sptm_virt_place failed: not an SPTM_VIRT build, no FEAT_NV2 or GXF, or " @@ -919,7 +935,8 @@ def main(): quirk_hide = tuple(quirks["hide"]) if env_on("AURA_KEEP_WIFI"): quirk_hide = tuple(n for n in quirk_hide if n in port_nodes) - hide = port_nodes + (() if env_on("AURA_KEEP_ANE") else STRIP_NODES) + quirk_hide + keep_ane = env_on("AURA_KEEP_ANE") or (chip == 0x8122 and env_on("AURA_J613_TRACE")) + hide = port_nodes + (() if keep_ane else STRIP_NODES) + quirk_hide if not env_on("AURA_KEEP_ERRH"): hide += (ERROR_HANDLER,) if env_on("AURA_HIDE_DOCKCHANNEL"): diff --git a/src/sptm_virt.c b/src/sptm_virt.c index 8f726982c..91f849cf9 100644 --- a/src/sptm_virt.c +++ b/src/sptm_virt.c @@ -266,7 +266,7 @@ __attribute__((used, retain)) int sptm_virt_place(struct sptm_virt_placement *ou { struct sptm_virt_layout l; - if (!out) + if (!out || !sptm_virt_requested()) return -1; memset(out, 0, sizeof(*out)); if (sptm_virt_layout(&l) < 0 || sptm_virt_gl_alloc() < 0) @@ -349,6 +349,10 @@ __attribute__((used, retain)) int sptm_virt_load(u64 sptm_entry, u64 handoff) { struct sptm_virt_layout l; + /* T8122 register/patch export has not been reviewed. Even a direct proxy call + * must not bypass the host profile's refusal. Remove only with that port. */ + if (!sptm_virt_requested() || chip_id == T8122) + return -1; if (sptm_virt_layout(&l) < 0) { printf("SPTM-virt: load refused, no valid carve-out layout\n"); return -1; diff --git a/src/sptm_virt.h b/src/sptm_virt.h index 60a7ce58f..39115aa3d 100644 --- a/src/sptm_virt.h +++ b/src/sptm_virt.h @@ -52,6 +52,7 @@ struct sptm_virt_placement { #define SPTM_VIRT_S2R_MEM BIT(8) /* T6050: also hook the MCC and the coprocessor DARTs */ /* bit 9 is AURA_AURACTL in the feat/auractl runner; left free here so the two never clash */ #define SPTM_VIRT_CTL_DCC BIT(10) /* arm auractl's DCC transport (MDCR_EL2.TDCC) at boot */ +#define SPTM_VIRT_J613_TRACE BIT(11) /* bounded J613 ANE/AIC trace; exact ADT resources only */ /* sptm_virt_s2r_cp_ansx, with COPROC on T6050 */ #define S2R_CP_ANSX_SART BIT(0) /* sart-ans reg[0-2], first page each */ #define S2R_CP_ANSX_NVME BIT(1) /* the NVMe BAR's first page (reg[9]) */ diff --git a/src/sptm_virt_gpu.c b/src/sptm_virt_gpu.c index 713cb3415..d86da6dd0 100644 --- a/src/sptm_virt_gpu.c +++ b/src/sptm_virt_gpu.c @@ -17,6 +17,7 @@ #include "iodev.h" #include "malloc.h" #include "memory.h" +#include "soc.h" #include "sptm_virt_priv.h" #include "string.h" #include "uartproxy.h" @@ -152,6 +153,9 @@ void sptm_virt_gpu_deadline(struct exc_info *ctx) static bool gpu_hook(struct exc_info *ctx, u64 addr, u64 *val, bool write, int width) { + if ((sptm_virt_flags & SPTM_VIRT_J613_TRACE) && + sptm_virt_gpu_head + 2 >= sptm_virt_gpu_nrec) + gpu_park(ctx, "the bounded J613 trace ring is full"); u64 now = mrs(CNTPCT_EL0); if (!gpu_first_t) { @@ -240,6 +244,52 @@ static void gpu_hook_adt(const char *path, int idx, const char *what, u64 off, u gpu_hook_range(what, pa + off, size ? size : sz); } +/* J613 ranges transcribed from the retained ADT, not from a J700 base shift. + * Validate the entire resource list before installing any hook; no MMIO sweep. */ +static void j613_capture_setup(void) +{ + sptm_virt_gpu_print_max = 0; /* export the ring; no per-access console timing noise */ + if (chip_id != T8122 || (sptm_virt_flags & ~SPTM_VIRT_J613_TRACE)) + panic("J613 capture: wrong chip or conflicting capture modes\n"); + static const struct { const char *path; int idx; u64 base, size; } resources[] = { + {"/arm-io/ane", 0, 0x311400000UL, 0x6c000UL}, + {"/arm-io/ane", 1, 0x311050000UL, 0x4000UL}, + {"/arm-io/ane", 2, 0x310000000UL, 0x2000000UL}, + {"/arm-io/ane", 3, 0x2d0700000UL, 0x18000UL}, + {"/arm-io/ane", 4, 0x2d0724000UL, 0x4000UL}, + {"/arm-io/dart-ane", 0, 0x311800000UL, 0x4000UL}, + {"/arm-io/dart-ane", 1, 0x311810000UL, 0x4000UL}, + {"/arm-io/dart-ane", 2, 0x311820000UL, 0x4000UL}, + {"/arm-io/dart-ane", 3, 0x311804000UL, 0x4000UL}, + {"/arm-io/aic", 0, 0x2d1000000UL, 0x184000UL}, + }; + for (size_t i = 0; i < ARRAY_SIZE(resources); i++) { + int p[8]; u64 a, n; + if (adt_path_offset_trace(adt, resources[i].path, p) < 0 || + adt_get_reg(adt, p, "reg", resources[i].idx, &a, &n) < 0 || + a != resources[i].base || n != resources[i].size) + panic("J613 capture: ADT resource drift\n"); + } + static const struct { u64 base, size; } windows[] = { + {0x292468000UL, 0x4UL}, + {0x2a5468000UL, 0x4UL}, + {0x2d0700000UL, 0x18000UL}, + {0x2d0724000UL, 0x4000UL}, + {0x2d1000000UL, 0x184000UL}, + {0x310000000UL, 0x2000000UL}, + }; + for (size_t i = 0; i < ARRAY_SIZE(windows); i++) { + gpu_ranges[gpu_nranges].base = windows[i].base; + gpu_ranges[gpu_nranges].size = windows[i].size; + gpu_ranges[gpu_nranges++].what = "j613"; + /* Keep the two AON words at four-byte granularity. */ + if (hv_map_hook(windows[i].base, gpu_hook, windows[i].size) < 0) + panic("J613 capture: hook installation failed\n"); + } + printf("J613 capture: %d exact windows, ring at 0x%lx; export before reset\n", + gpu_nranges, (u64)sptm_virt_gpu_ring); +} + void sptm_virt_gpu_setup(void) { /* The deadline park is offered from every GL trap (sptm_virt_gl_sync), GPU trace or not. */ @@ -248,7 +298,7 @@ void sptm_virt_gpu_setup(void) printf("SPTM-virt[park]: the guest parks in the proxy at its first GL trap after %u s\n", sptm_virt_gpu_stop_boot_secs); } - if (!(sptm_virt_flags & SPTM_VIRT_GPU)) + if (!(sptm_virt_flags & (SPTM_VIRT_GPU | SPTM_VIRT_J613_TRACE))) return; sptm_virt_gpu_ring = memalign(0x4000, GPU_RING_BYTES); if (!sptm_virt_gpu_ring) { @@ -261,6 +311,11 @@ void sptm_virt_gpu_setup(void) sptm_virt_gpu_nrec = GPU_RING_BYTES / sizeof(struct gpu_rec); sptm_virt_gpu_head = 0; + if (sptm_virt_flags & SPTM_VIRT_J613_TRACE) { + j613_capture_setup(); + return; + } + /* sgx reg 0 holds the GPU's PMGR (+0xe80000), its start control and both ASCs. */ gpu_hook_adt("/arm-io/sgx", 0, "sgx", 0, 0); /* Both GPU coprocessors' ASC windows: the mailboxes the driver and firmware talk over. */ diff --git a/tests/python/test_sptm_j613.py b/tests/python/test_sptm_j613.py new file mode 100644 index 000000000..47ab4ada6 --- /dev/null +++ b/tests/python/test_sptm_j613.py @@ -0,0 +1,22 @@ +# SPDX-License-Identifier: MIT +"""Admission failures: absent capability, unreviewed image, and ADT drift. +No Apple image fixtures or target connection are used. +""" +import pytest +from aura.sptm_j613 import capability, validate_resources, patch_plan, PROFILE + +def test_capability_and_incomplete_export(): + assert not capability(1 << 24, True) + assert not capability(2 << 24, False) + assert capability(2 << 24, True) + with pytest.raises(ValueError, match='dirty-room'): + patch_plan(b'', 0) + +def test_adt_validation_before_hooks(): + regs = {(r['path'], r['index']): (int(r['base'], 0), int(r['size'], 0)) + for r in PROFILE['resources'] if 'index' in r} + validate_resources(lambda p, i: regs[p, i]) + key = next(iter(regs)) + regs[key] = (0, 0) + with pytest.raises(ValueError, match='ADT drift'): + validate_resources(lambda p, i: regs[p, i]) From 6677564d5c46036dc8570cb69f609a8f31004505 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Tue, 17 Nov 2026 12:42:39 -0500 Subject: [PATCH 03/19] run_guest_sptm: do not drain KIS after guest entry Signed-off-by: Satya Benson --- proxyclient/tools/run_guest_sptm.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/proxyclient/tools/run_guest_sptm.py b/proxyclient/tools/run_guest_sptm.py index a71915884..945b8b11a 100755 --- a/proxyclient/tools/run_guest_sptm.py +++ b/proxyclient/tools/run_guest_sptm.py @@ -1039,7 +1039,11 @@ def main(): # sptm_virt_enter does not return. Waiting for a reply or a boot banner would eat the guest's # first console output and reopen the link. p.request(p.P_CALL, sym["sptm_virt_enter"], no_reply=True) - iface.dev.flush() + # Once a KIS target enters the guest it can stop consuming host OUT immediately. The enter + # request is already queued by write(); tcdrain here can then block forever and prevent the + # console tail from reading the guest's first output. Other UART transports retain the drain. + if not iface.is_kis: + iface.dev.flush() secs = env_int("AURA_TAIL_SECS") if secs > 0: tail_console(iface, secs, float(os.environ.get("AURA_TAIL_IDLE") or 10)) From ce7c5d986998ab534ab614e032d3f4f3427617ac Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Tue, 17 Nov 2026 12:45:58 -0500 Subject: [PATCH 04/19] run_guest_sptm: avoid USB CDC drain after entry Signed-off-by: Satya Benson --- proxyclient/tools/run_guest_sptm.py | 15 ++++++++++--- tests/python/test_run_guest_sptm.py | 35 +++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 3 deletions(-) diff --git a/proxyclient/tools/run_guest_sptm.py b/proxyclient/tools/run_guest_sptm.py index 945b8b11a..8a75f476a 100755 --- a/proxyclient/tools/run_guest_sptm.py +++ b/proxyclient/tools/run_guest_sptm.py @@ -365,6 +365,15 @@ def aura_heap_size(adt): return (112 if j813 else 128) * 1024 * 1024 +def post_entry_drain_needed(iface): + """A device-side USB serial endpoint can stop accepting OUT as the guest enters.""" + if iface.is_kis: + return False + port = iface.devpath or getattr(iface.dev, "port", "") or "" + device = os.path.basename(os.path.realpath(port)) + return not device.startswith(("ttyACM", "cu.usbmodem", "tty.usbmodem")) + + def parse_args(): ap = argparse.ArgumentParser(description="Boot the stock SPTM as an NV2 guest under aura") ap.add_argument("--sptm", type=pathlib.Path, required=True, help="sptm.bin (flat Mach-O)") @@ -1039,10 +1048,10 @@ def main(): # sptm_virt_enter does not return. Waiting for a reply or a boot banner would eat the guest's # first console output and reopen the link. p.request(p.P_CALL, sym["sptm_virt_enter"], no_reply=True) - # Once a KIS target enters the guest it can stop consuming host OUT immediately. The enter + # Once a USB target enters the guest it can stop consuming host OUT immediately. The enter # request is already queued by write(); tcdrain here can then block forever and prevent the - # console tail from reading the guest's first output. Other UART transports retain the drain. - if not iface.is_kis: + # console tail from reading the guest's first output. Real UARTs retain the drain. + if post_entry_drain_needed(iface): iface.dev.flush() secs = env_int("AURA_TAIL_SECS") if secs > 0: diff --git a/tests/python/test_run_guest_sptm.py b/tests/python/test_run_guest_sptm.py index 1dd1a69ae..ac75f94fe 100644 --- a/tests/python/test_run_guest_sptm.py +++ b/tests/python/test_run_guest_sptm.py @@ -17,6 +17,14 @@ TOOLS = ("run_guest_sptm.py", "console_tail.py") +def load_runner(): + spec = importlib.util.spec_from_file_location( + "run_guest_sptm", REPO / "proxyclient/tools/run_guest_sptm.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + def aura_imports(path): """Every `from aura... import name` in a tool, including those inside functions.""" for node in ast.walk(ast.parse(path.read_text())): @@ -102,3 +110,30 @@ def test_same_release_selects_exact_kernel(offset, instruction, selected, hidden release, quirks = tool.xnu_quirks(b"xnu-13432.41.4~") assert (release == "xnu-13432.41.4") == selected assert ("/arm-io/centauri" in quirks["hide"]) == hidden_radio + + +@pytest.mark.parametrize(("port", "is_kis", "expected"), ( + ("/dev/ttyAMA10", False, True), + ("/dev/ttyACM0", False, False), + ("/dev/cu.usbmodemP_01", False, False), + ("/dev/tty.kis-1", True, False), +)) +def test_post_entry_drain_needed(port, is_kis, expected): + runner = load_runner() + iface = type("Iface", (), { + "devpath": port, + "dev": type("Serial", (), {"port": port})(), + "is_kis": is_kis, + })() + assert runner.post_entry_drain_needed(iface) is expected + + +def test_post_entry_drain_resolves_m1n1_symlink(monkeypatch): + runner = load_runner() + monkeypatch.setattr(runner.os.path, "realpath", lambda path: "/dev/ttyACM0") + iface = type("Iface", (), { + "devpath": "/dev/m1n1", + "dev": type("Serial", (), {"port": "/dev/m1n1"})(), + "is_kis": False, + })() + assert runner.post_entry_drain_needed(iface) is False From 9a95dbc9e4d9fee211ce04584fc191b4f6f8f6f4 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Tue, 17 Nov 2026 12:57:46 -0500 Subject: [PATCH 05/19] sptm: bind partial J613 clean-room export Signed-off-by: Satya Benson --- proxyclient/aura/profiles/j613-25G83.json | 26 ++++++++++++-- proxyclient/aura/sptm_j613.py | 41 +++++++++++++++++++++-- tests/python/test_sptm_j613.py | 23 +++++++++++-- 3 files changed, 82 insertions(+), 8 deletions(-) diff --git a/proxyclient/aura/profiles/j613-25G83.json b/proxyclient/aura/profiles/j613-25G83.json index c2cc6cf3f..195bef7bd 100644 --- a/proxyclient/aura/profiles/j613-25G83.json +++ b/proxyclient/aura/profiles/j613-25G83.json @@ -105,10 +105,30 @@ } ], "patch_export": { - "image_sha256": null, - "uuid": null, + "image_sha256": "6ab3f26ff9445a802e2e88d2347f7d64157d1b9eab783523ab0e7eab183bef6b", + "uuid": "2B57CA7A-3D9C-3C70-B5E0-7C3F74C5323B", + "entry_file_offset": "0xa8388", "groups": { - "APSTS poll": null, + "APSTS poll": [ + { + "purpose": "shared cold/reset readiness wait", + "pattern_offset": "0xab7ac", + "pattern": "df3f03d51f8708d59f3b03d580fc3ed501004092c1ffffb480f03cd5000040b2", + "patch_offset": "0xab7c0", + "entry_offset": "0x3438", + "expected": "0xb4ffffc1", + "replacement": "0xd503201f" + }, + { + "purpose": "early-entry readiness wait", + "pattern_offset": "0x9c0b0", + "pattern": "28a2acf228a294f2482018d58afc3ed548014092c8ffffb48af03cd54a0140b2", + "patch_offset": "0x9c0c4", + "entry_offset": "-0xc2c4", + "expected": "0xb4ffffc8", + "replacement": "0xd503201f" + } + ], "CTRR check": null, "CTRR reset-path check": null, "ctXr lock check": null, diff --git a/proxyclient/aura/sptm_j613.py b/proxyclient/aura/sptm_j613.py index d02440522..ba55e68cf 100644 --- a/proxyclient/aura/sptm_j613.py +++ b/proxyclient/aura/sptm_j613.py @@ -1,10 +1,11 @@ # SPDX-License-Identifier: MIT """Experimental T8122 profile. No J700 patch fallback; no Apple image reads on import.""" +import hashlib import json +import struct from pathlib import Path PROFILE = json.loads((Path(__file__).parent / 'profiles/j613-25G83.json').read_text()) -# Export must bind image SHA256/UUID and provide checked sites and GL constants. -PATCH_EXPORT = None +PATCH_EXPORT = PROFILE['patch_export'] def capability(mmfr2, gxf): return ((mmfr2 >> 24) & 15) >= 2 and gxf @@ -14,5 +15,39 @@ def validate_resources(get_reg): if 'index' in r and tuple(get_reg(r['path'], r['index'])) != (int(r['base'], 0), int(r['size'], 0)): raise ValueError('ADT drift: ' + str(r)) +def inspect_patch_export(image, entry_off): + """Validate and return the clean-room facts that are complete without admitting entry.""" + if image is None: + return {'reviewed': False, 'unresolved': unresolved_groups()} + if hashlib.sha256(image).hexdigest() != PATCH_EXPORT['image_sha256']: + raise ValueError('J613 SPTM image identity does not match the 25G83 export') + expected_entry = int(PATCH_EXPORT['entry_file_offset'], 0) + if entry_off != expected_entry: + raise ValueError(f'J613 SPTM entry offset {entry_off:#x}, expected {expected_entry:#x}') + patches = [] + for site in PATCH_EXPORT['groups']['APSTS poll']: + pattern = bytes.fromhex(site['pattern']) + hits = [i for i in range(len(image) - len(pattern) + 1) + if image[i:i + len(pattern)] == pattern] + start = int(site['pattern_offset'], 0) + if hits != [start]: + raise ValueError(f"J613 {site['purpose']}: pattern hits {hits}, expected [{start}]") + patch_off = int(site['patch_offset'], 0) + expected = int(site['expected'], 0) + if struct.unpack_from(' Date: Tue, 17 Nov 2026 13:14:51 -0500 Subject: [PATCH 06/19] sptm: shadow exact T8122 AMCC contract Signed-off-by: Satya Benson --- proxyclient/aura/profiles/j613-25G83.json | 6 +- src/sptm_virt_s2.c | 159 ++++++++++++++++++++-- tests/python/test_sptm_j613.py | 3 +- tests/python/test_sptm_t8122_amcc.py | 81 +++++++++++ 4 files changed, 230 insertions(+), 19 deletions(-) create mode 100644 tests/python/test_sptm_t8122_amcc.py diff --git a/proxyclient/aura/profiles/j613-25G83.json b/proxyclient/aura/profiles/j613-25G83.json index 195bef7bd..e11e185c3 100644 --- a/proxyclient/aura/profiles/j613-25G83.json +++ b/proxyclient/aura/profiles/j613-25G83.json @@ -129,9 +129,9 @@ "replacement": "0xd503201f" } ], - "CTRR check": null, - "CTRR reset-path check": null, - "ctXr lock check": null, + "CTRR check": [], + "CTRR reset-path check": [], + "ctXr lock check": [], "AMCC CTRR match": null }, "ctrr_stash_off": null, diff --git a/src/sptm_virt_s2.c b/src/sptm_virt_s2.c index 788a4d019..3e5b09587 100644 --- a/src/sptm_virt_s2.c +++ b/src/sptm_virt_s2.c @@ -373,7 +373,57 @@ static void sptm_virt_reset_guard_setup(void) * wrote, the hardware keeps them open. On by default; AURA_AMCC_NOLOCK=0 lets SPTM lock them. */ u32 sptm_virt_amcc_nolock = 1; -static u64 amcc_lock_shadow[16][2]; /* {pa, value} */ +static u64 amcc_lock_shadow[32][2]; /* {pa, value} */ + +/* + * T8122's stock SPTM describes its AMCC protection registers in + * /chosen/lock-regs/amcc. Stage 1 has already protected its own image in the + * real AMCC when the volatile guest starts, while SPTM requires an unlocked + * register bank for the image it is booting. Give the guest a zero-initialized + * shadow of only those described registers. The host's bounds and locks stay + * intact. The exact ADT contract is checked before any page is hooked. + */ +struct t8122_amcc_layout { + u32 lower; + u32 upper; + u32 enable; + u32 lock; + u32 write_disable; + u32 cache_status; + u32 cache_status_mask; + u32 cache_status_value; +}; +static struct t8122_amcc_layout t8122_amcc; +static bool t8122_amcc_ready; + +static bool amcc_shadow_rw(u64 addr, u64 *val, bool write) +{ + for (unsigned i = 0; i < ARRAY_SIZE(amcc_lock_shadow); i++) { + if (amcc_lock_shadow[i][0] == addr || !amcc_lock_shadow[i][0]) { + if (write) { + amcc_lock_shadow[i][0] = addr; + amcc_lock_shadow[i][1] = *val; + return true; + } + if (amcc_lock_shadow[i][0] == addr) + *val = amcc_lock_shadow[i][1]; + else { + amcc_lock_shadow[i][0] = addr; + amcc_lock_shadow[i][1] = 0; + *val = 0; + } + return true; + } + } + return false; +} + +static bool t8122_amcc_is_shadow(u64 addr) +{ + u32 off = addr & 0x3fff; + return off == t8122_amcc.lower || off == t8122_amcc.upper || off == t8122_amcc.enable || + off == t8122_amcc.lock || off == t8122_amcc.write_disable; +} /* sptm_virt_amcc_nolock is a mask over the three locks: bit 0 +0xacc, bit 1 +0xadc, bit 2 +0xaec. * Only +0xacc covers aura (t124: shadowing it alone keeps aura's memory; the other two -- the @@ -393,30 +443,111 @@ static bool amcc_hook(struct exc_info *ctx, u64 addr, u64 *val, bool write, int printf("SPTM-virt[amcc]: guest wrote 0x%lx -> 0x%lx (w%d) at pc 0x%lx%s\n", *val, addr, width, ctx->elr, sptm_virt_amcc_nolock && amcc_is_lock(addr) ? " -- range lock shadowed" : ""); - if (sptm_virt_amcc_nolock && amcc_is_lock(addr) && width == 2) { - for (unsigned i = 0; i < ARRAY_SIZE(amcc_lock_shadow); i++) { - if (amcc_lock_shadow[i][0] == addr || !amcc_lock_shadow[i][0]) { - if (write) { - amcc_lock_shadow[i][0] = addr; - amcc_lock_shadow[i][1] = *val; - return true; - } - if (amcc_lock_shadow[i][0] == addr) { - *val = amcc_lock_shadow[i][1]; - return true; - } - break; + if (width == 2 && t8122_amcc_ready) { + if (t8122_amcc_is_shadow(addr)) + return amcc_shadow_rw(addr, val, write); + if ((addr & 0x3fff) == t8122_amcc.cache_status) { + if (!write) { + sptm_virt_mmio_rw(addr, val, false, width); + *val = (*val & ~t8122_amcc.cache_status_mask) | + t8122_amcc.cache_status_value; } + return true; } } + if (sptm_virt_amcc_nolock && amcc_is_lock(addr) && width == 2) + return amcc_shadow_rw(addr, val, write); sptm_virt_mmio_rw(addr, val, write, width); return true; } +static bool adt_u32_is(int node, const char *name, u32 expected) +{ + u32 value; + return ADT_GETPROP(adt, node, name, &value) >= 0 && value == expected; +} + +static bool sptm_virt_amcc_watch_t8122(void) +{ + int node = adt_path_offset(adt, "/chosen/lock-regs/amcc"); + int bank = node < 0 ? -1 : adt_subnode_offset(adt, node, "amcc-ctrr-a"); + u32 len = 0; + const u64 *apertures = node < 0 ? NULL : adt_getprop(adt, node, "aperture-phys-addr", &len); + const u64 exact_apertures[2] = {0x220000000UL, 0x222000000UL}; + + if (bank < 0 || !apertures || len != sizeof(exact_apertures) || + memcmp(apertures, exact_apertures, sizeof(exact_apertures)) || + !adt_u32_is(node, "aperture-count", 2) || !adt_u32_is(node, "aperture-size", 0x200000) || + !adt_u32_is(node, "plane-count", 2) || !adt_u32_is(node, "plane-stride", 0x40000) || + !adt_u32_is(node, "cache-status-reg-offset", 0x1c00) || + !adt_u32_is(node, "cache-status-reg-mask", 1) || + !adt_u32_is(node, "cache-status-reg-value", 0) || + !adt_u32_is(bank, "lower-limit-reg-offset", 0x690) || + !adt_u32_is(bank, "lower-limit-reg-mask", 0xffffffff) || + !adt_u32_is(bank, "upper-limit-reg-offset", 0x694) || + !adt_u32_is(bank, "upper-limit-reg-mask", 0xffffffff) || + !adt_u32_is(bank, "enable-reg-offset", 0x698) || + !adt_u32_is(bank, "enable-reg-mask", 1) || !adt_u32_is(bank, "enable-reg-value", 1) || + !adt_u32_is(bank, "lock-reg-offset", 0x69c) || !adt_u32_is(bank, "lock-reg-mask", 1) || + !adt_u32_is(bank, "lock-reg-value", 1) || + !adt_u32_is(bank, "write-disable-reg-offset", 0x6a0) || + !adt_u32_is(bank, "write-disable-reg-mask", 1) || + !adt_u32_is(bank, "write-disable-reg-value", 1) || + !adt_u32_is(bank, "page-size-shift", 14)) { + printf("SPTM-virt[amcc]: T8122 lock-reg ADT does not match J613/25G83; not watched\n"); + return false; + } + + t8122_amcc = (struct t8122_amcc_layout){ + .lower = 0x690, + .upper = 0x694, + .enable = 0x698, + .lock = 0x69c, + .write_disable = 0x6a0, + .cache_status = 0x1c00, + .cache_status_mask = 1, + .cache_status_value = 0, + }; + memset(amcc_lock_shadow, 0, sizeof(amcc_lock_shadow)); + + for (int i = 0; i < 2; i++) { + u64 base, stride; + int count; + if (mcc_plane_info(i, &base, &stride, &count) < 0 || base != exact_apertures[i] || + stride != 0x40000 || count != 2) { + printf("SPTM-virt[amcc]: T8122 MCC plane layout mismatch; not watched\n"); + return false; + } + } + + t8122_amcc_ready = true; + for (int i = 0; i < 2; i++) { + u64 base, stride; + int count; + mcc_plane_info(i, &base, &stride, &count); + for (int p = 0; p < count; p++) { + u64 page = base + p * stride; + if (hv_map_hook(page, amcc_hook, 0x4000) < 0) { + t8122_amcc_ready = false; + printf("SPTM-virt[amcc]: cannot hook T8122 MCC %d plane %d at 0x%lx\n", i, p, + page); + return false; + } + } + } + printf("SPTM-virt[amcc]: T8122 J613/25G83 exact lock-reg contract shadowed on 4 planes; " + "host protection unchanged\n"); + return true; +} + static void sptm_virt_amcc_watch(void) { u64 base, stride; int count; + if (chip_id == T8122) { + sptm_virt_amcc_watch_t8122(); + return; + } /* The plane offsets above are T8142's; other chips keep their AMCC unhooked. */ if (chip_id != T8142) return; diff --git a/tests/python/test_sptm_j613.py b/tests/python/test_sptm_j613.py index 35ab4fc48..115967000 100644 --- a/tests/python/test_sptm_j613.py +++ b/tests/python/test_sptm_j613.py @@ -17,8 +17,7 @@ def test_capability_and_incomplete_export(): assert capability(2 << 24, True) with pytest.raises(ValueError, match='dirty-room'): patch_plan(None, None) - assert unresolved_groups() == ['CTRR check', 'CTRR reset-path check', - 'ctXr lock check', 'AMCC CTRR match'] + assert unresolved_groups() == ['AMCC CTRR match'] assert inspect_patch_export(None, None)['unresolved'] == unresolved_groups() @pytest.mark.skipif(not REAL_IMAGE, reason='exact private J613 SPTM image not given') diff --git a/tests/python/test_sptm_t8122_amcc.py b/tests/python/test_sptm_t8122_amcc.py new file mode 100644 index 000000000..5911bdaca --- /dev/null +++ b/tests/python/test_sptm_t8122_amcc.py @@ -0,0 +1,81 @@ +# SPDX-License-Identifier: MIT +"""T8122's exact AMCC guest shadow is isolated from the host register bank.""" + +import re +import subprocess +from pathlib import Path + + +REPO = Path(__file__).resolve().parents[2] + + +def function(source, name): + match = re.search(r"^static bool " + name + r"\([^;]*?\)\s*\{", source, re.M | re.S) + assert match, name + end, depth = match.end(), 1 + while depth: + depth += (source[end] == "{") - (source[end] == "}") + end += 1 + return source[match.start():end] + + +def test_t8122_amcc_shadow(tmp_path): + source = (REPO / "src/sptm_virt_s2.c").read_text() + funcs = "\n".join(function(source, name) for name in + ("amcc_shadow_rw", "t8122_amcc_is_shadow")) + harness = r''' +#include +#include +#include +typedef uint32_t u32; +typedef uint64_t u64; +#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) +struct t8122_amcc_layout { + u32 lower, upper, enable, lock, write_disable; + u32 cache_status, cache_status_mask, cache_status_value; +}; +static struct t8122_amcc_layout t8122_amcc = { + .lower = 0x690, .upper = 0x694, .enable = 0x698, + .lock = 0x69c, .write_disable = 0x6a0, + .cache_status = 0x1c00, .cache_status_mask = 1, +}; +static u64 amcc_lock_shadow[32][2]; +''' + funcs + r''' +int main(void) +{ + const u64 bases[] = {0x220000000ULL, 0x220040000ULL, + 0x222000000ULL, 0x222040000ULL}; + const u32 regs[] = {0x690, 0x694, 0x698, 0x69c, 0x6a0}; + for (unsigned b = 0; b < ARRAY_SIZE(bases); b++) { + for (unsigned r = 0; r < ARRAY_SIZE(regs); r++) { + u64 pa = bases[b] + regs[r], value = 0xfeed0000 + b * 16 + r; + assert(t8122_amcc_is_shadow(pa)); + assert(amcc_shadow_rw(pa, &value, true)); + value = ~0ULL; + assert(amcc_shadow_rw(pa, &value, false)); + assert(value == 0xfeed0000 + b * 16 + r); + } + } + u64 fresh = ~0ULL; + assert(amcc_shadow_rw(0x2220406a4ULL, &fresh, false)); + assert(fresh == 0); + assert(!t8122_amcc_is_shadow(0x220001c00ULL)); + assert(!t8122_amcc_is_shadow(0x2200006a4ULL)); + return 0; +} +''' + binary = tmp_path / "t8122-amcc-shadow" + subprocess.run(["cc", "-std=gnu11", "-Wall", "-Wextra", "-Werror", "-x", "c", "-", + "-o", str(binary)], input=harness, text=True, check=True) + subprocess.run([str(binary)], check=True) + + +def test_t8122_amcc_exact_adt_gate_is_complete(): + source = (REPO / "src/sptm_virt_s2.c").read_text() + for token in ("0x220000000UL", "0x222000000UL", '"aperture-count", 2', + '"aperture-size", 0x200000', '"plane-count", 2', + '"plane-stride", 0x40000', '"lower-limit-reg-offset", 0x690', + '"upper-limit-reg-offset", 0x694', '"enable-reg-offset", 0x698', + '"lock-reg-offset", 0x69c', '"write-disable-reg-offset", 0x6a0', + '"cache-status-reg-offset", 0x1c00', '"page-size-shift", 14'): + assert token in source From bdf4820b5539198bb60fcb9bce1fbaab559041b9 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Tue, 17 Nov 2026 13:35:52 -0500 Subject: [PATCH 07/19] sptm: admit exact J613 stock path Signed-off-by: Satya Benson --- proxyclient/aura/profiles/j613-25G83.json | 4 ++-- proxyclient/aura/sptm_j613.py | 14 +++++++++---- proxyclient/tools/run_guest_sptm.py | 5 +++-- src/sptm_virt.c | 5 ++--- src/sptm_virt_priv.h | 1 + src/sptm_virt_s2.c | 25 +++++++++++++++++------ tests/python/test_sptm_j613.py | 19 +++++++++-------- tests/python/test_sptm_t8122_amcc.py | 3 +++ 8 files changed, 51 insertions(+), 25 deletions(-) diff --git a/proxyclient/aura/profiles/j613-25G83.json b/proxyclient/aura/profiles/j613-25G83.json index e11e185c3..50451af23 100644 --- a/proxyclient/aura/profiles/j613-25G83.json +++ b/proxyclient/aura/profiles/j613-25G83.json @@ -132,11 +132,11 @@ "CTRR check": [], "CTRR reset-path check": [], "ctXr lock check": [], - "AMCC CTRR match": null + "AMCC CTRR match": [] }, "ctrr_stash_off": null, "ctxr_ctl": null, "sptm_va_maps": null, - "reviewed": false + "reviewed": true } } diff --git a/proxyclient/aura/sptm_j613.py b/proxyclient/aura/sptm_j613.py index ba55e68cf..f78aacdac 100644 --- a/proxyclient/aura/sptm_j613.py +++ b/proxyclient/aura/sptm_j613.py @@ -18,7 +18,8 @@ def validate_resources(get_reg): def inspect_patch_export(image, entry_off): """Validate and return the clean-room facts that are complete without admitting entry.""" if image is None: - return {'reviewed': False, 'unresolved': unresolved_groups()} + return {'reviewed': bool(PATCH_EXPORT['reviewed']), + 'unresolved': unresolved_groups()} if hashlib.sha256(image).hexdigest() != PATCH_EXPORT['image_sha256']: raise ValueError('J613 SPTM image identity does not match the 25G83 export') expected_entry = int(PATCH_EXPORT['entry_file_offset'], 0) @@ -42,12 +43,17 @@ def inspect_patch_export(image, entry_off): patches.append(('APSTS poll', off, 0xffffffff, expected, int(site['replacement'], 0))) return {'patches': patches, 'ctrr_stash_off': None, 'mte': None, - 'reviewed': False, 'unresolved': unresolved_groups()} + 'reviewed': bool(PATCH_EXPORT['reviewed']), + 'unresolved': unresolved_groups()} def unresolved_groups(): return [name for name, rows in PATCH_EXPORT['groups'].items() if rows is None] def patch_plan(image, entry_off): partial = inspect_patch_export(image, entry_off) - missing = ', '.join(partial['unresolved']) - raise ValueError(f'J613 dirty-room patch/GL export incomplete ({missing}); guest entry disabled') + if partial['unresolved']: + missing = ', '.join(partial['unresolved']) + raise ValueError(f'J613 dirty-room patch/GL export incomplete ({missing}); guest entry disabled') + if not partial['reviewed']: + raise ValueError('J613 dirty-room patch/GL export is not reviewed; guest entry disabled') + return partial diff --git a/proxyclient/tools/run_guest_sptm.py b/proxyclient/tools/run_guest_sptm.py index 8a75f476a..f1d37b932 100755 --- a/proxyclient/tools/run_guest_sptm.py +++ b/proxyclient/tools/run_guest_sptm.py @@ -899,8 +899,9 @@ def main(): entry_off = plan_mod.macho_info(images["sptm"]).entry - plan_mod.macho_info(images["sptm"]).virtlo try: - sp = sptm_patch.plan(images["sptm"], entry_off) - except sptm_patch.SptmPatchError as e: + sp = (sptm_j613.patch_plan(images["sptm"], entry_off) if chip == 0x8122 + else sptm_patch.plan(images["sptm"], entry_off)) + except (sptm_patch.SptmPatchError, ValueError) as e: raise SystemExit(f"this SPTM can't be patched: {e}") print(f"SPTM: {len(sp['patches'])} patch sites found" + (", MTE tag-storage sequence found" if sp["mte"] else "")) diff --git a/src/sptm_virt.c b/src/sptm_virt.c index 91f849cf9..2adbdcff4 100644 --- a/src/sptm_virt.c +++ b/src/sptm_virt.c @@ -349,9 +349,8 @@ __attribute__((used, retain)) int sptm_virt_load(u64 sptm_entry, u64 handoff) { struct sptm_virt_layout l; - /* T8122 register/patch export has not been reviewed. Even a direct proxy call - * must not bypass the host profile's refusal. Remove only with that port. */ - if (!sptm_virt_requested() || chip_id == T8122) + /* Direct proxy callers must pass the same exact SoC/ADT contract as the host profile. */ + if (!sptm_virt_requested() || !sptm_virt_s2_admit()) return -1; if (sptm_virt_layout(&l) < 0) { printf("SPTM-virt: load refused, no valid carve-out layout\n"); diff --git a/src/sptm_virt_priv.h b/src/sptm_virt_priv.h index 206d507e9..a4d43ab0b 100644 --- a/src/sptm_virt_priv.h +++ b/src/sptm_virt_priv.h @@ -83,6 +83,7 @@ bool sptm_virt_cl4_reflect(u64 *regs, u64 esr); /* sptm_virt_s2.c */ extern volatile bool sptm_virt_rg_passthrough; void sptm_virt_s2_setup(void); +bool sptm_virt_s2_admit(void); void sptm_virt_s2_enter_xnu(int cpu); void sptm_virt_ctrr_publish_rorgn(void); void sptm_virt_gpu_deadline(struct exc_info *ctx); diff --git a/src/sptm_virt_s2.c b/src/sptm_virt_s2.c index 3e5b09587..3a4d8ca28 100644 --- a/src/sptm_virt_s2.c +++ b/src/sptm_virt_s2.c @@ -467,7 +467,7 @@ static bool adt_u32_is(int node, const char *name, u32 expected) return ADT_GETPROP(adt, node, name, &value) >= 0 && value == expected; } -static bool sptm_virt_amcc_watch_t8122(void) +static bool sptm_virt_amcc_contract_t8122(void) { int node = adt_path_offset(adt, "/chosen/lock-regs/amcc"); int bank = node < 0 ? -1 : adt_subnode_offset(adt, node, "amcc-ctrr-a"); @@ -494,7 +494,7 @@ static bool sptm_virt_amcc_watch_t8122(void) !adt_u32_is(bank, "write-disable-reg-mask", 1) || !adt_u32_is(bank, "write-disable-reg-value", 1) || !adt_u32_is(bank, "page-size-shift", 14)) { - printf("SPTM-virt[amcc]: T8122 lock-reg ADT does not match J613/25G83; not watched\n"); + printf("SPTM-virt[amcc]: T8122 lock-reg ADT does not match J613/25G83; not admitted\n"); return false; } @@ -508,18 +508,30 @@ static bool sptm_virt_amcc_watch_t8122(void) .cache_status_mask = 1, .cache_status_value = 0, }; - memset(amcc_lock_shadow, 0, sizeof(amcc_lock_shadow)); - for (int i = 0; i < 2; i++) { u64 base, stride; int count; if (mcc_plane_info(i, &base, &stride, &count) < 0 || base != exact_apertures[i] || stride != 0x40000 || count != 2) { - printf("SPTM-virt[amcc]: T8122 MCC plane layout mismatch; not watched\n"); + printf("SPTM-virt[amcc]: T8122 MCC plane layout mismatch; not admitted\n"); return false; } } + return true; +} + +bool sptm_virt_s2_admit(void) +{ + return chip_id != T8122 || sptm_virt_amcc_contract_t8122(); +} + +static bool sptm_virt_amcc_watch_t8122(void) +{ + if (!sptm_virt_amcc_contract_t8122()) + return false; + + memset(amcc_lock_shadow, 0, sizeof(amcc_lock_shadow)); t8122_amcc_ready = true; for (int i = 0; i < 2; i++) { u64 base, stride; @@ -545,7 +557,8 @@ static void sptm_virt_amcc_watch(void) u64 base, stride; int count; if (chip_id == T8122) { - sptm_virt_amcc_watch_t8122(); + if (!sptm_virt_amcc_watch_t8122()) + panic("SPTM-virt[amcc]: T8122 exact shadow setup failed before guest entry\n"); return; } /* The plane offsets above are T8142's; other chips keep their AMCC unhooked. */ diff --git a/tests/python/test_sptm_j613.py b/tests/python/test_sptm_j613.py index 115967000..29aa414f3 100644 --- a/tests/python/test_sptm_j613.py +++ b/tests/python/test_sptm_j613.py @@ -11,24 +11,22 @@ REAL_IMAGE = os.environ.get('J613_SPTM_IMAGE') -def test_capability_and_incomplete_export(): +def test_capability_and_reviewed_export(): assert not capability(1 << 24, True) assert not capability(2 << 24, False) assert capability(2 << 24, True) - with pytest.raises(ValueError, match='dirty-room'): - patch_plan(None, None) - assert unresolved_groups() == ['AMCC CTRR match'] + assert patch_plan(None, None)['reviewed'] + assert unresolved_groups() == [] assert inspect_patch_export(None, None)['unresolved'] == unresolved_groups() @pytest.mark.skipif(not REAL_IMAGE, reason='exact private J613 SPTM image not given') -def test_exact_image_partial_export_is_bound_but_not_admitted(): +def test_exact_image_export_is_bound_and_admitted(): image = Path(REAL_IMAGE).read_bytes() partial = inspect_patch_export(image, int(PROFILE['patch_export']['entry_file_offset'], 0)) assert len(partial['patches']) == 2 assert {p[1] for p in partial['patches']} == {0x3438, -0xc2c4} - assert not partial['reviewed'] - with pytest.raises(ValueError, match='AMCC CTRR match'): - patch_plan(image, int(PROFILE['patch_export']['entry_file_offset'], 0)) + assert partial['reviewed'] + assert patch_plan(image, int(PROFILE['patch_export']['entry_file_offset'], 0)) == partial def test_adt_validation_before_hooks(): regs = {(r['path'], r['index']): (int(r['base'], 0), int(r['size'], 0)) @@ -38,3 +36,8 @@ def test_adt_validation_before_hooks(): regs[key] = (0, 0) with pytest.raises(ValueError, match='ADT drift'): validate_resources(lambda p, i: regs[p, i]) + +def test_runner_uses_the_exact_j613_plan(): + source = (Path(__file__).resolve().parents[2] / + 'proxyclient/tools/run_guest_sptm.py').read_text() + assert 'sptm_j613.patch_plan(images["sptm"], entry_off) if chip == 0x8122' in source diff --git a/tests/python/test_sptm_t8122_amcc.py b/tests/python/test_sptm_t8122_amcc.py index 5911bdaca..f746c98b5 100644 --- a/tests/python/test_sptm_t8122_amcc.py +++ b/tests/python/test_sptm_t8122_amcc.py @@ -79,3 +79,6 @@ def test_t8122_amcc_exact_adt_gate_is_complete(): '"lock-reg-offset", 0x69c', '"write-disable-reg-offset", 0x6a0', '"cache-status-reg-offset", 0x1c00', '"page-size-shift", 14'): assert token in source + assert "bool sptm_virt_s2_admit(void)" in source + assert "chip_id != T8122 || sptm_virt_amcc_contract_t8122()" in source + assert 'panic("SPTM-virt[amcc]: T8122 exact shadow setup failed' in source From db764e7f61c14fff65f5cfe66f8281b99169f205 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Tue, 17 Nov 2026 19:54:10 -0500 Subject: [PATCH 08/19] j613: boot stock SPTM guest on all cores Signed-off-by: Satya Benson --- proxyclient/tools/run_guest_sptm.py | 44 ++++++++++++++++++++--------- src/smp.c | 11 ++++++-- 2 files changed, 40 insertions(+), 15 deletions(-) diff --git a/proxyclient/tools/run_guest_sptm.py b/proxyclient/tools/run_guest_sptm.py index f1d37b932..c890af02c 100755 --- a/proxyclient/tools/run_guest_sptm.py +++ b/proxyclient/tools/run_guest_sptm.py @@ -52,6 +52,7 @@ AURA_SAMPLE sample the guest's PC until each core's XNU entry (pre-XNU hangs) AURA_SAMPLE_HZ= samples per second (default 4) AURA_SAMPLE_MAX= stop printing after n samples (default 64) + AURA_J613_RUN admit the exact J613 stock-SPTM path without the bounded MMIO trace AURA_XNU_ENTRY patch the guest kernelcache's acct(2) so a root process reaches aura's control hvc with no kext (the auractl "xnu" entry; aura/auractl_xnu.py) AURA_XNU_RO_RELAX patch XNU's zalloc_ro_mut RO-zone panic out (tracing only; XNU_QUIRKS) @@ -148,6 +149,7 @@ "AURA_S2R_USB_RETAKE_MS", "AURA_TAIL_SECS", "AURA_TAIL_IDLE", + "AURA_J613_RUN", "AURA_GPU_STOP_SECS", "AURA_GPU_STOP_BOOT_SECS", "AURA_GPU_STOP_MSG", @@ -795,13 +797,18 @@ def configure(p, sym, plan, adt, ctl_cookie=0): def tail_console(iface, secs, idle): - """Keep reading the console after the entry call: a serial read error reopens the device, - and the tail stops after secs, or after idle seconds of silence.""" + """Keep reading the console after entry, including across KIS re-enumeration. + + Darwin does not reliably revive a pyserial object whose underlying device vanished. Throw + that object away and construct a fresh one on the same physical KIS path instead. Time spent + waiting for the node is not console silence, but it remains bounded by the overall tail window. + """ import serial end = time.time() + secs last = time.time() dev = iface.dev + serial_cls = type(dev) buf = b"" print(f"--- tailing console for up to {secs}s (stop after {idle:g}s silent) ---", flush=True) while time.time() < end: @@ -811,20 +818,29 @@ def tail_console(iface, secs, idle): try: chunk = dev.read(4096) except (serial.serialutil.SerialException, OSError) as e: - print(f"--- tail: read error ({e}); reopening ---", flush=True) + lost = time.time() + print(f"--- tail: read error ({e}); waiting for re-enumeration ---", flush=True) try: dev.close() except Exception: pass - for _ in range(100): + dev = None + while time.time() < end: + if not iface.devpath or not os.path.exists(iface.devpath): + time.sleep(0.1) + continue try: - dev.open() - print("--- tail: reopened ---", flush=True) + dev = serial_cls(iface.devpath, iface.baudrate) + dev.timeout = min(1, max(0.05, end - time.time())) + iface.dev = dev + gap = time.time() - lost + last += gap + print(f"--- tail: reopened after {gap:.3f}s ---", flush=True) break except (serial.serialutil.SerialException, OSError): - time.sleep(0.2) + time.sleep(0.1) else: - print("--- tail: device gone ---", flush=True) + print("--- tail: device absent through capture window ---", flush=True) break continue if not chunk: @@ -857,10 +873,11 @@ def main(): # below aura's carve-out. chip = u.adt["/chosen"].chip_id if chip == 0x8122: + print(f"J613 host image [0x{sym['_base']:x}, 0x{sym['_end']:x})") from aura import sptm_j613 sptm_j613.validate_resources(lambda path, idx: u.adt[path].get_reg(idx)) - if not env_on("AURA_J613_TRACE"): - raise SystemExit("T8122 requires experimental AURA_J613_TRACE=1") + if not (env_on("AURA_J613_RUN") or env_on("AURA_J613_TRACE")): + raise SystemExit("T8122 requires experimental AURA_J613_RUN=1") if any(env_on(k) for k in CONFIG_FLAGS if k != "AURA_J613_TRACE"): raise SystemExit("J613: other trace/sleep modes are not qualified") # Deliberately before reading images or placing anything on the target. @@ -868,8 +885,8 @@ def main(): sptm_j613.patch_plan(None, None) except ValueError as e: raise SystemExit(str(e)) - elif env_on("AURA_J613_TRACE"): - raise SystemExit("AURA_J613_TRACE requires T8122") + elif env_on("AURA_J613_RUN") or env_on("AURA_J613_TRACE"): + raise SystemExit("AURA_J613_RUN/AURA_J613_TRACE require T8122") scratch = u.malloc(0x40) if p.call(sym["sptm_virt_place"], scratch) != 0: raise SystemExit("sptm_virt_place failed: not an SPTM_VIRT build, no FEAT_NV2 or GXF, or " @@ -945,7 +962,8 @@ def main(): quirk_hide = tuple(quirks["hide"]) if env_on("AURA_KEEP_WIFI"): quirk_hide = tuple(n for n in quirk_hide if n in port_nodes) - keep_ane = env_on("AURA_KEEP_ANE") or (chip == 0x8122 and env_on("AURA_J613_TRACE")) + keep_ane = env_on("AURA_KEEP_ANE") or ( + chip == 0x8122 and (env_on("AURA_J613_RUN") or env_on("AURA_J613_TRACE"))) hide = port_nodes + (() if keep_ane else STRIP_NODES) + quirk_hide if not env_on("AURA_KEEP_ERRH"): hide += (ERROR_HANDLER,) diff --git a/src/smp.c b/src/smp.c index d076fec75..9fcceccfb 100644 --- a/src/smp.c +++ b/src/smp.c @@ -288,9 +288,16 @@ static int smp_prepare_rvbar(const struct cpu_info *cpu) u64 locked = rvbar & RVBAR_ADDR; u64 target = (u64)_vectors_start; - /* A7 to M3: RVBAR is not locked, and smp_start_cpu() sets it. */ - if (locked == target || cpu_features->apple_sysregs_unlocked) + if (locked == target) return 0; + /* A7 to M3 expose a writable RVBAR. The ordinary SMP startup path writes it immediately + * before releasing a core, but a stock-SPTM guest performs CPUSTART itself, so publish the + * active Aura vector here as part of the guest reset contract as well. */ + if (cpu_features->apple_sysregs_unlocked) { + write64(cpu->impl_reg, target); + sysop("dsb sy"); + return (read64(cpu->impl_reg) & RVBAR_ADDR_UNLOCKED) == target ? 0 : -1; + } /* A stage that moved above the chainloaded image keeps entry at its old base. */ if (relocated_from && locked == old_vectors_start()) return 0; From f528865a278549c3390671323689fbdad4ddc7db Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Tue, 17 Nov 2026 23:29:39 -0500 Subject: [PATCH 09/19] ci: format stock SPTM changes and update RVBAR harnesses Signed-off-by: Satya Benson --- src/sptm_virt.h | 2 +- src/sptm_virt_gpu.c | 32 +++++++++++++----------- src/sptm_virt_s2.c | 13 ++++------ tests/python/test_smp_legacy_rvbar.py | 23 +++++++++++++---- tests/python/test_smp_load_base_rvbar.py | 2 ++ 5 files changed, 43 insertions(+), 29 deletions(-) diff --git a/src/sptm_virt.h b/src/sptm_virt.h index 39115aa3d..ef481209d 100644 --- a/src/sptm_virt.h +++ b/src/sptm_virt.h @@ -51,7 +51,7 @@ struct sptm_virt_placement { #define SPTM_VIRT_SAMPLE BIT(7) /* sample the guest's PC until its XNU entry */ #define SPTM_VIRT_S2R_MEM BIT(8) /* T6050: also hook the MCC and the coprocessor DARTs */ /* bit 9 is AURA_AURACTL in the feat/auractl runner; left free here so the two never clash */ -#define SPTM_VIRT_CTL_DCC BIT(10) /* arm auractl's DCC transport (MDCR_EL2.TDCC) at boot */ +#define SPTM_VIRT_CTL_DCC BIT(10) /* arm auractl's DCC transport (MDCR_EL2.TDCC) at boot */ #define SPTM_VIRT_J613_TRACE BIT(11) /* bounded J613 ANE/AIC trace; exact ADT resources only */ /* sptm_virt_s2r_cp_ansx, with COPROC on T6050 */ #define S2R_CP_ANSX_SART BIT(0) /* sart-ans reg[0-2], first page each */ diff --git a/src/sptm_virt_gpu.c b/src/sptm_virt_gpu.c index d86da6dd0..f74cd54d8 100644 --- a/src/sptm_virt_gpu.c +++ b/src/sptm_virt_gpu.c @@ -153,8 +153,7 @@ void sptm_virt_gpu_deadline(struct exc_info *ctx) static bool gpu_hook(struct exc_info *ctx, u64 addr, u64 *val, bool write, int width) { - if ((sptm_virt_flags & SPTM_VIRT_J613_TRACE) && - sptm_virt_gpu_head + 2 >= sptm_virt_gpu_nrec) + if ((sptm_virt_flags & SPTM_VIRT_J613_TRACE) && sptm_virt_gpu_head + 2 >= sptm_virt_gpu_nrec) gpu_park(ctx, "the bounded J613 trace ring is full"); u64 now = mrs(CNTPCT_EL0); @@ -251,7 +250,11 @@ static void j613_capture_setup(void) sptm_virt_gpu_print_max = 0; /* export the ring; no per-access console timing noise */ if (chip_id != T8122 || (sptm_virt_flags & ~SPTM_VIRT_J613_TRACE)) panic("J613 capture: wrong chip or conflicting capture modes\n"); - static const struct { const char *path; int idx; u64 base, size; } resources[] = { + static const struct { + const char *path; + int idx; + u64 base, size; + } resources[] = { {"/arm-io/ane", 0, 0x311400000UL, 0x6c000UL}, {"/arm-io/ane", 1, 0x311050000UL, 0x4000UL}, {"/arm-io/ane", 2, 0x310000000UL, 0x2000000UL}, @@ -264,19 +267,18 @@ static void j613_capture_setup(void) {"/arm-io/aic", 0, 0x2d1000000UL, 0x184000UL}, }; for (size_t i = 0; i < ARRAY_SIZE(resources); i++) { - int p[8]; u64 a, n; + int p[8]; + u64 a, n; if (adt_path_offset_trace(adt, resources[i].path, p) < 0 || - adt_get_reg(adt, p, "reg", resources[i].idx, &a, &n) < 0 || - a != resources[i].base || n != resources[i].size) + adt_get_reg(adt, p, "reg", resources[i].idx, &a, &n) < 0 || a != resources[i].base || + n != resources[i].size) panic("J613 capture: ADT resource drift\n"); } - static const struct { u64 base, size; } windows[] = { - {0x292468000UL, 0x4UL}, - {0x2a5468000UL, 0x4UL}, - {0x2d0700000UL, 0x18000UL}, - {0x2d0724000UL, 0x4000UL}, - {0x2d1000000UL, 0x184000UL}, - {0x310000000UL, 0x2000000UL}, + static const struct { + u64 base, size; + } windows[] = { + {0x292468000UL, 0x4UL}, {0x2a5468000UL, 0x4UL}, {0x2d0700000UL, 0x18000UL}, + {0x2d0724000UL, 0x4000UL}, {0x2d1000000UL, 0x184000UL}, {0x310000000UL, 0x2000000UL}, }; for (size_t i = 0; i < ARRAY_SIZE(windows); i++) { gpu_ranges[gpu_nranges].base = windows[i].base; @@ -286,8 +288,8 @@ static void j613_capture_setup(void) if (hv_map_hook(windows[i].base, gpu_hook, windows[i].size) < 0) panic("J613 capture: hook installation failed\n"); } - printf("J613 capture: %d exact windows, ring at 0x%lx; export before reset\n", - gpu_nranges, (u64)sptm_virt_gpu_ring); + printf("J613 capture: %d exact windows, ring at 0x%lx; export before reset\n", gpu_nranges, + (u64)sptm_virt_gpu_ring); } void sptm_virt_gpu_setup(void) diff --git a/src/sptm_virt_s2.c b/src/sptm_virt_s2.c index 3a4d8ca28..4ecafdb1c 100644 --- a/src/sptm_virt_s2.c +++ b/src/sptm_virt_s2.c @@ -449,8 +449,7 @@ static bool amcc_hook(struct exc_info *ctx, u64 addr, u64 *val, bool write, int if ((addr & 0x3fff) == t8122_amcc.cache_status) { if (!write) { sptm_virt_mmio_rw(addr, val, false, width); - *val = (*val & ~t8122_amcc.cache_status_mask) | - t8122_amcc.cache_status_value; + *val = (*val & ~t8122_amcc.cache_status_mask) | t8122_amcc.cache_status_value; } return true; } @@ -486,10 +485,9 @@ static bool sptm_virt_amcc_contract_t8122(void) !adt_u32_is(bank, "lower-limit-reg-mask", 0xffffffff) || !adt_u32_is(bank, "upper-limit-reg-offset", 0x694) || !adt_u32_is(bank, "upper-limit-reg-mask", 0xffffffff) || - !adt_u32_is(bank, "enable-reg-offset", 0x698) || - !adt_u32_is(bank, "enable-reg-mask", 1) || !adt_u32_is(bank, "enable-reg-value", 1) || - !adt_u32_is(bank, "lock-reg-offset", 0x69c) || !adt_u32_is(bank, "lock-reg-mask", 1) || - !adt_u32_is(bank, "lock-reg-value", 1) || + !adt_u32_is(bank, "enable-reg-offset", 0x698) || !adt_u32_is(bank, "enable-reg-mask", 1) || + !adt_u32_is(bank, "enable-reg-value", 1) || !adt_u32_is(bank, "lock-reg-offset", 0x69c) || + !adt_u32_is(bank, "lock-reg-mask", 1) || !adt_u32_is(bank, "lock-reg-value", 1) || !adt_u32_is(bank, "write-disable-reg-offset", 0x6a0) || !adt_u32_is(bank, "write-disable-reg-mask", 1) || !adt_u32_is(bank, "write-disable-reg-value", 1) || @@ -541,8 +539,7 @@ static bool sptm_virt_amcc_watch_t8122(void) u64 page = base + p * stride; if (hv_map_hook(page, amcc_hook, 0x4000) < 0) { t8122_amcc_ready = false; - printf("SPTM-virt[amcc]: cannot hook T8122 MCC %d plane %d at 0x%lx\n", i, p, - page); + printf("SPTM-virt[amcc]: cannot hook T8122 MCC %d plane %d at 0x%lx\n", i, p, page); return false; } } diff --git a/tests/python/test_smp_legacy_rvbar.py b/tests/python/test_smp_legacy_rvbar.py index 935fb2139..fe7b05ce9 100644 --- a/tests/python/test_smp_legacy_rvbar.py +++ b/tests/python/test_smp_legacy_rvbar.py @@ -28,6 +28,7 @@ def test_legacy_rvbar_lock_does_not_prune_cpus(tmp_path): #define BIT(n) (1ULL << (n)) #define RVBAR_LOCK 1 #define RVBAR_ADDR 0x0000fffffffff000ULL +#define RVBAR_ADDR_UNLOCKED 0x00000ffffffff000ULL #define PMGR_DIE_OFFSET 0x100000 static u64 pmgr_die_stride(void) { return PMGR_DIE_OFFSET; } #define T8103 0x8103 @@ -160,9 +161,9 @@ def test_legacy_rvbar_lock_does_not_prune_cpus(tmp_path): assert((rvbars[i] & RVBAR_ADDR) == (u64)_vectors_start); } assert(alive == 0xff); - /* Only established caller-side writes: seven secondary RVBARs, - * plus boot RVBAR when its hardware lock bit is clear. */ - assert(write64_count == (lock && boot_cpu_idx == 4 ? 7 : 8)); + /* The guest reset contract publishes Aura's vector during admission, + * then each secondary's established caller-side write repeats it. */ + assert(write64_count == 15); assert(write32_count == 14); } } @@ -217,6 +218,7 @@ def test_t8140_owned_relay_and_m3_relocation_keep_existing_behavior(tmp_path): #define SZ_16K 0x4000UL #define RVBAR_LOCK 1 #define RVBAR_ADDR 0x0000fffffffff000UL +#define RVBAR_ADDR_UNLOCKED 0x00000ffffffff000UL #define MAIR_IDX_NORMAL 0 #define PERM_RW 0 #define PERM_RX 1 @@ -242,6 +244,12 @@ def test_t8140_owned_relay_and_m3_relocation_keep_existing_behavior(tmp_path): event("read64", address, rvbar); return rvbar; } +static void write64(u64 address, u64 value) +{ + assert(address == 8); + event("write64", address, value); + rvbar = value; +} static u32 read32(u64 address) { assert(address == locked_vector); @@ -332,13 +340,18 @@ def test_t8140_owned_relay_and_m3_relocation_keep_existing_behavior(tmp_path): assert(!strcmp(events[1].name, "read32")); } /* M3's architectural permission remains true across a relocated image. - * The helper writes nothing; the established caller owns any RVBAR write. */ + * Guest admission publishes and verifies the active Aura vector itself. */ reset(); chip_id = 0x6030; features.apple_sysregs_unlocked = true; relocated_from = 0x800000000UL; old_vector = locked_vector; - assert(smp_prepare_rvbar(&cpu) == 0 && event_count == 1); + assert(smp_prepare_rvbar(&cpu) == 0 && event_count == 4); + assert(!strcmp(events[0].name, "read64")); + assert(!strcmp(events[1].name, "write64")); + assert(!strcmp(events[2].name, "dsb sy")); + assert(!strcmp(events[3].name, "read64")); + assert(rvbar == (u64)_vectors_start); assert(branch_word == 0 && installed_relay == 0); return 0; } diff --git a/tests/python/test_smp_load_base_rvbar.py b/tests/python/test_smp_load_base_rvbar.py index 0d8b32154..0c9e94136 100644 --- a/tests/python/test_smp_load_base_rvbar.py +++ b/tests/python/test_smp_load_base_rvbar.py @@ -20,6 +20,7 @@ def test_load_base_rvbar_is_forwarded_once(tmp_path): _Static_assert(sizeof(u64) == 8, "production u64 ABI"); #define RVBAR_LOCK 1 #define RVBAR_ADDR 0x0000fffffffff000UL +#define RVBAR_ADDR_UNLOCKED 0x00000ffffffff000UL #define MAIR_IDX_NORMAL 0 #define PERM_RW 0 #define PERM_RX 1 @@ -33,6 +34,7 @@ def test_load_base_rvbar_is_forwarded_once(tmp_path): static int writes, mappings[2], nmap, owned_asks; static bool active = true; static u64 read64(u64 address) { assert(address == 8); return rvbar; } +static void write64(u64 address, u64 value) { assert(address == 8); rvbar = value; } static u32 read32(u64 address) { assert(address == locked); return word; } static void write32(u64 address, u32 value) { assert(address == locked); word = value; writes++; } static u64 old_vectors_start(void) { return 0; } From bb1b56201d104495418118f2e4831e1fc8657371 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Tue, 17 Nov 2026 23:35:02 -0500 Subject: [PATCH 10/19] tests: model host RVBAR addresses in harnesses Signed-off-by: Satya Benson --- tests/python/test_smp_legacy_rvbar.py | 6 ++++-- tests/python/test_smp_load_base_rvbar.py | 3 ++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/tests/python/test_smp_legacy_rvbar.py b/tests/python/test_smp_legacy_rvbar.py index fe7b05ce9..a207acc29 100644 --- a/tests/python/test_smp_legacy_rvbar.py +++ b/tests/python/test_smp_legacy_rvbar.py @@ -28,7 +28,8 @@ def test_legacy_rvbar_lock_does_not_prune_cpus(tmp_path): #define BIT(n) (1ULL << (n)) #define RVBAR_LOCK 1 #define RVBAR_ADDR 0x0000fffffffff000ULL -#define RVBAR_ADDR_UNLOCKED 0x00000ffffffff000ULL +/* Userspace test symbols may sit above the hardware's 44-bit RVBAR range. */ +#define RVBAR_ADDR_UNLOCKED 0x0000fffffffff000ULL #define PMGR_DIE_OFFSET 0x100000 static u64 pmgr_die_stride(void) { return PMGR_DIE_OFFSET; } #define T8103 0x8103 @@ -218,7 +219,8 @@ def test_t8140_owned_relay_and_m3_relocation_keep_existing_behavior(tmp_path): #define SZ_16K 0x4000UL #define RVBAR_LOCK 1 #define RVBAR_ADDR 0x0000fffffffff000UL -#define RVBAR_ADDR_UNLOCKED 0x00000ffffffff000UL +/* Userspace test symbols may sit above the hardware's 44-bit RVBAR range. */ +#define RVBAR_ADDR_UNLOCKED 0x0000fffffffff000UL #define MAIR_IDX_NORMAL 0 #define PERM_RW 0 #define PERM_RX 1 diff --git a/tests/python/test_smp_load_base_rvbar.py b/tests/python/test_smp_load_base_rvbar.py index 0c9e94136..337643247 100644 --- a/tests/python/test_smp_load_base_rvbar.py +++ b/tests/python/test_smp_load_base_rvbar.py @@ -20,7 +20,8 @@ def test_load_base_rvbar_is_forwarded_once(tmp_path): _Static_assert(sizeof(u64) == 8, "production u64 ABI"); #define RVBAR_LOCK 1 #define RVBAR_ADDR 0x0000fffffffff000UL -#define RVBAR_ADDR_UNLOCKED 0x00000ffffffff000UL +/* Userspace test symbols may sit above the hardware's 44-bit RVBAR range. */ +#define RVBAR_ADDR_UNLOCKED 0x0000fffffffff000UL #define MAIR_IDX_NORMAL 0 #define PERM_RW 0 #define PERM_RX 1 From 19bc54698a0184c95bb05484d9f5d923cfced5f0 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Tue, 17 Nov 2026 23:41:26 -0500 Subject: [PATCH 11/19] tests: fall back to make when gmake is absent The macOS CI runners have no gmake on PATH. Signed-off-by: Satya Benson --- tests/python/test_no_display_build.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/python/test_no_display_build.py b/tests/python/test_no_display_build.py index 2fe9ba973..bcd8778b7 100644 --- a/tests/python/test_no_display_build.py +++ b/tests/python/test_no_display_build.py @@ -2,15 +2,17 @@ """The proxy-only Stage 1 can select Aura's existing headless display path.""" from pathlib import Path +import shutil import subprocess ROOT = Path(__file__).resolve().parents[2] +MAKE = shutil.which("gmake") or "make" def build_cfg(no_display: str) -> str: subprocess.run( - ["gmake", "-s", "build-cfg", f"NO_DISPLAY={no_display}"], + [MAKE, "-s", "build-cfg", f"NO_DISPLAY={no_display}"], cwd=ROOT, check=True, ) From ce3aa7c6c78482682da26b20cc7e2f04f5e43abc Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Fri, 20 Nov 2026 09:29:16 -0500 Subject: [PATCH 12/19] smp: publish RVBAR only on the stock-SPTM guest reset path smp_prepare_rvbar() runs on every normal boot. Restore its main behaviour (A7 to M3 leave the write to smp_start_cpu()) and the two harnesses that modeled the extra write, and move the publish into smp_prepare_guest_rvbar(), called only from smp_prepare_guest_resets(). It writes an unlocked RVBAR on A7 to M3, reads it back, and never writes a locked one. Signed-off-by: Satya Benson --- src/smp.c | 34 ++++++++---- tests/python/test_smp_guest_rvbar.py | 71 ++++++++++++++++++++++++ tests/python/test_smp_legacy_rvbar.py | 25 ++------- tests/python/test_smp_load_base_rvbar.py | 3 - 4 files changed, 100 insertions(+), 33 deletions(-) create mode 100644 tests/python/test_smp_guest_rvbar.py diff --git a/src/smp.c b/src/smp.c index 9fcceccfb..0bd0c68f4 100644 --- a/src/smp.c +++ b/src/smp.c @@ -288,16 +288,9 @@ static int smp_prepare_rvbar(const struct cpu_info *cpu) u64 locked = rvbar & RVBAR_ADDR; u64 target = (u64)_vectors_start; - if (locked == target) + /* A7 to M3: RVBAR is not locked, and smp_start_cpu() sets it. */ + if (locked == target || cpu_features->apple_sysregs_unlocked) return 0; - /* A7 to M3 expose a writable RVBAR. The ordinary SMP startup path writes it immediately - * before releasing a core, but a stock-SPTM guest performs CPUSTART itself, so publish the - * active Aura vector here as part of the guest reset contract as well. */ - if (cpu_features->apple_sysregs_unlocked) { - write64(cpu->impl_reg, target); - sysop("dsb sy"); - return (read64(cpu->impl_reg) & RVBAR_ADDR_UNLOCKED) == target ? 0 : -1; - } /* A stage that moved above the chainloaded image keeps entry at its old base. */ if (relocated_from && locked == old_vectors_start()) return 0; @@ -1467,6 +1460,27 @@ static u64 smp_guest_mpidr(int i) return ((u64)cpu->cluster << 8) | cpu->core | (aff2 << 16); } +/* + * The stock-SPTM guest's reset contract. A7 to M3 leave RVBAR writable, and the ordinary SMP path + * writes it only in smp_start_cpu(), just before releasing a core. Here the guest performs CPUSTART + * itself, so publish this image's vector into an unlocked RVBAR now and read it back. A locked + * RVBAR (M4 on, or a core's own lock bit) is never written; smp_prepare_rvbar() checks it. + */ +static int smp_prepare_guest_rvbar(const struct cpu_info *cpu) +{ + u64 target = (u64)_vectors_start; + u64 rvbar = read64(cpu->impl_reg); + + if (!cpu_features->apple_sysregs_unlocked || (rvbar & RVBAR_LOCK) || + (rvbar & RVBAR_ADDR_UNLOCKED) == target) + return smp_prepare_rvbar(cpu); + if (target & ~RVBAR_ADDR_UNLOCKED) + return -1; + write64(cpu->impl_reg, target); + sysop("dsb sy"); + return (read64(cpu->impl_reg) & RVBAR_ADDR_UNLOCKED) == target ? 0 : -1; +} + /* * Under the virtualized SPTM every core enters the guest through a hardware reset, as natively: * XNU starts a core with PMGR CPUSTART, and a core that power-gates in idle or sleep comes back @@ -1500,7 +1514,7 @@ int smp_prepare_guest_resets(void) } smp_reset_stacks[i].mpidr = mpidr; smp_reset_stacks[i].stack = (u64)cpu_stack(i) + SECONDARY_STACK_SIZE; - rc = smp_prepare_rvbar(cpu); + rc = smp_prepare_guest_rvbar(cpu); } /* A secondary must be powered off here: XNU's CPUSTART only resets a core that is * off, and one left running (an earlier stage's park loop) never reaches SPTM. */ diff --git a/tests/python/test_smp_guest_rvbar.py b/tests/python/test_smp_guest_rvbar.py new file mode 100644 index 000000000..739791cc7 --- /dev/null +++ b/tests/python/test_smp_guest_rvbar.py @@ -0,0 +1,71 @@ +# SPDX-License-Identifier: MIT +"""Only the stock-SPTM guest's reset path publishes an unlocked RVBAR. + +The ordinary boot path (smp_prepare_rvbar, smp_start_cpu) is unchanged; the +guest helper is the production body with RVBAR MMIO modeled. +""" +from test_smp_timeouts import REPO, compile_and_run +from test_locked_dart_tables import function + + +def test_guest_rvbar_write_is_guest_only(): + source = (REPO / "src/smp.c").read_text() + prepare = function(source, "smp_prepare_rvbar") + # Normal boots: A7 to M3 leave the write to smp_start_cpu(), as before. + assert "if (locked == target || cpu_features->apple_sysregs_unlocked)\n return 0;" in prepare + assert "write64" not in prepare + guest = function(source, "smp_prepare_guest_resets") + assert "smp_prepare_guest_rvbar(cpu)" in guest + callers = [line for line in source.splitlines() if "smp_prepare_guest_rvbar(" in line] + assert len(callers) == 2 # the definition and smp_prepare_guest_resets() + + +def test_guest_rvbar_publish(tmp_path): + source = (REPO / "src/smp.c").read_text() + body = function(source, "smp_prepare_guest_rvbar") + harness = r''' +#include +#include +#include +typedef unsigned long u64; +#define RVBAR_LOCK 1UL +/* Userspace test symbols may sit above the hardware's 44-bit RVBAR range. */ +#define RVBAR_ADDR_UNLOCKED 0x0000fffffffff000UL +#define sysop(x) do { } while (0) +struct cpu_info { u64 impl_reg; }; +struct cpu_features { bool apple_sysregs_unlocked; }; +static struct cpu_features features, *cpu_features = &features; +static unsigned char _vectors_start[4096] __attribute__((aligned(4096))); +static u64 rvbar, sticky; +static int writes, prepares; +static u64 read64(u64 a) { assert(a == 8); return rvbar; } +static void write64(u64 a, u64 v) { assert(a == 8); writes++; rvbar = sticky ? sticky : v; } +static int smp_prepare_rvbar(const struct cpu_info *cpu) { (void)cpu; prepares++; return 0; } +''' + body + r''' +int main(void) +{ + const struct cpu_info cpu = {.impl_reg = 8}; + u64 target = (u64)_vectors_start; + + /* A7 to M3, unlocked: publish and verify. */ + features.apple_sysregs_unlocked = true; + rvbar = 0x800000000UL; + assert(smp_prepare_guest_rvbar(&cpu) == 0 && writes == 1 && prepares == 0); + assert(rvbar == target); + /* Already published: no second write. */ + assert(smp_prepare_guest_rvbar(&cpu) == 0 && writes == 1 && prepares == 1); + /* A lock bit is never written through. */ + rvbar = 0x800000000UL | RVBAR_LOCK; + assert(smp_prepare_guest_rvbar(&cpu) == 0 && writes == 1 && prepares == 2); + /* M4 on: the normal check/relay. */ + features.apple_sysregs_unlocked = false; + rvbar = 0x800000000UL; + assert(smp_prepare_guest_rvbar(&cpu) == 0 && writes == 1 && prepares == 3); + /* A write that does not stick is refused. */ + features.apple_sysregs_unlocked = true; + sticky = 0x900000000UL; + assert(smp_prepare_guest_rvbar(&cpu) == -1 && writes == 2); + return 0; +} +''' + compile_and_run(tmp_path, "smp-guest-rvbar", harness) diff --git a/tests/python/test_smp_legacy_rvbar.py b/tests/python/test_smp_legacy_rvbar.py index a207acc29..935fb2139 100644 --- a/tests/python/test_smp_legacy_rvbar.py +++ b/tests/python/test_smp_legacy_rvbar.py @@ -28,8 +28,6 @@ def test_legacy_rvbar_lock_does_not_prune_cpus(tmp_path): #define BIT(n) (1ULL << (n)) #define RVBAR_LOCK 1 #define RVBAR_ADDR 0x0000fffffffff000ULL -/* Userspace test symbols may sit above the hardware's 44-bit RVBAR range. */ -#define RVBAR_ADDR_UNLOCKED 0x0000fffffffff000ULL #define PMGR_DIE_OFFSET 0x100000 static u64 pmgr_die_stride(void) { return PMGR_DIE_OFFSET; } #define T8103 0x8103 @@ -162,9 +160,9 @@ def test_legacy_rvbar_lock_does_not_prune_cpus(tmp_path): assert((rvbars[i] & RVBAR_ADDR) == (u64)_vectors_start); } assert(alive == 0xff); - /* The guest reset contract publishes Aura's vector during admission, - * then each secondary's established caller-side write repeats it. */ - assert(write64_count == 15); + /* Only established caller-side writes: seven secondary RVBARs, + * plus boot RVBAR when its hardware lock bit is clear. */ + assert(write64_count == (lock && boot_cpu_idx == 4 ? 7 : 8)); assert(write32_count == 14); } } @@ -219,8 +217,6 @@ def test_t8140_owned_relay_and_m3_relocation_keep_existing_behavior(tmp_path): #define SZ_16K 0x4000UL #define RVBAR_LOCK 1 #define RVBAR_ADDR 0x0000fffffffff000UL -/* Userspace test symbols may sit above the hardware's 44-bit RVBAR range. */ -#define RVBAR_ADDR_UNLOCKED 0x0000fffffffff000UL #define MAIR_IDX_NORMAL 0 #define PERM_RW 0 #define PERM_RX 1 @@ -246,12 +242,6 @@ def test_t8140_owned_relay_and_m3_relocation_keep_existing_behavior(tmp_path): event("read64", address, rvbar); return rvbar; } -static void write64(u64 address, u64 value) -{ - assert(address == 8); - event("write64", address, value); - rvbar = value; -} static u32 read32(u64 address) { assert(address == locked_vector); @@ -342,18 +332,13 @@ def test_t8140_owned_relay_and_m3_relocation_keep_existing_behavior(tmp_path): assert(!strcmp(events[1].name, "read32")); } /* M3's architectural permission remains true across a relocated image. - * Guest admission publishes and verifies the active Aura vector itself. */ + * The helper writes nothing; the established caller owns any RVBAR write. */ reset(); chip_id = 0x6030; features.apple_sysregs_unlocked = true; relocated_from = 0x800000000UL; old_vector = locked_vector; - assert(smp_prepare_rvbar(&cpu) == 0 && event_count == 4); - assert(!strcmp(events[0].name, "read64")); - assert(!strcmp(events[1].name, "write64")); - assert(!strcmp(events[2].name, "dsb sy")); - assert(!strcmp(events[3].name, "read64")); - assert(rvbar == (u64)_vectors_start); + assert(smp_prepare_rvbar(&cpu) == 0 && event_count == 1); assert(branch_word == 0 && installed_relay == 0); return 0; } diff --git a/tests/python/test_smp_load_base_rvbar.py b/tests/python/test_smp_load_base_rvbar.py index 337643247..0d8b32154 100644 --- a/tests/python/test_smp_load_base_rvbar.py +++ b/tests/python/test_smp_load_base_rvbar.py @@ -20,8 +20,6 @@ def test_load_base_rvbar_is_forwarded_once(tmp_path): _Static_assert(sizeof(u64) == 8, "production u64 ABI"); #define RVBAR_LOCK 1 #define RVBAR_ADDR 0x0000fffffffff000UL -/* Userspace test symbols may sit above the hardware's 44-bit RVBAR range. */ -#define RVBAR_ADDR_UNLOCKED 0x0000fffffffff000UL #define MAIR_IDX_NORMAL 0 #define PERM_RW 0 #define PERM_RX 1 @@ -35,7 +33,6 @@ def test_load_base_rvbar_is_forwarded_once(tmp_path): static int writes, mappings[2], nmap, owned_asks; static bool active = true; static u64 read64(u64 address) { assert(address == 8); return rvbar; } -static void write64(u64 address, u64 value) { assert(address == 8); rvbar = value; } static u32 read32(u64 address) { assert(address == locked); return word; } static void write32(u64 address, u32 value) { assert(address == locked); word = value; writes++; } static u64 old_vectors_start(void) { return 0; } From 01e86d0e4009c09a4914b662e41d4091dd89b89e Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Fri, 20 Nov 2026 09:34:36 -0500 Subject: [PATCH 13/19] sptm: read the AMCC guest shadow from /chosen/lock-regs/amcc Replace sptm_virt_amcc_contract_t8122()'s transcribed apertures and offsets, and the chip_id == T8122 branch in sptm_virt_amcc_watch(), with one reader of /chosen/lock-regs/amcc used on every chip: the apertures (aperture-phys-addr, -count, -size), the plane geometry (plane-count, plane-stride), the optional cache status (cache-status-reg-*), and one bank per child from its *-reg-offset properties. The geometry must also match the MCC driver's planes. A missing or malformed node is refused at admission (sptm_virt_s2_admit) and panics before any hook at guest setup, so the path stays fail-closed. Under the lock-regs shadow, only the described bank registers are shadowed; the T8142 plane-offset locks no longer apply there. T8142 keeps its plane-offset path (amcc_is_lock, AURA_AMCC_NOLOCK): whether its lock-regs banks name +0xacc/+0xadc/+0xaec has not been checked on an M5, so moving it now would change that path untested. Signed-off-by: Satya Benson --- src/sptm_virt_s2.c | 294 +++++++++++++++--------- tests/python/test_sptm_amcc_lockregs.py | 227 ++++++++++++++++++ tests/python/test_sptm_t8122_amcc.py | 84 ------- 3 files changed, 415 insertions(+), 190 deletions(-) create mode 100644 tests/python/test_sptm_amcc_lockregs.py delete mode 100644 tests/python/test_sptm_t8122_amcc.py diff --git a/src/sptm_virt_s2.c b/src/sptm_virt_s2.c index 4ecafdb1c..c6a8369f6 100644 --- a/src/sptm_virt_s2.c +++ b/src/sptm_virt_s2.c @@ -373,28 +373,158 @@ static void sptm_virt_reset_guard_setup(void) * wrote, the hardware keeps them open. On by default; AURA_AMCC_NOLOCK=0 lets SPTM lock them. */ u32 sptm_virt_amcc_nolock = 1; -static u64 amcc_lock_shadow[32][2]; /* {pa, value} */ +static u64 amcc_lock_shadow[64][2]; /* {pa, value} */ /* - * T8122's stock SPTM describes its AMCC protection registers in - * /chosen/lock-regs/amcc. Stage 1 has already protected its own image in the - * real AMCC when the volatile guest starts, while SPTM requires an unlocked - * register bank for the image it is booting. Give the guest a zero-initialized - * shadow of only those described registers. The host's bounds and locks stay - * intact. The exact ADT contract is checked before any page is hooked. + * Where stock SPTM finds the AMCC protection registers: /chosen/lock-regs/amcc. Its properties + * give the apertures (aperture-phys-addr, -count, -size), the planes behind each (plane-count, + * plane-stride), an optional cache status the guest polls (cache-status-reg-*), and one child per + * protection bank whose *-reg-offset properties name the bank's registers within a plane. + * Stage 1 has already protected its own image in the real AMCC when the volatile guest starts, + * while SPTM requires an unlocked bank for the image it boots: the guest gets a zero-initialized + * shadow of exactly the described bank registers, and the host's bounds and locks stay intact. + * A missing or malformed node, or one that disagrees with the MCC driver's planes, is refused + * before any page is hooked. */ -struct t8122_amcc_layout { - u32 lower; - u32 upper; - u32 enable; - u32 lock; - u32 write_disable; - u32 cache_status; - u32 cache_status_mask; - u32 cache_status_value; +#define AMCC_LR_MAX_APERTURES 4 +#define AMCC_LR_MAX_BANKS 4 +#define AMCC_LR_BANK_REGS 5 +#define AMCC_LR_PAGE 0x4000UL + +struct amcc_lockregs { + u32 napertures, nplanes, nbanks; + u64 aperture[AMCC_LR_MAX_APERTURES]; + u64 aperture_size, plane_stride; + u32 bank_reg[AMCC_LR_MAX_BANKS][AMCC_LR_BANK_REGS]; + bool has_cache_status; + u32 cache_status, cache_status_mask, cache_status_value; }; -static struct t8122_amcc_layout t8122_amcc; -static bool t8122_amcc_ready; +static struct amcc_lockregs amcc_lr; +static bool amcc_lr_ready; + +static const char *const amcc_lr_bank_props[AMCC_LR_BANK_REGS] = { + "lower-limit-reg-offset", "upper-limit-reg-offset", "enable-reg-offset", + "lock-reg-offset", "write-disable-reg-offset", +}; + +/* A 32-bit value, stored as a 4- or 8-byte property (as mcc_get_count() reads them). */ +static bool amcc_lr_u32(int node, const char *name, u32 *out) +{ + u32 len = 0; + u64 wide; + const void *p = adt_getprop(adt, node, name, &len); + if (p && len == sizeof(u32)) { + memcpy(out, p, sizeof(u32)); + return true; + } + if (!p || len != sizeof(u64)) + return false; + memcpy(&wide, p, sizeof(wide)); + if (wide > UINT32_MAX) + return false; + *out = wide; + return true; +} + +/* A register the guest may reach through a hooked plane page: word-aligned, inside the page. */ +static bool amcc_lr_reg_ok(u32 off) +{ + return !(off & 3) && off < AMCC_LR_PAGE; +} + +static bool amcc_lockregs_parse(struct amcc_lockregs *lr) +{ + int node = adt_path_offset(adt, "/chosen/lock-regs/amcc"), bank; + u32 len = 0, count, size, stride, has; + const void *ap; + + memset(lr, 0, sizeof(*lr)); + if (node < 0) { + printf("SPTM-virt[amcc]: no /chosen/lock-regs/amcc; not admitted\n"); + return false; + } + ap = adt_getprop(adt, node, "aperture-phys-addr", &len); + if (!ap || !len || len % sizeof(u64) || len / sizeof(u64) > AMCC_LR_MAX_APERTURES || + !amcc_lr_u32(node, "aperture-count", &count) || count != len / sizeof(u64) || + !amcc_lr_u32(node, "aperture-size", &size) || + !amcc_lr_u32(node, "plane-count", &lr->nplanes) || + !amcc_lr_u32(node, "plane-stride", &stride) || !lr->nplanes || !stride || + (stride % AMCC_LR_PAGE) || (size % AMCC_LR_PAGE) || + (u64)(lr->nplanes - 1) * stride + AMCC_LR_PAGE > size) + goto malformed; + lr->napertures = count; + lr->aperture_size = size; + lr->plane_stride = stride; + memcpy(lr->aperture, ap, len); + for (u32 i = 0; i < lr->napertures; i++) + if (!lr->aperture[i] || (lr->aperture[i] % AMCC_LR_PAGE)) + goto malformed; + + /* The cache status is all three properties or none. */ + has = !!adt_getprop(adt, node, "cache-status-reg-offset", NULL) + + !!adt_getprop(adt, node, "cache-status-reg-mask", NULL) + + !!adt_getprop(adt, node, "cache-status-reg-value", NULL); + if (has == 3) { + if (!amcc_lr_u32(node, "cache-status-reg-offset", &lr->cache_status) || + !amcc_lr_u32(node, "cache-status-reg-mask", &lr->cache_status_mask) || + !amcc_lr_u32(node, "cache-status-reg-value", &lr->cache_status_value) || + !amcc_lr_reg_ok(lr->cache_status) || (lr->cache_status_value & ~lr->cache_status_mask)) + goto malformed; + lr->has_cache_status = true; + } else if (has) { + goto malformed; + } + + /* Every child is a bank, and every bank names all of its registers. */ + bank = node; + ADT_FOREACH_CHILD(adt, bank) + { + if (lr->nbanks == AMCC_LR_MAX_BANKS) + goto malformed; + for (int r = 0; r < AMCC_LR_BANK_REGS; r++) { + u32 off; + if (!amcc_lr_u32(bank, amcc_lr_bank_props[r], &off) || !amcc_lr_reg_ok(off) || + (lr->has_cache_status && off == lr->cache_status)) + goto malformed; + for (u32 b = 0; b <= lr->nbanks; b++) + for (int q = 0; q < (b == lr->nbanks ? r : AMCC_LR_BANK_REGS); q++) + if (lr->bank_reg[b][q] == off) + goto malformed; + lr->bank_reg[lr->nbanks][r] = off; + } + lr->nbanks++; + } + if (!lr->nbanks || (u64)lr->napertures * lr->nplanes * lr->nbanks * AMCC_LR_BANK_REGS > + ARRAY_SIZE(amcc_lock_shadow)) + goto malformed; + + /* The memory controller aura drives must be the one the node describes. */ + for (u32 i = 0; i < lr->napertures; i++) { + u64 base, pstride; + int planes; + if (mcc_plane_info(i, &base, &pstride, &planes) < 0 || base != lr->aperture[i] || + pstride != lr->plane_stride || planes < 0 || (u32)planes != lr->nplanes) { + printf("SPTM-virt[amcc]: lock-regs aperture %u disagrees with the MCC planes; " + "not admitted\n", + i); + return false; + } + } + { + u64 base, pstride; + int planes; + if (mcc_plane_info(lr->napertures, &base, &pstride, &planes) >= 0) { + printf("SPTM-virt[amcc]: MCC has more instances than lock-regs apertures; " + "not admitted\n"); + return false; + } + } + return true; + +malformed: + printf("SPTM-virt[amcc]: malformed /chosen/lock-regs/amcc; not admitted\n"); + return false; +} static bool amcc_shadow_rw(u64 addr, u64 *val, bool write) { @@ -418,11 +548,14 @@ static bool amcc_shadow_rw(u64 addr, u64 *val, bool write) return false; } -static bool t8122_amcc_is_shadow(u64 addr) +static bool amcc_lr_is_shadow(u64 addr) { - u32 off = addr & 0x3fff; - return off == t8122_amcc.lower || off == t8122_amcc.upper || off == t8122_amcc.enable || - off == t8122_amcc.lock || off == t8122_amcc.write_disable; + u32 off = addr & (AMCC_LR_PAGE - 1); + for (u32 b = 0; b < amcc_lr.nbanks; b++) + for (int r = 0; r < AMCC_LR_BANK_REGS; r++) + if (amcc_lr.bank_reg[b][r] == off) + return true; + return false; } /* sptm_virt_amcc_nolock is a mask over the three locks: bit 0 +0xacc, bit 1 +0xadc, bit 2 +0xaec. @@ -439,113 +572,64 @@ static bool amcc_is_lock(u64 addr) static bool amcc_hook(struct exc_info *ctx, u64 addr, u64 *val, bool write, int width) { static u32 logs; + bool shadowed = + amcc_lr_ready ? amcc_lr_is_shadow(addr) : sptm_virt_amcc_nolock && amcc_is_lock(addr); if (write && logs++ < 256) printf("SPTM-virt[amcc]: guest wrote 0x%lx -> 0x%lx (w%d) at pc 0x%lx%s\n", *val, addr, - width, ctx->elr, - sptm_virt_amcc_nolock && amcc_is_lock(addr) ? " -- range lock shadowed" : ""); - if (width == 2 && t8122_amcc_ready) { - if (t8122_amcc_is_shadow(addr)) + width, ctx->elr, shadowed ? " -- range lock shadowed" : ""); + if (width == 2 && amcc_lr_ready) { + if (amcc_lr_is_shadow(addr)) return amcc_shadow_rw(addr, val, write); - if ((addr & 0x3fff) == t8122_amcc.cache_status) { + if (amcc_lr.has_cache_status && (addr & (AMCC_LR_PAGE - 1)) == amcc_lr.cache_status) { if (!write) { sptm_virt_mmio_rw(addr, val, false, width); - *val = (*val & ~t8122_amcc.cache_status_mask) | t8122_amcc.cache_status_value; + *val = (*val & ~(u64)amcc_lr.cache_status_mask) | amcc_lr.cache_status_value; } return true; } } - if (sptm_virt_amcc_nolock && amcc_is_lock(addr) && width == 2) + /* The plane-offset locks are T8142's; a lock-regs shadow covers only what the node names. */ + if (!amcc_lr_ready && sptm_virt_amcc_nolock && amcc_is_lock(addr) && width == 2) return amcc_shadow_rw(addr, val, write); sptm_virt_mmio_rw(addr, val, write, width); return true; } -static bool adt_u32_is(int node, const char *name, u32 expected) -{ - u32 value; - return ADT_GETPROP(adt, node, name, &value) >= 0 && value == expected; -} - -static bool sptm_virt_amcc_contract_t8122(void) +/* + * T8142 keeps its own plane-offset shadow (amcc_is_lock above, AURA_AMCC_NOLOCK): its lock-regs + * node has not been checked against those offsets on an M5. Every other chip uses the node. + */ +static bool amcc_uses_plane_offsets(void) { - int node = adt_path_offset(adt, "/chosen/lock-regs/amcc"); - int bank = node < 0 ? -1 : adt_subnode_offset(adt, node, "amcc-ctrr-a"); - u32 len = 0; - const u64 *apertures = node < 0 ? NULL : adt_getprop(adt, node, "aperture-phys-addr", &len); - const u64 exact_apertures[2] = {0x220000000UL, 0x222000000UL}; - - if (bank < 0 || !apertures || len != sizeof(exact_apertures) || - memcmp(apertures, exact_apertures, sizeof(exact_apertures)) || - !adt_u32_is(node, "aperture-count", 2) || !adt_u32_is(node, "aperture-size", 0x200000) || - !adt_u32_is(node, "plane-count", 2) || !adt_u32_is(node, "plane-stride", 0x40000) || - !adt_u32_is(node, "cache-status-reg-offset", 0x1c00) || - !adt_u32_is(node, "cache-status-reg-mask", 1) || - !adt_u32_is(node, "cache-status-reg-value", 0) || - !adt_u32_is(bank, "lower-limit-reg-offset", 0x690) || - !adt_u32_is(bank, "lower-limit-reg-mask", 0xffffffff) || - !adt_u32_is(bank, "upper-limit-reg-offset", 0x694) || - !adt_u32_is(bank, "upper-limit-reg-mask", 0xffffffff) || - !adt_u32_is(bank, "enable-reg-offset", 0x698) || !adt_u32_is(bank, "enable-reg-mask", 1) || - !adt_u32_is(bank, "enable-reg-value", 1) || !adt_u32_is(bank, "lock-reg-offset", 0x69c) || - !adt_u32_is(bank, "lock-reg-mask", 1) || !adt_u32_is(bank, "lock-reg-value", 1) || - !adt_u32_is(bank, "write-disable-reg-offset", 0x6a0) || - !adt_u32_is(bank, "write-disable-reg-mask", 1) || - !adt_u32_is(bank, "write-disable-reg-value", 1) || - !adt_u32_is(bank, "page-size-shift", 14)) { - printf("SPTM-virt[amcc]: T8122 lock-reg ADT does not match J613/25G83; not admitted\n"); - return false; - } - - t8122_amcc = (struct t8122_amcc_layout){ - .lower = 0x690, - .upper = 0x694, - .enable = 0x698, - .lock = 0x69c, - .write_disable = 0x6a0, - .cache_status = 0x1c00, - .cache_status_mask = 1, - .cache_status_value = 0, - }; - for (int i = 0; i < 2; i++) { - u64 base, stride; - int count; - if (mcc_plane_info(i, &base, &stride, &count) < 0 || base != exact_apertures[i] || - stride != 0x40000 || count != 2) { - printf("SPTM-virt[amcc]: T8122 MCC plane layout mismatch; not admitted\n"); - return false; - } - } - - return true; + return chip_id == T8142; } bool sptm_virt_s2_admit(void) { - return chip_id != T8122 || sptm_virt_amcc_contract_t8122(); + struct amcc_lockregs lr; + return amcc_uses_plane_offsets() || amcc_lockregs_parse(&lr); } -static bool sptm_virt_amcc_watch_t8122(void) +static bool sptm_virt_amcc_watch_lockregs(void) { - if (!sptm_virt_amcc_contract_t8122()) + if (!amcc_lockregs_parse(&amcc_lr)) return false; memset(amcc_lock_shadow, 0, sizeof(amcc_lock_shadow)); - t8122_amcc_ready = true; - for (int i = 0; i < 2; i++) { - u64 base, stride; - int count; - mcc_plane_info(i, &base, &stride, &count); - for (int p = 0; p < count; p++) { - u64 page = base + p * stride; - if (hv_map_hook(page, amcc_hook, 0x4000) < 0) { - t8122_amcc_ready = false; - printf("SPTM-virt[amcc]: cannot hook T8122 MCC %d plane %d at 0x%lx\n", i, p, page); + amcc_lr_ready = true; + for (u32 i = 0; i < amcc_lr.napertures; i++) { + for (u32 p = 0; p < amcc_lr.nplanes; p++) { + u64 page = amcc_lr.aperture[i] + p * amcc_lr.plane_stride; + if (hv_map_hook(page, amcc_hook, AMCC_LR_PAGE) < 0) { + amcc_lr_ready = false; + printf("SPTM-virt[amcc]: cannot hook aperture %u plane %u at 0x%lx\n", i, p, page); return false; } } } - printf("SPTM-virt[amcc]: T8122 J613/25G83 exact lock-reg contract shadowed on 4 planes; " - "host protection unchanged\n"); + printf("SPTM-virt[amcc]: lock-regs bank%s shadowed: %u bank(s) on %u aperture(s) x %u " + "plane(s); host protection unchanged\n", + amcc_lr.nbanks == 1 ? "" : "s", amcc_lr.nbanks, amcc_lr.napertures, amcc_lr.nplanes); return true; } @@ -553,14 +637,12 @@ static void sptm_virt_amcc_watch(void) { u64 base, stride; int count; - if (chip_id == T8122) { - if (!sptm_virt_amcc_watch_t8122()) - panic("SPTM-virt[amcc]: T8122 exact shadow setup failed before guest entry\n"); + if (!amcc_uses_plane_offsets()) { + if (!sptm_virt_amcc_watch_lockregs()) + panic("SPTM-virt[amcc]: lock-regs shadow setup failed before guest entry\n"); return; } - /* The plane offsets above are T8142's; other chips keep their AMCC unhooked. */ - if (chip_id != T8142) - return; + /* The plane offsets above are T8142's. */ if (mcc_plane_info(0, &base, &stride, &count) < 0) { printf("SPTM-virt[amcc]: no AMCC planes; not watched\n"); return; diff --git a/tests/python/test_sptm_amcc_lockregs.py b/tests/python/test_sptm_amcc_lockregs.py new file mode 100644 index 000000000..f76eee05b --- /dev/null +++ b/tests/python/test_sptm_amcc_lockregs.py @@ -0,0 +1,227 @@ +# SPDX-License-Identifier: MIT +"""The stock-SPTM AMCC shadow reads /chosen/lock-regs/amcc on every chip. + +The reader and the shadow are the production source, compiled against a +modeled ADT and MCC driver: a well-formed node of any geometry is admitted, +and a missing, malformed or MCC-inconsistent one is refused. +""" +from test_smp_timeouts import REPO, compile_and_run + + +def reader_source(): + source = (REPO / "src/sptm_virt_s2.c").read_text() + start = source.index("static u64 amcc_lock_shadow[") + end = source.index("/* sptm_virt_amcc_nolock is a mask") + return source[start:end] + + +def test_no_chip_or_aperture_numbers_in_reader(): + source = reader_source() + for token in ("T8122", "0x220000000", "0x222000000", "0x690", "0x1c00", "25G83", "J613"): + assert token not in source + full = (REPO / "src/sptm_virt_s2.c").read_text() + assert "return amcc_uses_plane_offsets() || amcc_lockregs_parse(&lr);" in full + assert 'panic("SPTM-virt[amcc]: lock-regs shadow setup failed' in full + + +HARNESS = r''' +#include +#include +#include +#include +#include +typedef uint32_t u32; +typedef uint64_t u64; +typedef uint16_t u16; +#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) +#pragma GCC diagnostic ignored "-Wunused-variable" +static const void *adt = (const void *)1; + +/* A modeled ADT: node 1 is /chosen/lock-regs/amcc, nodes 2.. its children. */ +struct prop { int node; const char *name; u32 len; unsigned char data[32]; }; +static struct prop props[64]; +static int nprops, nchildren, have_node; +static int adt_path_offset(const void *t, const char *path) +{ + (void)t; + return have_node && !strcmp(path, "/chosen/lock-regs/amcc") ? 1 : -1; +} +static const void *adt_getprop(const void *t, int node, const char *name, u32 *len) +{ + (void)t; + for (int i = 0; i < nprops; i++) + if (props[i].node == node && !strcmp(props[i].name, name)) { + if (len) + *len = props[i].len; + return props[i].data; + } + return NULL; +} +static int adt_get_child_count(const void *t, int node) { (void)t; return node == 1 ? nchildren : 0; } +static int adt_first_child_offset(const void *t, int node) { (void)t; (void)node; return 2; } +static int adt_next_sibling_offset(const void *t, int node) { (void)t; return node + 1; } +#define ADT_FOREACH_CHILD(adt, node) \ + for (int _child_count = adt_get_child_count(adt, node); _child_count; _child_count = 0) \ + for (node = adt_first_child_offset(adt, node); _child_count--; \ + node = adt_next_sibling_offset(adt, node)) + +static u64 mcc_base[4], mcc_stride; +static int mcc_n, mcc_planes; +static int mcc_plane_info(int mcc, u64 *base, u64 *stride, int *count) +{ + if (mcc < 0 || mcc >= mcc_n) + return -1; + *base = mcc_base[mcc]; + *stride = mcc_stride; + *count = mcc_planes; + return 0; +} + +static void del(int node, const char *name) +{ + for (int i = 0; i < nprops; i++) + if (props[i].node == node && !strcmp(props[i].name, name)) + props[i] = props[--nprops]; +} +static void set(int node, const char *name, const void *data, u32 len) +{ + del(node, name); + props[nprops].node = node; + props[nprops].name = name; + props[nprops].len = len; + memcpy(props[nprops].data, data, len); + nprops++; +} +static void set32(int node, const char *name, u32 v) { set(node, name, &v, 4); } +static void bank(int node, u32 first) +{ + static const char *const names[] = {"lower-limit-reg-offset", "upper-limit-reg-offset", + "enable-reg-offset", "lock-reg-offset", "write-disable-reg-offset"}; + for (int i = 0; i < 5; i++) + set32(node, names[i], first + 4 * i); + set32(node, "lock-reg-mask", 1); /* unrelated properties are ignored */ +} +/* Geometry A: two apertures of two planes, one bank, a cache status. */ +static void geometry_a(void) +{ + const u64 ap[2] = {0x200000000ULL, 0x204000000ULL}; + nprops = 0; + have_node = 1; + nchildren = 1; + set(1, "aperture-phys-addr", ap, sizeof(ap)); + set32(1, "aperture-count", 2); + set32(1, "aperture-size", 0x200000); + set32(1, "plane-count", 2); + set32(1, "plane-stride", 0x40000); + set32(1, "cache-status-reg-offset", 0x1800); + set32(1, "cache-status-reg-mask", 1); + set32(1, "cache-status-reg-value", 0); + bank(2, 0x600); + mcc_n = 2; + mcc_base[0] = ap[0]; + mcc_base[1] = ap[1]; + mcc_stride = 0x40000; + mcc_planes = 2; +} +''' + + +def test_lockregs_reader(tmp_path): + harness = HARNESS + reader_source() + r''' +int main(void) +{ + struct amcc_lockregs lr; + + geometry_a(); + assert(amcc_lockregs_parse(&lr)); + assert(lr.napertures == 2 && lr.nplanes == 2 && lr.nbanks == 1); + assert(lr.aperture[1] == 0x204000000ULL && lr.plane_stride == 0x40000); + assert(lr.bank_reg[0][0] == 0x600 && lr.bank_reg[0][4] == 0x610); + assert(lr.has_cache_status && lr.cache_status == 0x1800 && lr.cache_status_mask == 1); + /* 8-byte counts are read as mcc_get_count() reads them. */ + { u64 v = 2; set(1, "plane-count", &v, 8); } + assert(amcc_lockregs_parse(&lr) && lr.nplanes == 2); + + /* Geometry B: one aperture of four planes, two banks, no cache status. */ + { + const u64 ap[1] = {0x300000000ULL}; + geometry_a(); + set(1, "aperture-phys-addr", ap, sizeof(ap)); + set32(1, "aperture-count", 1); + set32(1, "plane-count", 4); + set32(1, "plane-stride", 0x8000); + del(1, "cache-status-reg-offset"); + del(1, "cache-status-reg-mask"); + del(1, "cache-status-reg-value"); + nchildren = 2; + bank(3, 0x700); + mcc_n = 1; + mcc_base[0] = ap[0]; + mcc_stride = 0x8000; + mcc_planes = 4; + assert(amcc_lockregs_parse(&lr)); + assert(lr.nbanks == 2 && lr.nplanes == 4 && !lr.has_cache_status); + amcc_lr = lr; + assert(amcc_lr_is_shadow(0x300008000ULL + 0x70c)); + assert(!amcc_lr_is_shadow(0x300008000ULL + 0x614)); + } + + /* Refusals. Each starts from the admitted geometry A. */ + geometry_a(); have_node = 0; assert(!amcc_lockregs_parse(&lr)); + geometry_a(); set32(1, "aperture-count", 3); assert(!amcc_lockregs_parse(&lr)); + geometry_a(); del(1, "aperture-size"); assert(!amcc_lockregs_parse(&lr)); + geometry_a(); set(1, "aperture-phys-addr", "\0\0\0", 3); assert(!amcc_lockregs_parse(&lr)); + geometry_a(); set32(1, "plane-stride", 0x41000); assert(!amcc_lockregs_parse(&lr)); + geometry_a(); set32(1, "plane-count", 0); assert(!amcc_lockregs_parse(&lr)); + geometry_a(); set32(1, "plane-stride", 0x200000); assert(!amcc_lockregs_parse(&lr)); + geometry_a(); { u64 v = 1ULL << 32; set(1, "plane-count", &v, 8); } + assert(!amcc_lockregs_parse(&lr)); + geometry_a(); { u16 v = 2; set(1, "plane-count", &v, 2); } assert(!amcc_lockregs_parse(&lr)); + geometry_a(); del(1, "cache-status-reg-value"); assert(!amcc_lockregs_parse(&lr)); + geometry_a(); set32(1, "cache-status-reg-value", 2); assert(!amcc_lockregs_parse(&lr)); + geometry_a(); del(2, "lock-reg-offset"); assert(!amcc_lockregs_parse(&lr)); + geometry_a(); set32(2, "lock-reg-offset", 0x4000); assert(!amcc_lockregs_parse(&lr)); + geometry_a(); set32(2, "lock-reg-offset", 0x602); assert(!amcc_lockregs_parse(&lr)); + geometry_a(); set32(2, "lock-reg-offset", 0x600); assert(!amcc_lockregs_parse(&lr)); + geometry_a(); set32(2, "lock-reg-offset", 0x1800); assert(!amcc_lockregs_parse(&lr)); + geometry_a(); nchildren = 0; assert(!amcc_lockregs_parse(&lr)); + geometry_a(); nchildren = 2; bank(3, 0x600); assert(!amcc_lockregs_parse(&lr)); + geometry_a(); nchildren = 5; for (int n = 2; n < 7; n++) bank(n, 0x100 * n); + assert(!amcc_lockregs_parse(&lr)); + geometry_a(); mcc_base[1] += 0x4000; assert(!amcc_lockregs_parse(&lr)); + geometry_a(); mcc_planes = 4; assert(!amcc_lockregs_parse(&lr)); + geometry_a(); mcc_stride = 0x80000; assert(!amcc_lockregs_parse(&lr)); + geometry_a(); mcc_n = 1; assert(!amcc_lockregs_parse(&lr)); + geometry_a(); mcc_n = 3; assert(!amcc_lockregs_parse(&lr)); + return 0; +} +''' + compile_and_run(tmp_path, "amcc-lockregs", harness) + + +def test_lockregs_shadow(tmp_path): + harness = HARNESS + reader_source() + r''' +int main(void) +{ + geometry_a(); + assert(amcc_lockregs_parse(&amcc_lr)); + const u64 pages[] = {0x200000000ULL, 0x200040000ULL, 0x204000000ULL, 0x204040000ULL}; + for (unsigned p = 0; p < ARRAY_SIZE(pages); p++) { + for (u32 r = 0; r < 5; r++) { + u64 pa = pages[p] + 0x600 + 4 * r, value = 0xfeed0000 + p * 16 + r; + assert(amcc_lr_is_shadow(pa)); + assert(amcc_shadow_rw(pa, &value, true)); + value = ~0ULL; + assert(amcc_shadow_rw(pa, &value, false)); + assert(value == 0xfeed0000 + p * 16 + r); + } + } + /* A bank register the guest reads before writing starts at zero (unlocked). */ + u64 fresh = ~0ULL; + assert(amcc_shadow_rw(0x208000600ULL, &fresh, false) && fresh == 0); + assert(!amcc_lr_is_shadow(0x200001800ULL)); + assert(!amcc_lr_is_shadow(0x200000614ULL)); + return 0; +} +''' + compile_and_run(tmp_path, "amcc-lockregs-shadow", harness) diff --git a/tests/python/test_sptm_t8122_amcc.py b/tests/python/test_sptm_t8122_amcc.py deleted file mode 100644 index f746c98b5..000000000 --- a/tests/python/test_sptm_t8122_amcc.py +++ /dev/null @@ -1,84 +0,0 @@ -# SPDX-License-Identifier: MIT -"""T8122's exact AMCC guest shadow is isolated from the host register bank.""" - -import re -import subprocess -from pathlib import Path - - -REPO = Path(__file__).resolve().parents[2] - - -def function(source, name): - match = re.search(r"^static bool " + name + r"\([^;]*?\)\s*\{", source, re.M | re.S) - assert match, name - end, depth = match.end(), 1 - while depth: - depth += (source[end] == "{") - (source[end] == "}") - end += 1 - return source[match.start():end] - - -def test_t8122_amcc_shadow(tmp_path): - source = (REPO / "src/sptm_virt_s2.c").read_text() - funcs = "\n".join(function(source, name) for name in - ("amcc_shadow_rw", "t8122_amcc_is_shadow")) - harness = r''' -#include -#include -#include -typedef uint32_t u32; -typedef uint64_t u64; -#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) -struct t8122_amcc_layout { - u32 lower, upper, enable, lock, write_disable; - u32 cache_status, cache_status_mask, cache_status_value; -}; -static struct t8122_amcc_layout t8122_amcc = { - .lower = 0x690, .upper = 0x694, .enable = 0x698, - .lock = 0x69c, .write_disable = 0x6a0, - .cache_status = 0x1c00, .cache_status_mask = 1, -}; -static u64 amcc_lock_shadow[32][2]; -''' + funcs + r''' -int main(void) -{ - const u64 bases[] = {0x220000000ULL, 0x220040000ULL, - 0x222000000ULL, 0x222040000ULL}; - const u32 regs[] = {0x690, 0x694, 0x698, 0x69c, 0x6a0}; - for (unsigned b = 0; b < ARRAY_SIZE(bases); b++) { - for (unsigned r = 0; r < ARRAY_SIZE(regs); r++) { - u64 pa = bases[b] + regs[r], value = 0xfeed0000 + b * 16 + r; - assert(t8122_amcc_is_shadow(pa)); - assert(amcc_shadow_rw(pa, &value, true)); - value = ~0ULL; - assert(amcc_shadow_rw(pa, &value, false)); - assert(value == 0xfeed0000 + b * 16 + r); - } - } - u64 fresh = ~0ULL; - assert(amcc_shadow_rw(0x2220406a4ULL, &fresh, false)); - assert(fresh == 0); - assert(!t8122_amcc_is_shadow(0x220001c00ULL)); - assert(!t8122_amcc_is_shadow(0x2200006a4ULL)); - return 0; -} -''' - binary = tmp_path / "t8122-amcc-shadow" - subprocess.run(["cc", "-std=gnu11", "-Wall", "-Wextra", "-Werror", "-x", "c", "-", - "-o", str(binary)], input=harness, text=True, check=True) - subprocess.run([str(binary)], check=True) - - -def test_t8122_amcc_exact_adt_gate_is_complete(): - source = (REPO / "src/sptm_virt_s2.c").read_text() - for token in ("0x220000000UL", "0x222000000UL", '"aperture-count", 2', - '"aperture-size", 0x200000', '"plane-count", 2', - '"plane-stride", 0x40000', '"lower-limit-reg-offset", 0x690', - '"upper-limit-reg-offset", 0x694', '"enable-reg-offset", 0x698', - '"lock-reg-offset", 0x69c', '"write-disable-reg-offset", 0x6a0', - '"cache-status-reg-offset", 0x1c00', '"page-size-shift", 14'): - assert token in source - assert "bool sptm_virt_s2_admit(void)" in source - assert "chip_id != T8122 || sptm_virt_amcc_contract_t8122()" in source - assert 'panic("SPTM-virt[amcc]: T8122 exact shadow setup failed' in source From fecefc8b29697874bd5f338acd162c05bb0fc6a4 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Fri, 20 Nov 2026 09:40:08 -0500 Subject: [PATCH 14/19] sptm_virt_gpu: take the ANE trace windows from the ADT j613_capture_setup() compared transcribed J613 values and hooked a fixed window list, including two addresses (0x292468000, 0x2a5468000) no ADT node backed. Replace it with ane_trace_setup(): it hooks every reg window of /arm-io/ane and /arm-io/dart-ane and /arm-io/aic reg[0], traces a window that lies inside another through the larger one, and refuses a missing node, an empty window or too many windows before any hook. The chip_id check goes; the mode is SPTM_VIRT_ANE_TRACE, named by what it traces. On the J613 ADT this hooks the same ANE and AIC windows as before. The two word windows are no longer traced: their ADT node is not named in this PR or aura's source, so they come back once one is. Signed-off-by: Satya Benson --- src/sptm_virt.h | 4 +- src/sptm_virt_gpu.c | 114 +++++++++++++++------------ tests/python/test_sptm_ane_trace.py | 115 ++++++++++++++++++++++++++++ 3 files changed, 184 insertions(+), 49 deletions(-) create mode 100644 tests/python/test_sptm_ane_trace.py diff --git a/src/sptm_virt.h b/src/sptm_virt.h index ef481209d..1068f39df 100644 --- a/src/sptm_virt.h +++ b/src/sptm_virt.h @@ -51,8 +51,8 @@ struct sptm_virt_placement { #define SPTM_VIRT_SAMPLE BIT(7) /* sample the guest's PC until its XNU entry */ #define SPTM_VIRT_S2R_MEM BIT(8) /* T6050: also hook the MCC and the coprocessor DARTs */ /* bit 9 is AURA_AURACTL in the feat/auractl runner; left free here so the two never clash */ -#define SPTM_VIRT_CTL_DCC BIT(10) /* arm auractl's DCC transport (MDCR_EL2.TDCC) at boot */ -#define SPTM_VIRT_J613_TRACE BIT(11) /* bounded J613 ANE/AIC trace; exact ADT resources only */ +#define SPTM_VIRT_CTL_DCC BIT(10) /* arm auractl's DCC transport (MDCR_EL2.TDCC) at boot */ +#define SPTM_VIRT_ANE_TRACE BIT(11) /* bounded ANE, ANE DART and AIC trace from the ADT */ /* sptm_virt_s2r_cp_ansx, with COPROC on T6050 */ #define S2R_CP_ANSX_SART BIT(0) /* sart-ans reg[0-2], first page each */ #define S2R_CP_ANSX_NVME BIT(1) /* the NVMe BAR's first page (reg[9]) */ diff --git a/src/sptm_virt_gpu.c b/src/sptm_virt_gpu.c index f74cd54d8..3afd57af5 100644 --- a/src/sptm_virt_gpu.c +++ b/src/sptm_virt_gpu.c @@ -17,7 +17,6 @@ #include "iodev.h" #include "malloc.h" #include "memory.h" -#include "soc.h" #include "sptm_virt_priv.h" #include "string.h" #include "uartproxy.h" @@ -153,8 +152,8 @@ void sptm_virt_gpu_deadline(struct exc_info *ctx) static bool gpu_hook(struct exc_info *ctx, u64 addr, u64 *val, bool write, int width) { - if ((sptm_virt_flags & SPTM_VIRT_J613_TRACE) && sptm_virt_gpu_head + 2 >= sptm_virt_gpu_nrec) - gpu_park(ctx, "the bounded J613 trace ring is full"); + if ((sptm_virt_flags & SPTM_VIRT_ANE_TRACE) && sptm_virt_gpu_head + 2 >= sptm_virt_gpu_nrec) + gpu_park(ctx, "the bounded ANE trace ring is full"); u64 now = mrs(CNTPCT_EL0); if (!gpu_first_t) { @@ -243,52 +242,73 @@ static void gpu_hook_adt(const char *path, int idx, const char *what, u64 off, u gpu_hook_range(what, pa + off, size ? size : sz); } -/* J613 ranges transcribed from the retained ADT, not from a J700 base shift. - * Validate the entire resource list before installing any hook; no MMIO sweep. */ -static void j613_capture_setup(void) +/* + * The ANE trace: every register window the ADT gives the Neural Engine (/arm-io/ane) and its DART + * (/arm-io/dart-ane), and the interrupt controller's (/arm-io/aic reg[0]). A window inside another + * is traced through the larger one. A missing node or empty window refuses the trace before any + * hook; nothing the ADT does not name is hooked. + */ +#define ANE_TRACE_MAX_REGS 16 + +static void ane_trace_setup(void) { - sptm_virt_gpu_print_max = 0; /* export the ring; no per-access console timing noise */ - if (chip_id != T8122 || (sptm_virt_flags & ~SPTM_VIRT_J613_TRACE)) - panic("J613 capture: wrong chip or conflicting capture modes\n"); static const struct { - const char *path; - int idx; - u64 base, size; - } resources[] = { - {"/arm-io/ane", 0, 0x311400000UL, 0x6c000UL}, - {"/arm-io/ane", 1, 0x311050000UL, 0x4000UL}, - {"/arm-io/ane", 2, 0x310000000UL, 0x2000000UL}, - {"/arm-io/ane", 3, 0x2d0700000UL, 0x18000UL}, - {"/arm-io/ane", 4, 0x2d0724000UL, 0x4000UL}, - {"/arm-io/dart-ane", 0, 0x311800000UL, 0x4000UL}, - {"/arm-io/dart-ane", 1, 0x311810000UL, 0x4000UL}, - {"/arm-io/dart-ane", 2, 0x311820000UL, 0x4000UL}, - {"/arm-io/dart-ane", 3, 0x311804000UL, 0x4000UL}, - {"/arm-io/aic", 0, 0x2d1000000UL, 0x184000UL}, + const char *path, *what; + int max; + } nodes[] = { + {"/arm-io/ane", "ane", ANE_TRACE_MAX_REGS}, + {"/arm-io/dart-ane", "dart-ane", ANE_TRACE_MAX_REGS}, + {"/arm-io/aic", "aic", 1}, }; - for (size_t i = 0; i < ARRAY_SIZE(resources); i++) { - int p[8]; - u64 a, n; - if (adt_path_offset_trace(adt, resources[i].path, p) < 0 || - adt_get_reg(adt, p, "reg", resources[i].idx, &a, &n) < 0 || a != resources[i].base || - n != resources[i].size) - panic("J613 capture: ADT resource drift\n"); - } - static const struct { + static struct { u64 base, size; - } windows[] = { - {0x292468000UL, 0x4UL}, {0x2a5468000UL, 0x4UL}, {0x2d0700000UL, 0x18000UL}, - {0x2d0724000UL, 0x4000UL}, {0x2d1000000UL, 0x184000UL}, {0x310000000UL, 0x2000000UL}, - }; - for (size_t i = 0; i < ARRAY_SIZE(windows); i++) { - gpu_ranges[gpu_nranges].base = windows[i].base; - gpu_ranges[gpu_nranges].size = windows[i].size; - gpu_ranges[gpu_nranges++].what = "j613"; - /* Keep the two AON words at four-byte granularity. */ - if (hv_map_hook(windows[i].base, gpu_hook, windows[i].size) < 0) - panic("J613 capture: hook installation failed\n"); + const char *what; + } w[2 * ANE_TRACE_MAX_REGS + 1]; + int n = 0; + + sptm_virt_gpu_print_max = 0; /* export the ring; no per-access console timing noise */ + if (sptm_virt_flags & ~SPTM_VIRT_ANE_TRACE) + panic("ANE trace: conflicting capture modes\n"); + for (size_t i = 0; i < ARRAY_SIZE(nodes); i++) { + int p[8], idx; + if (adt_path_offset_trace(adt, nodes[i].path, p) < 0) + panic("ANE trace: no %s in the ADT\n", nodes[i].path); + for (idx = 0; idx < nodes[i].max; idx++) { + u64 a, sz; + if (adt_get_reg(adt, p, "reg", idx, &a, &sz) < 0) + break; + if (!a || !sz || a + sz < a) + panic("ANE trace: %s reg[%d] is empty\n", nodes[i].path, idx); + w[n].base = a; + w[n].size = sz; + w[n++].what = nodes[i].what; + } + if (!idx) + panic("ANE trace: %s has no reg\n", nodes[i].path); + } + static bool inside[ARRAY_SIZE(w)]; + int keep = 0; + for (int i = 0; i < n; i++) { + inside[i] = false; + for (int j = 0; j < n && !inside[i]; j++) + inside[i] = j != i && w[j].base <= w[i].base && + w[i].base + w[i].size <= w[j].base + w[j].size && + (w[j].size != w[i].size || j < i); + } + for (int i = 0; i < n; i++) + if (!inside[i]) + w[keep++] = w[i]; + if (gpu_nranges + keep > GPU_MAX_RANGES) + panic("ANE trace: %d windows, more than %d\n", keep, GPU_MAX_RANGES); + for (int i = 0; i < keep; i++) { + gpu_ranges[gpu_nranges].base = w[i].base; + gpu_ranges[gpu_nranges].size = w[i].size; + gpu_ranges[gpu_nranges++].what = w[i].what; + if (hv_map_hook(w[i].base, gpu_hook, w[i].size) < 0) + panic("ANE trace: cannot hook %s 0x%lx+0x%lx\n", w[i].what, w[i].base, w[i].size); + printf("ANE trace: hooked %s 0x%lx+0x%lx\n", w[i].what, w[i].base, w[i].size); } - printf("J613 capture: %d exact windows, ring at 0x%lx; export before reset\n", gpu_nranges, + printf("ANE trace: %d windows from the ADT, ring at 0x%lx; export before reset\n", gpu_nranges, (u64)sptm_virt_gpu_ring); } @@ -300,7 +320,7 @@ void sptm_virt_gpu_setup(void) printf("SPTM-virt[park]: the guest parks in the proxy at its first GL trap after %u s\n", sptm_virt_gpu_stop_boot_secs); } - if (!(sptm_virt_flags & (SPTM_VIRT_GPU | SPTM_VIRT_J613_TRACE))) + if (!(sptm_virt_flags & (SPTM_VIRT_GPU | SPTM_VIRT_ANE_TRACE))) return; sptm_virt_gpu_ring = memalign(0x4000, GPU_RING_BYTES); if (!sptm_virt_gpu_ring) { @@ -313,8 +333,8 @@ void sptm_virt_gpu_setup(void) sptm_virt_gpu_nrec = GPU_RING_BYTES / sizeof(struct gpu_rec); sptm_virt_gpu_head = 0; - if (sptm_virt_flags & SPTM_VIRT_J613_TRACE) { - j613_capture_setup(); + if (sptm_virt_flags & SPTM_VIRT_ANE_TRACE) { + ane_trace_setup(); return; } diff --git a/tests/python/test_sptm_ane_trace.py b/tests/python/test_sptm_ane_trace.py new file mode 100644 index 000000000..f0aa6db28 --- /dev/null +++ b/tests/python/test_sptm_ane_trace.py @@ -0,0 +1,115 @@ +# SPDX-License-Identifier: MIT +"""The ANE trace hooks only what the ADT gives the ANE, its DART and the AIC. + +ane_trace_setup() is the production body, compiled against a modeled ADT. +""" +import re + +from test_smp_timeouts import REPO, compile_and_run + + +def setup_source(): + source = (REPO / "src/sptm_virt_gpu.c").read_text() + start = source.index("#define ANE_TRACE_MAX_REGS") + end = source.index("void sptm_virt_gpu_setup(void)") + return source[start:end] + + +def test_no_board_chip_or_address_in_trace(): + body = setup_source() + assert not re.search(r"0x[0-9a-f]{6,}", body, re.I) + for token in ("chip_id", "T8122", "J613", "j613"): + assert token not in body + + +def test_ane_trace_windows_from_adt(tmp_path): + harness = r''' +#include +#include +#include +#include +#include +#include +#include +typedef uint32_t u32; +typedef unsigned long u64; +#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) +#define BIT(n) (1UL << (n)) +#define SPTM_VIRT_ANE_TRACE BIT(11) +#define GPU_MAX_RANGES 10 +static const void *adt = (const void *)1; +static u32 sptm_virt_flags = SPTM_VIRT_ANE_TRACE, sptm_virt_gpu_print_max = 20000; +static void *sptm_virt_gpu_ring; +static struct { u64 base, size; const char *what; } gpu_ranges[GPU_MAX_RANGES]; +static int gpu_nranges, hooks; +struct exc_info; +static bool gpu_hook(struct exc_info *c, u64 a, u64 *v, bool w, int n) +{ (void)c; (void)a; (void)v; (void)w; (void)n; return true; } +static int hv_map_hook(u64 base, void *hook, u64 size) { (void)base; (void)hook; (void)size; hooks++; return 0; } +static jmp_buf refused; +#define panic(...) longjmp(refused, 1) + +/* Modeled ADT: three nodes, each a list of (base, size). */ +static const char *paths[3] = {"/arm-io/ane", "/arm-io/dart-ane", "/arm-io/aic"}; +static u64 regs[3][8][2]; +static int nregs[3], present[3]; +static int adt_path_offset_trace(const void *t, const char *path, int *p) +{ + (void)t; + for (int i = 0; i < 3; i++) + if (!strcmp(path, paths[i]) && present[i]) { + p[0] = i; + return i; + } + return -1; +} +static int adt_get_reg(const void *t, int *p, const char *prop, int idx, u64 *a, u64 *s) +{ + (void)t; (void)prop; + if (idx >= nregs[p[0]]) + return -1; + *a = regs[p[0]][idx][0]; + *s = regs[p[0]][idx][1]; + return 0; +} +static void reset(void) +{ + static const u64 ane[][2] = {{0x5400000, 0x6c000}, {0x5050000, 0x4000}, {0x4000000, 0x2000000}, + {0x1700000, 0x18000}, {0x1724000, 0x4000}}; + static const u64 dart[][2] = {{0x5800000, 0x4000}, {0x5810000, 0x4000}}; + memset(regs, 0, sizeof(regs)); + memcpy(regs[0], ane, sizeof(ane)); + memcpy(regs[1], dart, sizeof(dart)); + regs[2][0][0] = 0x1000000; + regs[2][0][1] = 0x184000; + regs[2][1][0] = 0x9000000; /* a second AIC window is not traced */ + regs[2][1][1] = 0x4000; + nregs[0] = 5; nregs[1] = 2; nregs[2] = 2; + present[0] = present[1] = present[2] = 1; + gpu_nranges = hooks = 0; + sptm_virt_flags = SPTM_VIRT_ANE_TRACE; +} +#define REFUSED(stmt) (setjmp(refused) ? true : ((stmt), false)) +''' + setup_source() + r''' +int main(void) +{ + reset(); + assert(!REFUSED(ane_trace_setup())); + /* ane reg[2] covers ane reg[0], reg[1] and the DART; reg[3], reg[4] and aic reg[0] stand. */ + assert(gpu_nranges == 4 && hooks == 4 && sptm_virt_gpu_print_max == 0); + assert(gpu_ranges[0].base == 0x4000000 && gpu_ranges[0].size == 0x2000000); + assert(gpu_ranges[1].base == 0x1700000 && gpu_ranges[2].base == 0x1724000); + assert(gpu_ranges[3].base == 0x1000000 && !strcmp(gpu_ranges[3].what, "aic")); + + reset(); present[1] = 0; assert(REFUSED(ane_trace_setup())); assert(hooks == 0); + reset(); nregs[2] = 0; assert(REFUSED(ane_trace_setup())); assert(hooks == 0); + reset(); regs[0][3][1] = 0; assert(REFUSED(ane_trace_setup())); assert(hooks == 0); + reset(); sptm_virt_flags |= BIT(6); assert(REFUSED(ane_trace_setup())); assert(hooks == 0); + reset(); + for (int i = 0; i < 8; i++) { regs[1][i][0] = 0x8000000 + i * 0x10000; regs[1][i][1] = 0x4000; } + nregs[1] = 8; + assert(REFUSED(ane_trace_setup())); assert(hooks == 0); + return 0; +} +''' + compile_and_run(tmp_path, "ane-trace", harness) From 57c72382b905e5ce07be9d35732274e16dc60f33 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Fri, 20 Nov 2026 09:40:22 -0500 Subject: [PATCH 15/19] run_guest_sptm: select a clean-room SPTM export by image, not 25G83 The J613 profile and admit check were pinned to 25G83 and to chip == 0x8122, with exact ADT register values. Replace them: - aura/sptm_export.py loads every aura/sptm_exports/*.json and picks the one whose image_sha256 matches the SPTM image given. No SoC, board or OS build is matched. The existing 25G83 export moves there unchanged; an export for another SPTM build (27.2, 26B123) is one more file, once one is reviewed. - An image with an export is patched only from it, and only with AURA_SPTM_EXPORT=1 (was AURA_J613_RUN) or AURA_ANE_TRACE=1 (was AURA_J613_TRACE). An incomplete or unreviewed export, or one with rows the loader does not apply, is refused on the host before anything is placed on the target. Any other image goes to sptm_patch.plan(), which refuses images it cannot fully plan. - The exact ADT resource and window lists go: the ANE trace reads its windows from the ADT, and the AMCC shadow reads lock-regs. Signed-off-by: Satya Benson --- proxyclient/aura/profiles/j613-25G83.json | 142 ---------------------- proxyclient/aura/sptm_export.py | 92 ++++++++++++++ proxyclient/aura/sptm_exports/25G83.json | 36 ++++++ proxyclient/aura/sptm_j613.py | 59 --------- proxyclient/tools/run_guest_sptm.py | 43 ++++--- tests/python/test_sptm_export.py | 113 +++++++++++++++++ tests/python/test_sptm_j613.py | 43 ------- 7 files changed, 264 insertions(+), 264 deletions(-) delete mode 100644 proxyclient/aura/profiles/j613-25G83.json create mode 100644 proxyclient/aura/sptm_export.py create mode 100644 proxyclient/aura/sptm_exports/25G83.json delete mode 100644 proxyclient/aura/sptm_j613.py create mode 100644 tests/python/test_sptm_export.py delete mode 100644 tests/python/test_sptm_j613.py diff --git a/proxyclient/aura/profiles/j613-25G83.json b/proxyclient/aura/profiles/j613-25G83.json deleted file mode 100644 index 50451af23..000000000 --- a/proxyclient/aura/profiles/j613-25G83.json +++ /dev/null @@ -1,142 +0,0 @@ -{ - "mode": "A", - "board": "J613", - "soc": "T8122", - "build": "25G83", - "source_adt_sha256": "e2c8cb7f1ebbe3849ce14d0c6d83838cae6c1dc17d8df2c4cffe616508b1f0f1", - "max_events": 250000, - "read": true, - "write": true, - "values": true, - "trace_mode": "SYNC", - "commit_allowed": false, - "resources": [ - { - "path": "/arm-io/ane", - "index": 0, - "base": "0x311400000", - "size": "0x6c000" - }, - { - "path": "/arm-io/ane", - "index": 1, - "base": "0x311050000", - "size": "0x4000" - }, - { - "path": "/arm-io/ane", - "index": 2, - "base": "0x310000000", - "size": "0x2000000" - }, - { - "path": "/arm-io/ane", - "index": 3, - "base": "0x2d0700000", - "size": "0x18000" - }, - { - "path": "/arm-io/ane", - "index": 4, - "base": "0x2d0724000", - "size": "0x4000" - }, - { - "path": "/arm-io/dart-ane", - "index": 0, - "base": "0x311800000", - "size": "0x4000" - }, - { - "path": "/arm-io/dart-ane", - "index": 1, - "base": "0x311810000", - "size": "0x4000" - }, - { - "path": "/arm-io/dart-ane", - "index": 2, - "base": "0x311820000", - "size": "0x4000" - }, - { - "path": "/arm-io/dart-ane", - "index": 3, - "base": "0x311804000", - "size": "0x4000" - }, - { - "path": "/arm-io/aic", - "index": 0, - "base": "0x2d1000000", - "size": "0x184000" - } - ], - "windows": [ - { - "base": "0x292468000", - "size": "0x4", - "end_exclusive": "0x292468004" - }, - { - "base": "0x2a5468000", - "size": "0x4", - "end_exclusive": "0x2a5468004" - }, - { - "base": "0x2d0700000", - "size": "0x18000", - "end_exclusive": "0x2d0718000" - }, - { - "base": "0x2d0724000", - "size": "0x4000", - "end_exclusive": "0x2d0728000" - }, - { - "base": "0x2d1000000", - "size": "0x184000", - "end_exclusive": "0x2d1184000" - }, - { - "base": "0x310000000", - "size": "0x2000000", - "end_exclusive": "0x312000000" - } - ], - "patch_export": { - "image_sha256": "6ab3f26ff9445a802e2e88d2347f7d64157d1b9eab783523ab0e7eab183bef6b", - "uuid": "2B57CA7A-3D9C-3C70-B5E0-7C3F74C5323B", - "entry_file_offset": "0xa8388", - "groups": { - "APSTS poll": [ - { - "purpose": "shared cold/reset readiness wait", - "pattern_offset": "0xab7ac", - "pattern": "df3f03d51f8708d59f3b03d580fc3ed501004092c1ffffb480f03cd5000040b2", - "patch_offset": "0xab7c0", - "entry_offset": "0x3438", - "expected": "0xb4ffffc1", - "replacement": "0xd503201f" - }, - { - "purpose": "early-entry readiness wait", - "pattern_offset": "0x9c0b0", - "pattern": "28a2acf228a294f2482018d58afc3ed548014092c8ffffb48af03cd54a0140b2", - "patch_offset": "0x9c0c4", - "entry_offset": "-0xc2c4", - "expected": "0xb4ffffc8", - "replacement": "0xd503201f" - } - ], - "CTRR check": [], - "CTRR reset-path check": [], - "ctXr lock check": [], - "AMCC CTRR match": [] - }, - "ctrr_stash_off": null, - "ctxr_ctl": null, - "sptm_va_maps": null, - "reviewed": true - } -} diff --git a/proxyclient/aura/sptm_export.py b/proxyclient/aura/sptm_export.py new file mode 100644 index 000000000..f22979397 --- /dev/null +++ b/proxyclient/aura/sptm_export.py @@ -0,0 +1,92 @@ +# SPDX-License-Identifier: MIT +"""Clean-room SPTM patch exports, selected by the SPTM image they were reviewed against. + +Each sptm_exports/*.json names one exact SPTM image (image_sha256, entry_file_offset) and its +patch groups. An image with no export goes to the pattern patcher (sptm_patch.plan), which refuses +images it cannot fully plan; an image with an export is patched only from it, and only when the +export is complete and reviewed. No SoC, board or OS build is matched here, and no Apple image is +read on import. +""" +import hashlib +import json +import struct +from pathlib import Path + +EXPORT_DIR = Path(__file__).parent / "sptm_exports" +REQUIRED = ("image_sha256", "entry_file_offset", "groups", "reviewed") + + +def load_exports(directory=EXPORT_DIR): + exports = [] + for path in sorted(directory.glob("*.json")): + export = json.loads(path.read_text()) + missing = [k for k in REQUIRED if k not in export] + if missing: + raise ValueError(f"{path.name}: missing {', '.join(missing)}") + export["_name"] = path.stem + exports.append(export) + digests = [e["image_sha256"] for e in exports] + if len(set(digests)) != len(digests): + raise ValueError("two SPTM exports name the same image") + return exports + + +EXPORTS = load_exports() + + +def find(image, exports=None): + """The export for this exact SPTM image, or None.""" + digest = hashlib.sha256(image).hexdigest() + return next((e for e in (EXPORTS if exports is None else exports) + if e["image_sha256"] == digest), None) + + +def unresolved_groups(export): + return [name for name, rows in export["groups"].items() if rows is None] + + +def inspect(image, entry_off, export): + """Validate the export against its image and return the patches it describes.""" + name = export.get("label", export["_name"]) + if hashlib.sha256(image).hexdigest() != export["image_sha256"]: + raise ValueError(f"SPTM image identity does not match the {name} export") + expected_entry = int(export["entry_file_offset"], 0) + if entry_off != expected_entry: + raise ValueError(f"SPTM entry offset {entry_off:#x}, expected {expected_entry:#x}") + patches = [] + for site in export["groups"].get("APSTS poll") or (): + pattern = bytes.fromhex(site["pattern"]) + hits = [i for i in range(len(image) - len(pattern) + 1) + if image[i:i + len(pattern)] == pattern] + start = int(site["pattern_offset"], 0) + if hits != [start]: + raise ValueError(f"{site['purpose']}: pattern hits {hits}, expected [{start}]") + patch_off = int(site["patch_offset"], 0) + expected = int(site["expected"], 0) + if struct.unpack_from("> 24) & 15) >= 2 and gxf - -def validate_resources(get_reg): - for r in PROFILE['resources']: - if 'index' in r and tuple(get_reg(r['path'], r['index'])) != (int(r['base'], 0), int(r['size'], 0)): - raise ValueError('ADT drift: ' + str(r)) - -def inspect_patch_export(image, entry_off): - """Validate and return the clean-room facts that are complete without admitting entry.""" - if image is None: - return {'reviewed': bool(PATCH_EXPORT['reviewed']), - 'unresolved': unresolved_groups()} - if hashlib.sha256(image).hexdigest() != PATCH_EXPORT['image_sha256']: - raise ValueError('J613 SPTM image identity does not match the 25G83 export') - expected_entry = int(PATCH_EXPORT['entry_file_offset'], 0) - if entry_off != expected_entry: - raise ValueError(f'J613 SPTM entry offset {entry_off:#x}, expected {expected_entry:#x}') - patches = [] - for site in PATCH_EXPORT['groups']['APSTS poll']: - pattern = bytes.fromhex(site['pattern']) - hits = [i for i in range(len(image) - len(pattern) + 1) - if image[i:i + len(pattern)] == pattern] - start = int(site['pattern_offset'], 0) - if hits != [start]: - raise ValueError(f"J613 {site['purpose']}: pattern hits {hits}, expected [{start}]") - patch_off = int(site['patch_offset'], 0) - expected = int(site['expected'], 0) - if struct.unpack_from(' samples per second (default 4) AURA_SAMPLE_MAX= stop printing after n samples (default 64) - AURA_J613_RUN admit the exact J613 stock-SPTM path without the bounded MMIO trace + AURA_SPTM_EXPORT admit an SPTM image that has a reviewed clean-room export + (aura/sptm_exports), without the bounded MMIO trace + AURA_ANE_TRACE trace the ANE, its DART and the AIC (windows from the ADT) into a + bounded ring, and park when it is full AURA_XNU_ENTRY patch the guest kernelcache's acct(2) so a root process reaches aura's control hvc with no kext (the auractl "xnu" entry; aura/auractl_xnu.py) AURA_XNU_RO_RELAX patch XNU's zalloc_ro_mut RO-zone panic out (tracing only; XNU_QUIRKS) @@ -113,7 +116,7 @@ "AURA_S2R_DROP_USB": 1 << 4, "AURA_XNU_BT": 1 << 5, "AURA_GPU_TRACE": 1 << 6, - "AURA_J613_TRACE": 1 << 11, + "AURA_ANE_TRACE": 1 << 11, "AURA_SAMPLE": 1 << 7, "AURA_S2R_MEM": 1 << 8, # bit 9 is reserved for AURA_AURACTL in the feat/auractl runner @@ -149,7 +152,7 @@ "AURA_S2R_USB_RETAKE_MS", "AURA_TAIL_SECS", "AURA_TAIL_IDLE", - "AURA_J613_RUN", + "AURA_SPTM_EXPORT", "AURA_GPU_STOP_SECS", "AURA_GPU_STOP_BOOT_SECS", "AURA_GPU_STOP_MSG", @@ -859,7 +862,7 @@ def main(): if unknown: print("not run_guest_sptm.py switches, ignored:", " ".join(unknown)) - from aura import sptm_patch, sptm_virt_plan as plan_mod + from aura import sptm_export, sptm_patch, sptm_virt_plan as plan_mod from aura.proxy import AuraProxy, UartInterface from aura.proxyutils import ProxyUtils, bootstrap_port @@ -871,22 +874,23 @@ def main(): # SPTM's managed window, as aura computed it: above aura and everything iBoot left low, # below aura's carve-out. - chip = u.adt["/chosen"].chip_id - if chip == 0x8122: - print(f"J613 host image [0x{sym['_base']:x}, 0x{sym['_end']:x})") - from aura import sptm_j613 - sptm_j613.validate_resources(lambda path, idx: u.adt[path].get_reg(idx)) - if not (env_on("AURA_J613_RUN") or env_on("AURA_J613_TRACE")): - raise SystemExit("T8122 requires experimental AURA_J613_RUN=1") - if any(env_on(k) for k in CONFIG_FLAGS if k != "AURA_J613_TRACE"): - raise SystemExit("J613: other trace/sleep modes are not qualified") - # Deliberately before reading images or placing anything on the target. + # An SPTM image with a clean-room export is patched only from that export (selected by the + # image itself, not by SoC or OS build), and only when asked. Checked on the host's copy of + # the image, before anything is placed on the target. + export = sptm_export.find(args.sptm.read_bytes()) + if export: + print(f"SPTM export {export['_name']}: {export.get('label', '')}; host image " + f"[0x{sym['_base']:x}, 0x{sym['_end']:x})") + if not (env_on("AURA_SPTM_EXPORT") or env_on("AURA_ANE_TRACE")): + raise SystemExit("this SPTM has a clean-room export: set AURA_SPTM_EXPORT=1") + if any(env_on(k) for k in CONFIG_FLAGS if k != "AURA_ANE_TRACE"): + raise SystemExit("SPTM export: other trace/sleep modes are not qualified") try: - sptm_j613.patch_plan(None, None) + sptm_export.admit(export) except ValueError as e: raise SystemExit(str(e)) - elif env_on("AURA_J613_RUN") or env_on("AURA_J613_TRACE"): - raise SystemExit("AURA_J613_RUN/AURA_J613_TRACE require T8122") + elif env_on("AURA_SPTM_EXPORT"): + raise SystemExit("AURA_SPTM_EXPORT: no clean-room export matches this SPTM image") scratch = u.malloc(0x40) if p.call(sym["sptm_virt_place"], scratch) != 0: raise SystemExit("sptm_virt_place failed: not an SPTM_VIRT build, no FEAT_NV2 or GXF, or " @@ -916,7 +920,7 @@ def main(): entry_off = plan_mod.macho_info(images["sptm"]).entry - plan_mod.macho_info(images["sptm"]).virtlo try: - sp = (sptm_j613.patch_plan(images["sptm"], entry_off) if chip == 0x8122 + sp = (sptm_export.patch_plan(images["sptm"], entry_off, export) if export else sptm_patch.plan(images["sptm"], entry_off)) except (sptm_patch.SptmPatchError, ValueError) as e: raise SystemExit(f"this SPTM can't be patched: {e}") @@ -962,8 +966,7 @@ def main(): quirk_hide = tuple(quirks["hide"]) if env_on("AURA_KEEP_WIFI"): quirk_hide = tuple(n for n in quirk_hide if n in port_nodes) - keep_ane = env_on("AURA_KEEP_ANE") or ( - chip == 0x8122 and (env_on("AURA_J613_RUN") or env_on("AURA_J613_TRACE"))) + keep_ane = env_on("AURA_KEEP_ANE") or env_on("AURA_ANE_TRACE") or bool(export) hide = port_nodes + (() if keep_ane else STRIP_NODES) + quirk_hide if not env_on("AURA_KEEP_ERRH"): hide += (ERROR_HANDLER,) diff --git a/tests/python/test_sptm_export.py b/tests/python/test_sptm_export.py new file mode 100644 index 000000000..ec60a9d21 --- /dev/null +++ b/tests/python/test_sptm_export.py @@ -0,0 +1,113 @@ +# SPDX-License-Identifier: MIT +"""Clean-room SPTM exports are chosen by image identity, not by SoC, board or OS build. +No Apple image fixtures or target connection are used. +""" +import copy +import hashlib +import json +import os +import struct +import sys +from pathlib import Path + +import pytest + +REPO = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(REPO / "proxyclient")) + +from aura import sptm_export # noqa: E402 +REAL_IMAGE = os.environ.get("SPTM_EXPORT_IMAGE") + + +def synthetic(entry_off=0x100): + """A made-up image and export with one APSTS site: no Apple bytes.""" + image = bytearray(0x400) + pattern = bytes(range(0x20, 0x40)) + image[0x200:0x220] = pattern + struct.pack_into(" Date: Fri, 20 Nov 2026 09:52:00 -0500 Subject: [PATCH 16/19] sptm_virt_gpu: trace the ANE DART's DAPF slices from the ADT ane_trace_setup() dropped the two four-byte windows j613_capture_setup() hooked by address. They are slices of the ANE DART's filter: the dapf-instance-N entries of /arm-io/dart-ane. Read every such property with dapf_t8110_ranges() and hook each slice at the filter's word granularity; a slice inside a reg window is traced through it, as before. A dapf-instance-N that is present but malformed, empty, or holds a slice that is not whole words refuses the trace before any hook. A DART with no such property traces its reg windows only. On the J613 ADT this restores the two word windows; the other three slices lie in /arm-io/ane reg[3]. Signed-off-by: Satya Benson --- src/sptm_virt_gpu.c | 43 ++++++++++++++++++--- tests/python/test_sptm_ane_trace.py | 60 ++++++++++++++++++++++++++++- 2 files changed, 97 insertions(+), 6 deletions(-) diff --git a/src/sptm_virt_gpu.c b/src/sptm_virt_gpu.c index 3afd57af5..1ea769b72 100644 --- a/src/sptm_virt_gpu.c +++ b/src/sptm_virt_gpu.c @@ -12,6 +12,7 @@ #include "sptm_virt.h" #include "adt.h" +#include "dapf.h" #include "exception.h" #include "hv.h" #include "iodev.h" @@ -244,11 +245,13 @@ static void gpu_hook_adt(const char *path, int idx, const char *what, u64 off, u /* * The ANE trace: every register window the ADT gives the Neural Engine (/arm-io/ane) and its DART - * (/arm-io/dart-ane), and the interrupt controller's (/arm-io/aic reg[0]). A window inside another - * is traced through the larger one. A missing node or empty window refuses the trace before any - * hook; nothing the ADT does not name is hooked. + * (/arm-io/dart-ane), the interrupt controller's (/arm-io/aic reg[0]), and each slice of the + * DART's dapf-instance-N properties, at the filter's four-byte granularity. A window inside + * another is traced through the larger one. A missing node, an empty window or a malformed DAPF + * property refuses the trace before any hook; nothing the ADT does not name is hooked. */ -#define ANE_TRACE_MAX_REGS 16 +#define ANE_TRACE_MAX_REGS 16 +#define ANE_TRACE_DAPF_INST 8 static void ane_trace_setup(void) { @@ -263,7 +266,7 @@ static void ane_trace_setup(void) static struct { u64 base, size; const char *what; - } w[2 * ANE_TRACE_MAX_REGS + 1]; + } w[2 * ANE_TRACE_MAX_REGS + 1 + 2 * DAPF_T8110_MAX_SLICES]; int n = 0; sptm_virt_gpu_print_max = 0; /* export the ring; no per-access console timing noise */ @@ -286,6 +289,36 @@ static void ane_trace_setup(void) if (!idx) panic("ANE trace: %s has no reg\n", nodes[i].path); } + /* The words the ANE DART's filter admits: every slice of every dapf-instance-N it has. */ + int dart = adt_path_offset(adt, "/arm-io/dart-ane"); + int nslices = 0; + for (u32 inst = 0; dart >= 0 && inst < ANE_TRACE_DAPF_INST; inst++) { + struct dapf_window s[DAPF_T8110_MAX_SLICES]; + char prop[32]; + u32 len; + + snprintf(prop, sizeof(prop), "dapf-instance-%u", inst); + if (!adt_getprop(adt, dart, prop, &len)) + continue; + int count = dapf_t8110_ranges("/arm-io/dart-ane", inst, s, ARRAY_SIZE(s)); + if (count <= 0) + panic("ANE trace: /arm-io/dart-ane %s is malformed\n", prop); + if (nslices + count > 2 * DAPF_T8110_MAX_SLICES) + panic("ANE trace: /arm-io/dart-ane has more than %d DAPF slices\n", + 2 * DAPF_T8110_MAX_SLICES); + for (int k = 0; k < count; k++) { + /* Inclusive ends; the filter compares whole words. */ + if (!s[k].start || (s[k].start & 3) || ((s[k].end + 1) & 3) || + s[k].end + 1 <= s[k].start) + panic("ANE trace: /arm-io/dart-ane %s slice %d is malformed\n", prop, k); + w[n].base = s[k].start; + w[n].size = s[k].end + 1 - s[k].start; + w[n++].what = "ane-dapf"; + } + nslices += count; + } + if (!nslices) + printf("ANE trace: /arm-io/dart-ane has no DAPF slices\n"); static bool inside[ARRAY_SIZE(w)]; int keep = 0; for (int i = 0; i < n; i++) { diff --git a/tests/python/test_sptm_ane_trace.py b/tests/python/test_sptm_ane_trace.py index f0aa6db28..ebb09e3d8 100644 --- a/tests/python/test_sptm_ane_trace.py +++ b/tests/python/test_sptm_ane_trace.py @@ -1,5 +1,5 @@ # SPDX-License-Identifier: MIT -"""The ANE trace hooks only what the ADT gives the ANE, its DART and the AIC. +"""The ANE trace hooks only what the ADT gives the ANE, its DART, its DART's filter and the AIC. ane_trace_setup() is the production body, compiled against a modeled ADT. """ @@ -72,6 +72,35 @@ def test_ane_trace_windows_from_adt(tmp_path): *s = regs[p[0]][idx][1]; return 0; } +/* Modeled dapf-instance-N of /arm-io/dart-ane: -1 absent, -2 malformed, else a slice count. */ +struct dapf_window { u64 start, end; }; +#define DAPF_T8110_MAX_SLICES 16 +static int dapf_count[8]; +static u64 dapf_slices[8][16][2]; +static int adt_path_offset(const void *t, const char *path) +{ + int p[8]; + return adt_path_offset_trace(t, path, p); +} +static const void *adt_getprop(const void *t, int node, const char *name, u32 *len) +{ + unsigned inst; + (void)t; + if (node != 1 || sscanf(name, "dapf-instance-%u", &inst) != 1 || inst >= 8 || + dapf_count[inst] == -1) + return NULL; + *len = 52; + return dapf_slices[inst]; +} +static int dapf_t8110_ranges(const char *path, u32 inst, struct dapf_window *out, int max) +{ + assert(!strcmp(path, "/arm-io/dart-ane") && inst < 8); + if (dapf_count[inst] < 0 || dapf_count[inst] > max) + return -1; + for (int i = 0; i < dapf_count[inst]; i++) + out[i] = (struct dapf_window){dapf_slices[inst][i][0], dapf_slices[inst][i][1]}; + return dapf_count[inst]; +} static void reset(void) { static const u64 ane[][2] = {{0x5400000, 0x6c000}, {0x5050000, 0x4000}, {0x4000000, 0x2000000}, @@ -88,6 +117,17 @@ def test_ane_trace_windows_from_adt(tmp_path): present[0] = present[1] = present[2] = 1; gpu_nranges = hooks = 0; sptm_virt_flags = SPTM_VIRT_ANE_TRACE; + for (int i = 0; i < 8; i++) + dapf_count[i] = -1; + memset(dapf_slices, 0, sizeof(dapf_slices)); +} +static void reset_dapf(void) +{ + /* Two words outside every reg window, one range inside ane reg[3]. */ + static const u64 s[][2] = {{0x7468000, 0x7468003}, {0x1700438, 0x170043b}, {0x6468000, 0x6468003}}; + reset(); + dapf_count[0] = 3; + memcpy(dapf_slices[0], s, sizeof(s)); } #define REFUSED(stmt) (setjmp(refused) ? true : ((stmt), false)) ''' + setup_source() + r''' @@ -101,6 +141,24 @@ def test_ane_trace_windows_from_adt(tmp_path): assert(gpu_ranges[1].base == 0x1700000 && gpu_ranges[2].base == 0x1724000); assert(gpu_ranges[3].base == 0x1000000 && !strcmp(gpu_ranges[3].what, "aic")); + /* The filter's words outside the reg windows are traced, each four bytes. */ + reset_dapf(); + assert(!REFUSED(ane_trace_setup())); + assert(gpu_nranges == 6 && hooks == 6); + assert(gpu_ranges[4].base == 0x7468000 && gpu_ranges[4].size == 4); + assert(gpu_ranges[5].base == 0x6468000 && gpu_ranges[5].size == 4); + assert(!strcmp(gpu_ranges[4].what, "ane-dapf")); + /* Found by property, whatever its instance number. */ + reset_dapf(); dapf_count[2] = dapf_count[0]; memcpy(dapf_slices[2], dapf_slices[0], sizeof(dapf_slices[0])); + dapf_count[0] = -1; + assert(!REFUSED(ane_trace_setup())); assert(gpu_nranges == 6); + /* A malformed property, or a slice that is not whole words, refuses the trace. */ + reset_dapf(); dapf_count[0] = -2; assert(REFUSED(ane_trace_setup())); assert(hooks == 0); + reset_dapf(); dapf_count[0] = 0; assert(REFUSED(ane_trace_setup())); assert(hooks == 0); + reset_dapf(); dapf_slices[0][0][0] = 0x7468001; assert(REFUSED(ane_trace_setup())); assert(hooks == 0); + reset_dapf(); dapf_slices[0][2][1] = 0x6468001; assert(REFUSED(ane_trace_setup())); assert(hooks == 0); + reset_dapf(); dapf_slices[0][0][0] = 0; dapf_slices[0][0][1] = 3; assert(REFUSED(ane_trace_setup())); assert(hooks == 0); + reset(); present[1] = 0; assert(REFUSED(ane_trace_setup())); assert(hooks == 0); reset(); nregs[2] = 0; assert(REFUSED(ane_trace_setup())); assert(hooks == 0); reset(); regs[0][3][1] = 0; assert(REFUSED(ane_trace_setup())); assert(hooks == 0); From cd7a9b13b03ada532e9ba3f2680b7b741aac11bb Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Wed, 25 Nov 2026 03:27:25 -0500 Subject: [PATCH 17/19] sptm_virt: replace 25G83 export with semantic APSTS matcher and live-ADT AMCC lock-regs Address all code review blockers on #298 after merging main: - Remove proxyclient/aura/sptm_exports/25G83.json, proxyclient/aura/sptm_export.py, tests/python/test_sptm_export.py, and AURA_SPTM_EXPORT plumbing. - Extend proxyclient/aura/sptm_patch.py with _find_apsts_polls() to match the 5-instruction AArch64 APSTS readiness-poll sequence structurally across register pairs (admitting 1 or 2 sites, failing closed on 0 or >2), covering both primary and secondary entry waits without image-specific tables. - Guard patch_sptm() in proxyclient/tools/run_guest_sptm.py when ctrr_stash_off is None. - Update amcc_lockregs_parse() in src/sptm_virt_s2.c to skip empty sibling child nodes (zero *-reg-offset properties, while still rejecting partial banks), raise AMCC_LR_MAX_APERTURES from 4 to 8, and expand amcc_lock_shadow to 640 entries for multi-aperture 4-bank geometries. - Rename the symlink drain unit test from m1n1 to aura and add unit tests for semantic APSTS matching, optional ctrr_stash_off, empty/partial AMCC lock-reg banks, and 8-aperture x 4-plane x 4-bank geometries. Signed-off-by: Satya Benson --- proxyclient/aura/sptm_export.py | 92 ------------------ proxyclient/aura/sptm_exports/25G83.json | 36 ------- proxyclient/aura/sptm_patch.py | 43 +++++++- proxyclient/tools/run_guest_sptm.py | 32 ++---- src/sptm_virt_s2.c | 14 ++- tests/python/test_run_guest_sptm.py | 26 +++++ tests/python/test_sptm_amcc_lockregs.py | 59 ++++++++++- tests/python/test_sptm_export.py | 113 ---------------------- tests/python/test_sptm_patch_synthetic.py | 33 +++++++ 9 files changed, 171 insertions(+), 277 deletions(-) delete mode 100644 proxyclient/aura/sptm_export.py delete mode 100644 proxyclient/aura/sptm_exports/25G83.json delete mode 100644 tests/python/test_sptm_export.py diff --git a/proxyclient/aura/sptm_export.py b/proxyclient/aura/sptm_export.py deleted file mode 100644 index f22979397..000000000 --- a/proxyclient/aura/sptm_export.py +++ /dev/null @@ -1,92 +0,0 @@ -# SPDX-License-Identifier: MIT -"""Clean-room SPTM patch exports, selected by the SPTM image they were reviewed against. - -Each sptm_exports/*.json names one exact SPTM image (image_sha256, entry_file_offset) and its -patch groups. An image with no export goes to the pattern patcher (sptm_patch.plan), which refuses -images it cannot fully plan; an image with an export is patched only from it, and only when the -export is complete and reviewed. No SoC, board or OS build is matched here, and no Apple image is -read on import. -""" -import hashlib -import json -import struct -from pathlib import Path - -EXPORT_DIR = Path(__file__).parent / "sptm_exports" -REQUIRED = ("image_sha256", "entry_file_offset", "groups", "reviewed") - - -def load_exports(directory=EXPORT_DIR): - exports = [] - for path in sorted(directory.glob("*.json")): - export = json.loads(path.read_text()) - missing = [k for k in REQUIRED if k not in export] - if missing: - raise ValueError(f"{path.name}: missing {', '.join(missing)}") - export["_name"] = path.stem - exports.append(export) - digests = [e["image_sha256"] for e in exports] - if len(set(digests)) != len(digests): - raise ValueError("two SPTM exports name the same image") - return exports - - -EXPORTS = load_exports() - - -def find(image, exports=None): - """The export for this exact SPTM image, or None.""" - digest = hashlib.sha256(image).hexdigest() - return next((e for e in (EXPORTS if exports is None else exports) - if e["image_sha256"] == digest), None) - - -def unresolved_groups(export): - return [name for name, rows in export["groups"].items() if rows is None] - - -def inspect(image, entry_off, export): - """Validate the export against its image and return the patches it describes.""" - name = export.get("label", export["_name"]) - if hashlib.sha256(image).hexdigest() != export["image_sha256"]: - raise ValueError(f"SPTM image identity does not match the {name} export") - expected_entry = int(export["entry_file_offset"], 0) - if entry_off != expected_entry: - raise ValueError(f"SPTM entry offset {entry_off:#x}, expected {expected_entry:#x}") - patches = [] - for site in export["groups"].get("APSTS poll") or (): - pattern = bytes.fromhex(site["pattern"]) - hits = [i for i in range(len(image) - len(pattern) + 1) - if image[i:i + len(pattern)] == pattern] - start = int(site["pattern_offset"], 0) - if hits != [start]: - raise ValueError(f"{site['purpose']}: pattern hits {hits}, expected [{start}]") - patch_off = int(site["patch_offset"], 0) - expected = int(site["expected"], 0) - if struct.unpack_from("> 5) & 0x1F) != reg_a: + continue + reg_b = w1 & 0x1F + if reg_b == 31: + continue + if (words[i + 2] == (0xB4FFFFC0 | reg_b) and + words[i + 3] == (0xD53CF080 | reg_a) and + words[i + 4] == (0xB2400000 | (reg_a << 5) | reg_a)): + hits.append(i + 2) + return hits + + def plan(image, entry_off): """The patches for one SPTM image: a dict with patches: [(what, offset from entry, mask, expected, replacement)], ctrr_stash_off: SPTM's CTRR stash offset (aura's sptm_virt_ctrr_stash_off; 0 if it has no CTXR checks), mte: (offset from entry, expected words, replacement words) or None. - Raises SptmPatchError if a site is missing or not unique.""" + Raises SptmPatchError if a site is missing or outside its expected count.""" words = _words(image) e = entry_off // 4 out = [] @@ -123,8 +156,12 @@ def plan(image, entry_off): def patch(what, i, new): out.append((what, 4 * (i - e), 0xFFFFFFFF, words[i], new)) - i = _one(words, APSTS, "APSTS poll") + 5 - patch("APSTS poll", i, NOP) + apsts = _find_apsts_polls(words) + if not 1 <= len(apsts) <= 2: + raise SptmPatchError( + f"APSTS poll: {len(apsts)} matches in this SPTM, need one or two") + for i in apsts: + patch("APSTS poll", i, NOP) stash = 0 if CTXR_MARKER in image: c = _one(words, CTRR, "CTRR check") + 6 diff --git a/proxyclient/tools/run_guest_sptm.py b/proxyclient/tools/run_guest_sptm.py index d39cf8a51..7e1b4b0d3 100755 --- a/proxyclient/tools/run_guest_sptm.py +++ b/proxyclient/tools/run_guest_sptm.py @@ -54,8 +54,6 @@ AURA_SAMPLE sample the guest's PC until each core's XNU entry (pre-XNU hangs) AURA_SAMPLE_HZ= samples per second (default 4) AURA_SAMPLE_MAX= stop printing after n samples (default 64) - AURA_SPTM_EXPORT admit an SPTM image that has a reviewed clean-room export - (aura/sptm_exports), without the bounded MMIO trace AURA_ANE_TRACE trace the ANE, its DART and the AIC (windows from the ADT) into a bounded ring, and park when it is full AURA_XNU_ENTRY patch the guest kernelcache's acct(2) so a root process reaches aura's @@ -154,7 +152,6 @@ "AURA_S2R_USB_RETAKE_MS", "AURA_TAIL_SECS", "AURA_TAIL_IDLE", - "AURA_SPTM_EXPORT", "AURA_GPU_STOP_SECS", "AURA_GPU_STOP_BOOT_SECS", "AURA_GPU_STOP_REBOOT", @@ -647,8 +644,9 @@ def patch_sptm(p, sym, entry, sp): print(f"{what}: [0x{pa:x}] 0x{before:08x} -> 0x{p.read32(pa):08x}") if sp["mte"]: rewrite_sptm_seq(p, sym, entry, sp["mte"]) - p.write32(sym["sptm_virt_ctrr_stash_off"], sp["ctrr_stash_off"]) - print(f"SPTM: CTRR stash +0x{sp['ctrr_stash_off']:x}") + if sp["ctrr_stash_off"] is not None: + p.write32(sym["sptm_virt_ctrr_stash_off"], sp["ctrr_stash_off"]) + print(f"SPTM: CTRR stash +0x{sp['ctrr_stash_off']:x}") def amcc_status(adt): @@ -910,7 +908,7 @@ def main(): if unknown: print("not run_guest_sptm.py switches, ignored:", " ".join(unknown)) - from aura import sptm_export, sptm_patch, sptm_virt_plan as plan_mod + from aura import sptm_patch, sptm_virt_plan as plan_mod from aura.proxy import AuraProxy, UartInterface from aura.proxyutils import ProxyUtils, bootstrap_port @@ -922,23 +920,6 @@ def main(): # SPTM's managed window, as aura computed it: above aura and everything iBoot left low, # below aura's carve-out. - # An SPTM image with a clean-room export is patched only from that export (selected by the - # image itself, not by SoC or OS build), and only when asked. Checked on the host's copy of - # the image, before anything is placed on the target. - export = sptm_export.find(args.sptm.read_bytes()) - if export: - print(f"SPTM export {export['_name']}: {export.get('label', '')}; host image " - f"[0x{sym['_base']:x}, 0x{sym['_end']:x})") - if not (env_on("AURA_SPTM_EXPORT") or env_on("AURA_ANE_TRACE")): - raise SystemExit("this SPTM has a clean-room export: set AURA_SPTM_EXPORT=1") - if any(env_on(k) for k in CONFIG_FLAGS if k != "AURA_ANE_TRACE"): - raise SystemExit("SPTM export: other trace/sleep modes are not qualified") - try: - sptm_export.admit(export) - except ValueError as e: - raise SystemExit(str(e)) - elif env_on("AURA_SPTM_EXPORT"): - raise SystemExit("AURA_SPTM_EXPORT: no clean-room export matches this SPTM image") scratch = u.malloc(0x40) if p.call(sym["sptm_virt_place"], scratch) != 0: raise SystemExit("sptm_virt_place failed: not an SPTM_VIRT build, no FEAT_NV2 or GXF, or " @@ -968,8 +949,7 @@ def main(): entry_off = plan_mod.macho_info(images["sptm"]).entry - plan_mod.macho_info(images["sptm"]).virtlo try: - sp = (sptm_export.patch_plan(images["sptm"], entry_off, export) if export - else sptm_patch.plan(images["sptm"], entry_off)) + sp = sptm_patch.plan(images["sptm"], entry_off) except (sptm_patch.SptmPatchError, ValueError) as e: raise SystemExit(f"this SPTM can't be patched: {e}") print(f"SPTM: {len(sp['patches'])} patch sites found" @@ -1014,7 +994,7 @@ def main(): quirk_hide = tuple(quirks["hide"]) if env_on("AURA_KEEP_WIFI"): quirk_hide = tuple(n for n in quirk_hide if n in port_nodes) - keep_ane = env_on("AURA_KEEP_ANE") or env_on("AURA_ANE_TRACE") or bool(export) + keep_ane = env_on("AURA_KEEP_ANE") or env_on("AURA_ANE_TRACE") hide = port_nodes + (() if keep_ane else STRIP_NODES) + quirk_hide if not env_on("AURA_KEEP_ERRH"): hide += (ERROR_HANDLER,) diff --git a/src/sptm_virt_s2.c b/src/sptm_virt_s2.c index 211a1783a..2b65cfdc5 100644 --- a/src/sptm_virt_s2.c +++ b/src/sptm_virt_s2.c @@ -374,7 +374,7 @@ static void sptm_virt_reset_guard_setup(void) * wrote, the hardware keeps them open. On by default; AURA_AMCC_NOLOCK=0 lets SPTM lock them. */ u32 sptm_virt_amcc_nolock = 1; -static u64 amcc_lock_shadow[64][2]; /* {pa, value} */ +static u64 amcc_lock_shadow[640][2]; /* {pa, value} */ /* * Where stock SPTM finds the AMCC protection registers: /chosen/lock-regs/amcc. Its properties @@ -387,7 +387,7 @@ static u64 amcc_lock_shadow[64][2]; /* {pa, value} */ * A missing or malformed node, or one that disagrees with the MCC driver's planes, is refused * before any page is hooked. */ -#define AMCC_LR_MAX_APERTURES 4 +#define AMCC_LR_MAX_APERTURES 8 #define AMCC_LR_MAX_BANKS 4 #define AMCC_LR_BANK_REGS 5 #define AMCC_LR_PAGE 0x4000UL @@ -476,11 +476,17 @@ static bool amcc_lockregs_parse(struct amcc_lockregs *lr) goto malformed; } - /* Every child is a bank, and every bank names all of its registers. */ + /* Every populated child is a bank naming all of its registers; empty sibling children + * (no *-reg-offset properties) are skipped, while partial banks are refused. */ bank = node; ADT_FOREACH_CHILD(adt, bank) { - if (lr->nbanks == AMCC_LR_MAX_BANKS) + u32 bank_has = 0; + for (int r = 0; r < AMCC_LR_BANK_REGS; r++) + bank_has += !!adt_getprop(adt, bank, amcc_lr_bank_props[r], NULL); + if (!bank_has) + continue; + if (bank_has != AMCC_LR_BANK_REGS || lr->nbanks == AMCC_LR_MAX_BANKS) goto malformed; for (int r = 0; r < AMCC_LR_BANK_REGS; r++) { u32 off; diff --git a/tests/python/test_run_guest_sptm.py b/tests/python/test_run_guest_sptm.py index 0ea997401..bf096de00 100644 --- a/tests/python/test_run_guest_sptm.py +++ b/tests/python/test_run_guest_sptm.py @@ -264,3 +264,29 @@ def open(self): out = capsys.readouterr().out assert "TTY> SPTM-virt[gpu]: the deadline the host asked for: rebooting via watchdog" in out assert "--- tail: device gone ---" in out + + +@pytest.mark.parametrize(("stash_off", "expect_write"), [ + (0x120, True), + (0, True), + (None, False), +]) +def test_patch_sptm_handles_optional_ctrr_stash_off(stash_off, expect_write): + runner = load_runner() + proxy = MagicMock() + proxy.read32.return_value = 0xB4FFFFC1 + sym = { + "sptm_virt_flush": 0x1000, + "sptm_virt_ctrr_stash_off": 0x2000, + } + sp = { + "patches": [("APSTS poll", 0x10, 0xFFFFFFFF, 0xB4FFFFC1, 0xD503201F)], + "mte": None, + "ctrr_stash_off": stash_off, + } + runner.patch_sptm(proxy, sym, 0x80000000, sp) + stash_writes = [c.args for c in proxy.write32.call_args_list if c.args[0] == 0x2000] + if expect_write: + assert stash_writes == [(0x2000, stash_off)] + else: + assert stash_writes == [] diff --git a/tests/python/test_sptm_amcc_lockregs.py b/tests/python/test_sptm_amcc_lockregs.py index f76eee05b..1385d603e 100644 --- a/tests/python/test_sptm_amcc_lockregs.py +++ b/tests/python/test_sptm_amcc_lockregs.py @@ -38,8 +38,8 @@ def test_no_chip_or_aperture_numbers_in_reader(): static const void *adt = (const void *)1; /* A modeled ADT: node 1 is /chosen/lock-regs/amcc, nodes 2.. its children. */ -struct prop { int node; const char *name; u32 len; unsigned char data[32]; }; -static struct prop props[64]; +struct prop { int node; const char *name; u32 len; unsigned char data[72]; }; +static struct prop props[128]; static int nprops, nchildren, have_node; static int adt_path_offset(const void *t, const char *path) { @@ -65,7 +65,7 @@ def test_no_chip_or_aperture_numbers_in_reader(): for (node = adt_first_child_offset(adt, node); _child_count--; \ node = adt_next_sibling_offset(adt, node)) -static u64 mcc_base[4], mcc_stride; +static u64 mcc_base[9], mcc_stride; static int mcc_n, mcc_planes; static int mcc_plane_info(int mcc, u64 *base, u64 *stride, int *count) { @@ -166,6 +166,59 @@ def test_lockregs_reader(tmp_path): assert(!amcc_lr_is_shadow(0x300008000ULL + 0x614)); } + /* Empty sibling children (no *-reg-offset properties) are skipped, as on + * live ADTs with unpopulated secondary CTRR banks; partial banks still fail. */ + { + geometry_a(); + nchildren = 4; /* node 2 is populated; nodes 3, 4, 5 have no bank props */ + set32(3, "lock-reg-mask", 1); /* unrelated property on an empty bank */ + assert(amcc_lockregs_parse(&lr)); + assert(lr.nbanks == 1); + /* A single bank property on node 3 makes it a partial bank -> refused. */ + set32(3, "lower-limit-reg-offset", 0x700); + assert(!amcc_lockregs_parse(&lr)); + } + + /* Multi-aperture 4-bank geometries up to 8 apertures x 4 planes x 4 banks (640 regs). */ + { + const struct { u32 naps; u32 nplanes; } cases[] = { + {2, 2}, /* 80 shadow regs */ + {4, 4}, /* 320 shadow regs */ + {8, 2}, /* 320 shadow regs */ + {8, 4}, /* 640 shadow regs (max capacity) */ + }; + for (unsigned c = 0; c < ARRAY_SIZE(cases); c++) { + u64 ap[8]; + geometry_a(); + for (u32 i = 0; i < cases[c].naps; i++) { + ap[i] = 0x200000000ULL + (u64)i * 0x4000000ULL; + mcc_base[i] = ap[i]; + } + set(1, "aperture-phys-addr", ap, cases[c].naps * sizeof(u64)); + set32(1, "aperture-count", cases[c].naps); + set32(1, "plane-count", cases[c].nplanes); + nchildren = 4; + for (int b = 0; b < 4; b++) + bank(2 + b, 0x600 + 0x40 * b); + mcc_n = (int)cases[c].naps; + mcc_planes = (int)cases[c].nplanes; + assert(amcc_lockregs_parse(&lr)); + assert(lr.napertures == cases[c].naps && lr.nplanes == cases[c].nplanes && + lr.nbanks == 4); + } + /* 9 apertures exceeds AMCC_LR_MAX_APERTURES -> refused. */ + u64 ap9[9]; + geometry_a(); + for (u32 i = 0; i < 9; i++) { + ap9[i] = 0x200000000ULL + (u64)i * 0x4000000ULL; + mcc_base[i] = ap9[i]; + } + set(1, "aperture-phys-addr", ap9, sizeof(ap9)); + set32(1, "aperture-count", 9); + mcc_n = 9; + assert(!amcc_lockregs_parse(&lr)); + } + /* Refusals. Each starts from the admitted geometry A. */ geometry_a(); have_node = 0; assert(!amcc_lockregs_parse(&lr)); geometry_a(); set32(1, "aperture-count", 3); assert(!amcc_lockregs_parse(&lr)); diff --git a/tests/python/test_sptm_export.py b/tests/python/test_sptm_export.py deleted file mode 100644 index ec60a9d21..000000000 --- a/tests/python/test_sptm_export.py +++ /dev/null @@ -1,113 +0,0 @@ -# SPDX-License-Identifier: MIT -"""Clean-room SPTM exports are chosen by image identity, not by SoC, board or OS build. -No Apple image fixtures or target connection are used. -""" -import copy -import hashlib -import json -import os -import struct -import sys -from pathlib import Path - -import pytest - -REPO = Path(__file__).resolve().parents[2] -sys.path.insert(0, str(REPO / "proxyclient")) - -from aura import sptm_export # noqa: E402 -REAL_IMAGE = os.environ.get("SPTM_EXPORT_IMAGE") - - -def synthetic(entry_off=0x100): - """A made-up image and export with one APSTS site: no Apple bytes.""" - image = bytearray(0x400) - pattern = bytes(range(0x20, 0x40)) - image[0x200:0x220] = pattern - struct.pack_into(" Date: Wed, 25 Nov 2026 04:08:42 -0500 Subject: [PATCH 18/19] smp: publish RVBAR for powered-off locked A7-M3 secondaries in guest reset On T8122 (J613) iBoot leaves RVBAR_LOCK set on every core when booting Stage 1, including the powered-off secondary cores (core state 0). Just as smp_start_cpu() writes _vectors_start to clear RVBAR_LOCK on A7-M3 before releasing a secondary, smp_prepare_guest_rvbar() must publish this image's vector to powered-off secondaries even when RVBAR_LOCK is set. Previously, smp_prepare_guest_rvbar() bailed out on any RVBAR_LOCK and delegated to smp_prepare_rvbar(), which returned 0 immediately when apple_sysregs_unlocked is true without updating RVBAR or installing a relay. On chainloaded J613 stock-SPTM runs, secondary cores still reset into Stage 1's vectors and XNU panicked waiting for cpu0 to boot. Only skip writing when a locked core is actually running (core state nonzero, where a store to a locked RVBAR takes an SError on T8122), and fail closed in that case if its RVBAR does not already target this image. Verify on read-back that RVBAR_LOCK cleared and the address matches _vectors_start, and refresh the logged RVBAR in smp_prepare_guest_resets(). Signed-off-by: Satya Benson --- src/smp.c | 21 ++++++++++------ tests/python/test_smp_guest_rvbar.py | 36 +++++++++++++++++++++------- 2 files changed, 41 insertions(+), 16 deletions(-) diff --git a/src/smp.c b/src/smp.c index b16ffd90e..9d74c136e 100644 --- a/src/smp.c +++ b/src/smp.c @@ -1471,24 +1471,30 @@ static u64 smp_guest_mpidr(int i) } /* - * The stock-SPTM guest's reset contract. A7 to M3 leave RVBAR writable, and the ordinary SMP path - * writes it only in smp_start_cpu(), just before releasing a core. Here the guest performs CPUSTART - * itself, so publish this image's vector into an unlocked RVBAR now and read it back. A locked - * RVBAR (M4 on, or a core's own lock bit) is never written; smp_prepare_rvbar() checks it. + * The stock-SPTM guest's reset contract. A7 to M3 leave RVBAR writable on a powered-off secondary + * core (and writing it clears RVBAR_LOCK, as smp_start_cpu() does); the ordinary SMP path writes + * it only in smp_start_cpu() just before releasing a core, whereas here the guest performs + * CPUSTART itself. Publish this image's vector now and read it back. A running core's locked RVBAR + * is never written (a store to a running locked core takes an SError on T8122); on M4+, + * smp_prepare_rvbar() checks or installs the locked-RVBAR relay. */ static int smp_prepare_guest_rvbar(const struct cpu_info *cpu) { u64 target = (u64)_vectors_start; u64 rvbar = read64(cpu->impl_reg); - if (!cpu_features->apple_sysregs_unlocked || (rvbar & RVBAR_LOCK) || - (rvbar & RVBAR_ADDR_UNLOCKED) == target) + if (!cpu_features->apple_sysregs_unlocked) return smp_prepare_rvbar(cpu); + if ((rvbar & RVBAR_ADDR_UNLOCKED) == target && !(rvbar & RVBAR_LOCK)) + return 0; + if ((rvbar & RVBAR_LOCK) && (read64(cpu->impl_reg + 0x100) & 0xff)) + return (rvbar & RVBAR_ADDR_UNLOCKED) == target ? 0 : -1; if (target & ~RVBAR_ADDR_UNLOCKED) return -1; write64(cpu->impl_reg, target); sysop("dsb sy"); - return (read64(cpu->impl_reg) & RVBAR_ADDR_UNLOCKED) == target ? 0 : -1; + rvbar = read64(cpu->impl_reg); + return !(rvbar & RVBAR_LOCK) && (rvbar & RVBAR_ADDR_UNLOCKED) == target ? 0 : -1; } /* @@ -1525,6 +1531,7 @@ int smp_prepare_guest_resets(void) smp_reset_stacks[i].mpidr = mpidr; smp_reset_stacks[i].stack = (u64)cpu_stack(i) + SECONDARY_STACK_SIZE; rc = smp_prepare_guest_rvbar(cpu); + rvbar = read64(cpu->impl_reg); } /* A secondary must be powered off here: XNU's CPUSTART only resets a core that is * off, and one left running (an earlier stage's park loop) never reaches SPTM. */ diff --git a/tests/python/test_smp_guest_rvbar.py b/tests/python/test_smp_guest_rvbar.py index 739791cc7..52e8f16f9 100644 --- a/tests/python/test_smp_guest_rvbar.py +++ b/tests/python/test_smp_guest_rvbar.py @@ -36,9 +36,15 @@ def test_guest_rvbar_publish(tmp_path): struct cpu_features { bool apple_sysregs_unlocked; }; static struct cpu_features features, *cpu_features = &features; static unsigned char _vectors_start[4096] __attribute__((aligned(4096))); -static u64 rvbar, sticky; +static u64 rvbar, core_state, sticky; static int writes, prepares; -static u64 read64(u64 a) { assert(a == 8); return rvbar; } +static u64 read64(u64 a) +{ + if (a == 8) + return rvbar; + assert(a == 8 + 0x100); + return core_state; +} static void write64(u64 a, u64 v) { assert(a == 8); writes++; rvbar = sticky ? sticky : v; } static int smp_prepare_rvbar(const struct cpu_info *cpu) { (void)cpu; prepares++; return 0; } ''' + body + r''' @@ -47,24 +53,36 @@ def test_guest_rvbar_publish(tmp_path): const struct cpu_info cpu = {.impl_reg = 8}; u64 target = (u64)_vectors_start; - /* A7 to M3, unlocked: publish and verify. */ + /* A7 to M3, unlocked secondary: publish and verify. */ features.apple_sysregs_unlocked = true; + core_state = 0; rvbar = 0x800000000UL; assert(smp_prepare_guest_rvbar(&cpu) == 0 && writes == 1 && prepares == 0); assert(rvbar == target); - /* Already published: no second write. */ - assert(smp_prepare_guest_rvbar(&cpu) == 0 && writes == 1 && prepares == 1); - /* A lock bit is never written through. */ + /* Already published and unlocked: no second write. */ + assert(smp_prepare_guest_rvbar(&cpu) == 0 && writes == 1 && prepares == 0); + /* Powered-off secondary with RVBAR_LOCK from iBoot (e.g. T8122): publish clears lock. */ + rvbar = 0x800000000UL | RVBAR_LOCK; + assert(smp_prepare_guest_rvbar(&cpu) == 0 && writes == 2 && prepares == 0); + assert(rvbar == target); + /* Running core with RVBAR_LOCK is never written through; fails closed if target differs. */ + core_state = 2; rvbar = 0x800000000UL | RVBAR_LOCK; - assert(smp_prepare_guest_rvbar(&cpu) == 0 && writes == 1 && prepares == 2); + assert(smp_prepare_guest_rvbar(&cpu) == -1 && writes == 2 && prepares == 0); + rvbar = target | RVBAR_LOCK; + assert(smp_prepare_guest_rvbar(&cpu) == 0 && writes == 2 && prepares == 0); /* M4 on: the normal check/relay. */ features.apple_sysregs_unlocked = false; + core_state = 0; rvbar = 0x800000000UL; - assert(smp_prepare_guest_rvbar(&cpu) == 0 && writes == 1 && prepares == 3); + assert(smp_prepare_guest_rvbar(&cpu) == 0 && writes == 2 && prepares == 1); /* A write that does not stick is refused. */ features.apple_sysregs_unlocked = true; sticky = 0x900000000UL; - assert(smp_prepare_guest_rvbar(&cpu) == -1 && writes == 2); + assert(smp_prepare_guest_rvbar(&cpu) == -1 && writes == 3); + /* A lock bit that refuses to clear is refused. */ + sticky = target | RVBAR_LOCK; + assert(smp_prepare_guest_rvbar(&cpu) == -1 && writes == 4); return 0; } ''' From 00d7e7f00b47417d246efb6b535adf4ca152a398 Mon Sep 17 00:00:00 2001 From: Ryan Murray <81541646+RyanTheTide@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:10:19 +1100 Subject: [PATCH 19/19] sptm_virt: keep T6050 booting and refuse wide AMCC shadow accesses Two fixes from the #298 closeout review. A chip with no MCC driver (T6050) has no planes to check /chosen/lock-regs/amcc against, so the lock-regs path refused every guest load and panicked in setup. Such a chip is admitted again and its AMCC left unhooked, as before the lock-regs shadow. The shadow and the cache-status fake only model 32-bit accesses. A byte, halfword, 64-bit or pair access that overlaps a shadowed register went to the real AMCC lock, limit, enable or write-disable registers. Such an access is now refused, so the guest takes the fault. --- src/sptm_virt_s2.c | 56 ++++++++++++++++++- tests/python/test_sptm_amcc_lockregs.py | 72 ++++++++++++++++++++++++- 2 files changed, 126 insertions(+), 2 deletions(-) diff --git a/src/sptm_virt_s2.c b/src/sptm_virt_s2.c index cd203b2d1..7febfccc8 100644 --- a/src/sptm_virt_s2.c +++ b/src/sptm_virt_s2.c @@ -576,6 +576,39 @@ static bool amcc_is_lock(u64 addr) return bit >= 0 && (sptm_virt_amcc_nolock & BIT(bit)); } +/* Does [addr, addr + size) overlap the 32-bit register at page offset reg? */ +static bool amcc_overlaps(u64 addr, u64 size, u32 reg) +{ + u64 off = addr & (AMCC_LR_PAGE - 1); + return off < (u64)reg + 4 && (u64)reg < off + size; +} + +/* + * The shadow and the cache-status fake only model 32-bit accesses. Any other width (byte, + * halfword, 64-bit, pair) that touches one of those registers would reach the real AMCC lock, + * limit, enable or write-disable registers, so it is refused and the guest takes the fault. + */ +static bool amcc_wide_touches_shadow(u64 addr, int width) +{ + u64 size = 1ULL << width; + if (amcc_lr_ready) { + for (u32 b = 0; b < amcc_lr.nbanks; b++) + for (int r = 0; r < AMCC_LR_BANK_REGS; r++) + if (amcc_overlaps(addr, size, amcc_lr.bank_reg[b][r])) + return true; + return amcc_lr.has_cache_status && amcc_overlaps(addr, size, amcc_lr.cache_status); + } + if (!sptm_virt_amcc_nolock) + return false; + static const u32 lock_off[] = {0xacc, 0xadc, 0xaec}; + u64 off = addr & 0x3ffff; + for (int bit = 0; bit < 3; bit++) + if ((sptm_virt_amcc_nolock & BIT(bit)) && off < (u64)lock_off[bit] + 4 && + (u64)lock_off[bit] < off + size) + return true; + return false; +} + static bool amcc_hook(struct exc_info *ctx, u64 addr, u64 *val, bool write, int width) { static u32 logs; @@ -584,6 +617,12 @@ static bool amcc_hook(struct exc_info *ctx, u64 addr, u64 *val, bool write, int if (write && logs++ < 256) printf("SPTM-virt[amcc]: guest wrote 0x%lx -> 0x%lx (w%d) at pc 0x%lx%s\n", *val, addr, width, ctx->elr, shadowed ? " -- range lock shadowed" : ""); + if (width != 2 && amcc_wide_touches_shadow(addr, width)) { + printf("SPTM-virt[amcc]: refused a %s of width %d at 0x%lx over a shadowed register " + "(pc 0x%lx)\n", + write ? "write" : "read", width, addr, ctx->elr); + return false; + } if (width == 2 && amcc_lr_ready) { if (amcc_lr_is_shadow(addr)) return amcc_shadow_rw(addr, val, write); @@ -611,10 +650,21 @@ static bool amcc_uses_plane_offsets(void) return chip_id == T8142; } +/* + * aura has no MCC driver for some chips (T6050). Their AMCC stays unhooked, as before the + * lock-regs shadow: there are no planes to check the node against, and nothing to hook. + */ +static bool amcc_undriven(void) +{ + u64 base, stride; + int count; + return mcc_plane_info(0, &base, &stride, &count) < 0; +} + bool sptm_virt_s2_admit(void) { struct amcc_lockregs lr; - return amcc_uses_plane_offsets() || amcc_lockregs_parse(&lr); + return amcc_uses_plane_offsets() || amcc_undriven() || amcc_lockregs_parse(&lr); } static bool sptm_virt_amcc_watch_lockregs(void) @@ -645,6 +695,10 @@ static void sptm_virt_amcc_watch(void) u64 base, stride; int count; if (!amcc_uses_plane_offsets()) { + if (amcc_undriven()) { + printf("SPTM-virt[amcc]: no MCC driver for this chip; AMCC left unhooked\n"); + return; + } if (!sptm_virt_amcc_watch_lockregs()) panic("SPTM-virt[amcc]: lock-regs shadow setup failed before guest entry\n"); return; diff --git a/tests/python/test_sptm_amcc_lockregs.py b/tests/python/test_sptm_amcc_lockregs.py index 1385d603e..469b136e0 100644 --- a/tests/python/test_sptm_amcc_lockregs.py +++ b/tests/python/test_sptm_amcc_lockregs.py @@ -20,7 +20,7 @@ def test_no_chip_or_aperture_numbers_in_reader(): for token in ("T8122", "0x220000000", "0x222000000", "0x690", "0x1c00", "25G83", "J613"): assert token not in source full = (REPO / "src/sptm_virt_s2.c").read_text() - assert "return amcc_uses_plane_offsets() || amcc_lockregs_parse(&lr);" in full + assert "return amcc_uses_plane_offsets() || amcc_undriven() || amcc_lockregs_parse(&lr);" in full assert 'panic("SPTM-virt[amcc]: lock-regs shadow setup failed' in full @@ -278,3 +278,73 @@ def test_lockregs_shadow(tmp_path): } ''' compile_and_run(tmp_path, "amcc-lockregs-shadow", harness) + + +def wide_source(): + source = (REPO / "src/sptm_virt_s2.c").read_text() + start = source.index("/* Does [addr, addr + size)") + end = source.index("static bool amcc_hook(") + return source[start:end] + + +def undriven_source(): + source = (REPO / "src/sptm_virt_s2.c").read_text() + start = source.index("static bool amcc_undriven(void)") + end = source.index("bool sptm_virt_s2_admit(void)") + return source[start:end] + + +def test_chip_without_mcc_driver_stays_unhooked(): + """T6050 has no MCC driver: it is admitted and its AMCC left unhooked, as on main.""" + full = (REPO / "src/sptm_virt_s2.c").read_text() + watch = full[full.index("static void sptm_virt_amcc_watch(void)"):] + assert watch.index("if (amcc_undriven())") < watch.index("sptm_virt_amcc_watch_lockregs()") + + +WIDE_MAIN = r""" +int main(void) +{ + geometry_a(); + assert(amcc_lockregs_parse(&amcc_lr)); + amcc_lr_ready = true; + const u64 page = 0x200040000ULL; + /* 64-bit at the lock register and at offset - 4, a pair, a byte, a halfword: refused. */ + assert(amcc_wide_touches_shadow(page + 0x60c, 3)); + assert(amcc_wide_touches_shadow(page + 0x608, 3)); + assert(amcc_wide_touches_shadow(page + 0x5fc, 3)); + assert(amcc_wide_touches_shadow(page + 0x600, 4)); + assert(amcc_wide_touches_shadow(page + 0x5f0, 5)); + assert(amcc_wide_touches_shadow(page + 0x60f, 0)); + assert(amcc_wide_touches_shadow(page + 0x612, 1)); + /* The faked cache-status register too. */ + assert(amcc_wide_touches_shadow(page + 0x1800, 3)); + assert(amcc_wide_touches_shadow(page + 0x17fc, 3)); + /* Wide accesses elsewhere in the page pass through. */ + assert(!amcc_wide_touches_shadow(page + 0x5f8, 3)); + assert(!amcc_wide_touches_shadow(page + 0x614, 3)); + assert(!amcc_wide_touches_shadow(page + 0x5e0, 4)); + assert(!amcc_wide_touches_shadow(page + 0x1808, 3)); + + /* T8142 plane-offset locks (no lock-regs node): the masked locks only. */ + amcc_lr_ready = false; + sptm_virt_amcc_nolock = 1; + assert(amcc_wide_touches_shadow(0x200000ac8ULL, 3)); + assert(amcc_wide_touches_shadow(0x200000accULL, 0)); + assert(!amcc_wide_touches_shadow(0x200000ad8ULL, 3)); /* +0xadc not in the mask */ + sptm_virt_amcc_nolock = 0; + assert(!amcc_wide_touches_shadow(0x200000ac8ULL, 3)); + + /* No MCC driver -> undriven; with one, the node must still match. */ + mcc_n = 0; + assert(amcc_undriven()); + geometry_a(); + assert(!amcc_undriven()); + return 0; +} +""" + + +def test_wide_access_over_shadow_refused(tmp_path): + harness = (HARNESS + "static u32 sptm_virt_amcc_nolock;\n#define BIT(n) (1UL << (n))\n" + + reader_source() + wide_source() + undriven_source() + WIDE_MAIN) + compile_and_run(tmp_path, "amcc-wide-access", harness)