From 11ad2e4d9f22cb6eb0cbfde18bbed461768a62b2 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 15:56:00 +0000 Subject: [PATCH] Test the CCPLEX model and the hwtest sweep in CI, and document both - tests/ccplex: a self-contained BPMP payload (ARM, arm-none-eabi-gcc; the AArch64 side is pre-assembled words) that drives CPU0 through bdk's ccplex_boot_cpu0() register sequence. It checks that an unpowered release is refused with its reason, that a powered one runs at EL3 from the SB vector and writes the mailbox, that CPU0 sees TIMERUS move, that WFE parks the core, and that RST_CPUG_CMPLX_SET stops it. `make test`. - tests/hwtest: build hwtest-rcm from a pinned commit with distro toolchains (an empty base_rules stands in for devkitARM, the CPU0 stub builds with gcc-aarch64-linux-gnu) and run its whole sweep headless, checking the CPU0-driven Wi-Fi probe enumerates the CYW4356. - CI runs both in the Linux job and keeps their logs on failure. - Makefile: `test` target; the clean rule's line continuation was a literal "\n" that only worked by accident. - README/DESIGN: CCPLEX CPU0, the uc_mmio_map bus, the block-level clock and TIMERUS poll pacing, the new bug-history entries. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb --- .github/workflows/build.yml | 28 +++++- .gitignore | 2 + DESIGN.md | 166 +++++++++++++++++++++++++++++++++--- Makefile | 23 ++++- README.md | 68 ++++++++++++--- tests/ccplex/link.ld | 10 +++ tests/ccplex/payload.c | 165 +++++++++++++++++++++++++++++++++++ tests/ccplex/run.sh | 50 +++++++++++ tests/hwtest/build.sh | 31 +++++++ tests/hwtest/run.sh | 49 +++++++++++ 10 files changed, 566 insertions(+), 26 deletions(-) create mode 100644 tests/ccplex/link.ld create mode 100644 tests/ccplex/payload.c create mode 100755 tests/ccplex/run.sh create mode 100755 tests/hwtest/build.sh create mode 100755 tests/hwtest/run.sh diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 044bc74..09fcb32 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -27,7 +27,8 @@ jobs: run: | sudo apt-get update -qq sudo apt-get install -y --no-install-recommends \ - build-essential pkg-config libunicorn-dev libsdl2-dev + build-essential pkg-config libunicorn-dev libsdl2-dev \ + gcc-arm-none-eabi libnewlib-arm-none-eabi gcc-aarch64-linux-gnu - name: Build run: make -j"$(nproc)" @@ -44,6 +45,31 @@ jobs: grep -q "RCM Payload Emulator" out.txt \ || { echo "banner missing - binary did not start"; exit 1; } + - name: CCPLEX regression test + # A small self-contained payload boots CPU0 through bdk's + # ccplex_boot_cpu0() register sequence: an unpowered release must be + # refused, a powered one must run an AArch64 blob at EL3, and WFE must + # park the core. + run: make test + + - name: hwtest end to end + # hwtest-rcm's whole hardware sweep, including the Wi-Fi probe that + # hands PCIe to an AArch64 stub on CPU0. Built from a pinned commit + # with distro toolchains; the run must enumerate the CYW4356. + run: | + tests/hwtest/build.sh build-hwtest + tests/hwtest/run.sh ./rcm_emu build-hwtest/hwtest-rcm/build/hwtest.bin + + - name: Keep test logs + if: failure() + uses: actions/upload-artifact@v4 + with: + name: test-logs + path: | + tests/ccplex/out.log + tests/hwtest/out.log + if-no-files-found: ignore + - name: Upload artifact uses: actions/upload-artifact@v4 with: diff --git a/.gitignore b/.gitignore index 3d8cec6..0c77899 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ rcm_emu rcm_emu.exe *.o *.d +*.elf # Runtime captures last_fb.rgba @@ -26,5 +27,6 @@ last_audio*.wav __pycache__/ *.pyc backup/ +build-hwtest/ imgui.ini rcm_emu.ini diff --git a/DESIGN.md b/DESIGN.md index e2232f7..e194859 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -10,12 +10,15 @@ them. Read [README.md](README.md) first for usage. flowchart TB main["main.cpp
arg parsing, payload load, CLI
emulation loop, auto-script state"] - main -->|uc_emu_start| uc["Unicorn Engine
ARM32, T210
IRAM / DRAM / MMIO"] + main -->|bpmp_run| uc["Unicorn Engine
ARM32 BPMP
IRAM / DRAM / MMIO"] + main -->|ccplex_run| a57["t210/ccplex
2nd Unicorn engine, AArch64
CCPLEX CPU0 (Cortex-A57)"] + a57 -->|MMIO callbacks| mmio + a57 -.->|shares| uc main -->|sdl_display_*| sdl["display/sdl_display
block-linear de-swizzle
rotate, blit"] main -->|config_window_*| cfg["display/config_window
2nd SDL window + ImGui
live hardware tweaks"] main -->|console_window_*| con["display/console_window
3rd SDL window + ImGui
per-port UART TX log + RX inject"] - uc -->|MMIO trap| mmio["t210/mmio.cpp
central read/write dispatch
by address range"] + uc -->|MMIO callbacks| mmio["t210/mmio.cpp
mmio_bus_read / mmio_bus_write
shared by both masters"] mmio --> sdmmc["sdmmc
SDMMC1 / SDMMC4
CMD0..18, EXT_CSD, ADMA2"] mmio --> se["se_engine
AES-128, SHA-256
BIS keyslot override"] @@ -23,6 +26,7 @@ flowchart TB mmio --> i2c1["I2C_1 slaves (inline)
MAX17050, TMP451,
BQ24193, BM92T36"] mmio --> i2c5["I2C_5 slaves (inline)
MAX77620, MAX77621"] mmio --> stubs["inline stubs
GPIO, PMC, TSEC, KFUSE,
PWM, DC, CLK, TMR, FUSE, UART"] + mmio --> pcie["pcie
AFI, root ports, CYW4356
(CPU-complex master only)"] cfg -.->|writes atomics| state["EmuState
(emu_state.h)"] con -.->|RX inject / TX log| state @@ -35,6 +39,11 @@ touchscreen atomics, framebuffer parameters from the display controller, file descriptors for SD and eMMC images, and a deterministic `emu_usec` counter used for auto-script timing. +Two processors can execute: the BPMP, which every RCM payload runs on, and - +once a payload boots it - CPU0 of the CCPLEX. Each is its own Unicorn engine; +both map the same host memory for IRAM, DRAM and TZRAM, and both reach the +same peripheral models through one dispatch (see [CCPLEX CPU0](#ccplex-cpu0)). + ## Boot flow (Hekate as the example) 1. The payload is loaded into IRAM (Internal RAM) at `0x40010000` via @@ -65,10 +74,27 @@ Mapped explicitly in `setup_emulation()`: | `0x80000000 – 0x90000000` | 256 MB | DRAM low | | `0xC0000000 – 0xFFFFFFFF` | 1 GB | DRAM high (covers FB at 0xF5A00000) | | `0x00000000 – 0x01000000` | 16 MB | low scratch (some null derefs) | -| Various MMIO pages | 4 KB ea | trapped via UC hooks | +| `0x7C010000 – 0x7C020000` | 64 KB | TZRAM (shared with CPU0) | +| Peripheral windows | 4 KB ea | `uc_mmio_map` callbacks | -MMIO (Memory-Mapped I/O) ranges are added as plain mapped pages with read and -write hooks. The actual register modelling lives in `t210/mmio.cpp`. +MMIO (Memory-Mapped I/O) windows are `uc_mmio_map()` regions: Unicorn calls +`mmio_cb_read` / `mmio_cb_write`, which forward to `mmio_bus_read` / +`mmio_bus_write` in `t210/mmio.cpp`, where the register models live. The list +of windows is `kRegions` in the same file; it is flattened to 4 KiB pages and +mapped as contiguous runs, once per engine. + +They used to be plain RAM pages with `UC_HOOK_MEM_READ` / `UC_HOOK_MEM_WRITE` +hooks, a read's result written into the page with `uc_mem_write` before the +load completed. Unicorn sends every guest load and store through its slow path +while any memory hook exists, so ordinary IRAM/DRAM traffic paid for MMIO's +hooks, and each MMIO read cost a walk of Unicorn's region list on top. An +unmapped access in the peripheral band now gets an MMIO page of its own on the +fly (`hook_unmapped`), so the generic register cache still sees it. + +The "read back what was written" behaviour of simple registers (PINMUX, PWM, +UART LCR, CLK_SOURCE_* ...) comes from `mmio_regs`, a `RegCache` +(`t210/regcache.h`): flat 4 KiB pages with a presence bitmap and a last-page +cache, replacing a `std::map` that was a measurable share of all MMIO time. ## Subsystems @@ -252,8 +278,12 @@ Hekate and Nyx draw into a block-linear surface. One block-height row covers 5. Blits to an SDL_Texture at the host window current size. The de-swizzle is the hottest path. It is inlined and operates on `u32` -units. A blit cache keys on `(addr, w, h, stride, sw, rot, bh)` so identical -frames don't re-touch the surface. +units. The surface is read straight from the host memory behind emulated DRAM, +and a frame whose bytes and layout `(addr, w, h, stride, sw, bh, rot)` match +the previous one skips the de-swizzle and the texture upload entirely. No +renderer uses `PRESENTVSYNC`: the CPU runs on the same thread, the loop +already paces redraws to ~60 Hz, and a vsync'd present could stall the +emulated CPU for a whole frame. ### UART @@ -326,9 +356,9 @@ needed. The 64 KB TX log trim happens in-place during the write hook. - **TSEC.** `DMATRFCMD_IDLE` is reported set, and the keygen status word is hardcoded to `0xB0B0B0B0` (the success magic from AMS, the Atmosphère keygen). No firmware is actually executed. -- **Timer and RTC.** Backed by `EmuState::emu_usec`, incremented per CPU - batch by a fixed amount so timing is deterministic across runs. The - auto-script feature relies on this. +- **Timer and RTC.** Backed by `EmuState::emu_usec`, derived from retired + instructions (see [Determinism](#determinism-and-the-auto-script-flag)), so + timing is identical across runs. The auto-script feature relies on this. - **Probe-magic constants.** Several reads return fixed values, not because they are tweakable but because the chip-detection code expects exact cookies: `MAX17050.DevName=0x00AC`, `BQ24193.VendorPart=0x2F`, the BM92T36 @@ -338,10 +368,34 @@ needed. The 64 KB TX log trim happens in-place during the write hook. ## Determinism and the auto-script flag -`emu_usec` advances by a constant per Unicorn batch, never by host wall-clock. +`emu_usec` is derived from retired BPMP instructions, never from host +wall-clock: `emu_usec = skipped_us + insn_count / 10`, where `skipped_us` is +whatever a FLOW_CTLR timed halt (`bpmp_usleep` / `bpmp_msleep`) jumped over. That makes the entire run reproducible: a payload at PC X always sees timer value Y, regardless of how busy the host machine is. +The count comes from a `UC_HOOK_BLOCK` callback in `t210/bpmp.cpp`, not from +a callback on every instruction (which kept Unicorn off its fast path for all +code). Each translated block's instructions are counted once from its bytes +(Thumb: a halfword with top bits `0b11101`/`0b11110`/`0b11111` opens a 32-bit +instruction, which includes the Thumb-1 BL pair), cached per block, and +credited when the block has run. Totals match per-instruction counting +exactly; inside a block an MMIO read sees the time at the block's start. A +batch ends by stopping the engine from the block hook, which Unicorn honours +*before* running that block, so no instruction is ever counted twice or lost. + +**TIMERUS poll pacing.** Ten instructions per microsecond is a deliberate +dilation - real silicon retires a few hundred - and it is what makes busy-waits +cheap. It is harmless for `while (now - start < us)`, but not for a wait that +must *see* a value. bdk's `fan_get_speed()` is one: `int timer = get_tmr_us() + +2000000; while ((timer - get_tmr_us()) > 0)` is unsigned arithmetic, i.e. +`!= 0`, and compiles to `cmp; bne`. Its ~30-instruction body is 0.1 us on +hardware and 3 us here, so the counter stepped past the deadline and the loop +spun until TIMERUS wrapped. So while TIMERUS reads come at most 200 +instructions apart (under a microsecond at real speed), the clock advances at +most 1 us between them. Only increments are capped, so time stays monotonic for +every observer and a wait still ends at the emulated time it asked for. + The `--auto-pin-recovery` and `--auto-te-script` flags exploit this. A real interactive run was captured by logging every keyboard up and down event with the matching `emu_usec`, then the same schedule was re-applied verbatim in @@ -363,6 +417,67 @@ Because `emu_usec` is deterministic, the same timestamps land at the same UI states across runs. Adding a new automated flow is "press the buttons once with `[input]` logging on, copy the timestamps". +## CCPLEX CPU0 + +`t210/ccplex.cpp` models CPU0 of the main CPU cluster, enough for a payload to +hand work to it the way bdk's `ccplex_boot_cpu0()` does. hwtest-rcm's Wi-Fi +probe is the driving case: PCIe answers a CPU-complex master only (TRM ch.16 / +ch.19: MSELECT is CCPLEX hardware, the BPMP-Lite is an AHB master), so it +copies an AArch64 stub to DRAM, boots CPU0 at it, and supervises through a +mailbox while the stub trains the link and enumerates the CYW4356. + +**Release.** The model shadows the registers the boot sequence writes and +starts the core when `RST_CPUG_CMPLX_CLR` clears the last of CPU0's reset bits +(CPURESET0, DBGRESET0, CORERESET0, bit 30, NONCPURESET) - but only if the core +could actually run: + +| Precondition | Where it comes from | +| --- | --- | +| CPU rail up | Erista: MAX77621 @ I2C5 0x1B VOUT_EN and its EN pin, MAX77620 GPIO5 driven high. Mariko: MAX77812 EN_CTRL.EN_M4 | +| CRAIL, C0NC, CE0 ungated | PMC PWRGATE_STATUS bits 0, 15, 14 | +| CPUG clock on, PLLX up if CCLK uses it | CLK_ENB_V bit 0, CCLK_BURST_POLICY, PLLX_BASE | +| MSELECT clocked and out of reset | CLK_ENB_V bit 3, RST_DEV_V bit 3 | +| RAM repair requested | FLOW_CTLR_RAM_REPAIR | +| An AArch64 vector in IRAM/DRAM | SB_AA64_RESET_LOW bit 0 + address, SB_AA64_RESET_HIGH | + +A release that misses one prints `[ccplex] CPU0 released from reset but +cannot run: ` and the core stays dark, which is what silicon does, +minus the explanation. Asserting a reset bit, gating a partition or dropping +the rail stops a running core. + +**Entry at EL3.** A real A57 leaves reset at EL3, AArch64, MMU off. Unicorn +builds its ARM64 core at EL1 and cannot be moved: a PSTATE write does not +rebuild the translator's cached `hflags`, and Unicorn never delivers guest +exceptions, so no SMC can carry it up either. ERET can: its helper takes the +current EL from PSTATE and rebuilds `hflags` for the target. So each boot +creates a fresh engine (no stale translations of a rewritten stub), writes +PSTATE = SPSR_EL3 = EL3h with DAIF masked and ELR_EL3 = ELR_EL1 = the vector, +and starts it on a one-instruction `eret` trampoline in a page at 1 TiB that +only CPU0 maps. + +**Bus.** CPU0's engine maps IRAM, DRAM and TZRAM from the same host memory +as the BPMP's and the same MMIO windows. `g_bus_master` says who is issuing an +access; the PCIe model refuses the BPMP (`0xFFFFFFFF`, and one warning +explaining why) and serves CPU0. MSELECT reads its TRM reset value +`0x07FF4020`, AFI_PCIE_CONFIG `0x00103025`, and LNKSTA `0x3011` once the link +is up - the values hwtest's healthy-console capture shows. An access CPU0 +makes to an address nothing decodes wedges it, as on silicon; the BPMP's +watchdog on the mailbox heartbeat is what reports it. + +**Time.** CPU0 keeps its own clock: 1 ns per retired instruction (PLLX runs +the A57 at ~1 GHz) plus 250 ns per bus access (MSELECT, the APC bridge, APB). +While it runs, the main loop cuts the BPMP's batch into 250 us slices and runs +CPU0 up to the BPMP's time after each - lockstep at a finer grain than the +500 us the BPMP polls the mailbox at. During a CPU0 slice `emu_usec` is CPU0's +clock, so every register model timestamps with the right core's time. WFE / +WFI park the core to the end of the slice: the stub's final `for(;;) wfe;` +would otherwise spin through a billion instructions per emulated second. + +`make test` runs `tests/ccplex/`, a self-contained payload that checks the +refusal, the EL3 entry, the mailbox, WFE parking and the reset. +`tests/hwtest/` builds hwtest-rcm with distro toolchains and runs its whole +sweep; CI runs both. + ## Bug history These are baked into the current source. Listed here so future maintainers @@ -398,13 +513,38 @@ don't repeat the diagnosis: `APBDEV_PMC_CNTRL.MAIN_RST`, then exit or flip `state->reboot_requested`. +- **A hwtest sweep never finished.** It stalled in the fan spin-up test: + bdk's `fan_get_speed()` waits for TIMERUS to *equal* a deadline, and the + dilated clock stepped past it. Fix: TIMERUS poll pacing (see + [Determinism](#determinism-and-the-auto-script-flag)). +- **Per-instruction hooks.** Three `UC_HOOK_CODE` callbacks (one registered + twice), one doing a `uc_mem_read` per instruction for a NOP-slide check + whose counter never reset, plus memory hooks forcing every load and store + onto Unicorn's slow path, and a display path that re-converted and + re-allocated every frame. Reaching hwtest's fan test took 2.7 s; it takes + 0.8 s now, and the whole sweep about 3 s. Fix: block-level clock, + `uc_mmio_map` windows, a change-detecting display path. +- **MAX77621 writes were dropped**, so after bdk's `hw_init()` disabled the + Erista CPU/GPU bucks a payload still read them as on. Fix: register files + for MAX77621 and MAX77812. +- **Mariko's MAX77812 was unreachable through bdk.** bdk picks its address + from `FUSE_RESERVED_ODM28_B01` bit 0; left clear it talked to the NAK'd + PHASE31 address 0x31. Fix: a Mariko reads the bit set (retail PHASE211, + 0x33). +- **Windows image I/O ran in text mode.** MinGW's `open()` defaults to it, + so `_read()` rewrote CR LF and stopped at 0x1A inside SD/eMMC sectors, and + its 32-bit `st_size` could not size a 4 GiB rawnand chunk. Fix: `O_BINARY` + and `_fstati64` (`platform.h`). + See `git log` for the commit-by-commit diagnosis trail if you want more detail on any of them. ## Adding a new peripheral -1. Decide on an MMIO range and add a new `else if` branch in `mmio_read` or - `mmio_write` (or a dedicated module like `i2c3.cpp`). +1. Decide on an MMIO range, make sure it is covered by `kRegions`, and add a + branch in `mmio_bus_read` / `mmio_bus_write` (or a dedicated module like + `i2c3.cpp`). Both processors reach it; check `g_bus_master` if the real + block answers only one of them. 2. If the device participates in the boot fence (status registers polled by the BDK), make sure the read returns the "ready" or "done" state. Silent `0` returns are the most common cause of hangs. diff --git a/Makefile b/Makefile index 8a705d0..df8126e 100644 --- a/Makefile +++ b/Makefile @@ -59,7 +59,7 @@ WIN_CXXFLAGS = -Wall -g -O2 -std=c++17 -MMD -MP -I. -I$(IMGUI_DIR) WIN_LIBS = -lmingw32 -lSDL2main -lSDL2 -lunicorn -lpthread -lwinmm -limm32 -lole32 -loleaut32 -lversion -lsetupapi -lcfgmgr32 -lcomdlg32 -lgdi32 -lrpcrt4 -lws2_32 -luuid -lshell32 -ladvapi32 -luser32 WIN_LDFLAGS = -static -static-libgcc -static-libstdc++ -.PHONY: all clean windows +.PHONY: all clean windows test all: $(OUTPUT) @@ -84,5 +84,24 @@ $(OUTPUT): $(OBJS) # (or after `make clean`) since the files don't exist yet. -include $(OBJS:.o=.d) +# ---- Regression tests -------------------------------------------------------- +# +# `make test` boots the emulator headless on small self-contained payloads and +# checks what they report. Needs arm-none-eabi-gcc for the BPMP side (the +# AArch64 side of the CCPLEX test is pre-assembled words in the source). +TEST_CC = arm-none-eabi-gcc +TEST_OBJCOPY = arm-none-eabi-objcopy +TEST_CFLAGS = -marm -march=armv4t -O2 -ffreestanding -nostdlib -fno-builtin \ + -Wall -Wextra + +tests/ccplex/payload.bin: tests/ccplex/payload.c tests/ccplex/link.ld + $(TEST_CC) $(TEST_CFLAGS) -T tests/ccplex/link.ld -o tests/ccplex/payload.elf $< + $(TEST_OBJCOPY) -O binary tests/ccplex/payload.elf $@ + +test: $(OUTPUT) tests/ccplex/payload.bin + sh tests/ccplex/run.sh ./$(OUTPUT) tests/ccplex/payload.bin + clean: - rm -f $(OUTPUT) $(OBJS) $(OBJS:.o=.d) \n $(WIN_OUT) $(WIN_OBJS) $(WIN_OBJS:.o=.d) + rm -f $(OUTPUT) $(OBJS) $(OBJS:.o=.d) \ + tests/ccplex/payload.elf tests/ccplex/payload.bin tests/ccplex/out.log \ + $(WIN_OUT) $(WIN_OBJS) $(WIN_OBJS:.o=.d) diff --git a/README.md b/README.md index af61f8c..44e2b42 100644 --- a/README.md +++ b/README.md @@ -7,9 +7,10 @@ precompiled `.bin` (Hekate, Lockpick_RCM, TegraExplorer, custom payloads) and executes its ARM32 code on an emulated Tegra X1 (T210) environment, with a windowed framebuffer and keyboard input mapped to the Switch hardware buttons. -It is **not** a console emulator. Only the BPMP (Boot and Power Management -Processor) bootloader stage is modelled. You will not boot Horizon, run NSPs, -or load games. The intended use is payload development and scripted +It is **not** a console emulator. The BPMP (Boot and Power Management +Processor) bootloader stage is what is modelled, plus CPU0 of the main CPU +cluster for payloads that boot it to run bare-metal AArch64 code. You will not +boot Horizon, run NSPs, or load games. The intended use is payload development and scripted verification, plus security research where iterating on real hardware would be slow or destructive. @@ -21,6 +22,10 @@ slow or destructive. bypasses the parts of the chain that aren't fully modelled. - Run **TegraExplorer**, including `.te` script execution from an emulated SD card. +- Run **hwtest-rcm**'s complete hardware sweep in a few seconds, including its + Wi-Fi probe, which boots **CPU0** (Cortex-A57, AArch64) to bring up PCIe and + enumerate the CYW4356 - PCIe answers a CPU-complex master only. See + [CCPLEX CPU0](#ccplex-cpu0). - Replay deterministic button sequences via `--auto-pin-recovery` or `--auto-te-script`, so a payload flow can be exercised from a CI run or a one-shot script. @@ -141,6 +146,45 @@ Audio goes to WASAPI on Windows and ALSA/PulseAudio on Linux; SDL picks the backend, so nothing in the emulator cares which. `RCM_EMU_NO_AUDIO=1` skips playback entirely, which is what CI uses since a runner has no sound device. +## CCPLEX CPU0 + +A payload can boot the first Cortex-A57 exactly as bdk's `ccplex_boot_cpu0()` +does - CPU rail, PLLX, CCLK, the CRAIL/C0NC/CE0 partitions, RAM repair, the +AArch64 vector in `SB_AA64_RESET_LOW/HIGH`, then `RST_CPUG_CMPLX_CLR` - and the +emulator runs it: AArch64, entered at EL3 with the MMU off at the vector, +sharing IRAM, DRAM and every peripheral with the BPMP, in lockstep with it on +the emulated clock. Output is prefixed `[ccplex]`: + +``` +[ccplex] CPU0 released: AArch64 EL3, MMU off, entry 0xA0000000 (boot #1) +[pcie] root port 1: link UP, gen1 x1 (healthy WLAN) +[uartB] CPU0 : ran to completion (hb=613) +[uartB] AFI (CPU) : cfg=00103025 witness=A5A50000 -> APERTURE LIVE +[uartB] RP1 link : UP, DL active (LNKSTA=3011 gen1 x1) +[uartB] EP config : 14E4:43EC Broadcom BCM/CYW4356 WLAN +[uartB] Result : WLAN core enumerated on the PCIe bus +[ccplex] CPU0 stopped (held in reset) after 19402985 instructions, 4846717 bus accesses +``` + +A release with something missing does not run the core - silicon would not - +and says what was missing, e.g. `[ccplex] CPU0 released from reset but cannot +run: CPU rail off (MAX77621 VOUT_EN / MAX77620 GPIO5 EN pin)`. PCIe and +MSELECT answer CPU0 only; the BPMP reads all ones from them, as measured on +real consoles. Details in [DESIGN.md](DESIGN.md#ccplex-cpu0). + +## Tests + +```bash +make test # CCPLEX regression payload (needs arm-none-eabi-gcc) +tests/hwtest/build.sh build-hwtest # build hwtest-rcm (+ gcc-aarch64-linux-gnu) +tests/hwtest/run.sh ./rcm_emu build-hwtest/hwtest-rcm/build/hwtest.bin +``` + +The first boots CPU0 from a small self-contained payload and checks the +refusal of an unpowered release, the EL3 entry, the mailbox, WFE parking and +the reset. The second runs hwtest-rcm's whole hardware sweep headless and +checks that the CPU0-driven Wi-Fi probe enumerates the endpoint. CI runs both. + ## Live hardware tweaks Press `M` in the main window to open a second window that exposes the values @@ -232,7 +276,7 @@ needed. | `--prod-keys` | `prod.keys` | Override BIS keys from a Lockpick-style key file. | | `--oem` | `erista` \| `mariko` | Switch SoC generation. Drives `APB_MISC_GP_HIDREV` so Hekate's `h_cfg.t210b01` matches and pkg1 identification skips the right OEM header. Default `erista`. | | `--bt-radio` | `healthy` \| `faulty` \| `absent` | Broadcom CYW4356 behaviour on UART-D. `healthy` powers up on the `BT_REG_ON` edge, holds `BT_HOST_WAKE` high, asserts `RTS_N` and answers HCI; `faulty` reproduces the 2110-1118 console (module fitted, never leaves POR); `absent` additionally leaves `BT_UART_RXD` in a break condition. Overrides `[bluetooth] radio` in the ini. Default `healthy`. | -| `--wifi-radio` | `healthy` \| `faulty` \| `absent` | The WLAN half of the same CYW4356: a PCI Express endpoint on root port 1. `healthy` trains the link, enumerates as `14E4:43EC` and answers a ChipCommon ChipID read with `0x4356`; `faulty` still trains and enumerates but reads all ones on the backplane (live PCIe front-end, dead radio die); `absent` never leaves detect. The model also enforces the datasheet's power-up ordering, so a payload that releases PERST# too early gets a link that stays down and a `[pcie]` line naming the reason. Overrides `[wifi] radio` in the ini. Default `healthy`. | +| `--wifi-radio` | `healthy` \| `faulty` \| `absent` | The WLAN half of the same CYW4356: a PCI Express endpoint on root port 1, reachable only from CPU0 (the BPMP reads all ones, as on silicon). `healthy` trains the link, enumerates as `14E4:43EC` and answers a ChipCommon ChipID read with `0x4356`; `faulty` still trains and enumerates but reads all ones on the backplane (live PCIe front-end, dead radio die); `absent` never leaves detect. The model also enforces the datasheet's power-up ordering, so a payload that releases PERST# too early gets a link that stays down and a `[pcie]` line naming the reason. Overrides `[wifi] radio` in the ini. Default `healthy`. | | `--auto-pin-recovery` | (none) | Drive the Lockpick PIN-recovery menu without user input. | | `--auto-te-script` | (none) | Drive `recover_pin.te` in TegraExplorer without input. | @@ -244,9 +288,11 @@ flowchart LR root --> top["main.cpp
emu_state.h
Makefile
Dockerfile
README.md / DESIGN.md"] root --> t210["t210/
(SoC peripheral models)"] root --> display["display/"] + root --> tests["tests/
ccplex/, hwtest/"] - t210 --> mmio["mmio.{h,cpp}
memory_map.h
tegra_bl.h"] - t210 --> sdmmc["sdmmc.{h,cpp}
SDMMC1 / SDMMC4"] + t210 --> mmio["mmio.{h,cpp}
memory_map.h
regcache.h, tegra_bl.h"] + t210 --> cpus["bpmp.{h,cpp} BPMP clock
ccplex.{h,cpp} CPU0 (A57)"] + t210 --> pcie["pcie.{h,cpp}
root complex + CYW4356"] t210 --> se["se_engine.{h,cpp}
AES-128, SHA-256"] t210 --> i2c["i2c3.{h,cpp}
STMFTS / FTS4 touch"] @@ -257,8 +303,10 @@ For implementation details, see [DESIGN.md](DESIGN.md). ## Limitations -- **BPMP only.** Horizon and Atmosphère need A57 core emulation. This only - models the ARM7 bootloader environment. +- **BPMP plus one A57.** CPU0 runs bare-metal AArch64 handed to it by a + payload; there is no GIC, no generic timer, no secondary cores and no guest + exception delivery (a fault halts CPU0 and says so). Horizon and Atmosphère + are out of reach. - **Subset of MMIO (Memory-Mapped I/O).** Peripherals are modelled to the depth required by the payloads above. New payloads may exercise registers that fall through to the default catch-all and need handlers added. @@ -267,8 +315,8 @@ For implementation details, see [DESIGN.md](DESIGN.md). `--prod-keys` is a pragmatic shortcut: when Lockpick writes a derived BIS (Boot Image Storage) key into a keyslot, the value from the user-supplied key file is substituted. RSA, RNG, and chunked SHA are stubs. -- **Single-threaded.** The CPU runs in batches on the main thread between SDL - event polls. Tight host CPU loops will starve the display refresh. +- **Single-threaded.** Both cores run in batches on the main thread between + SDL event polls. That is also what keeps them deterministic. ## Acknowledgements diff --git a/tests/ccplex/link.ld b/tests/ccplex/link.ld new file mode 100644 index 0000000..bdc1203 --- /dev/null +++ b/tests/ccplex/link.ld @@ -0,0 +1,10 @@ +/* Loaded and entered at 0x40010000, like any RCM payload. */ +ENTRY(_start) +SECTIONS { + . = 0x40010000; + .text : { KEEP(*(.text.start)) *(.text*) } + .rodata : { *(.rodata*) } + .data : { *(.data*) } + .bss : { *(.bss*) *(COMMON) } + /DISCARD/ : { *(.comment) *(.note*) *(.ARM.attributes) *(.ARM.exidx*) } +} diff --git a/tests/ccplex/payload.c b/tests/ccplex/payload.c new file mode 100644 index 0000000..9afbddb --- /dev/null +++ b/tests/ccplex/payload.c @@ -0,0 +1,165 @@ +/* + * CCPLEX regression payload. + * + * A freestanding BPMP payload (ARM mode, loaded at 0x40010000 like any RCM + * payload) that drives the emulator's CPU0 model through the same register + * sequence as bdk's ccplex_boot_cpu0(), and reports what happened on UART-B. + * tests/ccplex/run.sh checks the emulator's log for the expected lines. + * + * 1. Release CPU0 from reset with nothing powered. The core must NOT run, + * and the emulator must say which precondition is missing. + * 2. Do the real bring-up - CPU rail (MAX77620 GPIO5 + MAX77621 VOUT on + * I2C5), CRAIL/C0NC/CE0 partitions, CPUG + MSELECT clocks, MSELECT out + * of reset, PLLX, RAM repair, SB_AA64_RESET_LOW - then release it. An + * AArch64 blob copied to DRAM records CurrentEL and a TIMERUS delta in + * a mailbox, writes a magic word last, and parks in WFE. + * 3. Put CPU0 back into reset and power the console off. + * + * Built by `make test` with arm-none-eabi-gcc; no other toolchain needed, as + * the AArch64 side is a handful of pre-assembled words. + */ + +typedef unsigned int u32; + +#define REG(a) (*(volatile u32 *)(a)) + +#define TIMERUS 0x60005010u +#define CAR 0x60006000u +#define FLOW 0x60007000u +#define SB 0x6000C200u +#define UARTB_THR 0x70006040u +#define PMC 0x7000E400u +#define I2C5 0x7000D000u + +#define CPU_ENTRY 0xA0000000u +#define MBOX 0xA0030000u +#define PCIE_MAGIC 0x50434945u + +/* AArch64, entered at EL3 with the MMU off: + * mov w1, #0xa0030000 ; mailbox + * mrs x8, currentel + * str w8, [x1, #4] ; [1] = CurrentEL + * mov w4, #0x5010 + * movk w4, #0x6000, lsl #16 ; TIMERUS + * ldr w5, [x4] + * mov w6, #2000 + * 1:subs w6, w6, #1 + * b.ne 1b + * ldr w7, [x4] + * sub w7, w7, w5 + * str w7, [x1, #8] ; [2] = TIMERUS delta across the loop + * mov w2, #0x4945 + * movk w2, #0x5043, lsl #16 + * str w2, [x1] ; [0] = 'PCIE', written last + * 2:wfe + * b 2b + */ +static const u32 cpu0_blob[] = { + 0x52b40061, 0xd5384248, 0xb9000428, 0x528a0204, 0x72ac0004, 0xb9400085, + 0x5280fa06, 0x710004c6, 0x54ffffe1, 0xb9400087, 0x4b0500e7, 0xb9000827, + 0x528928a2, 0x72aa0862, 0xb9000022, 0xd503205f, 0x17ffffff, +}; + +static void putc_(char c) { REG(UARTB_THR) = (u32)(unsigned char)c; } + +static void puts_(const char *s) { + while (*s) + putc_(*s++); +} + +static void puthex(u32 v) { + for (int i = 28; i >= 0; i -= 4) + putc_("0123456789ABCDEF"[(v >> i) & 0xF]); +} + +static void udelay(u32 us) { + u32 start = REG(TIMERUS); + while (REG(TIMERUS) - start < us) + ; +} + +/* bdk-style normal-mode I2C write: [reg, val] in CMD_DATA1, 2 bytes, GO. */ +static void i2c5_write(u32 dev, u32 reg, u32 val) { + REG(I2C5 + 0x04) = dev << 1; /* CMD_ADDR0 */ + REG(I2C5 + 0x0C) = reg | (val << 8); /* CMD_DATA1 */ + REG(I2C5 + 0x00) = (1u << 1) | (1u << 9); /* CNFG: 2 bytes, write, GO */ +} + +static void pwrgate_on(u32 part) { + if (!(REG(PMC + 0x38) & (1u << part))) /* PWRGATE_STATUS */ + REG(PMC + 0x30) = part | (1u << 8); /* PWRGATE_TOGGLE */ +} + +#define RST_CPU0 ((1u << 30) | (1u << 24) | (1u << 16) | (1u << 0)) +#define RST_NONCPU (1u << 29) + +static void release_cpu0(void) { + REG(SB + 0x30) = CPU_ENTRY | 1u; /* SB_AA64_RESET_LOW */ + REG(SB + 0x34) = 0; /* SB_AA64_RESET_HIGH */ + REG(CAR + 0x454) = RST_NONCPU; /* RST_CPUG_CMPLX_CLR */ + REG(CAR + 0x454) = RST_CPU0; +} + +static void hold_cpu0(void) { + REG(CAR + 0x450) = RST_CPU0; /* RST_CPUG_CMPLX_SET */ + REG(CAR + 0x450) = RST_NONCPU; +} + +__attribute__((section(".text.start"), noreturn)) +void _start(void) { + volatile u32 *mb = (volatile u32 *)MBOX; + + puts_("ccplex test: start\n"); + for (u32 i = 0; i < sizeof(cpu0_blob) / sizeof(cpu0_blob[0]); i++) + ((volatile u32 *)CPU_ENTRY)[i] = cpu0_blob[i]; + for (u32 i = 0; i < 4; i++) + mb[i] = 0; + + /* 1. Nothing powered: the release must be refused. */ + release_cpu0(); + udelay(2000); + puts_(mb[0] == PCIE_MAGIC ? "unpowered: CPU0 RAN (wrong)\n" + : "unpowered: CPU0 stayed dark\n"); + hold_cpu0(); + + /* 2. The real bring-up, in ccplex_boot_cpu0() order. */ + i2c5_write(0x3C, 0x40, 0x1C); /* MAX77620 AME_GPIO: GPIO5 plain */ + i2c5_write(0x3C, 0x3B, 0x09); /* GPIO5: push-pull, out high */ + i2c5_write(0x1B, 0x00, 0x80 | 55); /* MAX77621 VOUT: on, 0.950 V */ + REG(CAR + 0x0E0) = (1u << 30) | (2u << 20) | (156u << 8) | 2u; /* PLLX */ + REG(CAR + 0x3B4) = 4u << 1; /* CLK_SOURCE_MSELECT */ + REG(CAR + 0x440) = 1u << 3; /* CLK_ENB_V_SET: MSELECT */ + REG(CAR + 0x020) = 0x20008888; /* CCLK_BURST: PLLX_OUT0_LJ */ + REG(CAR + 0x024) = 1u << 31; /* SUPER_CCLK_DIVIDER */ + REG(CAR + 0x440) = 1u << 0; /* CLK_ENB_V_SET: CPUG */ + pwrgate_on(0); /* CRAIL */ + pwrgate_on(15); /* C0NC */ + pwrgate_on(14); /* CE0 */ + REG(FLOW + 0x40) = 1; /* RAM_REPAIR_REQ */ + while (!(REG(FLOW + 0x40) & 2)) + ; + REG(CAR + 0x434) = 1u << 3; /* RST_DEV_V_CLR: MSELECT */ + release_cpu0(); + + u32 start = REG(TIMERUS); + while (mb[0] != PCIE_MAGIC && REG(TIMERUS) - start < 100000) + udelay(100); + puts_("powered: magic="); + puthex(mb[0]); + puts_(" el="); + puthex(mb[1]); + puts_(" dt="); + puthex(mb[2]); + putc_('\n'); + + /* Let CPU0 sit in its WFE park for a while: it must cost next to + * nothing, which the retired-instruction count at reset shows. */ + udelay(50000); + + /* 3. Back into reset, then power off. */ + hold_cpu0(); + puts_("ccplex test: done\n"); + i2c5_write(0x3C, 0x41, 0x02); /* MAX77620 ONOFFCNFG1: PWR_OFF */ + for (;;) + ; +} diff --git a/tests/ccplex/run.sh b/tests/ccplex/run.sh new file mode 100755 index 0000000..809160d --- /dev/null +++ b/tests/ccplex/run.sh @@ -0,0 +1,50 @@ +#!/bin/sh +# CCPLEX regression test: boot CPU0 from a BPMP payload and check what the +# emulator and the payload report. Usage: tests/ccplex/run.sh [rcm_emu] [payload] +EMU=${1:-./rcm_emu} +PAYLOAD=${2:-tests/ccplex/payload.bin} +LOG=${LOG:-tests/ccplex/out.log} + +SDL_VIDEODRIVER=dummy RCM_EMU_NO_AUDIO=1 timeout 120 "$EMU" "$PAYLOAD" \ + > "$LOG" 2>&1 +status=$? + +fail=0 +expect() { + if grep -q -- "$1" "$LOG"; then + echo " ok $2" + else + echo " FAIL $2 (missing: $1)" + fail=1 + fi +} + +echo "ccplex test (emulator exit $status):" +expect 'cannot run: CPU rail off' 'an unpowered release is refused, with the reason' +expect 'unpowered: CPU0 stayed dark' 'and the core really did not execute' +expect 'CPU0 released: AArch64 EL3, MMU off, entry 0xA0000000' 'a powered release boots CPU0 at the SB vector' +expect 'powered: magic=50434945' 'CPU0 ran the blob and wrote the mailbox' +expect 'el=0000000C' 'CPU0 came up at EL3' +expect 'CPU0 stopped (held in reset)' 'RST_CPUG_CMPLX_SET stops the core' +expect 'MAX77620 PWR_OFF received' 'the payload ran to its power-off' + +# TIMERUS as CPU0 saw it must have moved across its busy loop. +dt=$(sed -n 's/.*dt=\([0-9A-F]*\).*/\1/p' "$LOG" | head -1) +if [ -n "$dt" ] && [ "$dt" != "00000000" ]; then + echo " ok CPU0 sees time advance (TIMERUS delta 0x$dt)" +else + echo " FAIL CPU0's TIMERUS delta is zero or missing" + fail=1 +fi + +# Parked in WFE for ~50 ms, the core must retire next to nothing: the park +# loop sleeps to the end of each slice instead of spinning. +retired=$(sed -n 's/.*CPU0 stopped (held in reset) after \([0-9]*\) instructions.*/\1/p' "$LOG" | head -1) +if [ -n "$retired" ] && [ "$retired" -lt 100000 ]; then + echo " ok WFE parks the core ($retired instructions retired in total)" +else + echo " FAIL WFE did not park the core (retired: ${retired:-?})" + fail=1 +fi + +[ $fail -eq 0 ] && echo "ccplex test: PASS" || { echo "ccplex test: FAIL - see $LOG"; exit 1; } diff --git a/tests/hwtest/build.sh b/tests/hwtest/build.sh new file mode 100755 index 0000000..4446907 --- /dev/null +++ b/tests/hwtest/build.sh @@ -0,0 +1,31 @@ +#!/bin/sh +# Build hwtest-rcm (https://github.com/Creased/hwtest-rcm) with distro +# toolchains, CPU0 stub included. Usage: tests/hwtest/build.sh +# Produces /hwtest-rcm/build/hwtest.bin. +# +# hwtest's Makefile only needs $(DEVKITARM)/base_rules to exist - it names +# arm-none-eabi-gcc itself - so an empty file stands in for devkitARM, and +# Debian/Ubuntu's gcc-aarch64-linux-gnu builds the AArch64 stub, which is +# what hwtest's own CI does too. +# +# Pinned so a change on the hwtest side cannot turn this emulator's CI red +# without a commit here; bump HWTEST_REF deliberately. +set -e +WORK=${1:-build-hwtest} +HWTEST_REF=${HWTEST_REF:-3738e9a47e1833605fc5a30eeca0ea95caa3b936} + +mkdir -p "$WORK" +cd "$WORK" +if [ ! -d hwtest-rcm/.git ]; then + git init -q hwtest-rcm + git -C hwtest-rcm remote add origin https://github.com/Creased/hwtest-rcm.git +fi +git -C hwtest-rcm fetch -q --depth 1 origin "$HWTEST_REF" +git -C hwtest-rcm checkout -q FETCH_HEAD +git -C hwtest-rcm submodule update -q --init --depth 1 third_party/hekate + +mkdir -p devkitARM +: > devkitARM/base_rules +make -C hwtest-rcm -j"$(nproc)" DEVKITARM="$PWD/devkitARM" \ + A64_CC=aarch64-linux-gnu-gcc A64_OC=aarch64-linux-gnu-objcopy REQUIRE_A64=1 +ls -l hwtest-rcm/build/hwtest.bin diff --git a/tests/hwtest/run.sh b/tests/hwtest/run.sh new file mode 100755 index 0000000..72bc66e --- /dev/null +++ b/tests/hwtest/run.sh @@ -0,0 +1,49 @@ +#!/bin/sh +# End-to-end: run hwtest's whole hardware sweep in the emulator, headless, +# and check the CPU0-driven PCIe probe enumerated the Wi-Fi endpoint. +# Usage: tests/hwtest/run.sh [extra emulator args...] +# +# hwtest sits in its pager once the sweep is dumped, so the run is ended as +# soon as the dump's last line appears (with a hard timeout behind it). +EMU=${1:-./rcm_emu} +BIN=${2:-build-hwtest/hwtest-rcm/build/hwtest.bin} +shift 2 2>/dev/null +LOG=${LOG:-tests/hwtest/out.log} +LIMIT=${LIMIT:-300} + +# POWER at 3 s picks "Hardware test" on hwtest's launcher. +SDL_VIDEODRIVER=dummy RCM_EMU_NO_AUDIO=1 "$EMU" "$BIN" --input-script "3000 P" "$@" \ + > "$LOG" 2>&1 & +pid=$! +t=0 +until grep -q 'end of dump' "$LOG" 2>/dev/null || ! kill -0 $pid 2>/dev/null; do + sleep 1 + t=$((t + 1)) + if [ $t -ge "$LIMIT" ]; then + echo "hwtest: no end of dump after ${LIMIT}s" + break + fi +done +kill $pid 2>/dev/null +wait $pid 2>/dev/null +echo "hwtest: sweep took ~${t}s of wall time" + +fail=0 +expect() { + if grep -q -- "$1" "$LOG"; then + echo " ok $2" + else + echo " FAIL $2 (missing: $1)" + fail=1 + fi +} +expect 'end of dump' 'the whole sweep ran to its end' +expect '\[ccplex\] CPU0 released: AArch64 EL3' 'hwtest booted CPU0' +expect 'CPU0 : ran to completion' 'the CPU0 stub ran to completion' +expect 'AFI (CPU) : cfg=00103025 witness=A5A50000 -> APERTURE LIVE' 'the PCIe aperture decodes for CPU0' +expect 'RP1 link : UP, DL active (LNKSTA=3011' 'root port 1 trained' +expect 'EP config : 14E4:43EC' 'the CYW4356 endpoint enumerated' +expect 'CPU0 : powergated' 'the cluster was powergated again' +expect 'Wireless : pass' 'the Wireless verdict passed' + +[ $fail -eq 0 ] && echo "hwtest: PASS" || { echo "hwtest: FAIL - see $LOG"; exit 1; }