diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 044bc74..10392ee 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,39 @@ jobs:
grep -q "RCM Payload Emulator" out.txt \
|| { echo "banner missing - binary did not start"; exit 1; }
+ - name: CCPLEX, SE, USB and display regression tests
+ # Small self-contained payloads. One 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. One runs the Security Engine's RSA, SHA-256, AES and
+ # RNG against vectors computed in Python. One brings up USB gadgets on
+ # both device controllers for the --usb-host PC to enumerate, read
+ # back and write, and serves the disk over NBD (on a localhost port)
+ # to a Python client. The others drive the display controller and VIC in six
+ # scenarios, and the frame the emulator shows must match the picture
+ # drawn, pixel for pixel.
+ 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/se/out.log
+ tests/usb/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..2803d36 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,12 +3,14 @@ rcm_emu
rcm_emu.exe
*.o
*.d
+*.elf
# Runtime captures
last_fb.rgba
last_fb.meta
last_fb*.png
out.log
+out_*.log
out*.txt
emu_run*.log
emu_capture*.txt
@@ -26,5 +28,6 @@ last_audio*.wav
__pycache__/
*.pyc
backup/
+build-hwtest/
imgui.ini
rcm_emu.ini
diff --git a/DESIGN.md b/DESIGN.md
index e2232f7..8fe3297 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -10,19 +10,25 @@ 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 -->|sdl_display_*| sdl["display/sdl_display
block-linear de-swizzle
rotate, blit"]
+ 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
DC window scan-out
blend, turn, 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"]
+ mmio --> sdmmc["sdmmc
SDMMC1 / SDMMC4
CMD0..21, EXT_CSD, ADMA2
SD UHS-I, eMMC HS400"]
+ mmio --> se["se_engine
AES-128, SHA-256, RSA, RNG
BIS keyslot override"]
mmio --> i2c["i2c3
STMFTS / FTS4 touch"]
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 --> dc["DC + VIC (inline)
window registers A-D
VIC compose, flip/transpose"]
+ mmio --> stubs["inline stubs
GPIO, PMC, TSEC, KFUSE,
PWM, CLK, TMR, FUSE, UART"]
+ mmio --> pcie["pcie
AFI, root ports, CYW4356
(CPU-complex master only)"]
+ mmio --> usb["usb
USB2 + XUSB device controllers
and the --usb-host PC"]
cfg -.->|writes atomics| state["EmuState
(emu_state.h)"]
con -.->|RX inject / TX log| state
@@ -35,25 +41,39 @@ 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
- `uc_mem_write`. We also pre-write the 4-byte cookie `0x544457` ("WDT") at
- IRAM offset `0x4003FF18`. Hekate reads that location during early boot.
- When the cookie is present, it takes the `goto skip_lp0_minerva_config`
- branch and skips loading both `libsys_lp0.bso` and the Minerva
- DRAM-training module. Real DRAM training would touch the EMC (External
- Memory Controller) and MC (Memory Controller), neither of which the
- emulator models. The matching exception-enable cookie at `0x4003FF1C`
- stays zero, so the "hang detected" warning is suppressed.
+ `uc_mem_write`. Nothing else is planted: IRAM holds what it holds after a
+ cold boot.
2. PC is set to `0x40010000`, SP to `IPL_STACK_ADDR`. CPSR enters ARM mode.
-3. The IPL (Initial Program Loader) initialises clocks, fuses and the display,
- then continues straight into the boot menu without loading LP0 or Minerva.
-4. Hekate self-relocates into DRAM (`0xC0000000+`) and continues. The display
- pipeline resamples its DRAM-side framebuffer parameters.
-5. Nyx (the LVGL graphics stack) initialises and draws into a separate FB. The
- DC (Display Controller) `WINDOW_HEADER` register tracks the currently
- primary surface. The display code follows that pointer.
+3. The IPL (Initial Program Loader) initialises clocks, fuses, the DRAM
+ (`sdram_init`, at 204 MHz) and the display, mounts the SD card, loads
+ `bootloader/sys/libsys_lp0.bso` (it saves the LP0 SDRAM config to PMC
+ scratch) and trains the DRAM with Minerva
+ (`bootloader/sys/libsys_minerva.bso`) at 204, 800 and 1600 MHz, all as on
+ hardware (see [EMC and DRAM clock](#emc-and-dram-clock)). An SD image
+ without those modules gets hekate's "Missing LP0 (sleep) lib! / Missing
+ Minerva lib!" screen, which waits for a key press before the menu.
+ hekate prints "Missing Minerva lib!" for any Minerva failure, not only a
+ missing file: Minerva also refuses to start unless HIDREV reads chip
+ 0x21 and `FUSE_SKU_INFO` (0x110) reads 0x83 (ODIN). Both hold by
+ default; a `[fuses]` edit to 0x110 in the config window or
+ `rcm_emu.ini` brings the screen back.
+4. Hekate self-relocates into DRAM (`0xC0000000+`) and continues. It points
+ DC (Display Controller) window A at its portrait framebuffer and draws its
+ boot logo and menus there, sideways, for the landscape-mounted panel.
+5. Nyx (the LVGL GUI) takes over the trained Minerva context and from then
+ on alternates the DRAM between 1600 and 800 MHz on every GUI loop to save
+ power. It draws landscape into a second framebuffer and has VIC
+ turn every frame into the portrait surface that window A scans out. The
+ display follows the DC's windows, whatever they point at (see Display
+ pipeline).
## Memory map
@@ -65,10 +85,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
@@ -80,7 +117,8 @@ of the spec is modelled for the Hekate, Lockpick and TE init paths:
- CMD0 GO_IDLE, CMD1 SEND_OP_COND, CMD2 ALL_SEND_CID, CMD3 SEND_RELATIVE_ADDR,
CMD6 SWITCH, CMD7 SELECT_CARD, CMD8 SEND_EXT_CSD (eMMC) or SEND_IF_COND (SD),
CMD9 SEND_CSD, CMD13 SEND_STATUS, CMD16 SET_BLOCKLEN, CMD17 and CMD18
- READ_(MULTI_)BLOCK, CMD55 APP_CMD.
+ READ_(MULTI_)BLOCK, CMD11 VOLTAGE_SWITCH, CMD19 / CMD21 SEND_TUNING_BLOCK,
+ CMD55 APP_CMD.
- ADMA2 (Advanced DMA 2) with 64-bit descriptors, multi-block reads chunked
into the host file IO via `pread`-style calls.
- `--rawnand` opens the matching `rawnand.bin.NN` chunks and `fstat`s the first
@@ -101,32 +139,150 @@ of the spec is modelled for the Hekate, Lockpick and TE init paths:
sec_cnt) and writes it via the configured ADMA2 descriptor before raising
the IRQ.
+#### Host controller registers and HS400
+
+Each controller keeps its SDHCI registers (0x28-0x3F: power, clock, software
+reset, HOST_CONTROL2) and Tegra's vendor block (0x100-0x1FF) in a register
+file with the TRM's reset values, plus the side effects bdk waits on:
+
+- CLOCK_CONTROL reports INTERNAL_CLK_STABLE once INT_CLK_EN is set.
+ SOFTWARE_RESET's bits self-clear. RESET_ALL puts the standard registers
+ back to reset and leaves the vendor block alone.
+- AUTO_CAL_CONFIG.START and DLLCAL_CFG.CALIBRATE self-clear, and the status
+ registers report the calibration done.
+- Setting HOST_CONTROL2.EXEC_TUNING starts tuning. Each CMD19/CMD21 tries one
+ tap: with TAP_VAL_UPDATED_BY_HW the taps step from TUNING_CNTRL0.START_TAP
+ by TUNING_CNTRL1's step size, otherwise the tap in VENDOR_CLOCK_CNTRL is
+ used. A tap passes when it falls in the modelled data eye, taps 26..82.
+ After NUM_TUNING_ITERATIONS commands EXEC_TUNING clears and TUNED_CLK is
+ set. The pass map lands in TUNING_STATUS0, and the chosen tap, first +
+ (last - first) x (MUL_M + 1) / 2^DIV_N (TRM 32.9.2.14), lands in
+ VENDOR_CLOCK_CNTRL. The tuning block's BUFFER_READ_READY is held until the
+ card clock is re-enabled, the order in which bdk's tuning loop waits.
+- EXT_CSD is one 512-byte array that lives for a power cycle. CMD6 SWITCH
+ (write byte, set bits or clear bits) changes the bytes eMMC 5.1 makes
+ writable (BUS_WIDTH, HS_TIMING, PARTITION_CONFIG and a few more). CMD8
+ returns the array and CMD0 puts the card-reset fields back. CARD_TYPE
+ advertises HS400 at 1.8 V, so bdk goes 8-bit, then HS200 (tuned), then
+ HS400, and reports a 199.68 MHz card clock. BOOT0, BOOT1 and RPMB are
+ 4 MiB each, as on a Switch.
+
+#### The SD card: UHS-I
+
+The SD card is a UHS-I card (SD Physical Layer 3.01), so bdk runs it at
+SDR104 like the real slot:
+
+- ACMD41 with S18R answers S18A while the card still signals at 3.3 V, and
+ CMD11 moves it to 1.8 V. It stays there until it loses power: bdk's
+ supply GPIO (PE4) going low, or a reset. A card re-initialised without a
+ power cycle answers S18A = 0 but keeps offering its UHS speeds.
+- CMD6 (SWITCH_FUNC) reports and selects a function per group, per SD
+ 4.3.10: bus speed (SDR12 and SDR25/HS, plus SDR50, SDR104 and DDR50 at
+ 1.8 V), driver strength and power limit. CMD0 puts the functions back to
+ their defaults, not the voltage.
+- CMD19 tunes the SDR104 sampling point through the same tuning circuit as
+ the eMMC. hwtest reports a 199.68 MHz card clock.
+- With no image (`--sd`, or `sd.img` in the working directory) the slot is
+ empty: card detect (PZ1) reads no card and every SDMMC1 command times
+ out, as on a console with no card in. The config window can still insert
+ a blank card.
+- The CSD is an SD CSD 2.0 (SD 5.3.3): the image's size (32 GiB for a blank card)
+ and command classes that include class 8, so bdk reads the SD status.
+ That (ACMD13) reports the bus width ACMD6 set and a Class 10, U1, V10
+ card with 4 MB AUs; the SCR sets SD_SPEC3.
+
+### EMC and DRAM clock
+
+The EMC (External Memory Controller, `t210/mmio.cpp`) is a register file -
+reads return what was written, as `sdram_init` programmed it from the BCT -
+with the controller's own behaviour on top (TRM 18.11). That is what bdk's
+mode-register reads and Minerva, hekate's DRAM training and
+frequency-switching module, depend on:
+
+- **Banks.** A write to the broadcast bank (`EMC_BASE`) reaches both
+ channels; `EMC0_BASE` / `EMC1_BASE` address one channel each.
+- **Mode registers.** MRWs (`EMC_MRW`, `EMC_MRW2..15`) are remembered. An
+ MRR latches the answer into the channel's `EMC_MRR` and sets
+ `EMC_EMC_STATUS.MRR_DIVLD` until it is read. MR4 reports a normal
+ temperature, MR5-8 the configured DRAM ID, and MR18/MR19 the DQS interval
+ oscillator count: MR23's run time at the current DRAM clock over twice a
+ 400 ps tDQS2DQ. Minerva divides by that count.
+- **Digital DLL.** `EMC_DIG_DLL_STATUS` reports lock as soon as the DLL is
+ (re)started; `EMC_CFG_DIG_DLL.CFG_DLL_EN` reads back as written, which is
+ what Minerva spins on around each DLL restart. The DLL's code, `DLL_OUT`
+ (10:0), is where its calibration starts: the channel's
+ `EMC_DLL_CFG_1.DDLLCAL_CTRL_START_TRIM` (10:0, reset 0x20, TRM
+ 18.11.2.219), which the timing table programs per frequency. With no
+ delay line to drift, calibration has nothing to move it by. (Minerva's
+ `_digital_dll_prelock()` returns it; nothing reads it further.)
+- **Clock change.** A new source or divisor in CAR `CLK_SOURCE_EMC` (TRM
+ 5.2.73) is the CAR/EMC handshake: the EMC replays the writes queued in its
+ clock-change FIFO (`EMC_CCFIFO_DATA` / `_ADDR`) and raises
+ `CLKCHANGE_COMPLETE` in `EMC_INTSTATUS`. The DRAM clock follows from
+ `CLK_SOURCE_EMC` and the PLLM / PLLMB dividers; `PLLMB_BASE` (TRM 5.2.230)
+ locks once enabled, like the other PLLs.
+- **Status.** `EMC_EMC_STATUS` otherwise reports timing updates done, the
+ DRAM active and the state machines idle.
+- **Measured clock.** bdk's PTO counter measures the EMC at the modelled
+ clock (the measured 204 MHz figure at the boot clock).
+
+With the stock `bootloader/` folder, hekate's IPL trains 204, 800 and
+1600 MHz, and Nyx then switches between 800 and 1600 MHz on every GUI loop,
+each switch a full handshake with a CCFIFO replay.
+
### Security Engine (`t210/se_engine.cpp`)
Models the SE (Security Engine) register block at `0x70012000`. Supports:
-- **AES-128 ECB, CBC, CTR, CMAC.** The compact public-domain TinyAES core
- ([kokke/tiny-AES-c](https://github.com/kokke/tiny-AES-c)) drives one block
- at a time, with chaining state taken from `IV_ORIGINAL` or `IV_UPDATED` per
- slot and `xor_pos` from `CRYPTO_CONFIG`.
-- **SHA-256.** Implemented because the TE function `save_process_header`
- validates the save container hash. Without it, `readsave()` returns
- `Error: Save header is invalid!`. Oneshot only: one IN_LL buffer at a time,
- written into the `HASH_RESULT` registers as 8 big-endian dwords (the BDK
- driver byte-swaps on read).
-- **DST_KEYTABLE unwrap path.** When the destination is another keyslot, the
- result of a single block is written into the destination `KEYS_0_3` or
- `KEYS_4_7` register pair.
+- **AES-128 ECB, CBC, OFB, CTR, CMAC.** The compact public-domain TinyAES
+ core ([kokke/tiny-AES-c](https://github.com/kokke/tiny-AES-c)) drives one
+ block at a time through the SE's datapath: `INPUT_SEL` picks memory, the
+ previous AES output (OFB) or the linear counter (CTR); `XOR_POS` puts the
+ vector RAM before the core (CBC encrypt) or the vector / the memory data
+ after it (CBC decrypt, OFB, CTR); `VCTRAM_SEL` says what the vector becomes
+ next. The vector starts from the slot's `IV_ORIGINAL` or `IV_UPDATED`, and
+ a chaining mode leaves its final value in `IV_UPDATED`, which is how bdk
+ continues a chain into a trailing partial block and feeds the last block of
+ a CMAC. Checked against OpenSSL for every mode bdk uses, including
+ multi-block CMAC and partial blocks.
+- **SHA-256**, one-shot and in parts. `SHA_INIT_HASH` starts from the
+ standard state, `SHA_CONTINUE` from the one the last part left in
+ `HASH_RESULT` (8 big-endian dwords; the BDK driver byte-swaps on read), and
+ the part is padded only when `SHA_MSG_LEFT` says it is the last.
+ Implemented because the TE function `save_process_header` validates the
+ save container hash.
+- **DST_KEYTABLE unwrap path.** The result of a single block is written into
+ the destination slot's selected word quad.
+- **RSA** modular exponentiation, as Lockpick's bdk drives it
+ (`se_rsa_key_set()` / `se_rsa_exp_mod()`): two keyslots of up to 2048
+ bits, loaded a word at a time through `SE_RSA_KEYTABLE_ADDR/DATA` (least
+ significant word first), `KEY_SIZE` in 512-bit steps and `EXP_SIZE` in
+ words, the input a little-endian number over DMA and the result in
+ `SE_RSA_OUTPUT` (or memory). Montgomery multiplication on 32-bit words;
+ an even modulus fails the operation.
+- **RNG** into memory or a keyslot quad (`se_rng_pseudo()`, TegraExplorer's
+ `se_generate_random()`): `LAST_BLOCK + 1` blocks, cut to the buffer size.
+ The bytes come from a SplitMix64 generator with a fixed seed, reset with
+ the SE, so runs repeat. Nyx uses them for GPT partition GUIDs and the SD
+ benchmark's random offsets.
+- **Context save** (`SE_OP_CTX_SAVE`), as bdk's `se_aes_ctx_get_keys()` uses
+ it to read keyslots back: an RNG op seeds a secure random key (fixed, for
+ reproducibility), each saved keyslot quad is written out encrypted under it
+ in one CBC chain, and saving the SRK deposits it in PMC `SECURE_SCRATCH4..7`
+ for the driver to decrypt with.
- **`--prod-keys` BIS override.** When Lockpick writes the last word of a
derived BIS (Boot Image Storage) key into slots 0..5, the value from the
user-supplied key file is substituted. This sidesteps the
TSEC-firmware to `master_kek` to `master_key` derivation chain that is not
- fully modelled. For other keyslots, the SE behaves normally.
+ fully modelled. Clearing a slot and loading the context-save SRK are left
+ alone. For other keyslots, the SE behaves normally.
The 16 keyslots are stored in a flat `Keyslot ks_table[16]` with
-`key[32] / iv_orig[16] / iv_upd[16]`. RSA, RNG, and chunked SHA are stubbed.
-They return `OP_DONE` without producing data, which is enough for current
-payloads.
+`key[32] / iv_orig[16] / iv_upd[16]`. Block counts are bounded by what one
+linked-list entry can describe (16 MiB), and an operation whose buffers are
+unreachable finishes with `SE_INT_ERR_STAT` instead of computing on zeros.
+`tests/se/` checks RSA-2048 and RSA-1024 both ways against Python, SHA-256
+one-shot and in parts, AES-ECB and the RNG.
### Touchscreen (`t210/i2c3.cpp`)
@@ -159,11 +315,27 @@ down or reset are caught by `t210/mmio.cpp`:
caught on both the small CMD\_DATA1 path and the packet-mode TX_FIFO path
-- stops emulation and exits cleanly.
- Same register with `SFT_RST` (bit 7) set requests a payload soft-reboot
- via `state->reboot_requested`.
+ via `state->reboot_requested`, as a power cycle (`reboot_cold`).
- `APBDEV_PMC_CNTRL` (`0x00`) bit 4 (MAIN_RST) -- written by Hekate's
`power_set_state(REBOOT_RCM)` -- also requests a soft-reboot, so the user
can iterate on a payload without restarting `rcm_emu`.
+Either request stops the BPMP on the spot: `power_set_state()` follows the
+write with `bpmp_halt()`, which would otherwise end the run first.
+
+**What a reboot resets** (`mmio_soft_reset`). Everything on the SoC: the
+register cache (GPIO, pinmux, clocks), UART modes and receive FIFOs, the I2C
+controllers, the PMC's partitions, pad DPD and registers, CAR, the flow
+controller, the SE (back to the `--prod-keys` preload), touch, SDMMC (the
+eMMC back in its user area), the display controller, ACTMON, VIC, DSI, the
+PCIe root complex and CPU0. What survives is what survives on hardware: PMC
+SCRATCH0 and RST_STATUS, the RTC (still counting), and - unless the reboot
+is a power cycle - the PMIC with its rails and the external regulators. DRAM
+comes back as fresh zero pages (not a memset, which made all 2 GB resident),
+the BPMP's translations of IRAM, DRAM and low memory are dropped so the old
+run's code cannot run in place of the reloaded payload, the CPSR returns to
+its power-on SVC mode, scripted input restarts and every button is released.
+
### I²C-attached chips (battery, charger, thermal, USB-PD, PMIC ID)
Modelled inline in `t210/mmio.cpp::i2c_read`. The bus is disambiguated by
@@ -239,21 +411,69 @@ do not auto-creep into the build.
### Display pipeline (`display/sdl_display.cpp`)
-Hekate and Nyx draw into a block-linear surface. One block-height row covers
-16 GOBs (Group Of Bytes, NVIDIA's 64 by 8 pixel tile). The display thread:
+The display controller is modelled as the registers of its four windows,
+A-D (TRM 24.10-24.11), in `t210/mmio.cpp`. Payloads reach a window through
+the indirect window pages (0x700-0x83F), which write every window
+`DC_CMD_DISPLAY_WINDOW_HEADER` selects, or through a window's direct range
+(A 0xB80, B 0xD80, C 0xF80). Writes land in the window's assembly copy, and
+`WIN_x_ACT_REQ` in `DC_CMD_STATE_CONTROL` copies that into the active copy,
+so a half-programmed window never shows. Reads return what was written.
+`STATE_CONTROL` reads 0 (every request has completed), and `INT_STATUS`
+reports a frame end and a vblank, which bdk polls before DSI commands.
-1. Reads DC `WINDOW_HEADER` to follow the active surface (Window A, B, C or
- D).
-2. Looks up the FB pointer, stride and GOB block height latched from
- `DC_WIN_x_SURFACE_KIND`.
-3. De-swizzles into a linear RGBA buffer using a per-pixel address calc.
-4. Optionally rotates 0, 90, 180 or 270 degrees to match the panel orientation
- detected from window dimensions, with an `R` or `Shift+R` manual override.
-5. Blits to an SDL_Texture at the host window current size.
+Each display tick builds the picture the panel would receive, 720x1280 and
+portrait, the way the DC builds it:
-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.
+1. Every enabled window's surface is fetched from `START_ADDR`. The layout
+ comes from `SURFACE_KIND`: pitch, 16x16 tiled, or block linear with
+ 2^`BLOCK_HEIGHT` GOBs (Groups of Bytes, 64x8-byte tiles) per block. The
+ line pitch is `LINE_STRIDE`, and pixels are decoded per `COLOR_DEPTH`.
+ Block-linear byte order follows TRM 20.1.2 and Figure 47
+ (`t210/block_linear.h`, shared with VIC).
+2. The fetch starts at `ADDR_V_OFFSET * LINE_STRIDE + ADDR_H_OFFSET` (TRM
+ 24.11.1): the window's top-left pixel, top-right with H_DIRECTION,
+ bottom-left with V_DIRECTION, in surface terms. It walks away from there
+ per the direction bits, and SCAN_COLUMN walks columns instead of rows
+ (90/270 degrees, TRM Table 122). Pixels before `START_ADDR` or past the
+ surface are black. The result is scaled from `PRESCALED_SIZE` to `SIZE`,
+ nearest-neighbour, and placed at `POSITION`.
+3. The windows are stacked by layer depth and blended per
+ `BLEND_LAYER_CONTROL` and `BLEND_MATCH_SELECT`. The TRM sorts windows by
+ depth into its blend stages without saying which way; lower depth is
+ nearer the top here, as Linux programs later Tegras, and equal depths
+ stack A under D. Hekate's log console (window D, K1 = 200) shows
+ through as it does on the console.
+
+The panel picture is then turned for the host window. When the surface on
+show was turned on its way to the panel, by the DC (SCAN_COLUMN) or by a
+VIC compose (Nyx), the turn is undone. A GUI drawn landscape is then shown
+landscape. A surface drawn straight into portrait (hekate's logo and TUI,
+hwtest) is shown as the panel receives it. `Ctrl+R` / `Ctrl+Shift+R`
+override the turn, and `S` forces pitch or block-linear decoding for
+diagnosis. Until
+the payload first activates a window, the emulator's own framebuffer at
+`FB_BASE` stands in as window A.
+
+A frame whose surfaces' bytes and layout match the previous frame skips the
+rebuild and the texture upload. Surfaces are read straight from the host
+memory behind emulated DRAM. 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.
+
+### VIC (`t210/mmio.cpp`)
+
+bdk drives VIC through the Falcon private-register window. The model keeps
+the config struct's address (`VIC_SC_PRAMBASE`), the slots' source surfaces
+(`VIC_SC_SFC0_BASE_LUMA(n)`) and the target (`VIC_BL_TARGET_BASADR`). On
+`VIC_FC_COMPOSE` it reads bdk's `vic_config_t` from guest memory and draws
+every enabled slot into the target, scaling the source rect onto the
+dest rect, clipped to the target rect, with the output flip X, flip Y and
+transpose applied. The output size is given before the transpose, so a
+transposed target is H x W pixels, which is how the DC then reads it. The
+compose also records the target address and the turn applied, which the
+display uses to undo it. Nyx's 270-degree rotation is flip X then transpose.
+Slot and output surfaces are pitch or block linear (BlkKind 1, with
+2^BlkHeight GOBs per block).
### UART
@@ -310,8 +530,104 @@ All TX append / RX pop is single-threaded -- both the CPU emulation and ImGui
rendering run on the main thread between SDL polls -- so no locking is
needed. The 64 KB TX log trim happens in-place during the write hook.
+### USB device mode (`t210/usb.cpp`)
+
+bdk runs its gadgets - Nyx's USB mass storage for the SD card, eMMC and
+emuMMC, and its Joy-Con gamepad - on one of two device controllers, and both
+are modelled:
+
+- **Erista: the USB2 controller USB1** (0x7D000000, bdk `usbd.c`), an
+ EHCI-derived device controller. Each endpoint half has a 64-byte queue
+ head at `ENDPOINTLISTADDR` (bdk keeps them in the controller's own memory
+ at +0x1000) and a chain of transfer descriptors in DRAM. `ENDPTPRIME`
+ loads the first descriptor and sets its bit in `ENDPTSTATUS` until the
+ transfer retires; each descriptor it reaches is written back with the
+ bytes it did not move, and the endpoint's bit set in `ENDPTCOMPLETE`. A
+ SETUP lands in queue head 0 with `ENDPTSETUPSTAT` bit 0. `USBCMD.RESET`
+ resets the controller and clears itself; `PHY_CLK_VALID` follows the
+ UTMI PHY's enable and reset. bdk copies SETUP packets out with `memcpy()`,
+ so byte and halfword accesses are handled.
+- **Mariko: the XUSB device controller** (0x700D0000, bdk `xusbd.c`), the
+ device side of xHCI. Endpoints are device context indexes (0 control, 2
+ bulk OUT, 3 bulk IN), each with a context (the dequeue pointer and DCS in
+ word 2) and a ring of TRBs the driver fills and closes with a Link TRB,
+ ringing the doorbell. The controller posts events on a two-segment event
+ ring, flipping its cycle bit per pass and raising `ST.IP`: a Port Status
+ Change on a bus reset, a Setup event with a sequence number per SETUP, a
+ Transfer event with the residue and SUCCESS or SHORT_PKT per TRB.
+ `EP_HALT` halts an endpoint (`EP_STCHG` reports it), `EP_RELOAD` reloads a
+ context, and a `PORTSC` write with LWS and RxDetect arms the port.
+
+**The host.** `--usb-host` (or `[usb] host`, or the config window's USB
+device mode box) plugs in a PC; without it nothing is on the cable and a
+gadget waits for a connection until it gives up, as with no cable. The host
+sees whichever controller attaches, waits out the attach debounce, resets
+the bus at high speed and enumerates: device descriptor, `SET_ADDRESS` (with
+its 2 ms recovery), configuration, strings, `SET_CONFIGURATION`. It then gives
+the class driver 100 ms to bind, as a PC does - bdk's XUSB driver stalls a
+`GET_MAX_LUN` that arrives before the gadget asks for it - and runs the
+class:
+
+- *Mass storage (Bulk-Only Transport):* `GET_MAX_LUN`, INQUIRY, TEST UNIT
+ READY (answering the first unit attention with REQUEST SENSE), READ
+ CAPACITY, MODE SENSE(6) for the write-protect bit (asking for just the
+ 4-byte header: bdk stalls bulk IN on a reply shorter than asked), READ(10)
+ of the first 64 and the last 8 blocks, each logged with its CRC32 and
+ checked against the SD image when the disk is its size. Unless the disk is
+ write-protected or the read was wrong, the last 8 blocks are written back
+ as read (WRITE(10), SYNCHRONIZE CACHE) and read again. Then PREVENT ALLOW
+ MEDIUM REMOVAL, an eject (START STOP UNIT, LoEj) and TEST UNIT READY every
+ 500 ms until the gadget detaches, as Linux does.
+- *Mass storage over NBD* (`--usb-host nbd[:port]`, `[usb] nbd_port`): after
+ MODE SENSE the host sends PREVENT MEDIUM REMOVAL and serves the disk on
+ 127.0.0.1 with `t210/nbd.cpp`, a one-client NBD server (fixed newstyle
+ handshake: `EXPORT_NAME`, `LIST`, `INFO` and `GO`, with the export's size,
+ flags and 512-byte minimum block size; simple replies; READ, WRITE, FLUSH,
+ DISC). It is non-blocking and polled from the host every 100 us of
+ emulated time. A READ or WRITE is split into READ(10)s or WRITE(10)s of up
+ to 64 KiB, a FLUSH is a SYNCHRONIZE CACHE, and misaligned or out-of-range
+ requests are refused with `EINVAL` (writes to a write-protected disk with
+ `EPERM`, and the export is read-only). A quiet client gets a TEST UNIT
+ READY every emulated second, as Windows sends. When the client
+ disconnects the host allows removal and ejects as above.
+- *HID:* the report descriptor, `SET_IDLE` with an idle rate of 0 (report on
+ change), then the interrupt IN endpoint is polled. Nyx's gamepad has
+ nothing to report without Joy-Cons.
+
+The host advances on every access to either controller - it runs as far as
+the device and the emulated clock allow - so it needs no thread or main-loop
+hook and runs repeat exactly (an NBD session aside: its requests come when
+the client sends them). It logs `[usb-host]` lines; `RCM_USB_TRACE=1` also
+logs each transfer descriptor, TRB and doorbell.
+
+A device transfer that retires before the host has all it asked for ends the
+host's transfer only on a short packet: fewer bytes than a whole number of
+max-size packets (the queue head or endpoint context gives the size), or a
+zero-length packet, which the USB2 controller appends unless the queue head
+disables it (ZLT; bdk disables it on every endpoint) and the XUSB controller
+never adds. Otherwise the host carries on with the device's next transfer:
+bdk sends a READ(10) under 512 KiB as 32 KiB transfers.
+
+Nyx's SD card mass storage reads back identical to the image, takes the
+write check and reports "Disk ejected" on both SoCs. Over NBD, `nbdinfo`
+negotiates, `qemu-img convert` copies the whole 256 MiB disk byte for byte,
+and a `qemu-io` write lands in the SD image.
+
### Other peripherals (mostly stubs)
+- **CAR and MC.** Registers without behaviour of their own read back what
+ was written - the `CLK_SOURCE_*` dividers, PLL MISC words, the MC's
+ arbitration and address-map configuration - instead of 0.
+- **CAR reset and clock-enable banks.** `RST_DEVICES_x` and `CLK_OUT_ENB_x`
+ (L, H, U, V, W, X, Y) follow direct writes and their SET/CLR strobes, and
+ a read of any of the three returns the bank (TRM 5.2.100) - bdk's
+ `clock_sdmmc_is_active()` reads `RST_DEV_L_SET` and `CLK_ENB_L_SET`. The
+ PCIe and CPU models keep reset banks V, W, Y and clock bank V. The rest
+ start at the TRM reset values (bank U at a real console's reading), so at
+ RCM entry the display is unclocked and `display_init()` does not begin
+ with a panel teardown.
+- **USB PLL.** `UTMIPLL_HW_PWRDN_CFG0.LOCK` is set unless software holds
+ the PLL in IDDQ (the reset state), for bdk's `clock_enable_utmipll()`.
- **PINMUX (`APB_MISC` pad config) and PWM controller (`0x7000A000`).**
No active behaviour, but reads return whatever the payload last wrote
via the global `mmio_regs` cache. Hwtest's "Display backlight & PWM"
@@ -319,29 +635,67 @@ needed. The 64 KB TX log trim happens in-place during the write hook.
function nibble after `display_init`. The previous behaviour
(hardcoded `return 0`) silently dropped the muxed function bits and
made any read-back-style probe see all zeros.
-- **PLLs.** Reads on `PLL_BASE` registers return `ENABLE | LOCK` for any of
- the PLLs Minerva polls during DRAM training.
+- **PLLs.** PLLP and PLLD always read as measured on a console in RCM (up
+ and locked). The other `_BASE` registers read as measured until the
+ payload programs them (PLLM up but unlocked on Erista, the rest down),
+ then read back what was written, dividers included, with LOCK set
+ whenever ENABLE is. That includes PLLMB, which Minerva moves the EMC onto
+ for a frequency change, and PLLC4, which clocks the eMMC at HS200/HS400
+ (not while its IDDQ bit is set); PLLC2, PLLC3, PLLDP and PLLA1 lock the
+ same way.
- **KFUSE.** `STATE` returns `DONE | CRCPASS` immediately so the BDK function
`kfuse_wait_ready` doesn't hang.
- **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.
+ RTC SECONDS counts and is writable, and a MILLI_SECONDS read snapshots it
+ into SHADOW_SECONDS. TMR0..9 record when they were armed, so bdk's
+ `timer_usleep()` - TMR8 plus `FLOW_MODE_STOP_UNTIL_IRQ` - sleeps to the
+ timer's expiry.
+- **Flow controller.** `HALT_COP_EVENTS` MODE 0/1 do not halt; a timed
+ WAITEVENT advances the clock; STOP_UNTIL_IRQ wakes on the first armed
+ timer; an untimed halt ends the run - unless CPU0 is running, in which case
+ the BPMP stays parked and CPU0 runs on (fusee's and hekate's L4T handoff).
- **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
`FW_TYPE`/`MAN_ID`/`DEV_ID` triple, `TSEC.STATUS=0xB0B0B0B0`,
- `KFUSE.STATE=DONE|CRCPASS`, `PLL_BASE=ENABLE|LOCK`. Changing them breaks
+ `KFUSE.STATE=DONE|CRCPASS`, `PLL_BASE.LOCK` once enabled. Changing them breaks
the Hekate init path. They are hardcoded by design.
## 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
@@ -361,15 +715,151 @@ while (te_idx < n && state.emu_usec >= te_events[te_idx].at_us) {
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".
+with `[input]` logging on, copy the timestamps". `--input-script` does the
+same for any payload without a rebuild (`input_script.cpp`): button presses
+and touchscreen taps (` TAP `, in the 1280x720 picture, inverted
+through bdk's touch scaling) keyed to `emu_usec`. That is how Nyx's USB tools
+are reached headless.
+
+## 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.
+`RST_CPUG_CMPLX` starts at its TRM reset value, `0x2000feef`, and the core
+runs once CPURESET0 (bit 0), CORERESET0 (16), L2RESET (24) and NONCPURESET
+(29) are all clear. (bdk also clears PRESETDBG, bit 30, which only resets the
+CoreSight debug logic; bits 15:4 are reserved on this SoC.) It must also be
+able to run; a release that is refused is looked at again whenever one of
+these changes, since silicon starts the moment the last one arrives:
+
+| 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 |
+| 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.
+
+`RST_CPU_CMPLX_SET` (0x340, TRM 5.2.113) carries `RST_CPUG_CMPLX`'s fields and
+reset value: it is the active cluster's view, and the Switch runs the G
+cluster, so it and its CLR partner at 0x344 act on the same reset state.
+`CLK_CPUG_CMPLX` (0x378, TRM 5.2.122) and its SET/CLR strobes (0x460/0x464)
+stop a core's clock with `CPUGn_CLK_STP`; all three read the register back.
+CPU0 with its clock stopped keeps its state and executes nothing while
+emulated time passes, and carries on where it was once the stop is cleared.
+
+**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, 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. The whole config
+aperture and non-prefetchable window are decoded (extended registers read 0,
+unclaimed addresses all-ones, BARs wherever software puts them), and
+MSELECT_CONFIG.ENABLE_PCIE_APERTURE gates them. 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.
+
+**Code the BPMP rewrites.** Stores from one engine never reach the other's
+translation cache, so a stub loaded for a new job at the address of the last
+one would run the old code. The pages CPU0 executes from are remembered with
+a copy of their bytes, and before each slice any that changed have their
+translations dropped (`uc_ctl_remove_cache`). A full `UC_CTL_TB_FLUSH` would
+be simpler, but on Unicorn 2.0 it memsets the whole 1 GB code buffer.
+
+**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 - a
+model timing CPU0's PERST#-after-refclk sequence must use the clock CPU0
+waits on. CPU0 trails the BPMP by up to a slice, so a model both cores touch
+(ACTMON, the Bluetooth chip) compares times rather than subtracting them.
+Releasing CPU0 ends the BPMP's batch at the next block, so the first slice
+starts at once. 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, a core released with its clock stopped, the
+mailbox, WFE parking and the reset;
+`tests/se/`, which runs the SE's RSA, SHA-256, AES and RNG against vectors
+computed in Python (`gen_vectors.py` writes `vectors.h`); `tests/usb/`, a
+mass storage gadget over a RAM disk on each device controller (writable, and
+write-protected in scenario 4) and a HID gadget, which the `--usb-host` PC
+must enumerate, read back (the CRC32s it logs match the payload's), write
+back unchanged unless write-protected and see detach, plus a run with
+nothing on the cable and three NBD runs where `nbd_check.py` negotiates,
+reads the disk, is refused a misaligned and an out-of-range read, writes
+(or is refused on the write-protected disk), pipelines two reads, flushes
+and disconnects, and the disk's CRC32 after the eject must be the client's; and `tests/display/`, one payload built per scenario that drives the display
+controller and VIC the way bdk does (a pitch window; Nyx's VIC turn into
+pitch and into block-linear surfaces; a block-linear VIC source; the DC's
+own column scan with an address offset; a mirrored window with window D
+blended over it). `check.py` compares every pixel of the frame the emulator
+shows with the picture the payload drew. `tests/hwtest/` builds hwtest-rcm
+with distro toolchains and runs its whole sweep; CI runs all four.
## Bug history
These are baked into the current source. Listed here so future maintainers
don't repeat the diagnosis:
-- **Minerva DRAM training** hangs in a `PLL_BASE.LOCK` poll. Fix: always
- report `LOCK | ENABLE`.
+- **Minerva DRAM training** hangs in a `PLL_BASE.LOCK` poll. Fix: report
+ LOCK once the PLL is enabled.
+- **TegraExplorer hung on the eMMC.** Switching SDMMC4 to HS200 enables
+ PLLC4, and TegraExplorer's bdk waits for `PLLC4_BASE.LOCK` with no
+ timeout; the CAR model had no PLLC4, so Erista hung at the key dump and
+ both SoCs at "Browse EMMC". (hekate's newer bdk times the wait out, which
+ hid it.) Fix: PLLC4 locks once enabled, out of IDDQ.
+- **Every payload began with a display teardown.** `CLK_OUT_ENB_L` read a
+ real console's value taken after a payload had brought the display up, so
+ `display_init()` found DISP1 already clocked at RCM entry. Fix: the bank
+ starts at the TRM reset value and follows the payload's writes.
+- **Every USB gadget failed to start.** The USB controllers were plain
+ register caches, so `USBCMD.RESET` never cleared and bdk's
+ `usb_device_init()` timed out; Nyx's USB tools could not even wait for a
+ cable. Fix: both device controllers are modelled, with a PC to plug in.
+- **NBD reads of 64 KiB failed on Nyx.** The host took a device transfer
+ that moved less than it asked for as a short packet, so when bdk sent a
+ 64 KiB READ(10) as two 32 KiB transfers the data phase ended after the
+ first and the CSW read found data. Fix: only a transfer whose last packet
+ is short (or zero-length, including the USB2 controller's own ZLP when the
+ queue head allows it) ends the host's transfer; the test payload now sends
+ reads in 32 KiB transfers too.
+- **Minerva hung Nyx** (hekate 6.5.3 with the stock `bootloader/` folder
+ never reached its GUI). The emulator planted hekate's "watchdog fired"
+ cookie in IRAM so the IPL would skip Minerva; Nyx then trained the DRAM
+ itself, and Minerva spun on
+ `PLLMB_BASE.LOCK` (the CAR model had no PLLMB and read it as 0). Behind
+ that it would have spun on the DLL-enable bit it writes to
+ `EMC_CFG_DIG_DLL` and on `EMC_DIG_DLL_STATUS` lock, timed out on the
+ clock-change handshake, and divided by a zero MR18/MR19 oscillator count,
+ because every EMC register but three read 0. Fix: PLLMB, and the EMC
+ model described in [EMC and DRAM clock](#emc-and-dram-clock). With
+ Minerva working, the cookie is gone too, and hekate boots as on hardware.
- **`kfuse_wait_ready`** loops on `STATE.DONE`. Fix: stub `DONE | CRCPASS`.
- **AMS keygen** retries `tsec_query` 15 times until timeout. Fix: stub
`STATUS = 0xB0B0B0B0`.
@@ -384,6 +874,15 @@ don't repeat the diagnosis:
Now `fstat`-derived from `rawnand.bin.00`.
- **Save header SHA-256** rejected by TE because the SE only modelled AES.
Hence the SHA-256 path in `se_engine.cpp`.
+- **Display stride and window state.** The DC model took the line stride
+ from `PRESCALED_SIZE` rather than `LINE_STRIDE`, kept one set of window
+ parameters shared by all four windows (window D's 656-pixel width leaked
+ into window A), and the block-linear decoder had two GOB address bits
+ swapped. The renderer compensated with per-address heuristics (a
+ "known menu stride" of 2624, forced block-linear decoding of the IPL
+ carveout, a hard-coded 1280x720 geometry for Nyx's framebuffer). Fix:
+ per-window register files latched on `WIN_x_ACT_REQ`, a TRM-exact
+ scan-out, and a VIC that really rotates. The heuristics are gone.
- **PINMUX / PWM read-back** silently returned 0, so any probe that read
back its own pad-mux setting (e.g. hwtest checking `LCD_BL_PWM` is in
PWM0 mode) saw an unconfigured pin even after a successful write. Fix:
@@ -398,13 +897,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/Dockerfile b/Dockerfile
index 1b306df..2f87d35 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,18 +1,21 @@
-FROM ubuntu:24.04
-
-# Build environment for RCM Payload Emulator.
-# git is needed so the container can bootstrap the Dear ImGui submodule
-# (third_party/imgui) from the bind-mounted source tree on first build.
-RUN apt-get update && apt-get install -y --no-install-recommends \
- build-essential \
- pkg-config \
- git \
- libunicorn-dev \
- libsdl2-dev \
- && rm -rf /var/lib/apt/lists/*
-
-WORKDIR /work
-
-# Build command: docker run --rm -v $(pwd):/work rcm_emu
-# (init the imgui submodule if it's missing, then build)
-CMD ["sh", "-c", "git submodule update --init --recursive && make"]
+FROM ubuntu:24.04
+
+# Build environment for RCM Payload Emulator.
+# git is needed so the container can bootstrap the Dear ImGui submodule
+# (third_party/imgui) from the bind-mounted source tree on first build.
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ build-essential \
+ pkg-config \
+ git \
+ libunicorn-dev \
+ libsdl2-dev \
+ && rm -rf /var/lib/apt/lists/*
+
+WORKDIR /work
+
+# Build command: docker run --rm -v $(pwd):/work rcm_emu
+# (init the imgui submodule if it's missing, then build)
+# The source is bind-mounted and owned by the host user, not root: without
+# safe.directory, git refuses to touch it ("dubious ownership") and make never
+# runs.
+CMD ["sh", "-c", "git config --global --add safe.directory /work && git submodule update --init --recursive && make"]
diff --git a/Makefile b/Makefile
index 8a705d0..2e9f5a2 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,48 @@ $(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 $@
+
+tests/se/payload.bin: tests/se/payload.c tests/se/vectors.h tests/se/link.ld
+ $(TEST_CC) $(TEST_CFLAGS) -T tests/se/link.ld -o tests/se/payload.elf $<
+ $(TEST_OBJCOPY) -O binary tests/se/payload.elf $@
+
+USB_PAYLOADS = tests/usb/payload_1.bin tests/usb/payload_2.bin tests/usb/payload_3.bin \
+ tests/usb/payload_4.bin
+
+tests/usb/payload_%.bin: tests/usb/payload.c tests/usb/link.ld
+ $(TEST_CC) $(TEST_CFLAGS) -DSCENARIO=$* -T tests/usb/link.ld -o tests/usb/payload_$*.elf $<
+ $(TEST_OBJCOPY) -O binary tests/usb/payload_$*.elf $@
+
+DISPLAY_SCENARIOS = 1 2 3 4 5 6
+DISPLAY_PAYLOADS = $(DISPLAY_SCENARIOS:%=tests/display/payload_%.bin)
+
+tests/display/payload_%.bin: tests/display/payload.c tests/display/link.ld
+ $(TEST_CC) $(TEST_CFLAGS) -DSCENARIO=$* -T tests/display/link.ld -o tests/display/payload_$*.elf $<
+ $(TEST_OBJCOPY) -O binary tests/display/payload_$*.elf $@
+
+test: $(OUTPUT) tests/ccplex/payload.bin tests/se/payload.bin $(USB_PAYLOADS) $(DISPLAY_PAYLOADS)
+ sh tests/ccplex/run.sh ./$(OUTPUT) tests/ccplex/payload.bin
+ sh tests/se/run.sh ./$(OUTPUT) tests/se/payload.bin
+ sh tests/usb/run.sh ./$(OUTPUT) tests/usb
+ sh tests/display/run.sh ./$(OUTPUT) tests/display
+
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 \
+ tests/se/payload.elf tests/se/payload.bin tests/se/out.log \
+ tests/usb/payload_*.elf tests/usb/payload_*.bin tests/usb/out_*.log \
+ tests/display/payload_*.elf tests/display/payload_*.bin \
+ $(WIN_OUT) $(WIN_OBJS) $(WIN_OBJS:.o=.d)
diff --git a/README.md b/README.md
index af61f8c..61168a0 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,17 +22,29 @@ 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.
+ one-shot script. `--input-script` scripts buttons and touchscreen taps for
+ any payload.
+- Plug an emulated PC into the USB-C port (`--usb-host`): Nyx's USB mass
+ storage and gamepad gadgets enumerate on both the Erista (USB2) and Mariko
+ (XUSB) device controllers, and the PC reads a mass storage disk back,
+ checks it against the SD image, writes a few sectors back unchanged and
+ ejects it. With `--usb-host nbd` the PC serves the disk over NBD instead,
+ so it can be mounted on the machine running the emulator.
- Tweak emulated hardware live (battery, charger, thermal, USB-PD, PMIC,
- fuses, SD insertion) from a side window. See [Live hardware tweaks](#live-hardware-tweaks).
+ fuses, SD insertion, the USB host) from a side window. See [Live hardware tweaks](#live-hardware-tweaks).
- Inspect each Tegra UART port (TX history) and inject keystrokes into the
payload's RX FIFO from a separate console window. See [UART console](#uart-console).
- Read real eMMC (embedded MMC) dumps (`BOOT0`, multi-part `rawnand.bin.NN`)
and decrypt them with XTS-AES-128 (XEX-based Tweaked-codebook with ciphertext
stealing) against keys from `prod.keys`.
-- Serve a real FAT32 SD image to the payload (`--sd sd.img`).
+- Serve a real FAT32 SD image to the payload (`--sd sd.img`). Without one the
+ SD slot is empty.
## Quick start
@@ -141,6 +154,78 @@ 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, SE, USB + display regression payloads (arm-none-eabi-gcc, python3)
+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
+```
+
+`make test` runs small self-contained payloads: one boots CPU0 and checks the
+refusal of an unpowered release, the EL3 entry, the mailbox, a stopped clock,
+WFE parking and the reset; one checks the Security Engine's RSA, SHA-256, AES
+and RNG against vectors computed in Python; one brings up a USB mass storage
+gadget on each device controller (and a HID gadget) for the `--usb-host` PC to
+enumerate, read back and write, and serves it over NBD to a Python client;
+one drives the display controller and VIC and
+compares the frame pixel for pixel. The hwtest scripts run hwtest-rcm's whole
+hardware sweep headless and check that the CPU0-driven Wi-Fi probe enumerates
+the endpoint. CI runs both.
+
+## Mounting a gadget's disk
+
+`--usb-host nbd` turns the emulated PC into a bridge: when a mass storage
+gadget attaches - Nyx's SD card, eMMC or emuMMC under USB tools - the PC
+locks the medium (PREVENT MEDIUM REMOVAL, so Nyx will not unload it from its
+side) and serves it with the NBD protocol on 127.0.0.1, port 10809 or the one
+given as `nbd:`. Every NBD read, write and flush becomes SCSI
+commands to the gadget, so what reaches the SD image goes through bdk's UMS
+code as it would from a real PC. A write-protected disk (Nyx's eMMC in its
+default read-only mode) is exported read-only.
+
+```sh
+./rcm_emu hekate.bin --sd sd.img --usb-host nbd
+# in Nyx: Tools > USB Tools > SD Card, then on the host:
+sudo modprobe nbd max_part=8
+sudo nbd-client 127.0.0.1 10809 /dev/nbd0 -b 512
+sudo mount /dev/nbd0p1 /mnt # ... use it ...
+sudo umount /mnt && sudo nbd-client -d /dev/nbd0 # the disk is ejected
+```
+
+Without root, `qemu-img convert nbd://127.0.0.1:10809 copy.img` takes a
+copy, `qemu-io nbd://127.0.0.1:10809` reads and writes sectors, and
+`nbdfuse` exposes the disk as a file. The session ends when the client
+disconnects: the PC allows removal and ejects, and Nyx reports "Disk
+ejected". The port only listens while a disk is being served. In the config
+window, the USB device mode section has the same switch and port.
+
## Live hardware tweaks
Press `M` in the main window to open a second window that exposes the values
@@ -226,13 +311,15 @@ needed.
| Flag | Argument | Purpose |
| --------------------- | ------------- | --------------------------------------------------------- |
-| `--sd` | `sd.img` | Back the SD card (SDMMC1) with this raw FAT32 image. |
+| `--sd` | `sd.img` | Back the SD card (SDMMC1) with this raw FAT32 image. Without it (and with no `sd.img` in the working directory) the slot is empty. |
| `--boot0` | `BOOT0` | eMMC BOOT0 partition file (SDMMC4). |
| `--rawnand` | `rawnand.bin` | eMMC GPP partition prefix (auto-detects `.00`, `.01`, …). |
| `--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`. |
+| `--usb-host` | `nbd[:port]` (optional) | A PC on the USB-C port. It enumerates whatever USB gadget the payload brings up; a mass storage disk is read back (checked against the SD image), its last 8 sectors are written back unchanged and read again unless it is write-protected, and it is ejected; HID reports are polled. With `nbd` the disk is served over NBD on 127.0.0.1 (port 10809 by default) until the client disconnects, then ejected - see [Mounting a gadget's disk](#mounting-a-gadgets-disk). Logged as `[usb-host]`; `RCM_USB_TRACE=1` traces every transfer. Overrides `[usb] host` and `[usb] nbd_port` in the ini. |
+| `--input-script` | file or spec | Scripted input keyed to emulated time: ` P\|U\|D [hold_ms]` presses POWER / VOL+ / VOL-, ` TAP [hold_ms]` taps the touchscreen at (x, y) in the 1280x720 picture, `+N` times an event N ms after the previous one. Events are separated by `,`, `;` or newlines. |
| `--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,21 +331,26 @@ 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/, se/, usb/, display/, hwtest/"]
- t210 --> mmio["mmio.{h,cpp}
memory_map.h
tegra_bl.h"]
- t210 --> sdmmc["sdmmc.{h,cpp}
SDMMC1 / SDMMC4"]
- t210 --> se["se_engine.{h,cpp}
AES-128, SHA-256"]
+ 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, RSA, RNG"]
t210 --> i2c["i2c3.{h,cpp}
STMFTS / FTS4 touch"]
+ t210 --> usb["usb.{h,cpp}
USB device controllers + host PC"]
- display --> sdl["sdl_display.{h,cpp}
block-linear de-swizzle
+ SDL2"]
+ display --> sdl["sdl_display.{h,cpp}
DC window scan-out
+ SDL2"]
```
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.
@@ -266,9 +358,15 @@ For implementation details, see [DESIGN.md](DESIGN.md).
firmware and the full master-key unwrapping flow are not faithfully emulated.
`--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.
+ file is substituted. The random number generator starts from a fixed
+ seed, so runs repeat.
+- **Single-threaded.** Both cores run in batches on the main thread between
+ SDL event polls. That is also what keeps them deterministic.
+- **The USB host drives mass storage and HID only.** A gadget of another
+ class is enumerated and left configured. Over NBD, one client has the disk
+ per session: when it disconnects - `nbdinfo` and `qemu-img info` do so as
+ soon as they have their answer - the disk is ejected, as a PC ejects a
+ disk it has unmounted.
## Acknowledgements
diff --git a/display/config_window.cpp b/display/config_window.cpp
index ec0753c..60a220d 100644
--- a/display/config_window.cpp
+++ b/display/config_window.cpp
@@ -138,6 +138,8 @@ void reset_to_defaults(EmuState *s) {
X(usb_pd_inserted, "usb_pd", "inserted", 0) \
X(usb_pd_voltage_mv, "usb_pd", "voltage_mv", 0) \
X(usb_pd_amperage_ma, "usb_pd", "amperage_ma", 0) \
+ X(usb_host, "usb", "host", 0) \
+ X(usb_nbd_port, "usb", "nbd_port", 0) \
/* SoC / PMIC */ \
X(pmic_otp, "soc", "pmic_otp", 0) \
X(is_mariko, "soc", "is_mariko", 0) \
@@ -217,11 +219,13 @@ bool config_window_save_ini_impl(const EmuState *s, const char *path) {
fprintf(f, "radio=%s\n", wifi_radio_name(s->wifi_radio.load()));
// Fuses are dumped wholesale — small enough (256 × 4 bytes) and keeps the
- // load path branch-free.
+ // load path branch-free. Zero words too: loading layers the file over
+ // init_fuse_defaults(), so a fuse cleared in the UI and left out here
+ // came back at its default on the next start.
fprintf(f, "\n[fuses]\n");
for (size_t i = 0; i < EmuState::FUSE_WORDS; i++) {
uint32_t v = s->fuse_word[i].load();
- if (v) fprintf(f, "0x%03X=0x%08X\n", (unsigned)(i * 4), v);
+ fprintf(f, "0x%03X=0x%08X\n", (unsigned)(i * 4), v);
}
fclose(f);
@@ -643,6 +647,26 @@ void build_ui(EmuState *state) {
atomic_slider_int("PDO amperage (mA)", state->usb_pd_amperage_ma, 500, 3000, "%d mA");
}
+ if (ImGui::CollapsingHeader("USB device mode")) {
+ // The PC in t210/usb.cpp: it enumerates a gadget the payload brings up.
+ bool host = state->usb_host.load();
+ if (ImGui::Checkbox("PC on the USB-C port (--usb-host)", &host)) {
+ state->usb_host.store(host);
+ }
+ // Mass storage served over NBD instead (--usb-host nbd[:port]);
+ // takes effect when the next disk is attached.
+ bool nbd = state->usb_nbd_port.load() != 0;
+ if (ImGui::Checkbox("Serve mass storage over NBD", &nbd)) {
+ state->usb_nbd_port.store(nbd ? 10809 : 0);
+ }
+ if (nbd) {
+ atomic_slider_int("NBD port", state->usb_nbd_port, 1024, 65535, "%d");
+ ImGui::TextDisabled("127.0.0.1 only; the disk is ejected when the client disconnects.");
+ } else {
+ ImGui::TextDisabled("Mass storage is read back, written back unchanged and ejected;\nHID is polled.");
+ }
+ }
+
if (ImGui::CollapsingHeader("Display")) {
int bl = (int)state->backlight;
if (ImGui::SliderInt("Backlight", &bl, 0, 255)) {
@@ -757,7 +781,7 @@ void build_ui(EmuState *state) {
// Each row corresponds to a FUSE_BASE offset in Hekate's
// bdk/soc/fuse.h. Defaults match a typical Erista golden sample.
atomic_hex_input("0x100 PRODUCTION_MODE", state->fuse_at(0x100));
- atomic_hex_input("0x110 SKU_INFO", state->fuse_at(0x110));
+ atomic_hex_input("0x110 SKU_INFO (0x83 ODIN; Minerva needs it)", state->fuse_at(0x110));
atomic_hex_input("0x114 CPU_SPEEDO_0", state->fuse_at(0x114));
atomic_hex_input("0x118 CPU_IDDQ", state->fuse_at(0x118));
atomic_hex_input("0x128 OPT_FT_REV", state->fuse_at(0x128));
@@ -889,6 +913,7 @@ void build_ui(EmuState *state) {
}
ImGui::SameLine();
if (ImGui::Button("Reboot")) {
+ state->reboot_cold = true; // the user's reset is a power cycle
state->reboot_requested.store(true);
}
ImGui::Text("emu_usec: %llu", (unsigned long long)state->emu_usec);
@@ -944,7 +969,13 @@ bool config_window_init() {
fprintf(stderr, "[config_window] SDL_CreateWindow failed: %s\n", SDL_GetError());
return false;
}
- g_renderer = SDL_CreateRenderer(g_window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
+ // No PRESENTVSYNC: this window renders on the emulation thread, and
+ // vsync would stall the emulated CPU for up to a frame per present.
+ g_renderer = SDL_CreateRenderer(g_window, -1, SDL_RENDERER_ACCELERATED);
+ // Same fallback as the main window: no GPU renderer (a headless run, a
+ // VM without GL) should not cost the window altogether.
+ if (!g_renderer)
+ g_renderer = SDL_CreateRenderer(g_window, -1, SDL_RENDERER_SOFTWARE);
if (!g_renderer) {
fprintf(stderr, "[config_window] SDL_CreateRenderer failed: %s\n", SDL_GetError());
SDL_DestroyWindow(g_window);
diff --git a/display/console_window.cpp b/display/console_window.cpp
index 10623c0..1413c4d 100644
--- a/display/console_window.cpp
+++ b/display/console_window.cpp
@@ -165,7 +165,13 @@ bool console_window_init()
fprintf(stderr, "[console_window] SDL_CreateWindow failed: %s\n", SDL_GetError());
return false;
}
- g_renderer = SDL_CreateRenderer(g_window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
+ // No PRESENTVSYNC: this window renders on the emulation thread, and
+ // vsync would stall the emulated CPU for up to a frame per present.
+ g_renderer = SDL_CreateRenderer(g_window, -1, SDL_RENDERER_ACCELERATED);
+ // Same fallback as the main window: no GPU renderer (a headless run, a
+ // VM without GL) should not cost the window altogether.
+ if (!g_renderer)
+ g_renderer = SDL_CreateRenderer(g_window, -1, SDL_RENDERER_SOFTWARE);
if (!g_renderer) {
fprintf(stderr, "[console_window] SDL_CreateRenderer failed: %s\n", SDL_GetError());
SDL_DestroyWindow(g_window);
diff --git a/display/sdl_display.cpp b/display/sdl_display.cpp
index 25e9852..00bc449 100644
--- a/display/sdl_display.cpp
+++ b/display/sdl_display.cpp
@@ -2,10 +2,12 @@
#include "config_window.h"
#include "console_window.h"
#include "../emu_state.h"
+#include "../t210/block_linear.h"
#include "../t210/memory_map.h"
#include
#include
+#include
#include
#include
@@ -30,6 +32,8 @@ static bool event_targets_window(const SDL_Event &ev, Uint32 wid) {
static SDL_Window *window = nullptr;
static SDL_Renderer *renderer = nullptr;
static SDL_Texture *texture = nullptr;
+// The last converted frame (ARGB8888, out_w x out_h), reused across updates.
+static std::vector g_frame;
static int g_swizzle_override =
-1; // -1 = Auto, 0 = Pitch Linear, 2 = Block Linear
@@ -41,8 +45,10 @@ bool sdl_display_init() {
SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);
if (!window)
return false;
- renderer = SDL_CreateRenderer(
- window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
+ // No PRESENTVSYNC. The CPU runs on this same thread and the main loop
+ // already paces redraws to ~60 Hz by wall clock; with vsync on, each
+ // SDL_RenderPresent could block the emulated CPU for up to a whole frame.
+ renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
if (!renderer)
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_SOFTWARE);
if (!renderer)
@@ -51,139 +57,345 @@ bool sdl_display_init() {
return true;
}
+// ---- Scan-out ------------------------------------------------------------
+//
+// The frame is built the way the display controller builds it (TRM 24):
+// every enabled window's surface is fetched per its SURFACE_KIND (pitch,
+// 16x16 tiled or block linear) and LINE_STRIDE, turned per WIN_OPTIONS
+// (H/V direction, SCAN_COLUMN), scaled from PRESCALED_SIZE to SIZE and
+// placed at POSITION, the windows stacked by layer depth and blended per
+// BLEND_*. The result is the 720x1280 portrait picture the panel receives.
+//
+// For the host window that picture is then turned: when the surface on show
+// was itself turned on its way to the panel - by the DC (SCAN_COLUMN) or by
+// a VIC compose, as Nyx does - the turn is undone, so a GUI drawn landscape
+// is shown landscape. A surface drawn straight into portrait (hekate's TUI,
+// hwtest) is shown as the panel gets it. Ctrl+R / Ctrl+Shift+R override the
+// turn.
+
+namespace {
+
+constexpr uint32_t kPanelW = 720, kPanelH = 1280;
+
+// A picture turn as a 2x2 matrix on centred coordinates: out = M * in.
+struct Turn {
+ int a, b, c, d; // [[a b] [c d]]
+};
+
+Turn turn_of(uint32_t xf) { // dcwin::XF_* (flip, then transpose)
+ int fx = (xf & dcwin::XF_FLIP_X) ? -1 : 1;
+ int fy = (xf & dcwin::XF_FLIP_Y) ? -1 : 1;
+ if (xf & dcwin::XF_TRANSPOSE)
+ return {0, fy, fx, 0};
+ return {fx, 0, 0, fy};
+}
+
+Turn operator*(const Turn &l, const Turn &r) {
+ return {l.a * r.a + l.b * r.c, l.a * r.b + l.b * r.d,
+ l.c * r.a + l.d * r.c, l.c * r.b + l.d * r.d};
+}
+
+// The view rotation (as the render loop applies it, see rot below) that
+// undoes turn t, or 0 when t is a mirror image, which no rotation undoes.
+int undo_rot(const Turn &t) {
+ if (t.a * t.d - t.b * t.c != 1)
+ return 0;
+ Turn inv = {t.a, t.c, t.b, t.d}; // a rotation's inverse is its transpose
+ if (inv.a == 0 && inv.b == -1)
+ return 1;
+ if (inv.a == -1)
+ return 2;
+ if (inv.a == 0 && inv.b == 1)
+ return 3;
+ return 0;
+}
+
+uint32_t depth_bpp(uint32_t depth) {
+ if (depth <= 3)
+ return 1; // palettised
+ if (depth <= 7 || (depth >= 0x1E && depth <= 0x21))
+ return 2;
+ return 4;
+}
+
+// One pixel of a DC_WIN_COLOR_DEPTH format as ARGB8888.
+uint32_t depth_argb(const uint8_t *p, uint32_t depth) {
+ auto x5 = [](uint32_t v) { return (v << 3) | (v >> 2); };
+ auto x6 = [](uint32_t v) { return (v << 2) | (v >> 4); };
+ switch (depth) {
+ case 0x4: { // B4G4R4A4
+ uint32_t v = p[0] | (p[1] << 8);
+ return ((v >> 12) * 0x11u) << 24 | ((v >> 8) & 0xF) * 0x11u << 16 |
+ ((v >> 4) & 0xF) * 0x11u << 8 | (v & 0xF) * 0x11u;
+ }
+ case 0x5: { // B5G5R5A
+ uint32_t v = p[0] | (p[1] << 8);
+ return ((v & 0x8000) ? 0xFF000000u : 0) | x5((v >> 10) & 0x1F) << 16 |
+ x5((v >> 5) & 0x1F) << 8 | x5(v & 0x1F);
+ }
+ case 0x7: { // AB5G5R5
+ uint32_t v = p[0] | (p[1] << 8);
+ return ((v & 1) ? 0xFF000000u : 0) | x5(v >> 11) << 16 |
+ x5((v >> 6) & 0x1F) << 8 | x5((v >> 1) & 0x1F);
+ }
+ case 0xD: // R8G8B8A8
+ case 0xF:
+ return (uint32_t)p[3] << 24 | (uint32_t)p[0] << 16 |
+ (uint32_t)p[1] << 8 | p[2];
+ default:
+ break;
+ }
+ switch (depth_bpp(depth)) {
+ case 1:
+ return 0xFF000000u | p[0] * 0x010101u;
+ case 2: { // B5G6R5 and anything else 16-bit
+ uint32_t v = p[0] | (p[1] << 8);
+ return 0xFF000000u | x5(v >> 11) << 16 | x6((v >> 5) & 0x3F) << 8 |
+ x5(v & 0x1F);
+ }
+ default: // B8G8R8A8 (bytes B, G, R, A)
+ return (uint32_t)p[3] << 24 | (uint32_t)p[2] << 16 |
+ (uint32_t)p[1] << 8 | p[0];
+ }
+}
+
+struct Win {
+ int idx = 0;
+ uint64_t addr = 0;
+ uint32_t depth = 0, bpp = 4, kind = 0, gob_h = 1, stride = 0, gobs = 0;
+ uint32_t src_w = 0, src_h = 0; // the fetch, before the DC turns it
+ uint32_t x0 = 0, y0 = 0; // first pixel fetched (ADDR_H/V_OFFSET)
+ uint32_t cols = 0, rows = 0; // surface extent from START_ADDR
+ uint32_t pre_w = 0, pre_h = 0; // PRESCALED_SIZE, in pixels (post-turn)
+ uint32_t out_w = 0, out_h = 0; // SIZE
+ int32_t x = 0, y = 0;
+ uint32_t xf = 0, layer = 0, blend_layer = 0, blend_match = 0;
+ size_t len = 0;
+ const uint8_t *mem = nullptr;
+ std::vector copy; // when the surface is not in the DRAM window
+};
+
+// Byte offset of surface pixel (sx, sy).
+inline size_t fetch_off(const Win &w, uint32_t sx, uint32_t sy) {
+ uint32_t xb = sx * w.bpp;
+ switch (w.kind) {
+ case 1: // 16x16-byte tiles, row-major
+ return (size_t)(sy / 16) * w.stride * 16 + (xb / 16) * 256 +
+ (sy % 16) * 16 + (xb % 16);
+ case 2: // block linear
+ return bl_offset(xb, sy, w.gobs, w.gob_h);
+ default:
+ return (size_t)sy * w.stride + xb;
+ }
+}
+
+// Build window w from its active register file; false if it shows nothing.
+bool load_window(EmuState *state, uc_engine *uc, int idx, const uint32_t *r,
+ int swizzle_override, Win &w) {
+ if (!(r[dcwin::OPTIONS] & dcwin::WIN_ENABLE))
+ return false;
+ w.idx = idx;
+ w.depth = r[dcwin::COLOR_DEPTH] & 0x7F;
+ w.bpp = depth_bpp(w.depth);
+ uint32_t sk = r[dcwin::SURFACE_KIND];
+ w.kind = sk & 3;
+ w.gob_h = 1u << ((sk >> 4) & 7);
+ if (swizzle_override == 0) {
+ w.kind = 0;
+ } else if (swizzle_override == 2 && w.kind != 2) {
+ w.kind = 2;
+ w.gob_h = 16;
+ }
+ w.out_w = r[dcwin::SIZE] & 0x1FFF;
+ w.out_h = (r[dcwin::SIZE] >> 16) & 0x1FFF;
+ w.pre_w = (r[dcwin::PRESCALED] & 0x7FFF) / w.bpp;
+ w.pre_h = (r[dcwin::PRESCALED] >> 16) & 0x1FFF;
+ if (!w.pre_w || !w.pre_h) { // never programmed: no scaling
+ w.pre_w = w.out_w;
+ w.pre_h = w.out_h;
+ }
+ if (!w.out_w || !w.out_h)
+ return false;
+ uint32_t opt = r[dcwin::OPTIONS];
+ w.xf = ((opt & dcwin::H_DIRECTION) ? dcwin::XF_FLIP_X : 0) |
+ ((opt & dcwin::V_DIRECTION) ? dcwin::XF_FLIP_Y : 0) |
+ ((opt & dcwin::SCAN_COLUMN) ? dcwin::XF_TRANSPOSE : 0);
+ // SCAN_COLUMN walks the surface's columns: it is pre_h wide, pre_w tall.
+ bool column = w.xf & dcwin::XF_TRANSPOSE;
+ w.src_w = column ? w.pre_h : w.pre_w;
+ w.src_h = column ? w.pre_w : w.pre_h;
+ w.x = (int16_t)(r[dcwin::POSITION] & 0xFFFF);
+ w.y = (int16_t)(r[dcwin::POSITION] >> 16);
+ w.blend_layer = r[dcwin::BLEND_LAYER];
+ w.blend_match = r[dcwin::BLEND_MATCH];
+ w.layer = w.blend_layer & 0xFF;
+ w.stride = r[dcwin::LINE_STRIDE] & 0xFFFF;
+ if (!w.stride)
+ w.stride = w.src_w * w.bpp;
+ w.addr = (uint64_t)r[dcwin::START_ADDR] + (int64_t)state->manual_offset;
+ // The fetch starts at START_ADDR + ADDR_V_OFFSET * LINE_STRIDE +
+ // ADDR_H_OFFSET (TRM 24.11.1): the window's top-left pixel, or top-right
+ // with H_DIRECTION, bottom-left with V_DIRECTION - in surface terms,
+ // before SCAN_COLUMN turns it - and walks away from it.
+ uint64_t start = (uint64_t)r[dcwin::ADDR_V_OFF] * w.stride +
+ r[dcwin::ADDR_H_OFF];
+ w.y0 = (uint32_t)std::min(start / w.stride, 0xFFFF);
+ w.x0 = (uint32_t)(start % w.stride) / w.bpp;
+ w.cols = w.stride / w.bpp;
+ w.rows = (w.xf & dcwin::XF_FLIP_Y) ? w.y0 + 1 : w.y0 + w.src_h;
+ switch (w.kind) {
+ case 2:
+ w.gobs = (w.stride + 63) / 64;
+ w.len = bl_size(w.gobs, w.gob_h, w.rows);
+ break;
+ case 1:
+ w.len = (size_t)w.stride * ((w.rows + 15) / 16) * 16;
+ break;
+ default:
+ w.len = (size_t)w.stride * w.rows;
+ break;
+ }
+ if (w.len == 0 || w.len > 64u * 1024 * 1024)
+ return false;
+ if (state->dram_low_ptr && w.addr >= DRAM_BASE &&
+ w.addr + w.len <= DRAM_BASE + DRAM_WINDOW_SIZE) {
+ w.mem = state->dram_low_ptr + (w.addr - DRAM_BASE);
+ } else {
+ w.copy.resize(w.len);
+ if (uc_mem_read(uc, w.addr, w.copy.data(), w.len) != UC_ERR_OK)
+ return false;
+ w.mem = w.copy.data();
+ }
+ return true;
+}
+
+// Blend factor (0..255) per BLEND_MATCH_SELECT (TRM 24.10.13).
+uint32_t src_factor(uint32_t sel, uint32_t k1, uint32_t sa) {
+ switch (sel) {
+ case 1: return 255;
+ case 2: case 3: return k1; // K1, K1 x dst alpha (opaque dst)
+ case 4: return 255 - k1; // 1 - K1 x dst alpha
+ case 5: return k1 * sa / 255; // K1 x src alpha
+ default: return 0;
+ }
+}
+uint32_t dst_factor(uint32_t sel, uint32_t k1, uint32_t k2, uint32_t sa) {
+ switch (sel) {
+ case 1: return 255;
+ case 2: case 4: return k1;
+ case 3: return k2;
+ case 5: case 7: return 255 - k1;
+ case 6: return 255 - k1 * sa / 255;
+ default: return 0;
+ }
+}
+
+// Draw window w onto the panel picture.
+void draw_window(const Win &w, std::vector &panel) {
+ bool blend = !(w.blend_layer & (1u << 24));
+ uint32_t k1 = (w.blend_layer >> 8) & 0xFF, k2 = (w.blend_layer >> 16) & 0xFF;
+ uint32_t ssel = w.blend_match & 7, dsel = (w.blend_match >> 4) & 7;
+ bool hflip = w.xf & dcwin::XF_FLIP_X, vflip = w.xf & dcwin::XF_FLIP_Y;
+ bool column = w.xf & dcwin::XF_TRANSPOSE;
+ // Column scaling map, worked out once per window rather than per pixel.
+ static std::vector txs;
+ txs.resize(w.out_w);
+ for (uint32_t ox = 0; ox < w.out_w; ox++)
+ txs[ox] = (uint32_t)((uint64_t)ox * w.pre_w / w.out_w);
+ for (uint32_t oy = 0; oy < w.out_h; oy++) {
+ int32_t py = w.y + (int32_t)oy;
+ if (py < 0 || py >= (int32_t)kPanelH)
+ continue;
+ uint32_t ty = (uint32_t)((uint64_t)oy * w.pre_h / w.out_h);
+ for (uint32_t ox = 0; ox < w.out_w; ox++) {
+ int32_t px = w.x + (int32_t)ox;
+ if (px < 0 || px >= (int32_t)kPanelW)
+ continue;
+ uint32_t tx = txs[ox];
+ // (tx, ty) is post-turn; walk it back to the surface.
+ uint32_t a = column ? ty : tx, b = column ? tx : ty;
+ int64_t sx = hflip ? (int64_t)w.x0 - a : (int64_t)w.x0 + a;
+ int64_t sy = vflip ? (int64_t)w.y0 - b : (int64_t)w.y0 + b;
+ if (sx < 0 || sy < 0 || sx >= w.cols || sy >= w.rows)
+ continue; // before START_ADDR or past the surface
+ size_t off = fetch_off(w, (uint32_t)sx, (uint32_t)sy);
+ if (off + w.bpp > w.len)
+ continue;
+ uint32_t s = depth_argb(w.mem + off, w.depth);
+ uint32_t &d = panel[(size_t)py * kPanelW + px];
+ if (!blend) {
+ d = s | 0xFF000000u;
+ continue;
+ }
+ uint32_t sa = s >> 24;
+ uint32_t fs = src_factor(ssel, k1, sa), fd = dst_factor(dsel, k1, k2, sa);
+ uint32_t o = 0xFF000000u;
+ for (int sh = 0; sh < 24; sh += 8) {
+ uint32_t c = (((s >> sh) & 0xFF) * fs + ((d >> sh) & 0xFF) * fd) / 255;
+ o |= (c > 255 ? 255 : c) << sh;
+ }
+ d = o;
+ }
+ }
+}
+
+} // namespace
+
void sdl_display_update(EmuState *state, uc_engine *uc) {
if (!renderer)
return;
- uint32_t width = state->fb_width, height = state->fb_height,
- stride = state->fb_stride;
- if (width < 16 || height < 16)
- return;
-
- // If the current fb_addr is empty but we have a saved Window A with
- // content, prefer the Window A surface. This handles the case where
- // Hekate's TUI renders to IPL_FB (0xF5A00000) but the DC was repointed
- // to NYX_FB (0xF6200000) by a failed Nyx init sequence.
- uint64_t eff_addr = state->fb_addr;
- if (state->winA_addr && state->winA_addr != eff_addr) {
- // Quick check: sample a few dwords from fb_addr.
- uint32_t sample[4] = {0};
- uc_mem_read(uc, eff_addr, sample, sizeof(sample));
- bool empty = (sample[0] == 0 && sample[1] == 0 &&
- sample[2] == 0 && sample[3] == 0);
- if (empty) {
- // Check if winA_addr has content.
- uc_mem_read(uc, state->winA_addr, sample, sizeof(sample));
- if (sample[0] != 0 || sample[1] != 0 ||
- sample[2] != 0 || sample[3] != 0) {
- eff_addr = state->winA_addr;
- width = state->winA_w;
- height = state->winA_h;
- stride = state->winA_stride;
- }
- }
+ // The windows on show, bottom first. Until the payload programs the DC,
+ // the emulator's own framebuffer stands in as window A.
+ std::vector wins;
+ uint32_t boot_win[dcwin::kRegs] = {};
+ boot_win[dcwin::OPTIONS] = dcwin::WIN_ENABLE;
+ boot_win[dcwin::COLOR_DEPTH] = 0xC; // B8G8R8A8
+ boot_win[dcwin::SIZE] = kPanelH << 16 | kPanelW;
+ boot_win[dcwin::LINE_STRIDE] = kPanelW * 4;
+ boot_win[dcwin::BLEND_LAYER] = dcwin::BLEND_LAYER_RESET;
+ boot_win[dcwin::START_ADDR] = (uint32_t)FB_BASE;
+ for (int i = 0; i < 4; i++) {
+ const uint32_t *r = state->dc_programmed ? state->dc_win_active[i]
+ : (i == 0 ? boot_win : nullptr);
+ if (!r)
+ continue;
+ Win w;
+ if (load_window(state, uc, i, r, g_swizzle_override, w))
+ wins.push_back(std::move(w));
}
+ // The TRM sorts windows by depth into the blend stages (24.3.12) without
+ // saying which way; lower depth nearer the top, as Linux programs later
+ // Tegras (depth = 255 - zpos). Equal depths stack A (bottom) to D (top),
+ // which puts hekate's log window D over A, as its blending expects.
+ std::stable_sort(wins.begin(), wins.end(), [](const Win &l, const Win &r) {
+ return l.layer > r.layer;
+ });
- // Helper: is the address inside the IPL framebuffer carveout?
- auto addr_in_ipl_fb = [](uint64_t a) -> bool {
- return a >= FB_BASE && a < FB_BASE + FB_SIZE;
- };
-
- int rot = state->rotation_override;
-
- uint32_t sw = state->fb_swizzle;
- uint32_t eff_stride = stride;
- uint32_t bpp = 4;
- uint32_t bh = state->fb_bh ? state->fb_bh : 16; // Block height in GOBs
-
- // --- OVERRIDES & AUTO-DETECTS ---
- constexpr uint64_t kNyxFbBase = 0xF6200000ULL;
-
- if (g_swizzle_override != -1) {
- sw = (uint32_t)g_swizzle_override; // Manual User Override (S Key)
- } else if (eff_addr == kNyxFbBase) {
- // Nyx GUI uses VIC to rotate its 1280x720 landscape UI into 720x1280 portrait mode (NYX_FB_ADDRESS).
- // Our emulator's mock VIC only memcpys the data, so 0xF6200000 actually holds a 1280x720 landscape image!
- // Since the DC is programmed for 720x1280, it will scramble it.
- // We override the display geometry here to render the raw 1280x720 memory correctly.
- sw = 0;
- width = 1280;
- height = 720;
- eff_stride = 1280 * 4; // 32-bit XRGB
- rot = 0;
- bh = 4;
- } else if (eff_addr == FB_BASE && sw == 0 && width == 720u &&
- height == 1280u && eff_stride == width * 4u) {
- // Hekate TUI or static bootlogo: natively rendered as 720x1280 pitch-linear portrait.
- // Do not apply any automatic layout overrides.
- sw = 0;
- rot = 0; // The UI is drawn sideways in memory to appear upright on a landscape physical Switch screen.
- // On PC, we want to view it rotated so it resembles the physical landscape Switch!
- } else if (addr_in_ipl_fb(eff_addr) && sw == 0) {
- // IPL carveout with Sw=0: Hekate writes block-linear data but the DC
- // surface kind says pitch. Detect when the stride/dimensions don't
- // match a coherent pitch-linear layout and force block-linear decode.
- bool coherent_pitch =
- width > 0 && (eff_stride == width * 4u || eff_stride == width * 2u);
- bool portrait_stride_mismatch =
- height == 1280u && width == 720u && eff_stride != width * 4u;
- bool known_menu_stride = (eff_stride == 2624u && !coherent_pitch);
-
- // crop_portrait only forces BL when stride is incoherent — if stride
- // matches width*bpp, the data may already be VIC-de-swizzled pitch.
- bool crop_portrait_incoherent =
- height == 1280u && width < 720u && width >= 640u && !coherent_pitch;
-
- if (!coherent_pitch || portrait_stride_mismatch || known_menu_stride ||
- crop_portrait_incoherent) {
- sw = 2; // Force block-linear decode
- bh = 4; // Hekate menu uses BH=4
- }
+ // The largest window decides how the picture is turned for the host.
+ const Win *primary = nullptr;
+ for (const Win &w : wins)
+ if (!primary || (uint64_t)w.out_w * w.out_h >
+ (uint64_t)primary->out_w * primary->out_h ||
+ ((uint64_t)w.out_w * w.out_h ==
+ (uint64_t)primary->out_w * primary->out_h &&
+ w.idx < primary->idx))
+ primary = &w;
+ int rot = 0;
+ if (primary) {
+ Turn t = turn_of(primary->xf);
+ if (state->vic_out_addr && primary->addr == state->vic_out_addr)
+ t = t * turn_of(state->vic_out_xform);
+ rot = undo_rot(t);
}
-
- // Final heuristic: NEVER auto-rotate 720x1280 portrait buffers to landscape!
- if (rot == -1) {
- if (width == 720 && height == 1280) {
- rot = 0; // Hekate already drew it sideways for physical portrait, so rot=0 makes it look like a phone on PC monitor!
- // Actually wait: if drawn upright in memory (row-by-row), then rot=0 produces a tall 720x1280 window on PC where it is perfectly upright!
- // The user wants the white lines to be horizontal. This means we MUST let the window be 720x1280!
- } else {
- rot = (height > width) ? 1 : 0; // Legacy heuristic for other stuff
- }
- }
-
- // Manual rotation override always wins. The auto-detect branches above set
- // rot = 0 for Nyx and Hekate TUI surfaces; if the user pressed R/Shift+R
- // they expect the rotation to actually change, regardless of what the
- // auto-detect picked. -1 means "use auto-detect", anything else overrides.
+ state->last_auto_rot.store((uint32_t)rot);
if (state->rotation_override != -1)
rot = state->rotation_override & 3;
- // --- Compute GOB stride for block-linear ---
- uint32_t sw_gobs = (width * bpp + 63) / 64;
- if (sw == 2) {
- // For IPL carveout portrait surfaces, Hekate allocates a full 720px-wide
- // BL surface even when the DC window is cropped to 656px.
- if (addr_in_ipl_fb(state->fb_addr) && state->fb_addr != kNyxFbBase &&
- bpp == 4 && height == 1280u && width >= 640u && width <= 720u) {
- uint32_t sw_720 = (720u * bpp + 63) / 64u;
- if (sw_gobs < sw_720)
- sw_gobs = sw_720;
- }
- // If DC provides a stride that's GOB-aligned, prefer it
- if (eff_stride >= 64u && (eff_stride % 64u) == 0u) {
- uint32_t stride_gobs = eff_stride / 64u;
- if (stride_gobs > sw_gobs)
- sw_gobs = stride_gobs;
- }
- }
-
- uint32_t out_w = (rot & 1) ? height : width;
- uint32_t out_h = (rot & 1) ? width : height;
-
- // Cache the effective rotation and output dims so the SDL event handler can
- // invert the framebuffer→window transform when mapping mouse → panel coords.
- state->last_rot.store((uint32_t)((rot < 0) ? 0 : (rot & 3)));
+ uint32_t out_w = (rot & 1) ? kPanelH : kPanelW;
+ uint32_t out_h = (rot & 1) ? kPanelW : kPanelH;
+ // The SDL event handler inverts this view to map mouse -> panel coords.
+ state->last_rot.store((uint32_t)rot);
state->last_out_w.store(out_w);
state->last_out_h.store(out_h);
@@ -191,8 +403,8 @@ void sdl_display_update(EmuState *state, uc_engine *uc) {
if (!texture || out_w != last_w || out_h != last_h) {
if (texture)
SDL_DestroyTexture(texture);
- // Use ARGB8888: natively matches Tegra's BGRA memory layout on Little
- // Endian
+ // ARGB8888 matches the B8G8R8A8 bytes of a Tegra surface on a
+ // little-endian host.
texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888,
SDL_TEXTUREACCESS_STREAMING, out_w, out_h);
last_w = out_w;
@@ -200,138 +412,84 @@ void sdl_display_update(EmuState *state, uc_engine *uc) {
SDL_SetWindowSize(window, out_w, out_h);
}
- static uint32_t last_log_p[6] = {0}; // Addr, W, H, Rot, Sw, BH
- if (state->fb_addr != last_log_p[0] || width != last_log_p[1] ||
- height != last_log_p[2] || (uint32_t)rot != last_log_p[3] ||
- sw != last_log_p[4] || bh != last_log_p[5]) {
- printf("[display] LATCH: 0x%X (%dx%d), Rot: %d (Manual: %d), Sw: %d, "
- "GOBs: %u, BH: %u, BPP: %u\n",
- (uint32_t)state->fb_addr, width, height, rot,
- state->rotation_override, sw, sw_gobs, bh, bpp * 8);
- last_log_p[0] = state->fb_addr;
- last_log_p[1] = width;
- last_log_p[2] = height;
- last_log_p[3] = rot;
- last_log_p[4] = sw;
- last_log_p[5] = bh;
+ // Skip the rebuild and the texture upload when neither the surfaces' bytes
+ // nor the way they are laid out changed since the last frame - the common
+ // case for a payload sitting on a menu or waiting on hardware.
+ std::vector shape = {(uint64_t)rot, wins.size()}, where;
+ for (const Win &w : wins) {
+ shape.insert(shape.end(),
+ {(uint64_t)w.idx, w.addr, w.len, w.depth, w.kind, w.gob_h,
+ w.stride, (uint64_t)w.pre_w << 32 | w.pre_h,
+ (uint64_t)w.out_w << 32 | w.out_h, w.xf, w.blend_layer,
+ w.blend_match, (uint64_t)w.x0 << 32 | w.y0});
+ where.push_back((uint64_t)(uint32_t)w.x << 32 | (uint32_t)w.y);
}
+ static std::vector last_shape, last_where;
+ static std::vector last_bytes;
+ size_t total = 0;
+ for (const Win &w : wins)
+ total += w.len;
+ bool same = shape == last_shape && where == last_where &&
+ last_bytes.size() == total;
+ for (size_t i = 0, pos = 0; same && i < wins.size(); pos += wins[i++].len)
+ same = memcmp(last_bytes.data() + pos, wins[i].mem, wins[i].len) == 0;
- eff_addr =
- (eff_addr ? eff_addr : FB_BASE) +
- (uint64_t)(int64_t)state->manual_offset;
+ static bool snapshot_pending = true;
+ if (!same) {
+ // Log layout changes, but not moves: bdk slides its log window in.
+ if (shape != last_shape)
+ printf("[display] scan-out: %zu window(s), view %ux%u, rot %d (auto %u)\n",
+ wins.size(), out_w, out_h, rot, state->last_auto_rot.load());
+ last_shape = shape;
+ last_where = where;
+ last_bytes.resize(total);
+ size_t pos = 0;
+ for (const Win &w : wins) {
+ memcpy(last_bytes.data() + pos, w.mem, w.len);
+ pos += w.len;
+ }
+ snapshot_pending = true;
- // Compute framebuffer byte size
- size_t fb_size = (sw == 2) ? ((size_t)sw_gobs * ((height + 7) / 8) * 512)
- : ((size_t)eff_stride * height);
- if (fb_size < 1024)
- return;
- if (sw != 2 && eff_stride < 16)
- return; // Pitch-linear sanity check only
- if (fb_size > 32 * 1024 * 1024)
- fb_size = 32 * 1024 * 1024;
+ static std::vector panel;
+ panel.assign((size_t)kPanelW * kPanelH, 0xFF000000u); // black background
+ for (const Win &w : wins)
+ draw_window(w, panel);
- std::vector buf(fb_size);
- if (uc_mem_read(uc, eff_addr, buf.data(), fb_size) == UC_ERR_OK) {
- std::vector proc(out_w * out_h,
- 0xFF000000); // Initialize opaque black
-
- for (uint32_t sy = 0; sy < height; sy++) {
- for (uint32_t sx = 0; sx < width; sx++) {
- uint32_t off = 0;
- if (sw == 2) {
- if (bpp == 4) {
- // Use tegra_bl_byte_off_rgba8888 formula inline for 32bpp
- uint32_t gob_x = sx / 16u;
- uint32_t pixel_x = sx % 16u;
- uint32_t gob_y = sy / 8u;
- uint32_t line_y = sy % 8u;
- uint32_t block_y = gob_y / bh;
- uint32_t gob_in_block_y = gob_y % bh;
-
- uint32_t idx =
- (block_y * sw_gobs * bh * 128u) + (gob_x * bh * 128u) +
- (gob_in_block_y * 128u) + (pixel_x & 3u) +
- ((line_y & 1u) << 2) + ((pixel_x & 4u) << 1) +
- ((line_y & 2u) << 3) + ((pixel_x & 8u) << 2) +
- ((line_y & 4u) << 4);
- off = idx; // Already in uint32 units
- } else {
- // 16bpp block-linear (Nyx RGB565)
- uint32_t byte_x = sx * bpp;
- uint32_t gx = byte_x / 64;
- uint32_t px_in = byte_x % 64;
- uint32_t gy = sy / 8;
- uint32_t ly = sy % 8;
- uint32_t gob_off = ((ly >> 1) << 7) + ((px_in >> 4) << 5) +
- ((ly & 1) << 4) + (px_in & 0xF);
- uint32_t gob_idx =
- (gy / bh) * (sw_gobs * bh) + gx * bh + (gy % bh);
- uint32_t byte_off = gob_idx * 512 + gob_off;
- // Read 16-bit pixel and expand to 32-bit ARGB
- if (byte_off + 2 <= fb_size) {
- uint16_t u16 = *(uint16_t *)&buf[byte_off];
- uint32_t p = (((u16 >> 11) & 0x1F) << 19) |
- (((u16 >> 5) & 0x3F) << 10) |
- ((u16 & 0x1F) << 3) | 0xFF000000;
- uint32_t dx = sx, dy = sy;
- switch (rot) {
- case 1: dx = height - 1 - sy; dy = sx; break;
- case 2: dx = width - 1 - sx; dy = height - 1 - sy; break;
- case 3: dx = sy; dy = width - 1 - sx; break;
- default: break;
- }
- if (dx < out_w && dy < out_h)
- proc[dy * out_w + dx] = p;
- }
- continue; // Skip the common 32bpp path below
- }
- } else {
- off = (sy * eff_stride + sx * bpp) / 4;
- }
-
- if (off < fb_size / 4) {
- uint32_t p = ((uint32_t *)buf.data())[off];
- uint32_t dx = sx, dy = sy;
-
- switch (rot) {
- case 1:
- dx = height - 1 - sy;
- dy = sx;
- break;
- case 2:
- dx = width - 1 - sx;
- dy = height - 1 - sy;
- break;
- case 3:
- dx = sy;
- dy = width - 1 - sx;
- break;
- default:
- break; // 0
- }
- if (dx < out_w && dy < out_h) {
- // Native BGRA to ARGB8888 conversion mapping (forces A to 0xFF)
- proc[dy * out_w + dx] = p | 0xFF000000;
- }
+ // Turn the panel picture for the view: a panel pixel (sx, sy) of the
+ // W x H picture lands at
+ // rot 1: (H-1-sy, sx) 2: (W-1-sx, H-1-sy) 3: (sy, W-1-sx)
+ g_frame.resize((size_t)out_w * out_h);
+ for (uint32_t sy = 0; sy < kPanelH; sy++) {
+ const uint32_t *row = &panel[(size_t)sy * kPanelW];
+ for (uint32_t sx = 0; sx < kPanelW; sx++) {
+ uint32_t dx = sx, dy = sy;
+ switch (rot) {
+ case 1: dx = kPanelH - 1 - sy; dy = sx; break;
+ case 2: dx = kPanelW - 1 - sx; dy = kPanelH - 1 - sy; break;
+ case 3: dx = sy; dy = kPanelW - 1 - sx; break;
+ default: break;
}
+ g_frame[(size_t)dy * out_w + dx] = row[sx];
}
}
- SDL_UpdateTexture(texture, nullptr, proc.data(), out_w * 4);
+ SDL_UpdateTexture(texture, nullptr, g_frame.data(), out_w * 4);
+ }
- // Snapshot for PNG conversion — save periodically (~1s) so the last
- // written file always reflects the most recent frame content.
- static int snap_counter = 0;
- if (++snap_counter >= 60) { // ~1 second at 60 FPS
- snap_counter = 0;
- FILE *f = fopen("last_fb.rgba", "wb");
- if (f) {
- fwrite(proc.data(), 1, proc.size() * 4, f);
- fclose(f);
- FILE *fm = fopen("last_fb.meta", "w");
- if (fm) {
- fprintf(fm, "%u %u\n", out_w, out_h);
- fclose(fm);
- }
+ // Snapshot for PNG conversion - at most once a second (~60 frames), and
+ // only when the frame has changed since the last one written, so an idle
+ // payload does not rewrite a 3.5 MB file every second.
+ static int snap_counter = 0;
+ if (++snap_counter >= 60 && snapshot_pending && !g_frame.empty()) {
+ snap_counter = 0;
+ snapshot_pending = false;
+ FILE *f = fopen("last_fb.rgba", "wb");
+ if (f) {
+ fwrite(g_frame.data(), 1, g_frame.size() * 4, f);
+ fclose(f);
+ FILE *fm = fopen("last_fb.meta", "w");
+ if (fm) {
+ fprintf(fm, "%u %u\n", out_w, out_h);
+ fclose(fm);
}
}
}
@@ -364,30 +522,44 @@ static bool window_to_panel(EmuState *state, int mx, int my,
if (tx >= out_w) tx = out_w - 1;
if (ty >= out_h) ty = out_h - 1;
- // The rendered SDL view always represents the physical Switch screen in its
- // intended orientation (post-rotation, post-de-swizzle). Whatever the
- // framebuffer's in-memory layout, what the user sees is what they would see
- // looking at a Switch held landscape (long axis horizontal). The FTS4 panel
- // sits behind that physical screen with its long axis (panel_x) along the
- // long dimension and its short axis (panel_y) along the short.
- //
- // So we map the texture coord to panel coords by aspect: whichever of (tx,
- // ty) lives on the longer rendered axis is the long-axis sample.
- bool landscape = (out_w >= out_h);
- uint32_t long_pix = landscape ? tx : ty;
- uint32_t long_max = landscape ? out_w : out_h;
- uint32_t short_pix = landscape ? ty : tx;
- uint32_t short_max = landscape ? out_h : out_w;
+ // With the auto-detected turn, the view shows the picture the way the
+ // payload drew it (Nyx: landscape, as on a Switch held landscape). A
+ // manual override (Ctrl+R / Ctrl+Shift+R) turns that view by a further
+ // quarter-turn or two, so undo exactly that extra turn first: the render
+ // maps a source pixel (sx, sy) of a W x H image to
+ // 1: (H-1-sy, sx) 2: (W-1-sx, H-1-sy) 3: (sy, W-1-sx)
+ uint32_t delta = (state->last_rot.load() - state->last_auto_rot.load()) & 3;
+ uint32_t aw = (delta & 1) ? out_h : out_w; // auto-rotated view's size
+ uint32_t ah = (delta & 1) ? out_w : out_h;
+ uint32_t ax = tx, ay = ty;
+ switch (delta) {
+ case 1: ax = ty; ay = ah - 1 - tx; break;
+ case 2: ax = aw - 1 - tx; ay = ah - 1 - ty; break;
+ case 3: ax = aw - 1 - ty; ay = tx; break;
+ }
+
+ // The FTS4 panel sits behind that physical screen with its long axis
+ // (panel_x) along the long dimension and its short axis (panel_y) along
+ // the short, so whichever of (ax, ay) lives on the longer axis is the
+ // long-axis sample.
+ bool landscape = (aw >= ah);
+ uint32_t long_pix = landscape ? ax : ay;
+ uint32_t long_max = landscape ? aw : ah;
+ uint32_t short_pix = landscape ? ay : ax;
+ uint32_t short_max = landscape ? ah : aw;
if (long_max == 0) long_max = 1;
if (short_max == 0) short_max = 1;
- uint32_t px = (long_pix * 1264u) / long_max; // FTS4 X_REAL_MAX = 1264
- uint32_t py = (short_pix * 704u) / short_max; // FTS4 Y_REAL_MAX = 704
- if (px > 1264) px = 1264;
- if (py > 704) py = 704;
+ // bdk's touch.c clamps raw samples to EDGE_OFFSET..REAL_MAX (15..1264 and
+ // 15..704) and stretches that span over the 1280x720 screen, so the inverse
+ // starts at the edge offset, not at 0.
+ constexpr uint32_t kEdge = 15, kXMax = 1264, kYMax = 704;
+ uint32_t px = kEdge + (long_pix * (kXMax - kEdge)) / long_max;
+ uint32_t py = kEdge + (short_pix * (kYMax - kEdge)) / short_max;
+ if (px > kXMax) px = kXMax;
+ if (py > kYMax) py = kYMax;
*panel_x = (uint16_t)px;
*panel_y = (uint16_t)py;
- (void)state; // last_rot still cached for future use; current mapping is rotation-agnostic
return true;
}
@@ -425,11 +597,8 @@ bool sdl_display_poll_events(EmuState *state, uc_engine *uc) {
if (event.type == SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_LEFT) {
uint16_t px = 0, py = 0;
if (window_to_panel(state, event.button.x, event.button.y, &px, &py)) {
- state->tc_x.store(px);
- state->tc_y.store(py);
state->tc_pressed.store(true);
- state->tc_event_op.store(0x03); // FTS4_EV_MULTI_TOUCH_ENTER
- state->tc_event_pending.store(true);
+ state->touch_post(0x03, px, py); // FTS4_EV_MULTI_TOUCH_ENTER
printf("[touch] DOWN win=(%d,%d) panel=(%u,%u)\n",
event.button.x, event.button.y, px, py);
}
@@ -437,11 +606,8 @@ bool sdl_display_poll_events(EmuState *state, uc_engine *uc) {
if (event.type == SDL_MOUSEBUTTONUP && event.button.button == SDL_BUTTON_LEFT) {
uint16_t px = 0, py = 0;
if (window_to_panel(state, event.button.x, event.button.y, &px, &py)) {
- state->tc_x.store(px);
- state->tc_y.store(py);
state->tc_pressed.store(false);
- state->tc_event_op.store(0x04); // FTS4_EV_MULTI_TOUCH_LEAVE
- state->tc_event_pending.store(true);
+ state->touch_post(0x04, px, py); // FTS4_EV_MULTI_TOUCH_LEAVE
printf("[touch] UP win=(%d,%d) panel=(%u,%u)\n",
event.button.x, event.button.y, px, py);
}
@@ -449,10 +615,15 @@ bool sdl_display_poll_events(EmuState *state, uc_engine *uc) {
if (event.type == SDL_MOUSEMOTION && state->tc_pressed.load()) {
uint16_t px = 0, py = 0;
if (window_to_panel(state, event.motion.x, event.motion.y, &px, &py)) {
- state->tc_x.store(px);
- state->tc_y.store(py);
- state->tc_event_op.store(0x05); // FTS4_EV_MULTI_TOUCH_MOTION
- state->tc_event_pending.store(true);
+ // A release outside the window never reaches it when mouse capture
+ // is off (the ImGui backend turns SDL's auto-capture off process-
+ // wide), so a motion with the button up ends the touch instead.
+ if (!(event.motion.state & SDL_BUTTON_LMASK)) {
+ state->tc_pressed.store(false);
+ state->touch_post(0x04, px, py); // FTS4_EV_MULTI_TOUCH_LEAVE
+ } else {
+ state->touch_post(0x05, px, py); // FTS4_EV_MULTI_TOUCH_MOTION
+ }
}
}
if (event.type == SDL_KEYDOWN) {
@@ -482,7 +653,8 @@ bool sdl_display_poll_events(EmuState *state, uc_engine *uc) {
case SDLK_r: {
if (!ctrl) {
// Plain R: soft reboot. Same path as the config window's "Reboot"
- // button — re-prime IRAM payload + WDT cookie, wipe DRAM, reset PC.
+ // button — reload the payload into IRAM, wipe DRAM, reset PC.
+ state->reboot_cold = true; // the user's reset is a power cycle
state->reboot_requested = true;
printf("[diag] Reboot requested (R)\n");
} else {
diff --git a/emu_state.h b/emu_state.h
index d448634..f1a4aa0 100644
--- a/emu_state.h
+++ b/emu_state.h
@@ -91,6 +91,42 @@ inline bool wifi_radio_parse(const char *s, uint8_t *out) {
return false;
}
+// Tegra DC window registers (TRM 24.10-24.11) as slots in a window's
+// register file: the indirect window page 0x700-0x7FF is slots 0x000-0x0FF,
+// the WINBUF page 0x800-0x83F slots 0x100-0x13F.
+namespace dcwin {
+constexpr uint32_t kRegs = 0x140;
+constexpr uint32_t OPTIONS = 0x000; // DC_WIN_WIN_OPTIONS
+constexpr uint32_t COLOR_DEPTH = 0x003; // DC_WIN_COLOR_DEPTH
+constexpr uint32_t POSITION = 0x004; // DC_WIN_POSITION
+constexpr uint32_t SIZE = 0x005; // DC_WIN_SIZE (post-scaling)
+constexpr uint32_t PRESCALED = 0x006; // DC_WIN_PRESCALED_SIZE (bytes x lines)
+constexpr uint32_t LINE_STRIDE = 0x00A; // DC_WIN_LINE_STRIDE (bytes)
+constexpr uint32_t BLEND_LAYER = 0x016; // DC_WINBUF_BLEND_LAYER_CONTROL
+constexpr uint32_t BLEND_MATCH = 0x017; // DC_WINBUF_BLEND_MATCH_SELECT
+constexpr uint32_t START_ADDR = 0x100; // DC_WINBUF_START_ADDR
+constexpr uint32_t ADDR_H_OFF = 0x106; // DC_WINBUF_ADDR_H_OFFSET (bytes)
+constexpr uint32_t ADDR_V_OFF = 0x108; // DC_WINBUF_ADDR_V_OFFSET (lines)
+constexpr uint32_t SURFACE_KIND = 0x10B; // DC_WINBUF_SURFACE_KIND
+
+// WIN_OPTIONS bits.
+constexpr uint32_t H_DIRECTION = 1u << 0;
+constexpr uint32_t V_DIRECTION = 1u << 2;
+constexpr uint32_t SCAN_COLUMN = 1u << 4;
+constexpr uint32_t WIN_ENABLE = 1u << 30;
+
+// BLEND_LAYER_CONTROL resets to BLEND_BYPASS (TRM 24.10.12).
+constexpr uint32_t BLEND_LAYER_RESET = 0x01000000;
+
+// A picture turn, as flip-then-transpose: the source is mirrored left-right
+// (XF_FLIP_X) and/or top-bottom (XF_FLIP_Y), then rows become columns
+// (XF_TRANSPOSE). DC WIN_OPTIONS (H_DIRECTION, V_DIRECTION, SCAN_COLUMN) and
+// VIC's OutputFlipX/FlipY/Transpose both follow this convention.
+constexpr uint32_t XF_FLIP_X = 1u << 0;
+constexpr uint32_t XF_FLIP_Y = 1u << 1;
+constexpr uint32_t XF_TRANSPOSE = 1u << 2;
+} // namespace dcwin
+
struct EmuState {
uc_engine *uc = nullptr;
// Button state (updated by SDL keyboard events).
@@ -102,36 +138,58 @@ struct EmuState {
// Updated by SDL mouse events; consumed by i2c3_*/STMFTS code on CPU thread.
// Coordinates are in panel-raw space (X long axis 0..1264, Y short 0..704)
// matching what touch.c expects before its rescaling.
- std::atomic tc_x{0};
- std::atomic tc_y{0};
+ //
+ // Events queue up rather than overwrite each other: a click shorter than
+ // the payload's poll interval used to reach it as a bare LEAVE, the
+ // ENTER lost under it. Single producer (SDL), single consumer (I2C3).
+ struct TouchEvent { uint8_t op; uint16_t x, y; }; // op 3/4/5 = ENTER/LEAVE/MOTION
+ static constexpr uint32_t TC_QUEUE = 32;
+ TouchEvent tc_queue[TC_QUEUE] = {};
+ std::atomic tc_q_head{0}; // next slot the producer fills
+ std::atomic tc_q_tail{0}; // next slot the consumer takes
std::atomic tc_pressed{false};
- std::atomic tc_event_pending{false};
- std::atomic tc_event_op{0}; // 0x03=ENTER, 0x04=LEAVE, 0x05=MOTION
- uint8_t tc_finger_id = 1; // FTS4 finger IDs are 1-indexed
+ uint8_t tc_finger_id = 0; // raw FTS4 ID; bdk reports it + 1
+
+ // Queue a touch event. MOTION is dropped when the queue is nearly full,
+ // so an ENTER or LEAVE always finds room.
+ void touch_post(uint8_t op, uint16_t x, uint16_t y) {
+ uint32_t head = tc_q_head.load(), tail = tc_q_tail.load();
+ uint32_t used = head - tail;
+ if (used >= TC_QUEUE || (op == 0x05 && used >= TC_QUEUE - 4))
+ return;
+ tc_queue[head % TC_QUEUE] = {op, x, y};
+ tc_q_head.store(head + 1);
+ }
+ bool touch_take(TouchEvent *ev) {
+ uint32_t tail = tc_q_tail.load();
+ if (tail == tc_q_head.load())
+ return false;
+ *ev = tc_queue[tail % TC_QUEUE];
+ tc_q_tail.store(tail + 1);
+ return true;
+ }
// last_rot mirrors the rotation last applied by sdl_display_update.
// Read from the SDL event handler to invert the display→window transform.
std::atomic last_rot{0};
+ std::atomic last_auto_rot{0}; // what auto-detect picked, before any override
std::atomic last_out_w{1280};
std::atomic last_out_h{720};
- // Display state.
- uint64_t fb_addr = 0, pre_addr = 0;
- uint32_t fb_width = 720, pre_w = 720;
- uint32_t fb_height = 1280, pre_h = 1280;
- uint32_t fb_stride = 2880, pre_stride = 2880;
- uint32_t fb_swizzle = 0, pre_sw = 0;
- uint32_t fb_rotation = 0, pre_rot = 0;
- uint32_t pre_bh = 0; // block height in GOBs from DC surface-kind (0 = unset)
- uint32_t fb_sw_gobs = 80;
- uint32_t fb_bh = 0; // 0 = use display code default until DC surface-kind latches
-
- // DC window selection: tracks DC_CMD_DISPLAY_WINDOW_HEADER.
- // Bit 4 = Window A, Bit 5 = Window B, Bit 6 = Window C, Bit 7 = Window D.
- uint32_t dc_window_sel = 0x10; // Default: Window A
- // Saved Window A parameters (primary display surface).
- uint64_t winA_addr = 0;
- uint32_t winA_w = 720, winA_h = 1280, winA_stride = 2880;
- uint32_t winA_sw = 0, winA_rot = 0, winA_bh = 0;
+ // Display controller windows A-D (t210/mmio.cpp, Display). Each window
+ // has a register file indexed by dcwin:: slot. The CPU writes the
+ // assembly copy; DC_CMD_STATE_CONTROL's WIN_x_ACT_REQ copies it into the
+ // active copy, which is what the scan-out (display/sdl_display.cpp)
+ // decodes.
+ uint32_t dc_win[4][dcwin::kRegs] = {};
+ uint32_t dc_win_active[4][dcwin::kRegs] = {};
+ uint32_t dc_window_header = 0; // DC_CMD_DISPLAY_WINDOW_HEADER
+ // False from reset until the payload first activates a window. Until
+ // then the scan-out shows the emulator's own framebuffer (FB_BASE).
+ bool dc_programmed = false;
+ // Where the last VIC compose wrote, and how it turned the picture on the
+ // way (dcwin::XF_* bits). The scan-out undoes that turn for display.
+ uint64_t vic_out_addr = 0;
+ uint32_t vic_out_xform = 0;
std::atomic display_dirty{false};
std::atomic display_initialized{false};
int32_t manual_offset = 0;
@@ -141,6 +199,14 @@ struct EmuState {
std::atomic running{true};
std::atomic paused{false};
std::atomic reboot_requested{false};
+ // The reboot is a power cycle (PMIC software reset, the UI's Reboot):
+ // the regulators lose their state too. Otherwise it is a SoC reset
+ // (PMC MAIN_RST), which the PMIC, and its rails, sit out.
+ std::atomic reboot_cold{false};
+ // The BPMP parked itself for good (bpmp_halt(): WAITEVENT with no timer)
+ // while CPU0 still runs - the handoff fusee and hekate's L4T launch do.
+ // Time keeps passing for CPU0; the BPMP executes nothing until reset.
+ bool bpmp_halted = false;
// Payload kept around for soft reboot (re-write to IRAM and reset PC).
uint8_t *payload_ptr = nullptr;
@@ -254,6 +320,14 @@ struct EmuState {
// SD card insertion (GPIO Port Z bit 1 = 0 means inserted).
std::atomic sd_inserted{true};
+ // A PC on the USB-C port (--usb-host): it enumerates whatever gadget the
+ // payload brings up (t210/usb.cpp). Off, nothing is on the cable.
+ std::atomic usb_host{false};
+ // --usb-host nbd[:port]: instead of reading a mass storage disk back and
+ // ejecting it, the host serves it over NBD on 127.0.0.1:port until the
+ // client disconnects. 0: off.
+ std::atomic usb_nbd_port{0};
+
// SD card identity (returned for SDMMC1 CMD2 ALL_SEND_CID).
// Hekate parses these out of the R2 response per bdk/storage/sdmmc.c
// _sd_storage_parse_cid; the I2C handler builds the 16-byte CID payload
@@ -328,6 +402,8 @@ struct EmuState {
std::atomic& fuse_at(uint32_t offset) { return fuse_word[(offset & 0x3FC) / 4]; }
void init_fuse_defaults() {
+ for (auto &w : fuse_word)
+ w.store(0);
// Names below mirror Hekate's bdk/soc/fuse.h. Values picked from a
// typical Erista golden-sample dump (any retail Switch is similar).
fuse_at(0x100).store(1); // FUSE_PRODUCTION_MODE
diff --git a/input_script.cpp b/input_script.cpp
index db6588c..163c174 100644
--- a/input_script.cpp
+++ b/input_script.cpp
@@ -12,6 +12,11 @@
// VOL_UP | VOLUP | UP | U
// hold_ms how long to hold the button, default 200 ms.
//
+// TAP [hold_ms]
+//
+// touches the screen at (x, y) in the 1280x720 landscape picture bdk's
+// touch driver reports (Nyx's coordinates), and lifts after hold_ms.
+//
// '#' starts a comment. Example - walk 6 entries down a menu and select:
//
// rcm_emu payload.bin --input-script "3000 D, + D, + D, + D, + D, + D, + P"
@@ -27,6 +32,7 @@
#include "input_script.h"
#include "emu_state.h"
+#include
#include
#include
#include
@@ -36,7 +42,7 @@
namespace {
-enum class Key { Power, VolUp, VolDown, Uart, UartFile };
+enum class Key { Power, VolUp, VolDown, Uart, UartFile, Tap };
struct Event {
uint64_t at_us = 0; // press time
@@ -45,6 +51,7 @@ struct Event {
bool pressed = false;
bool released = false;
std::string data; // UART / UARTFILE payload
+ uint16_t x = 0, y = 0; // TAP: panel-raw coordinates
};
std::vector g_events;
@@ -60,6 +67,7 @@ const char *key_name(Key k) {
case Key::VolUp: return "VOL+";
case Key::Uart: return "UART";
case Key::UartFile: return "UARTFILE";
+ case Key::Tap: return "TAP";
default: return "VOL-";
}
}
@@ -80,6 +88,7 @@ bool parse_key(const std::string &tok, Key *out) {
// UARTFILE pushes a file's raw contents, for binary protocol work.
if (s == "UART") { *out = Key::Uart; return true; }
if (s == "UARTFILE") { *out = Key::UartFile; return true; }
+ if (s == "TAP" || s == "T") { *out = Key::Tap; return true; }
return false;
}
@@ -184,8 +193,24 @@ bool parse_text(const std::string &text) {
continue;
}
- uint64_t hold_ms = (tok.size() >= 3) ? strtoull(tok[2].c_str(), nullptr, 10)
- : kDefaultHoldMs;
+ size_t hold_tok = 2;
+ if (ev.key == Key::Tap) {
+ if (tok.size() < 4) {
+ fprintf(stderr, "[input-script] entry %d: expected ' TAP [hold_ms]'\n",
+ lineno);
+ return false;
+ }
+ // bdk's touch.c clamps raw samples to 15..1264 and 15..704 and
+ // stretches that span over 1280x720; invert it.
+ uint32_t x = std::min(strtoul(tok[2].c_str(), nullptr, 10), 1279);
+ uint32_t y = std::min(strtoul(tok[3].c_str(), nullptr, 10), 719);
+ ev.x = (uint16_t)(15 + (x * (1264 - 15) + 1279) / 1280);
+ ev.y = (uint16_t)(15 + (y * (704 - 15) + 719) / 720);
+ hold_tok = 4;
+ }
+ uint64_t hold_ms = (tok.size() > hold_tok)
+ ? strtoull(tok[hold_tok].c_str(), nullptr, 10)
+ : kDefaultHoldMs;
if (hold_ms == 0) hold_ms = kDefaultHoldMs;
ev.until_us = ev.at_us + hold_ms * 1000ULL;
prev_release_us = ev.until_us;
@@ -271,6 +296,30 @@ void input_script_tick(EmuState &state) {
break;
}
+ if (ev.key == Key::Tap) {
+ if (!ev.pressed && now >= ev.at_us) {
+ state.tc_pressed.store(true);
+ state.touch_post(0x03, ev.x, ev.y); // FTS4 ENTER
+ ev.pressed = true;
+ printf("[input-script] TAP down panel=(%u,%u) @%llu us (%zu/%zu)\n",
+ ev.x, ev.y, (unsigned long long)now, i + 1, g_events.size());
+ fflush(stdout);
+ break;
+ }
+ if (ev.pressed && !ev.released && now >= ev.until_us) {
+ state.tc_pressed.store(false);
+ state.touch_post(0x04, ev.x, ev.y); // FTS4 LEAVE
+ ev.released = true;
+ if (i == g_done) {
+ g_done++;
+ if (g_done == g_events.size())
+ printf("[input-script] sequence complete\n");
+ }
+ }
+ if (!ev.released) break;
+ continue;
+ }
+
std::atomic *btn = (ev.key == Key::Power) ? &state.btn_power
: (ev.key == Key::VolUp) ? &state.btn_vol_up
: &state.btn_vol_down;
@@ -280,6 +329,10 @@ void input_script_tick(EmuState &state) {
printf("[input-script] %s down @%llu us (%zu/%zu)\n", key_name(ev.key),
(unsigned long long)now, i + 1, g_events.size());
fflush(stdout);
+ // Even if the release is already due - a FLOW_CTLR sleep can jump the
+ // clock past it within one batch - the payload has to run with the
+ // button down at least once, or it never sees the press.
+ break;
}
if (ev.pressed && !ev.released && now >= ev.until_us) {
btn->store(false);
@@ -293,3 +346,12 @@ void input_script_tick(EmuState &state) {
if (!ev.released) break; // keep this event current until it's let go
}
}
+
+void input_script_restart(EmuState &state) {
+ for (Event &ev : g_events)
+ ev.pressed = ev.released = false;
+ g_done = 0;
+ state.btn_power = false;
+ state.btn_vol_up = false;
+ state.btn_vol_down = false;
+}
diff --git a/input_script.h b/input_script.h
index 9778506..09cd068 100644
--- a/input_script.h
+++ b/input_script.h
@@ -23,3 +23,7 @@ bool input_script_active();
// Apply any events that are due at the current state.emu_usec. Call once per
// emulator loop iteration; cheap no-op when no script is loaded.
void input_script_tick(EmuState &state);
+
+// Soft reboot: the emulated clock starts again from 0, so every event is
+// re-armed and any button the script was holding is let go.
+void input_script_restart(EmuState &state);
diff --git a/main.cpp b/main.cpp
index 240ab7d..072c8d1 100644
--- a/main.cpp
+++ b/main.cpp
@@ -22,9 +22,11 @@
#include
#include "emu_state.h"
-#include
+#include "platform.h"
#include "payload_picker.h"
#include "trace.h"
+#include "t210/bpmp.h"
+#include "t210/ccplex.h"
#include "t210/memory_map.h"
#include "t210/mmio.h"
#include "display/sdl_display.h"
@@ -32,18 +34,48 @@
#include "display/console_window.h"
#include "input_script.h"
+// Low 16 MB of the map (NULL-pointer writes land there); freed at exit.
+static uint8_t *g_low_ptr = nullptr;
+
+// Scripted-navigation progress (--auto-pin-recovery, --auto-te-script). A
+// soft reboot restarts both, as it restarts the emulated clock they run on.
+struct AutoScripts {
+ int pin_stage = 0;
+ uint64_t pin_t = 0;
+ int pin_logged_stage = -1;
+ size_t te_idx = 0;
+};
+static AutoScripts g_auto;
+
+// The IPL framebuffer starts out in hekate's background colour (0x1B1B1B),
+// at power-on and again after a reboot has handed DRAM back zeroed.
+static void fill_fb_background(EmuState *state) {
+ for (size_t i = 0; i < FB_SIZE; i += 4) {
+ state->fb_ptr[i + 0] = 0x1B; // B
+ state->fb_ptr[i + 1] = 0x1B; // G
+ state->fb_ptr[i + 2] = 0x1B; // R
+ state->fb_ptr[i + 3] = 0xFF; // A
+ }
+}
+
// ==================== Payload Loading ====================
static uint8_t *load_payload(const char *path, size_t *out_size) {
- FILE *f = fopen(path, "rb");
+ FILE *f = platform_fopen(path, "rb");
if (!f) {
fprintf(stderr, "[error] Cannot open payload: %s\n", path);
return nullptr;
}
- fseek(f, 0, SEEK_END);
- size_t size = ftell(f);
- fseek(f, 0, SEEK_SET);
+ long len = -1;
+ if (fseek(f, 0, SEEK_END) == 0)
+ len = ftell(f);
+ if (len <= 0 || fseek(f, 0, SEEK_SET) != 0) {
+ fclose(f);
+ fprintf(stderr, "[error] Payload is empty or unreadable: %s\n", path);
+ return nullptr;
+ }
+ size_t size = (size_t)len;
uint8_t *buf = (uint8_t *)malloc(size);
if (!buf) {
@@ -83,42 +115,6 @@ static uint8_t *load_payload(const char *path, size_t *out_size) {
// ==================== Emulation Setup ====================
-// Global for instruction tracing
-static uint32_t pc_trace[2000];
-static size_t pc_trace_idx = 0;
-static uint32_t last_valid_block = 0;
-static uc_hook trace_h, block_h;
-
-static void trace_callback(uc_engine *uc, uint64_t address, uint32_t size, void *user_data) {
- static uint32_t last_pc = 0;
- if (address == last_pc) return;
- last_pc = (uint32_t)address;
-
- pc_trace[pc_trace_idx] = (uint32_t)address;
- pc_trace_idx = (pc_trace_idx + 1) % 2000;
-
- // NOP-slide detection
- if (address >= 0x40030000 && address < 0x41000000) {
- uint16_t insn = 0;
- if (uc_mem_read(uc, address, &insn, 2) == UC_ERR_OK && insn == 0) {
- static int nop_count = 0;
- if (++nop_count > 10) {
- printf("\n[emu] NOP-slide detected at 0x%08llX! Last valid block: 0x%08X\n",
- (unsigned long long)address, last_valid_block);
- uc_emu_stop(uc);
- }
- } else {
- // nop_count = 0; // would need a persistent counter
- }
- }
-}
-
-static void block_callback(uc_engine *uc, uint64_t address, uint32_t size, void *user_data) {
- if (address >= 0x40000000 && address < 0x40030000) {
- last_valid_block = (uint32_t)address;
- }
-}
-
static uc_engine *setup_emulation(EmuState *state, uint8_t *payload, size_t payload_size) {
uc_engine *uc;
uc_err err;
@@ -131,9 +127,12 @@ static uc_engine *setup_emulation(EmuState *state, uint8_t *payload, size_t payl
}
state->uc = uc;
- // Setup hooks
- uc_hook_add(uc, &trace_h, UC_HOOK_CODE, (void*)trace_callback, nullptr, 1, 0);
- uc_hook_add(uc, &block_h, UC_HOOK_BLOCK, (void*)block_callback, nullptr, 1, 0);
+ // No UC_HOOK_CODE anywhere: a per-instruction callback keeps Unicorn off
+ // its fast path for every block it covers. This used to register three
+ // of them (one of them twice) - an instruction-trace ring buffer nothing
+ // read, a NOP-slide check that did a uc_mem_read per instruction, and
+ // the clock. The clock and the NOP-slide check now run once per block
+ // (t210/bpmp.cpp).
// Enable VFP/NEON
uint32_t cpacr = 0x00F00000;
@@ -152,24 +151,6 @@ static uc_engine *setup_emulation(EmuState *state, uint8_t *payload, size_t payl
(unsigned long long)(IRAM_BASE + IRAM_SIZE),
(unsigned)(IRAM_SIZE / 1024));
- uc_mem_write(uc, IPL_LOAD_ADDR, payload, payload_size);
-
- // Pre-set Hekate's "watchdog fired" magic at IRAM 0x4003FF18 (cookie "WDT")
- // so its early boot does `goto skip_lp0_minerva_config`, skipping both
- // libsys_lp0.bso and the Minerva DRAM-training path. The matching
- // EXCP_EN_ADDR (0x4003FF1C) is intentionally left zeroed so ERR_EXCEPTION
- // is *not* set and the user doesn't see a "hang detected" warning screen.
- // We can't model EMC/MC well enough for real Minerva training, so this is
- // the cleanest opt-out (the same path Hekate uses on hardware after a
- // legitimate WDT reset).
- {
- uint32_t wdt_magic = 0x544457; // "WDT"
- uc_mem_write(uc, 0x4003FF18, &wdt_magic, sizeof(wdt_magic));
- }
-
- // Setup instruction tracing
- uc_hook_add(uc, &trace_h, UC_HOOK_CODE, (void*)trace_callback, nullptr, 1, 0);
-
// ---- Map DRAM as one contiguous region ----
// 0x80000000 .. 0x100000000, i.e. the whole 32-bit-addressable DRAM window
// the BPMP can reach. This used to be two islands (256 MB at 0x80000000
@@ -179,18 +160,19 @@ static uc_engine *setup_emulation(EmuState *state, uint8_t *payload, size_t payl
// through. One contiguous block removes the hole and matches what real
// hardware presents.
//
- // Allocated host-side (calloc, so pages are lazily committed - the full
- // 2 GB is only ever resident if a payload actually touches all of it) and
- // kept as a host pointer so soft reboot can memset() it: Nyx loads here
- // and its file-static SD/eMMC caches would otherwise survive a reboot.
- err = uc_mem_map_ptr(uc, DRAM_BASE, DRAM_WINDOW_SIZE, UC_PROT_ALL,
- (state->dram_low_ptr = (uint8_t *)calloc(1, DRAM_WINDOW_SIZE)));
+ // Allocated host-side as demand-zero pages (zeroed_alloc), so the full
+ // 2 GB is only ever resident if a payload actually touches all of it, and
+ // kept as a host pointer so a soft reboot can hand it back zeroed: Nyx
+ // loads here and its file-static SD/eMMC caches would otherwise survive.
+ state->dram_low_ptr = zeroed_alloc(DRAM_WINDOW_SIZE);
if (!state->dram_low_ptr) {
fprintf(stderr, "[error] Failed to allocate %zu MB DRAM host buffer\n",
(size_t)(DRAM_WINDOW_SIZE / (1024 * 1024)));
uc_close(uc);
return nullptr;
}
+ err = uc_mem_map_ptr(uc, DRAM_BASE, DRAM_WINDOW_SIZE, UC_PROT_ALL,
+ state->dram_low_ptr);
if (err != UC_ERR_OK) {
fprintf(stderr, "[error] Failed to map DRAM: %s\n", uc_strerror(err));
uc_close(uc);
@@ -208,14 +190,7 @@ static uc_engine *setup_emulation(EmuState *state, uint8_t *payload, size_t payl
// ---- Map Framebuffer pointer ----
state->fb_ptr = state->dram_low_ptr + (FB_BASE - DRAM_BASE);
- // Fill with hekate background color (0x1B1B1B)
- for (size_t i = 0; i < FB_SIZE; i += 4) {
- state->fb_ptr[i + 0] = 0x1B; // B
- state->fb_ptr[i + 1] = 0x1B; // G
- state->fb_ptr[i + 2] = 0x1B; // R
- state->fb_ptr[i + 3] = 0xFF; // A
- }
- state->fb_addr = FB_BASE;
+ fill_fb_background(state);
printf("[emu] Defined FB: 0x%08llX - 0x%08llX (%u MB)\n",
(unsigned long long)FB_BASE,
(unsigned long long)(FB_BASE + FB_SIZE),
@@ -223,28 +198,34 @@ static uc_engine *setup_emulation(EmuState *state, uint8_t *payload, size_t payl
// ---- Map low memory (16MB @ 0x0) ----
// hekate seems to do a memset(0, ...) for clear screen if some ptr is NULL.
- uint8_t *low_ptr = (uint8_t *)calloc(1, 0x01000000);
- uc_mem_map_ptr(uc, 0, 0x01000000, UC_PROT_ALL, low_ptr);
+ // This covers the iROM range (0x100000, 96 KB) too, as zero-filled RAM:
+ // there are no BootROM contents to show, and Hekate's "Bootrom Info" /
+ // "Dump Bootrom" read it without faulting. (A read-only iROM map on top
+ // of this used to be attempted as well; it overlapped, so it always
+ // failed, unnoticed - and a read-only iROM would fault the NULL-pointer
+ // clear above.)
+ g_low_ptr = (uint8_t *)calloc(1, 0x01000000);
+ err = g_low_ptr ? uc_mem_map_ptr(uc, 0, 0x01000000, UC_PROT_ALL, g_low_ptr)
+ : UC_ERR_NOMEM;
+ if (err != UC_ERR_OK) {
+ fprintf(stderr, "[error] Failed to map low memory: %s\n", uc_strerror(err));
+ uc_close(uc);
+ return nullptr;
+ }
// ---- Nyx Storage (16MB @ 0xED000000) ----
// Already mapped as part of 2GB DRAM chunk
- // ---- Map Peripherals (PWM, SDMMC, etc.) ----
- // Map individual pages to allow MMIO hooks
- // The mappings previously declared manually were moved here:
- // Some are mapped earlier in setup_emulation properly using FB_BASE e.g.
- uc_mem_map(uc, 0x7000A000, 0x1000, UC_PROT_ALL); // PWM
- uc_mem_map(uc, 0x700B0000, 0x1000, UC_PROT_ALL); // SDMMC1
- uc_mem_map(uc, 0x7000E000, 0x1000, UC_PROT_ALL); // RTC/PMC
- uc_mem_map(uc, 0x6000C000, 0x2000, UC_PROT_ALL); // SYSREG/APB_SEMAPH
+ // Peripherals are all mapped by mmio_init() below as MMIO windows. PWM,
+ // SDMMC1, RTC/PMC and SYSREG used to be mapped here first as plain RAM,
+ // which only worked because MMIO was a pair of address-range hooks over
+ // whatever happened to be mapped.
- // BootROM (iROM) at 0x100000, 96 KB. We don't have the real BootROM
- // contents, but mapping the region as zero-filled lets Hekate's "Bootrom
- // Info" / "Dump Bootrom" features read it without faulting. The IPATCH
- // CAM at 0x6001DC00 is also zero-mapped so the ipatches table renders
- // empty (which matches an unpatched SoC).
- uc_mem_map(uc, 0x00100000, 0x18000, UC_PROT_READ | UC_PROT_EXEC); // iROM
- uc_mem_map(uc, 0x6001D000, 0x1000, UC_PROT_ALL); // IPATCH CAM page
+ // The IPATCH CAM at 0x6001DC00 is zero-mapped so the ipatches table
+ // renders empty (which matches an unpatched SoC).
+ err = uc_mem_map(uc, 0x6001D000, 0x1000, UC_PROT_ALL);
+ if (err != UC_ERR_OK)
+ fprintf(stderr, "[warn] IPATCH page not mapped: %s\n", uc_strerror(err));
// ---- heap region (32MB @ 0x90000000) ----
// Already mapped as part of 2GB DRAM chunk
@@ -267,9 +248,10 @@ static uc_engine *setup_emulation(EmuState *state, uint8_t *payload, size_t payl
printf("[emu] Initial PC=0x%08X SP=0x%08X\n", pc, sp);
- // ---- Setup MMIO hooks ----
+ // ---- Peripherals and the deterministic clock ----
mmio_init(uc, state);
- printf("[emu] MMIO hooks registered\n");
+ bpmp_attach(uc, state);
+ printf("[emu] MMIO windows mapped\n");
return uc;
}
@@ -374,6 +356,30 @@ int main(int argc, char *argv[]) {
fprintf(stderr, "[emu] Unknown --bt-radio value '%s'; expected"
" 'healthy', 'faulty' or 'absent'\n", mode);
}
+ } else if (strcmp(argv[i], "--usb-host") == 0) {
+ // A PC on the USB-C port: it enumerates whatever gadget the
+ // payload brings up and, for mass storage, reads it back - or,
+ // given "nbd[:port]", serves the disk over NBD.
+ state.usb_host = true;
+ if (i + 1 < argc && strncmp(argv[i + 1], "nbd", 3) == 0 &&
+ (argv[i + 1][3] == 0 || argv[i + 1][3] == ':')) {
+ const char *arg = argv[++i];
+ unsigned long port = 10809; // the NBD port
+ char *end = nullptr;
+ if (arg[3] == ':')
+ port = strtoul(arg + 4, &end, 10);
+ if (port == 0 || port > 65535 || (end && *end)) {
+ fprintf(stderr, "[emu] Bad --usb-host value '%s'; expected"
+ " nbd or nbd:\n", arg);
+ port = 10809;
+ }
+ state.usb_nbd_port = (uint16_t)port;
+ printf("[emu] USB host connected, serving mass storage over"
+ " NBD on port %lu [overrides ini]\n", port);
+ } else {
+ state.usb_nbd_port = 0;
+ printf("[emu] USB host connected [overrides ini]\n");
+ }
} else if (strcmp(argv[i], "--wifi-radio") == 0 && i + 1 < argc) {
// WLAN half of the same package, on PCIe. 'faulty' means
// something different here from the Bluetooth side: the link
@@ -407,8 +413,14 @@ int main(int argc, char *argv[]) {
else if (strcmp(argv[i], "--auto-te-script") == 0) auto_te_script = true;
// Generic scripted button input, for menu-driven payloads that can't
// be driven any other way from a headless / CI run.
- else if (strcmp(argv[i], "--input-script") == 0 && i + 1 < argc)
- input_script_load(argv[++i]);
+ else if (strcmp(argv[i], "--input-script") == 0 && i + 1 < argc) {
+ // A script that does not parse would leave a CI run idling until
+ // its timeout with nothing pressed; stop here instead.
+ if (!input_script_load(argv[++i])) {
+ fprintf(stderr, "[error] --input-script could not be loaded\n");
+ return 1;
+ }
+ }
}
// Default to sd.img in the working directory when --sd is not given, so the
@@ -420,12 +432,20 @@ int main(int argc, char *argv[]) {
}
if (sd_path) {
- state.sd_fd = open(sd_path, O_RDWR);
+ state.sd_fd = open(sd_path, O_RDWR | O_BINARY);
if (state.sd_fd < 0) perror("[emu] Failed to open SD image");
else printf("[emu] SD image opened: %s\n", sd_path);
}
+ // No image, no card: the slot starts empty, so card detect (PZ1) reads
+ // empty and SDMMC1 commands time out, as on a console with no card in.
+ // This used to present a blank card that FatFs then found no volume on.
+ // The config window's SD toggle can still insert a blank card.
+ if (state.sd_fd < 0 && state.sd_inserted.load()) {
+ state.sd_inserted = false;
+ printf("[emu] No SD image: the SD slot is empty\n");
+ }
if (boot0_path) {
- state.emmc_boot0_fd = open(boot0_path, O_RDWR);
+ state.emmc_boot0_fd = open(boot0_path, O_RDWR | O_BINARY);
if (state.emmc_boot0_fd < 0) perror("[emu] Failed to open BOOT0 image");
else printf("[emu] BOOT0 image opened: %s\n", boot0_path);
}
@@ -433,7 +453,7 @@ int main(int argc, char *argv[]) {
for (int i = 0; i < 16; i++) {
char path[512];
snprintf(path, sizeof(path), "%s.%02d", rawnand_prefix, i);
- int fd = open(path, O_RDWR);
+ int fd = open(path, O_RDWR | O_BINARY);
if (fd >= 0) {
state.emmc_gpp_fds.push_back(fd);
// printf("[emu] rawnand part %02d opened: %s\n", i, path);
@@ -480,6 +500,11 @@ int main(int argc, char *argv[]) {
const uint64_t BATCH_INSTRUCTIONS = 100000; // Instructions per batch
const int DISPLAY_UPDATE_MS = 16; // ~60 FPS
+ // While CPU0 is running the two cores advance in lockstep slices of this
+ // many BPMP instructions (250 us of emulated time). The BPMP polls CPU0's
+ // mailbox every 500 us, so neither side ever waits on a stale view of the
+ // other for longer than one of its own poll intervals.
+ const uint64_t CPU0_QUANTUM_INSTRUCTIONS = 2500;
auto last_display_update = std::chrono::steady_clock::now();
@@ -488,27 +513,52 @@ int main(int argc, char *argv[]) {
if (!sdl_display_poll_events(&state, uc)) break;
// Soft reboot: re-write the payload to IRAM, wipe DRAM (so Nyx and
- // the bootloader's file-static caches reset), reset PC/SP/clock and
- // re-prime the WDT cookie so Hekate's early boot skips Minerva again.
+ // the bootloader's file-static caches reset) and reset PC/SP/clock.
if (state.reboot_requested.exchange(false)) {
uc_emu_stop(uc);
- // One contiguous block now; dram_ptr is a view into it.
- memset(state.dram_low_ptr, 0, DRAM_WINDOW_SIZE);
- uc_mem_write(uc, IPL_LOAD_ADDR, state.payload_ptr, state.payload_len);
- uint32_t wdt_magic = 0x544457;
- uc_mem_write(uc, 0x4003FF18, &wdt_magic, sizeof(wdt_magic));
+ bool cold = state.reboot_cold.exchange(false);
+ // The SoC resets as a whole: CPU0 back into reset, the PCIe root
+ // complex and every other block back to power-on, the clock's
+ // half-counted block gone. A power cycle resets the PMIC too.
+ mmio_soft_reset(&state, cold);
+ bpmp_clock_reset();
+ // Fresh zero pages rather than a memset, which made all 2 GB
+ // resident.
+ zeroed_reset(state.dram_low_ptr, DRAM_WINDOW_SIZE);
+ fill_fb_background(&state);
+ size_t reload = state.payload_len;
+ if (reload > IRAM_SIZE - (IPL_LOAD_ADDR - IRAM_BASE))
+ reload = IRAM_SIZE - (IPL_LOAD_ADDR - IRAM_BASE);
+ uc_mem_write(uc, IPL_LOAD_ADDR, state.payload_ptr, reload);
+ // Neither the zeroed DRAM nor uc_mem_write() reaches the engine's
+ // code cache, so what the last run translated - a payload it
+ // chainloaded over this one's load address, Nyx in DRAM - would
+ // run again in place of the fresh bytes. Drop those translations.
+ // (Not UC_CTL_TB_FLUSH: on Unicorn 2.0 that memsets the whole
+ // 1 GB code buffer, seconds and a gigabyte of RSS per reboot.)
+ uc_ctl_remove_cache(uc, 0, 0x01000000);
+ uc_ctl_remove_cache(uc, IRAM_BASE, IRAM_BASE + IRAM_SIZE);
+ uc_ctl_remove_cache(uc, DRAM_BASE, DRAM_BASE + DRAM_WINDOW_SIZE);
+ // Mode first, as at power-on: SVC, ARM state, IRQ/FIQ/async
+ // aborts masked. SP is banked, so it is written in that mode.
+ uint32_t reset_cpsr = 0x1D3;
uint32_t reset_pc = IPL_LOAD_ADDR;
uint32_t reset_sp = IPL_STACK_ADDR;
- uint32_t reset_cpsr = 0; // ARM mode, all flags clear
- uc_reg_write(uc, UC_ARM_REG_PC, &reset_pc);
- uc_reg_write(uc, UC_ARM_REG_SP, &reset_sp);
uc_reg_write(uc, UC_ARM_REG_CPSR, &reset_cpsr);
- state.fb_addr = FB_BASE; // re-point display at the FB base
+ uc_reg_write(uc, UC_ARM_REG_SP, &reset_sp);
+ uc_reg_write(uc, UC_ARM_REG_PC, &reset_pc);
state.emu_usec = 0;
state.insn_count = 0;
+ state.bpmp_slept_us = 0;
state.touch_phase = 0;
state.paused = false;
- printf("[emu] Soft reboot complete (DRAM wiped)\n");
+ state.btn_power = false;
+ state.btn_vol_up = false;
+ state.btn_vol_down = false;
+ g_auto = AutoScripts();
+ input_script_restart(state);
+ printf("[emu] Soft reboot complete (%s, DRAM wiped)\n",
+ cold ? "power cycle" : "SoC reset");
}
if (!state.paused) {
@@ -528,8 +578,8 @@ int main(int argc, char *argv[]) {
// idle so recover_pin's final btn_wait blocks on us — keeps the
// result text visible in the framebuffer when the run times out.
if (auto_pin_recovery) {
- static int pin_stage = 0;
- static uint64_t pin_t = 0;
+ int &pin_stage = g_auto.pin_stage;
+ uint64_t &pin_t = g_auto.pin_t;
auto press_release = [&](std::atomic *btn,
uint64_t hold_us,
uint64_t cooldown_us) {
@@ -548,7 +598,7 @@ int main(int argc, char *argv[]) {
printf("[emu] Auto PIN recovery armed at emu_usec=%llu\n",
(unsigned long long)state.emu_usec);
}
- static int last_logged_stage = -1;
+ int &last_logged_stage = g_auto.pin_logged_stage;
if (pin_stage != last_logged_stage) {
printf("[emu] Auto PIN stage %d at emu_usec=%llu\n", pin_stage,
(unsigned long long)state.emu_usec);
@@ -610,7 +660,7 @@ int main(int argc, char *argv[]) {
{22850000, 'P', true}, {23020000, 'P', false},
};
static const size_t te_n = sizeof(te_events)/sizeof(te_events[0]);
- static size_t te_idx = 0;
+ size_t &te_idx = g_auto.te_idx;
while (te_idx < te_n && state.emu_usec >= te_events[te_idx].at_us) {
const InputEv &ev = te_events[te_idx];
std::atomic *btn = (ev.btn == 'P') ? &state.btn_power
@@ -625,6 +675,10 @@ int main(int argc, char *argv[]) {
te_idx++;
if (te_idx == te_n)
printf("[auto-te] sequence complete; idling for output\n");
+ // A time jump (FLOW_CTLR sleep) can make the release due
+ // in the same tick; the payload must see the press first.
+ if (ev.down)
+ break;
}
}
@@ -644,17 +698,54 @@ int main(int argc, char *argv[]) {
state.touch_x, state.touch_y);
}
- // Run a batch of ARM instructions
- uint32_t start_addr = pc;
- if (cpsr & (1 << 5)) start_addr |= 1;
+ // Run a batch of ARM instructions. With CPU0 up, the batch is cut
+ // into lockstep slices: the BPMP runs a quantum, then CPU0 runs up
+ // to the same emulated time. Scripted input and the display are
+ // still serviced once per full batch, as before.
+ uint64_t batch_end = state.insn_count + BATCH_INSTRUCTIONS;
+ uint64_t parked_left = BATCH_INSTRUCTIONS;
+ while (state.running && !state.paused &&
+ state.insn_count < batch_end) {
+ if (state.bpmp_halted) {
+ // The BPMP parked itself for good after handing off to
+ // CPU0. It retires nothing; time runs on for CPU0 at the
+ // rate the BPMP's clock would have advanced it.
+ if (!ccplex_cpu0_running()) {
+ printf("[emu] BPMP halted and CPU0 stopped, shutting down emulator\n");
+ state.running = false;
+ break;
+ }
+ if (parked_left < CPU0_QUANTUM_INSTRUCTIONS)
+ break;
+ parked_left -= CPU0_QUANTUM_INSTRUCTIONS;
+ state.emu_usec += CPU0_QUANTUM_INSTRUCTIONS / 10;
+ state.bpmp_slept_us += CPU0_QUANTUM_INSTRUCTIONS / 10;
+ ccplex_run(&state, state.emu_usec);
+ if (state.reboot_requested.load())
+ break;
+ continue;
+ }
+ uint64_t budget = batch_end - state.insn_count;
+ if (ccplex_cpu0_running() && budget > CPU0_QUANTUM_INSTRUCTIONS)
+ budget = CPU0_QUANTUM_INSTRUCTIONS;
- uc_err err = uc_emu_start(uc, start_addr, 0, 0, BATCH_INSTRUCTIONS);
- if (err != UC_ERR_OK) {
- uint32_t error_pc;
- uc_reg_read(uc, UC_ARM_REG_PC, &error_pc);
- fprintf(stderr, "\n[emu] FATAL: Emulation error at PC=0x%08X: %s\n", error_pc, uc_strerror(err));
- state.running = false;
- break;
+ uc_reg_read(uc, UC_ARM_REG_PC, &pc);
+ uc_reg_read(uc, UC_ARM_REG_CPSR, &cpsr);
+ uint32_t start_addr = pc;
+ if (cpsr & (1 << 5)) start_addr |= 1;
+
+ uc_err err = bpmp_run(uc, &state, start_addr, budget);
+ if (err != UC_ERR_OK) {
+ uint32_t error_pc;
+ uc_reg_read(uc, UC_ARM_REG_PC, &error_pc);
+ fprintf(stderr, "\n[emu] FATAL: Emulation error at PC=0x%08X: %s\n", error_pc, uc_strerror(err));
+ state.running = false;
+ break;
+ }
+ // CPU0 catches up to the BPMP's clock.
+ ccplex_run(&state, state.emu_usec);
+ if (state.reboot_requested.load())
+ break;
}
} else {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
@@ -689,11 +780,13 @@ int main(int argc, char *argv[]) {
console_window_shutdown();
config_window_shutdown();
sdl_display_shutdown();
+ ccplex_reset(&state); // closes CPU0's engine, if one is up
uc_close(uc);
free(state.iram_ptr);
+ free(g_low_ptr);
// dram_ptr is a view into dram_low_ptr's block; only free the base once.
- free(state.dram_low_ptr);
+ zeroed_free(state.dram_low_ptr, DRAM_WINDOW_SIZE);
free(state.payload_ptr);
// fb_ptr points inside dram_ptr; do not free separately.
diff --git a/make_sd.py b/make_sd.py
index 752ff64..49ef437 100644
--- a/make_sd.py
+++ b/make_sd.py
@@ -13,6 +13,7 @@ Usage:
"""
import argparse
import os
+import shlex
import subprocess
import sys
@@ -21,6 +22,9 @@ def build_sd_image(src_dir: str, out_img: str, size_mb: int) -> int:
if not os.path.isdir(src_dir):
print(f"[error] source folder not found: {src_dir}")
return 1
+ if size_mb < 64:
+ print("[error] --size-mb must be at least 64: FAT32 needs 65525 clusters")
+ return 1
src_dir_abs = os.path.abspath(src_dir)
out_img_abs = os.path.abspath(out_img)
@@ -45,6 +49,13 @@ def build_sd_image(src_dir: str, out_img: str, size_mb: int) -> int:
print(f"[*] formatting + populating via Docker (alpine)")
fdisk_script = f"o\\nn\\np\\n1\\n2048\\n\\nt\\nc\\nw\\n"
+ # FatFs (and every FAT driver) decides FAT12/16/32 by cluster count, and
+ # FAT32 needs at least 65525 clusters: 4 KiB clusters only get there from
+ # ~260 MB up. Below that, format with 512-byte clusters, or the payload's
+ # f_mount rejects the volume (FR_NO_FILESYSTEM).
+ spc = 8 if size_mb >= 512 else 1
+ # File names go into a shell command line: quote them.
+ q_fat, q_img = shlex.quote(fat_name), shlex.quote(img_name)
docker_cmd = [
"docker", "run", "--rm",
"-v", f"{work_dir}:/work",
@@ -53,10 +64,12 @@ def build_sd_image(src_dir: str, out_img: str, size_mb: int) -> int:
"alpine",
"sh", "-c",
"apk add --no-cache dosfstools mtools util-linux >/dev/null && "
- f"mkfs.fat -F 32 -s 8 {fat_name} && "
- f"mcopy -i {fat_name} -s /src/* :: && "
- f"printf '{fdisk_script}' | fdisk {img_name} && "
- f"dd if={fat_name} of={img_name} bs=1M seek=1 conv=notrunc status=none"
+ f"mkfs.fat -F 32 -s {spc} {q_fat} && "
+ # Every top-level entry, dotfiles included; an empty source is fine.
+ f"(cd /src && find . -mindepth 1 -maxdepth 1 "
+ f"-exec mcopy -i /work/{q_fat} -s {{}} :: \\;) && "
+ f"printf '{fdisk_script}' | fdisk {q_img} && "
+ f"dd if={q_fat} of={q_img} bs=1M seek=1 conv=notrunc status=none"
]
try:
subprocess.run(docker_cmd, check=True)
diff --git a/platform.cpp b/platform.cpp
new file mode 100644
index 0000000..7db8cac
--- /dev/null
+++ b/platform.cpp
@@ -0,0 +1,81 @@
+#include "platform.h"
+
+#include
+#include
+#include
+
+#ifdef _WIN32
+#include
+#else
+#include
+#endif
+
+// ---- Zero-filled memory, committed only where touched --------------------
+//
+// The emulated DRAM window is 2 GiB. calloc gets it from the OS as demand-
+// zero pages, so only what a payload touches becomes resident - but a soft
+// reboot used to memset() the whole block back to zero, which touched every
+// page and left the process 2 GiB resident from the first reboot on. These
+// allocate the same demand-zero memory directly, and hand back fresh zero
+// pages on reset, at the same address (the engines hold host pointers into
+// it), without touching any.
+
+uint8_t *zeroed_alloc(size_t size) {
+#ifdef _WIN32
+ return (uint8_t *)VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT,
+ PAGE_READWRITE);
+#else
+ void *p = mmap(nullptr, size, PROT_READ | PROT_WRITE,
+ MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
+ return p == MAP_FAILED ? nullptr : (uint8_t *)p;
+#endif
+}
+
+void zeroed_reset(uint8_t *p, size_t size) {
+#ifdef _WIN32
+ // Decommitted pages come back zero-filled when committed again.
+ if (!VirtualFree(p, size, MEM_DECOMMIT) ||
+ !VirtualAlloc(p, size, MEM_COMMIT, PAGE_READWRITE))
+ memset(p, 0, size);
+#else
+ // A fresh anonymous mapping over the old one: zero pages, same address.
+ if (mmap(p, size, PROT_READ | PROT_WRITE,
+ MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE | MAP_FIXED, -1,
+ 0) == MAP_FAILED)
+ memset(p, 0, size);
+#endif
+}
+
+void zeroed_free(uint8_t *p, size_t size) {
+ if (!p)
+ return;
+#ifdef _WIN32
+ (void)size;
+ VirtualFree(p, 0, MEM_RELEASE);
+#else
+ munmap(p, size);
+#endif
+}
+
+// ---- Opening files by name -------------------------------------------------
+
+FILE *platform_fopen(const char *path, const char *mode) {
+ FILE *f = fopen(path, mode);
+#ifdef _WIN32
+ // Command-line paths arrive in the ANSI code page, which fopen expects;
+ // SDL hands dropped files over as UTF-8, which it does not. Try the name
+ // as UTF-8 before giving up.
+ if (!f) {
+ int n = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, path, -1,
+ nullptr, 0);
+ int m = MultiByteToWideChar(CP_UTF8, 0, mode, -1, nullptr, 0);
+ if (n > 0 && m > 0) {
+ std::wstring wpath(n, L'\0'), wmode(m, L'\0');
+ MultiByteToWideChar(CP_UTF8, 0, path, -1, &wpath[0], n);
+ MultiByteToWideChar(CP_UTF8, 0, mode, -1, &wmode[0], m);
+ f = _wfopen(wpath.c_str(), wmode.c_str());
+ }
+ }
+#endif
+ return f;
+}
diff --git a/platform.h b/platform.h
new file mode 100644
index 0000000..4df407d
--- /dev/null
+++ b/platform.h
@@ -0,0 +1,69 @@
+#ifndef RCM_PLATFORM_H
+#define RCM_PLATFORM_H
+
+#include
+#include
+#include
+#include
+#include
+#include
+
+// Small portability helpers for the disk-image code, which is the one place
+// the emulator does raw POSIX file I/O.
+
+// MinGW's open() defaults to TEXT mode: _read() turns every CR LF into LF
+// and stops at the first 0x1A byte. On an SD card or eMMC image that is
+// silent sector corruption, so every image fd must be opened O_BINARY.
+// POSIX has no such flag (and no such mode), so it is a no-op there.
+#ifndef O_BINARY
+#define O_BINARY 0
+#endif
+
+// Size of an open file, in 64 bits. MinGW's plain struct stat carries a
+// 32-bit st_size, which cannot describe the 4 GiB chunks Hekate splits a
+// rawnand dump into; _fstati64 can.
+static inline int64_t file_size64(int fd) {
+#ifdef _WIN32
+ struct _stati64 st;
+ if (_fstati64(fd, &st) != 0)
+ return -1;
+ return (int64_t)st.st_size;
+#else
+ struct stat st;
+ if (fstat(fd, &st) != 0)
+ return -1;
+ return (int64_t)st.st_size;
+#endif
+}
+
+// pread/pwrite are POSIX and MinGW does not have them. Seek-then-read is
+// equivalent here: the emulated storage is touched only from the CPU thread,
+// so the atomicity real pread() buys against a shared file offset is not in
+// play.
+#ifdef _WIN32
+#include
+static inline ssize_t pread(int fd, void *buf, size_t n, long long off) {
+ if (_lseeki64(fd, off, SEEK_SET) < 0)
+ return -1;
+ return _read(fd, buf, (unsigned int)n);
+}
+static inline ssize_t pwrite(int fd, const void *buf, size_t n, long long off) {
+ if (_lseeki64(fd, off, SEEK_SET) < 0)
+ return -1;
+ return _write(fd, buf, (unsigned int)n);
+}
+#else
+#include
+#endif
+
+// Large zero-filled memory that only becomes resident where it is touched
+// (platform.cpp). zeroed_reset() makes all of it zero again, at the same
+// address, without touching it.
+uint8_t *zeroed_alloc(size_t size);
+void zeroed_reset(uint8_t *p, size_t size);
+void zeroed_free(uint8_t *p, size_t size);
+
+// fopen() that also accepts a UTF-8 name on Windows (a dropped file).
+FILE *platform_fopen(const char *path, const char *mode);
+
+#endif // RCM_PLATFORM_H
diff --git a/t210/block_linear.h b/t210/block_linear.h
new file mode 100644
index 0000000..615bc17
--- /dev/null
+++ b/t210/block_linear.h
@@ -0,0 +1,27 @@
+#pragma once
+
+#include
+#include
+
+// Tegra X1 block-linear surfaces (TRM 20.1.2), as the display controller and
+// VIC read and write them. A GOB is 64 bytes x 8 lines (512 bytes) of 16Bx2
+// sectors; GOBs stack gob_h high into a block, and blocks run left to right,
+// then down, gobs_per_row GOBs to a row.
+
+// Byte offset of byte column xb (pixel x * bytes per pixel) on line y.
+inline size_t bl_offset(uint32_t xb, uint32_t y, uint32_t gobs_per_row,
+ uint32_t gob_h) {
+ uint32_t gob_y = y / 8;
+ size_t gob = ((size_t)(gob_y / gob_h) * gobs_per_row + xb / 64) * gob_h +
+ gob_y % gob_h;
+ // Within the GOB, TRM Figure 47's sector order.
+ uint32_t x = xb % 64, l = y % 8;
+ return gob * 512 + (x / 32) * 256 + (l / 2) * 64 + ((x % 32) / 16) * 32 +
+ (l % 2) * 16 + (x % 16);
+}
+
+// Bytes a surface h lines tall occupies (whole blocks).
+inline size_t bl_size(uint32_t gobs_per_row, uint32_t gob_h, uint32_t h) {
+ return (size_t)gobs_per_row * 512 * gob_h *
+ ((h + 8 * gob_h - 1) / (8 * gob_h));
+}
diff --git a/t210/bpmp.cpp b/t210/bpmp.cpp
new file mode 100644
index 0000000..f7e5d91
--- /dev/null
+++ b/t210/bpmp.cpp
@@ -0,0 +1,262 @@
+#include "bpmp.h"
+
+#include
+#include
+
+#include "../emu_state.h"
+#include "memory_map.h"
+
+namespace {
+
+// ---- TIMERUS pacing --------------------------------------------------------
+//
+// Real silicon retires a few hundred BPMP instructions per microsecond; this
+// clock credits ten. That dilation is what makes busy-waits cheap to emulate,
+// and it is harmless for the usual `while (now - start < us)` wait. It is not
+// harmless for a wait that needs to SEE a particular counter value. bdk's own
+// fan_get_speed() is one:
+//
+// int timer = get_tmr_us() + 2000000;
+// while ((timer - get_tmr_us()) > 0) // int - u32: unsigned, so "!= 0"
+//
+// GCC compiles that to `cmp; bne`: the loop ends only on the exact deadline.
+// Its body is ~30 instructions - a tenth of a microsecond on hardware, three
+// microseconds here - so the emulated counter stepped past the deadline and
+// the loop spun until TIMERUS wrapped, about 72 emulated minutes later. That
+// is where a hwtest sweep used to stall, in the fan spin-up test.
+//
+// So polls are paced the way hardware paces them: while TIMERUS reads come
+// at most POLL_WINDOW instructions apart - under a microsecond at real speed -
+// the clock advances by at most 1 us from one read to the next. Time stays
+// monotonic for every observer (only increments are capped), a wait still
+// ends at the emulated time it asked for, and a loop that polls less often
+// than that runs on the plain instruction clock.
+constexpr uint64_t POLL_WINDOW = 200;
+
+struct Clock {
+ uint64_t limit = 0; // insn_count at which the current batch ends
+ uint32_t pending = 0; // instructions of the block now executing
+ // TIMERUS pacing (see above).
+ bool polling = false;
+ uint64_t poll_insn = 0; // insn_count at the last TIMERUS read
+ uint64_t poll_usec = 0; // value it returned
+ // Diagnostics.
+ uint64_t loop_addr = 0;
+ uint64_t loop_insns = 0;
+ bool stall_logged = false;
+ bool nop_slide_reported = false;
+};
+
+Clock clk;
+uc_hook h_block;
+
+// Credit `n` retired instructions. emu_usec ticks once per ten, exactly as
+// the per-instruction counter used to tick it, and anything a FLOW_CTLR
+// timed halt added to emu_usec directly is preserved.
+inline void commit(EmuState *s, uint32_t n) {
+ uint64_t before = s->insn_count;
+ s->insn_count += n;
+ uint64_t delta = s->insn_count / 10 - before / 10;
+ if (clk.polling && delta) {
+ if (s->insn_count - clk.poll_insn <= POLL_WINDOW) {
+ uint64_t cap = clk.poll_usec + 1;
+ uint64_t room = cap > s->emu_usec ? cap - s->emu_usec : 0;
+ if (delta > room)
+ delta = room;
+ } else {
+ clk.polling = false;
+ }
+ }
+ s->emu_usec += delta;
+}
+
+inline const uint8_t *code_ptr(const EmuState *s, uint64_t a, uint32_t len) {
+ if (a >= IRAM_BASE && a + len <= IRAM_BASE + IRAM_SIZE)
+ return s->iram_ptr + (a - IRAM_BASE);
+ if (a >= DRAM_BASE && a + len <= DRAM_BASE + DRAM_WINDOW_SIZE)
+ return s->dram_low_ptr + (a - DRAM_BASE);
+ return nullptr;
+}
+
+// Instructions in a translated block, counted the way Unicorn's per-
+// instruction hook saw them. ARM: all four bytes. Thumb: a halfword whose top
+// five bits are 0b11101, 0b11110 or 0b11111 opens a 32-bit instruction - on
+// this core (Unicorn's Cortex-A15) that includes the Thumb-1 BL/BLX prefix
+// and suffix pair, which decodes as one instruction.
+uint32_t decode_insns(uc_engine *uc, const EmuState *s, uint64_t addr,
+ uint32_t size) {
+ uint32_t cpsr = 0;
+ uc_reg_read(uc, UC_ARM_REG_CPSR, &cpsr);
+ if (!(cpsr & (1u << 5)))
+ return size >= 4 ? size / 4 : 1;
+
+ static uint8_t scratch[8192];
+ const uint8_t *p = code_ptr(s, addr, size);
+ if (!p) {
+ // Code outside IRAM/DRAM (the zero-filled iROM, low scratch): rare.
+ uint32_t n = size < sizeof(scratch) ? size : (uint32_t)sizeof(scratch);
+ if (uc_mem_read(uc, addr, scratch, n) != UC_ERR_OK)
+ return size >= 2 ? size / 2 : 1;
+ p = scratch;
+ size = n;
+ }
+ uint32_t n = 0;
+ for (uint32_t i = 0; i + 1 < size; n++) {
+ uint16_t hw = (uint16_t)(p[i] | (p[i + 1] << 8));
+ i += ((hw & 0xF800) >= 0xE800) ? 4 : 2;
+ }
+ return n ? n : 1;
+}
+
+// Decoding a hot block on every execution was most of this hook's cost, so
+// counts are cached per block. A block is identified by address and size,
+// and fingerprinted by its first and last words: code rewritten in place
+// (a relocation, a chainloaded payload) almost always changes one of those,
+// and when it does not, the translator's own retranslation still gives the
+// same instruction boundaries unless the 16/32-bit mix inside changed too.
+struct CountCacheEntry {
+ uint32_t addr;
+ uint32_t head;
+ uint32_t tail;
+ uint16_t size;
+ uint16_t count;
+};
+constexpr size_t kCountCacheSize = 1u << 16;
+CountCacheEntry count_cache[kCountCacheSize];
+
+inline uint32_t load32(const uint8_t *p) {
+ uint32_t v;
+ memcpy(&v, p, 4);
+ return v;
+}
+
+uint32_t count_insns(uc_engine *uc, const EmuState *s, uint64_t addr,
+ uint32_t size) {
+ const uint8_t *p = (size >= 4 && size < 0x10000) ? code_ptr(s, addr, size)
+ : nullptr;
+ if (!p)
+ return decode_insns(uc, s, addr, size);
+ uint32_t head = load32(p), tail = load32(p + size - 4);
+ CountCacheEntry &e = count_cache[(addr >> 1) & (kCountCacheSize - 1)];
+ if (e.addr == (uint32_t)addr && e.size == size && e.head == head &&
+ e.tail == tail && e.count)
+ return e.count;
+ uint32_t n = decode_insns(uc, s, addr, size);
+ e.addr = (uint32_t)addr;
+ e.size = (uint16_t)size;
+ e.head = head;
+ e.tail = tail;
+ e.count = (uint16_t)n;
+ return n;
+}
+
+// A payload that jumps into zeroed memory executes `movs r0, r0` (Thumb
+// 0x0000) or `andeq r0, r0, r0` (ARM) until it hits something. No compiler
+// emits sixteen zero bytes at the start of a block, so that is the signal.
+// The low 16 MB (a null function pointer lands there; the iROM has no
+// contents) is zero-filled RAM too, read through the engine as it is not
+// one of the host views.
+bool nop_slide(uc_engine *uc, const EmuState *s, uint64_t addr) {
+ static const uint8_t zero[16] = {0};
+ if (addr < 0x01000000) {
+ uint8_t buf[16];
+ return uc_mem_read(uc, addr, buf, sizeof(buf)) == UC_ERR_OK &&
+ memcmp(buf, zero, sizeof(zero)) == 0;
+ }
+ bool in_range = (addr >= 0x40030000 && addr < IRAM_BASE + IRAM_SIZE) ||
+ (addr >= DRAM_BASE && addr < DRAM_BASE + DRAM_WINDOW_SIZE);
+ if (!in_range)
+ return false;
+ const uint8_t *p = code_ptr(s, addr, 16);
+ if (!p)
+ return false;
+ return memcmp(p, zero, sizeof(zero)) == 0;
+}
+
+// Once per translated block, before it runs. Credits the previous block,
+// which has now fully executed. When the batch budget is spent it stops the
+// engine here, and Unicorn does not run this block at all - PC stays on its
+// first instruction and the next batch starts there - so it is not counted.
+void hook_block(uc_engine *uc, uint64_t address, uint32_t size, void *ud) {
+ EmuState *s = (EmuState *)ud;
+ commit(s, clk.pending);
+ clk.pending = 0;
+ if (s->insn_count >= clk.limit) {
+ uc_emu_stop(uc);
+ return;
+ }
+
+ if (nop_slide(uc, s, address)) {
+ if (!clk.nop_slide_reported) {
+ clk.nop_slide_reported = true;
+ printf("\n[emu] NOP-slide detected at 0x%08llX (zeroed memory being "
+ "executed) - emulation paused\n", (unsigned long long)address);
+ fflush(stdout);
+ }
+ s->paused = true;
+ uc_emu_stop(uc);
+ return;
+ }
+
+ clk.pending = count_insns(uc, s, address, size);
+
+ // A single-instruction self-loop (`b .`) spinning for a long time is a
+ // payload that has given up; say so once when it finally leaves it.
+ if (size <= 4 && address == clk.loop_addr) {
+ clk.loop_insns += clk.pending;
+ } else {
+ if (clk.loop_insns > 100000 && !clk.stall_logged) {
+ printf("[trace] STALL at PC=0x%08llX (looped %llu times)\n",
+ (unsigned long long)clk.loop_addr,
+ (unsigned long long)clk.loop_insns);
+ clk.stall_logged = true;
+ } else if (clk.loop_insns == 0) {
+ clk.stall_logged = false;
+ }
+ clk.loop_addr = address;
+ clk.loop_insns = 0;
+ }
+}
+
+} // namespace
+
+void bpmp_attach(uc_engine *uc, EmuState *state) {
+ uc_hook_add(uc, &h_block, UC_HOOK_BLOCK, (void *)hook_block, state, 1, 0);
+}
+
+uc_err bpmp_run(uc_engine *uc, EmuState *state, uint64_t begin,
+ uint64_t max_insns) {
+ clk.limit = state->insn_count + (max_insns ? max_insns : 1);
+ clk.pending = 0;
+ // `until` must be an address the core can never reach. 0 is not one: a
+ // null function pointer took the BPMP there, and from then on every start
+ // returned at once without running anything - the main loop spun forever
+ // waiting for instructions to retire. The PC is 32 bits wide.
+ uc_err err = uc_emu_start(uc, begin, 1ULL << 32, 0, 0);
+ // If something other than the budget ended the run (an MMIO handler
+ // calling uc_emu_stop, a fault), the block in flight has still run to its
+ // end - Unicorn only checks for a stop between blocks - so credit it.
+ commit(state, clk.pending);
+ clk.pending = 0;
+ return err;
+}
+
+void bpmp_clock_reset() {
+ clk = Clock();
+ memset(count_cache, 0, sizeof(count_cache));
+}
+
+uint32_t bpmp_timerus_read(EmuState *state) {
+ clk.polling = true;
+ clk.poll_insn = state->insn_count;
+ clk.poll_usec = state->emu_usec;
+ return (uint32_t)state->emu_usec;
+}
+
+void bpmp_clock_jumped() {
+ clk.polling = false;
+}
+
+void bpmp_yield() {
+ clk.limit = 0;
+}
diff --git a/t210/bpmp.h b/t210/bpmp.h
new file mode 100644
index 0000000..a15e0e9
--- /dev/null
+++ b/t210/bpmp.h
@@ -0,0 +1,54 @@
+#ifndef T210_BPMP_H
+#define T210_BPMP_H
+
+#include
+#include
+
+struct EmuState;
+
+/*
+ * BPMP execution and its deterministic clock.
+ *
+ * Emulated time is derived from retired instructions, never from the host:
+ * emu_usec = skipped_us + insn_count / 10, where skipped_us is whatever a
+ * FLOW_CTLR timed halt jumped over. That makes a run reproducible - the same
+ * payload sees the same TIMERUS value at the same instruction every time -
+ * which scripted input (--input-script, --auto-te-script) depends on.
+ *
+ * The instruction count used to come from a UC_HOOK_CODE callback on every
+ * single instruction, which kept Unicorn from running any translated block
+ * at native speed. It now comes from a block hook: the block's instructions
+ * are counted once, from its bytes, and credited when the block has run. The
+ * totals are exactly what per-instruction counting gave. What changed is
+ * resolution inside a block: an MMIO read there sees the time at the start
+ * of its block, not at its own instruction - a fraction of a microsecond at
+ * 10 instructions per microsecond.
+ */
+
+// Install the clock's block hook on the BPMP engine.
+void bpmp_attach(uc_engine *uc, EmuState *state);
+
+// Run from `begin` (bit 0 = Thumb) until at least `max_insns` more
+// instructions have retired, or something stops the engine. Batches end on
+// a block boundary.
+uc_err bpmp_run(uc_engine *uc, EmuState *state, uint64_t begin,
+ uint64_t max_insns);
+
+// Forget any half-accounted block (soft reboot).
+void bpmp_clock_reset();
+
+// TIMERUS_CNTR_1US as the BPMP reads it. See the pacing note in bpmp.cpp:
+// polls issued close together never see the counter skip a value.
+uint32_t bpmp_timerus_read(EmuState *state);
+
+// Time jumped forward outside instruction accounting (a FLOW_CTLR timed
+// halt): whatever poll loop was being paced is over.
+void bpmp_clock_jumped();
+
+// End the current batch at the next block boundary - a clean stop, unlike
+// uc_emu_stop() from an MMIO callback, which abandons the block in flight
+// with the PC back at its start. Used when CPU0 is released, so its first
+// slice starts now rather than a whole batch later.
+void bpmp_yield();
+
+#endif // T210_BPMP_H
diff --git a/t210/ccplex.cpp b/t210/ccplex.cpp
new file mode 100644
index 0000000..a4fea19
--- /dev/null
+++ b/t210/ccplex.cpp
@@ -0,0 +1,620 @@
+#include "ccplex.h"
+#include "bpmp.h"
+
+#include
+#include
+#include
+#include
+
+#include
+
+#include "../emu_state.h"
+#include "memory_map.h"
+#include "mmio.h"
+#include "pcie.h"
+
+// ==========================================================================
+// Registers (bdk soc/clock.h, soc/t210.h, soc/pmc.h; Tegra X1 TRM ch.5/16)
+// ==========================================================================
+
+#define CAR_CCLK_BURST_POLICY 0x020
+#define CCLK_RUN_SRC(v) (((v) >> 4) & 0xF)
+#define CCLK_SRC_PLLX_OUT0_LJ 8
+#define CCLK_SRC_PLLX_OUT0 14
+#define CAR_PLLX_BASE 0x0E0
+#define PLL_BASE_ENABLE (1u << 30)
+#define CAR_CLK_OUT_ENB_V 0x360
+#define CAR_CLK_ENB_V_SET 0x440
+#define CAR_CLK_ENB_V_CLR 0x444
+#define CLK_V_CPUG 0
+#define CLK_V_MSELECT 3
+#define CAR_RST_CPUG_CMPLX_SET 0x450
+#define CAR_RST_CPUG_CMPLX_CLR 0x454
+// RST_CPU_CMPLX_SET (TRM 5.2.113) has RST_CPUG_CMPLX's fields and reset value:
+// it is the active cluster's view, and the Switch runs the G cluster. Its
+// CLR partner at 0x344 is not in the TRM; it pairs the way every SET does.
+#define CAR_RST_CPU_CMPLX_SET 0x340
+#define CAR_RST_CPU_CMPLX_CLR 0x344
+// CLK_CPUG_CMPLX (TRM 5.2.122, reset 0) and its SET/CLR strobes (5.2.154/155):
+// CPUGn_CLK_STP (bits 11:8) stops core n's clock. Like the peripheral banks,
+// all three read back the register.
+#define CAR_CLK_CPUG_CMPLX 0x378
+#define CAR_CLK_CPUG_CMPLX_SET 0x460
+#define CAR_CLK_CPUG_CMPLX_CLR 0x464
+#define CPU0_CLK_STP (1u << 8)
+// RST_CPUG_CMPLX (TRM 5.2.152, reset 0x2000feef). CPU0 runs once nCPUPORESET
+// (CPURESET0, bit 0), nCORERESET (CORERESET0, bit 16), nL2RESET (bit 24) and
+// the nonCPU region's reset (NONCPURESET, bit 29) are all released.
+// ccplex_boot_cpu0() also clears PRESETDBG (bit 30), but that only resets
+// the CoreSight debug logic, which a core runs without; the DBGRESET/
+// WDRESET/DERESET bits in 15:4 are reserved on this SoC.
+#define RST_CPUG_CMPLX_RESET 0x2000FEEFu
+#define RST_CPU0_MASK ((1u << 0) | (1u << 16) | (1u << 24))
+#define RST_NONCPU (1u << 29)
+
+// SB block, SYSREG + 0x200.
+#define SB_CSR 0x00
+#define SB_AA64_RESET_LOW 0x30
+#define SB_AA64_RESET_HIGH 0x34
+#define SB_AA64_RST_AARCH64_MODE_EN (1u << 0)
+
+// PMC partitions carrying CPU0.
+#define POWER_RAIL_CRAIL 0
+#define POWER_RAIL_CE0 14
+#define POWER_RAIL_C0NC 15
+
+// ==========================================================================
+// Timing
+// ==========================================================================
+//
+// PLLX runs the A57s at ~1 GHz. Retiring one instruction per nanosecond is
+// the right order of magnitude, and it is ten times the rate the BPMP clock
+// model uses, which is the other thing that has to hold: CPU0 is the fast
+// core.
+//
+// A bus access is not free. From the A57, a register read goes out through
+// MSELECT and the APC bridge onto a 100-odd MHz APB, and costs a few hundred
+// nanoseconds. Charging it keeps a udelay() loop - which is nothing but
+// TIMERUS reads - at a realistic few million accesses per emulated second
+// instead of a billion instructions of busy-wait.
+static constexpr uint64_t NS_PER_INSN = 1;
+static constexpr uint64_t NS_PER_BUS_ACCESS = 250;
+
+// ==========================================================================
+// Reset entry
+// ==========================================================================
+//
+// A real A57 comes out of reset at EL3 in AArch64 and fetches from the
+// SB_AA64_RESET vector. Unicorn creates its ARM64 core at EL1 instead (a
+// backward-compatibility choice in its cpu init), and it cannot be moved:
+// writing PSTATE updates the mode bits but not the translator's cached
+// hflags, so the first `msr scr_el3` still decodes as EL1 and is UNDEFINED.
+// Nor can an exception carry it up, because Unicorn never delivers guest
+// exceptions - SMC and friends end the run.
+//
+// ERET can. Its helper takes the current EL from PSTATE - which the register
+// write did update - reads SPSR_EL3/ELR, and rebuilds hflags for the target
+// EL. So the core starts on a one-instruction trampoline in a page only CPU0
+// can see, with PSTATE, SPSR_EL3 = EL3h/DAIF masked and ELR = the vector.
+// The translator fetches the new PC's address from ELR at the EL it thinks
+// it is at (EL1), so ELR_EL1 carries it too. One ERET later the core is at
+// EL3h with interrupts masked and the MMU off: architectural reset state.
+//
+// The page sits at 1 TiB: inside the A57's 44-bit physical space, far
+// outside the Tegra's, so it can never alias anything a payload can reach.
+static constexpr uint64_t RESET_TRAMPOLINE = 0x10000000000ULL;
+static constexpr uint32_t A64_ERET = 0xD69F03E0;
+static constexpr uint32_t A64_WFE = 0xD503205F;
+static constexpr uint32_t A64_WFI = 0xD503207F;
+static constexpr uint64_t PSTATE_EL3H_DAIF = 0x3CD;
+
+namespace {
+
+enum class Cpu0 { Off, Running, Hung };
+
+struct Model {
+ uint32_t rst_cpug = RST_CPUG_CMPLX_RESET;
+ uint32_t clk_cpug = 0;
+ uint32_t clk_enb_v = 0;
+ uint32_t cclk_burst = 0;
+ uint32_t pllx_base = 0;
+ uint32_t sb_csr = 0;
+ uint32_t sb_rst_lo = 0;
+ uint32_t sb_rst_hi = 0;
+
+ Cpu0 cpu0 = Cpu0::Off;
+ uc_engine *uc = nullptr;
+ uint64_t pc = 0;
+ uint64_t ns = 0; // CPU0's clock, emulated nanoseconds
+ uint64_t target_ns = 0; // end of the slice being run
+ uint64_t pending = 0; // instructions in the block now executing
+ bool wfe_next = false; // the block now executing ends in WFE/WFI
+ bool in_run = false;
+ bool kill_pending = false;
+ bool reset_pending = false;
+ const char *kill_reason = nullptr;
+
+ uint64_t retired = 0;
+ uint64_t bus_accesses = 0;
+ uint32_t boots = 0;
+ const char *last_refusal = nullptr;
+};
+
+Model m;
+EmuState *g_state = nullptr;
+
+// Pages CPU0 has executed code from, with the bytes it translated; see
+// drop_stale_code().
+struct CodePage {
+ uint64_t base;
+ uint8_t bytes[4096];
+};
+std::vector> code_pages;
+uint64_t last_code_page = ~0ULL;
+uc_hook h_block, h_unmapped, h_intr;
+
+bool held() { return (m.rst_cpug & (RST_CPU0_MASK | RST_NONCPU)) != 0; }
+
+uint64_t entry_vector() {
+ return ((uint64_t)m.sb_rst_hi << 32) | (m.sb_rst_lo & ~1u);
+}
+
+bool entry_mapped(uint64_t a) {
+ return (a >= DRAM_BASE && a + 4 <= DRAM_BASE + DRAM_WINDOW_SIZE) ||
+ (a >= IRAM_BASE && a + 4 <= IRAM_BASE + IRAM_SIZE);
+}
+
+const uint8_t *host_ptr(uint64_t a, uint32_t len) {
+ // Valid for the identity map CPU0 runs with before (MMU off) and after
+ // (the stub's 1 GiB identity blocks) enabling the MMU.
+ if (a >= DRAM_BASE && a + len <= DRAM_BASE + DRAM_WINDOW_SIZE)
+ return g_state->dram_low_ptr + (a - DRAM_BASE);
+ if (a >= IRAM_BASE && a + len <= IRAM_BASE + IRAM_SIZE)
+ return g_state->iram_ptr + (a - IRAM_BASE);
+ return nullptr;
+}
+
+// Everything the core needs to actually execute once released. Returns the
+// first thing missing, or nullptr.
+const char *boot_blocked(EmuState *state) {
+ if (!cpu_rail_on(state))
+ return state->pmic_otp.load() == 0x53
+ ? "CPU rail off (MAX77812 EN_CTRL.EN_M4 clear)"
+ : "CPU rail off (MAX77621 VOUT_EN / MAX77620 GPIO5 EN pin)";
+ if (!pmc_partition_on(POWER_RAIL_CRAIL)) return "CRAIL partition powergated";
+ if (!pmc_partition_on(POWER_RAIL_C0NC)) return "C0NC partition powergated";
+ if (!pmc_partition_on(POWER_RAIL_CE0)) return "CE0 partition powergated";
+ if (!(m.clk_enb_v & (1u << CLK_V_CPUG))) return "CPUG clock disabled (CLK_ENB_V bit 0)";
+ uint32_t src = CCLK_RUN_SRC(m.cclk_burst);
+ if ((src == CCLK_SRC_PLLX_OUT0_LJ || src == CCLK_SRC_PLLX_OUT0) &&
+ !(m.pllx_base & PLL_BASE_ENABLE))
+ return "CCLK runs from PLLX but PLLX is disabled";
+ if (!(m.clk_enb_v & (1u << CLK_V_MSELECT))) return "MSELECT clock disabled";
+ if (!pcie_mselect_up()) return "MSELECT still in reset";
+ if (!(m.sb_rst_lo & SB_AA64_RST_AARCH64_MODE_EN))
+ return "SB_AA64_RESET_LOW has no AArch64 vector (AArch32 CPU boot is not modelled)";
+ if (!entry_mapped(entry_vector())) return "reset vector outside IRAM/DRAM";
+ return nullptr;
+}
+
+void destroy_engine() {
+ code_pages.clear();
+ last_code_page = ~0ULL;
+ if (!m.uc)
+ return;
+ mmio_unmap_bus(m.uc);
+ uc_close(m.uc);
+ m.uc = nullptr;
+}
+
+void stop_cpu0(const char *why) {
+ if (m.cpu0 == Cpu0::Off)
+ return;
+ if (m.in_run) {
+ // The core is the one executing: it just wrote the register that stops
+ // it. Finish the current access, then tear down once the run returns.
+ m.kill_pending = true;
+ m.kill_reason = why;
+ uc_emu_stop(m.uc);
+ return;
+ }
+ printf("[ccplex] CPU0 stopped (%s) after %llu instructions, %llu bus "
+ "accesses\n", why, (unsigned long long)m.retired,
+ (unsigned long long)m.bus_accesses);
+ fflush(stdout);
+ destroy_engine();
+ m.cpu0 = Cpu0::Off;
+}
+
+// ---- CPU0 engine hooks ---------------------------------------------------
+
+// ---- Code the BPMP rewrites under CPU0 ----------------------------------
+//
+// Stores the BPMP makes into shared DRAM/IRAM go through its own engine, so
+// this engine's translation cache never hears of them: a stub loaded for a
+// new job at the address of the last one would run the old one's code. A
+// full flush before every slice cures that but costs tens of milliseconds a
+// time (it walks the page descriptors of the whole 44-bit space), so instead
+// the pages CPU0 has executed from are remembered with a copy of their
+// bytes, and before each slice any that changed have just their own
+// translations dropped.
+void note_code_page(uint64_t address) {
+ uint64_t base = address & ~0xFFFULL;
+ if (base == last_code_page)
+ return;
+ last_code_page = base;
+ for (auto &p : code_pages)
+ if (p->base == base)
+ return;
+ const uint8_t *src = host_ptr(base, 4096);
+ if (!src || code_pages.size() >= 256)
+ return;
+ auto p = std::make_unique();
+ p->base = base;
+ memcpy(p->bytes, src, 4096);
+ code_pages.push_back(std::move(p));
+}
+
+void drop_stale_code() {
+ for (auto &p : code_pages) {
+ const uint8_t *now = host_ptr(p->base, 4096);
+ if (!now || memcmp(now, p->bytes, 4096) == 0)
+ continue;
+ uc_ctl_remove_cache(m.uc, p->base, p->base + 4096);
+ memcpy(p->bytes, now, 4096);
+ }
+}
+
+void commit_pending() {
+ m.ns += m.pending * NS_PER_INSN;
+ m.retired += m.pending;
+ m.pending = 0;
+}
+
+// Once per translated block, before it runs. Accounts the previous block
+// (which has now fully executed), ends the slice when CPU0's clock reaches
+// its target, and parks the core after a WFE/WFI. Stopping here means the
+// block is NOT executed - Unicorn leaves PC on its first instruction - so
+// the next slice picks it up again.
+void hook_block(uc_engine *uc, uint64_t address, uint32_t size, void *) {
+ commit_pending();
+ if (m.wfe_next) {
+ // The block that just ran ended in WFE/WFI: the core sleeps until
+ // something wakes it. Nothing in this model sends it an event, so it
+ // sleeps to the end of the slice and resumes - a spurious wake-up, which
+ // the architecture allows, and which a `for(;;) wfe;` park loop turns
+ // straight back into sleep. Without this that loop would spin through
+ // hundreds of millions of instructions per emulated second.
+ m.wfe_next = false;
+ if (m.ns < m.target_ns)
+ m.ns = m.target_ns;
+ }
+ g_state->emu_usec = m.ns / 1000;
+ if (m.ns >= m.target_ns || m.kill_pending) {
+ uc_emu_stop(uc);
+ return;
+ }
+ note_code_page(address);
+ // Every A64 instruction is four bytes.
+ m.pending = size >= 4 ? size / 4 : 1;
+ if (const uint8_t *p = host_ptr(address + size - 4, 4)) {
+ uint32_t last;
+ memcpy(&last, p, 4);
+ m.wfe_next = (last == A64_WFE || last == A64_WFI);
+ }
+}
+
+bool hook_unmapped(uc_engine *uc, uc_mem_type type, uint64_t address, int size,
+ int64_t value, void *) {
+ (void)size;
+ (void)value;
+ uint64_t pc = 0;
+ uc_reg_read(uc, UC_ARM64_REG_PC, &pc);
+ const char *kind = type == UC_MEM_FETCH_UNMAPPED ? "fetch"
+ : type == UC_MEM_WRITE_UNMAPPED ? "write"
+ : "read";
+ // Nothing decodes this address, so on silicon the transaction never
+ // completes and the core waits on it for ever. Return false: the run ends
+ // and the core is marked wedged, which is what the BPMP's watchdog on the
+ // mailbox heartbeat is there to notice.
+ printf("[ccplex] CPU0 %s of unmapped 0x%llX at PC=0x%llX: nothing answers, "
+ "CPU0 wedged\n", kind, (unsigned long long)address,
+ (unsigned long long)pc);
+ fflush(stdout);
+ return false;
+}
+
+void hook_intr(uc_engine *uc, uint32_t intno, void *) {
+ // Unicorn does not deliver guest exceptions (see the reset-entry note),
+ // so a fault cannot reach the stub's own vectors. Say what happened and
+ // stop the core rather than resume past the faulting instruction.
+ uint64_t pc = 0;
+ uc_reg_read(uc, UC_ARM64_REG_PC, &pc);
+ static const char *names[] = {"?", "UDEF", "SWI", "PREFETCH_ABORT",
+ "DATA_ABORT", "IRQ", "FIQ", "BKPT", "EXIT",
+ "KERNEL_TRAP", "HVC", "HYP_TRAP", "SMC"};
+ printf("[ccplex] CPU0 took exception %u (%s) near PC=0x%llX; exception "
+ "entry is not modelled, CPU0 halted\n", intno,
+ intno < sizeof(names) / sizeof(names[0]) ? names[intno] : "?",
+ (unsigned long long)pc);
+ fflush(stdout);
+ m.kill_pending = false;
+ m.cpu0 = Cpu0::Hung;
+ uc_emu_stop(uc);
+}
+
+bool start_cpu0(EmuState *state) {
+ uint64_t entry = entry_vector();
+ uc_engine *uc = nullptr;
+ uc_err err = uc_open(UC_ARCH_ARM64, UC_MODE_ARM, &uc);
+ if (err != UC_ERR_OK) {
+ printf("[ccplex] cannot create the CPU0 engine: %s\n", uc_strerror(err));
+ return false;
+ }
+ uc_ctl_set_cpu_model(uc, UC_CPU_ARM64_A57);
+
+ // IRAM, DRAM and TZRAM are the same host memory the BPMP engine maps, so
+ // a stub the BPMP copies into DRAM and the mailbox both cores poll are one
+ // set of bytes. Stores from the other engine bypass this one's self-
+ // modifying-code tracking, so ccplex_run() drops its translations before
+ // every slice.
+ err = uc_mem_map_ptr(uc, IRAM_BASE, IRAM_SIZE, UC_PROT_ALL, state->iram_ptr);
+ if (err == UC_ERR_OK)
+ err = uc_mem_map_ptr(uc, DRAM_BASE, DRAM_WINDOW_SIZE, UC_PROT_ALL,
+ state->dram_low_ptr);
+ if (err == UC_ERR_OK)
+ err = uc_mem_map(uc, RESET_TRAMPOLINE, 0x1000, UC_PROT_READ | UC_PROT_EXEC);
+ if (err != UC_ERR_OK) {
+ printf("[ccplex] cannot map CPU0 memory: %s\n", uc_strerror(err));
+ uc_close(uc);
+ return false;
+ }
+ mmio_map_bus(uc, state);
+ uc_mem_write(uc, RESET_TRAMPOLINE, &A64_ERET, sizeof(A64_ERET));
+
+ uint64_t v = PSTATE_EL3H_DAIF;
+ uc_reg_write(uc, UC_ARM64_REG_PSTATE, &v);
+ uc_arm64_cp_reg spsr_el3 = {4, 0, 3, 6, 0, PSTATE_EL3H_DAIF}; // crn crm op0 op1 op2
+ uc_arm64_cp_reg elr_el3 = {4, 0, 3, 6, 1, entry};
+ uc_arm64_cp_reg scr_el3 = {1, 1, 3, 6, 0, 0}; // reset: secure, nothing routed
+ uc_reg_write(uc, UC_ARM64_REG_CP_REG, &spsr_el3);
+ uc_reg_write(uc, UC_ARM64_REG_CP_REG, &elr_el3);
+ uc_reg_write(uc, UC_ARM64_REG_CP_REG, &scr_el3);
+ v = entry;
+ uc_reg_write(uc, UC_ARM64_REG_ELR_EL1, &v);
+
+ uc_hook_add(uc, &h_block, UC_HOOK_BLOCK, (void *)hook_block, nullptr, 1, 0);
+ uc_hook_add(uc, &h_unmapped, UC_HOOK_MEM_UNMAPPED, (void *)hook_unmapped,
+ nullptr, 1, 0);
+ uc_hook_add(uc, &h_intr, UC_HOOK_INTR, (void *)hook_intr, nullptr, 1, 0);
+
+ m.uc = uc;
+ m.pc = RESET_TRAMPOLINE;
+ m.ns = state->emu_usec * 1000; // released at the BPMP's current time
+ m.pending = 0;
+ m.wfe_next = false;
+ m.kill_pending = false;
+ m.retired = 0;
+ m.bus_accesses = 0;
+ m.cpu0 = Cpu0::Running;
+ m.boots++;
+ // Released from a BPMP register write: end the BPMP's batch at the next
+ // block so CPU0's first slice starts now, not up to a batch (~10 ms) later.
+ if (g_bus_master == BUS_BPMP)
+ bpmp_yield();
+ printf("[ccplex] CPU0 released: AArch64 EL3, MMU off, entry 0x%08llX "
+ "(boot #%u)\n", (unsigned long long)entry, m.boots);
+ fflush(stdout);
+ return true;
+}
+
+void try_release(EmuState *state) {
+ const char *why = boot_blocked(state);
+ if (why) {
+ // On silicon the core would never run and nothing would say why. Name
+ // it, once per distinct reason, so a payload that got the sequence wrong
+ // learns what it got wrong.
+ if (why != m.last_refusal)
+ printf("[ccplex] CPU0 released from reset but cannot run: %s\n", why);
+ m.last_refusal = why;
+ fflush(stdout);
+ return;
+ }
+ m.last_refusal = nullptr;
+ start_cpu0(state);
+}
+
+// Out of reset but refused: on silicon the core simply starts the moment the
+// last missing piece (clock, partition, rail, vector) arrives, so every such
+// change looks again.
+void maybe_release(EmuState *state) {
+ if (m.cpu0 == Cpu0::Off && !held() && state)
+ try_release(state);
+}
+
+} // namespace
+
+// ==========================================================================
+
+void ccplex_reset(EmuState *state) {
+ g_state = state;
+ if (m.in_run) {
+ // A reset from inside CPU0's own slice: defer the teardown to the end
+ // of the run.
+ m.kill_pending = true;
+ m.reset_pending = true;
+ m.kill_reason = "SoC reset";
+ uc_emu_stop(m.uc);
+ return;
+ }
+ destroy_engine();
+ uint32_t boots = m.boots;
+ m = Model();
+ m.boots = boots;
+}
+
+void ccplex_car_write(EmuState *state, uint32_t offset, uint32_t val) {
+ switch (offset) {
+ case CAR_CCLK_BURST_POLICY: m.cclk_burst = val; maybe_release(state); break;
+ case CAR_PLLX_BASE: m.pllx_base = val; maybe_release(state); break;
+ case CAR_CLK_OUT_ENB_V: m.clk_enb_v = val; maybe_release(state); break;
+ case CAR_CLK_ENB_V_SET: m.clk_enb_v |= val; maybe_release(state); break;
+ case CAR_CLK_ENB_V_CLR:
+ m.clk_enb_v &= ~val;
+ if ((val & (1u << CLK_V_CPUG)) && m.cpu0 == Cpu0::Running) {
+ // Clock stopped under a running core: it freezes where it is. Treat
+ // it as wedged until the next reset, which is how bdk always follows
+ // this write anyway.
+ printf("[ccplex] CPUG clock gated under a running CPU0 - core frozen\n");
+ m.cpu0 = Cpu0::Hung;
+ }
+ break;
+ case CAR_RST_CPUG_CMPLX_SET:
+ case CAR_RST_CPU_CMPLX_SET:
+ m.rst_cpug |= val;
+ if (val & (RST_CPU0_MASK | RST_NONCPU))
+ stop_cpu0("held in reset");
+ break;
+ case CAR_CLK_CPUG_CMPLX: m.clk_cpug = val; break;
+ case CAR_CLK_CPUG_CMPLX_SET: m.clk_cpug |= val; break;
+ case CAR_CLK_CPUG_CMPLX_CLR: m.clk_cpug &= ~val; break;
+ case CAR_RST_CPUG_CMPLX_CLR:
+ case CAR_RST_CPU_CMPLX_CLR: {
+ bool was_held = held();
+ m.rst_cpug &= ~val;
+ if (was_held && !held() && m.cpu0 == Cpu0::Off)
+ try_release(state);
+ break;
+ }
+ default:
+ break;
+ }
+}
+
+bool ccplex_car_read(uint32_t offset, uint32_t *out) {
+ switch (offset) {
+ case CAR_CLK_OUT_ENB_V:
+ *out = m.clk_enb_v;
+ return true;
+ case CAR_RST_CPUG_CMPLX_SET:
+ case CAR_RST_CPUG_CMPLX_CLR:
+ case CAR_RST_CPU_CMPLX_SET:
+ case CAR_RST_CPU_CMPLX_CLR:
+ *out = m.rst_cpug;
+ return true;
+ case CAR_CLK_CPUG_CMPLX:
+ case CAR_CLK_CPUG_CMPLX_SET:
+ case CAR_CLK_CPUG_CMPLX_CLR:
+ *out = m.clk_cpug;
+ return true;
+ default:
+ return false;
+ }
+}
+
+uint32_t ccplex_sb_read(uint32_t offset) {
+ switch (offset) {
+ case SB_CSR: return m.sb_csr;
+ case SB_AA64_RESET_LOW: return m.sb_rst_lo;
+ case SB_AA64_RESET_HIGH: return m.sb_rst_hi;
+ default: return 0;
+ }
+}
+
+void ccplex_sb_write(EmuState *state, uint32_t offset, uint32_t val) {
+ switch (offset) {
+ case SB_CSR:
+ // NS_RST_VEC_WR_DIS (bit 1) is sticky until reset. It only locks out
+ // non-secure writers, and the vector write below does not check it.
+ m.sb_csr |= val;
+ break;
+ case SB_AA64_RESET_LOW: m.sb_rst_lo = val; maybe_release(state); break;
+ case SB_AA64_RESET_HIGH: m.sb_rst_hi = val & 0xFFF; maybe_release(state); break;
+ default: break;
+ }
+}
+
+void ccplex_partition_changed(EmuState *state, int part, bool on) {
+ if (on) {
+ maybe_release(state);
+ return;
+ }
+ if (part == POWER_RAIL_CRAIL) stop_cpu0("CRAIL partition powergated");
+ if (part == POWER_RAIL_C0NC) stop_cpu0("C0NC partition powergated");
+ if (part == POWER_RAIL_CE0) stop_cpu0("CE0 partition powergated");
+}
+
+void ccplex_rail_changed(EmuState *state) {
+ if (m.cpu0 != Cpu0::Off && !cpu_rail_on(state))
+ stop_cpu0("CPU rail switched off");
+ else
+ maybe_release(state);
+}
+
+void ccplex_preconditions_changed(EmuState *state) { maybe_release(state); }
+
+void ccplex_bus_tick(EmuState *state) {
+ m.ns += NS_PER_BUS_ACCESS;
+ m.bus_accesses++;
+ state->emu_usec = m.ns / 1000;
+}
+
+uint64_t ccplex_now_us() { return m.ns / 1000; }
+
+bool ccplex_cpu0_running() { return m.cpu0 == Cpu0::Running && m.uc; }
+
+void ccplex_run(EmuState *state, uint64_t until_us) {
+ if (!ccplex_cpu0_running())
+ return;
+ uint64_t target = until_us * 1000;
+ if (m.ns >= target)
+ return;
+ // CPU0's clock stopped: the core keeps its state, time passes, nothing
+ // executes. Clearing CPU0_CLK_STP resumes it where it was.
+ if (m.clk_cpug & CPU0_CLK_STP) {
+ m.ns = target;
+ return;
+ }
+
+ // While CPU0 runs, it is the bus master and "now" is its clock: every
+ // register model reads state->emu_usec, and must see CPU0's time - a
+ // model timing CPU0's own sequence (PERST# after Trefclkstable, say) has
+ // to measure it on the clock CPU0 waits on. Both are put back afterwards.
+ // CPU0 trails the BPMP by up to a slice, so a model both cores touch sees
+ // time step back at the switch; such models must not assume `now` only
+ // grows.
+ uint64_t bpmp_usec = state->emu_usec;
+ BusMaster prev = g_bus_master;
+ g_bus_master = BUS_CPU0;
+ state->emu_usec = m.ns / 1000;
+ m.target_ns = target;
+ m.in_run = true;
+
+ drop_stale_code();
+
+ // `until` is an address an A64 PC can never hold (it is not 4-aligned).
+ // 0 would make a branch to address 0 end every slice before it starts.
+ uc_err err = uc_emu_start(m.uc, m.pc, ~0ULL, 0, 0);
+
+ commit_pending();
+ uc_reg_read(m.uc, UC_ARM64_REG_PC, &m.pc);
+ m.in_run = false;
+ g_bus_master = prev;
+ state->emu_usec = bpmp_usec;
+
+ if (m.kill_pending) {
+ m.kill_pending = false;
+ const char *why = m.kill_reason ? m.kill_reason : "stopped";
+ m.cpu0 = Cpu0::Running; // so stop_cpu0 does the teardown
+ stop_cpu0(why);
+ if (m.reset_pending)
+ ccplex_reset(state);
+ return;
+ }
+ if (err != UC_ERR_OK && m.cpu0 == Cpu0::Running) {
+ printf("[ccplex] CPU0 wedged at PC=0x%llX: %s\n",
+ (unsigned long long)m.pc, uc_strerror(err));
+ fflush(stdout);
+ m.cpu0 = Cpu0::Hung;
+ }
+}
diff --git a/t210/ccplex.h b/t210/ccplex.h
new file mode 100644
index 0000000..5816458
--- /dev/null
+++ b/t210/ccplex.h
@@ -0,0 +1,64 @@
+#ifndef T210_CCPLEX_H
+#define T210_CCPLEX_H
+
+#include
+
+struct EmuState;
+
+/*
+ * CCPLEX CPU0 - the first Cortex-A57 of the Tegra X1's main CPU cluster.
+ *
+ * An RCM payload runs on the BPMP, but it can boot CPU0 itself with bdk's
+ * ccplex_boot_cpu0(): rail on, PLLX, CCLK, the CRAIL/C0NC/CE0 partitions,
+ * RAM repair, the AArch64 reset vector in SB_AA64_RESET_LOW/HIGH, then
+ * RST_CPUG_CMPLX_CLR. hwtest does exactly that for its PCIe probe, because
+ * PCIe answers a CPU-complex master only.
+ *
+ * This model watches those registers and, when the core is released with
+ * every precondition met, runs it: a second Unicorn engine in AArch64 mode,
+ * entered at EL3 with the MMU off at the programmed vector, sharing IRAM,
+ * DRAM, TZRAM and every peripheral model with the BPMP. A release that is
+ * missing something does not start the core, and says which precondition
+ * was missing - on silicon the core would simply never run.
+ *
+ * Time: CPU0 keeps its own clock, advanced by the instructions it retires
+ * and by the latency of each bus access it makes, and the main loop runs it
+ * in short slices up to the BPMP's current time. WFE/WFI park it until the
+ * end of the slice. Everything is a pure function of the instruction stream,
+ * so runs stay deterministic.
+ */
+
+// Power-on state: CPU0 in reset, no vector, clocks off.
+void ccplex_reset(EmuState *state);
+
+// CAR (clock and reset controller) forwarding.
+void ccplex_car_write(EmuState *state, uint32_t offset, uint32_t val);
+bool ccplex_car_read(uint32_t offset, uint32_t *out);
+
+// SB block (SYSREG + 0x200): SB_CSR and the AArch64 reset vector.
+uint32_t ccplex_sb_read(uint32_t offset);
+void ccplex_sb_write(EmuState *state, uint32_t offset, uint32_t val);
+
+// A PMC power partition toggled / the CPU rail regulator changed. Losing any
+// of them under a running core stops it.
+void ccplex_partition_changed(EmuState *state, int part, bool on);
+void ccplex_rail_changed(EmuState *state);
+
+// Something CPU0 needs in order to run changed (MSELECT reset released, ...):
+// a core already out of reset but refused starts if nothing is missing now.
+void ccplex_preconditions_changed(EmuState *state);
+
+// CPU0's own clock, in emulated microseconds: what TIMERUS reads from CPU0.
+uint64_t ccplex_now_us();
+
+// Called by the MMIO front-end for every access CPU0 makes: charges the bus
+// latency to CPU0's clock before the access is dispatched.
+void ccplex_bus_tick(EmuState *state);
+
+// True while CPU0 is out of reset and executing (not parked on a hung bus).
+bool ccplex_cpu0_running();
+
+// Run CPU0 until its clock reaches `until_us` - the BPMP's current time.
+void ccplex_run(EmuState *state, uint64_t until_us);
+
+#endif // T210_CCPLEX_H
diff --git a/t210/i2c3.cpp b/t210/i2c3.cpp
index 7e5ecf1..05c0481 100644
--- a/t210/i2c3.cpp
+++ b/t210/i2c3.cpp
@@ -132,17 +132,15 @@ void push_controller_ready() {
if (ev_stack.size() < 32) ev_stack.push_back(ev);
}
-// If SDL has flagged a pending touch event, pack it into the FTS4 stack.
+// Move whatever SDL has queued into the FTS4 event stack, oldest first.
void try_emit_pending_touch(EmuState *state) {
- bool was_pending = state->tc_event_pending.exchange(false);
- if (!was_pending) return;
- uint8_t op = state->tc_event_op.load();
- uint16_t x = state->tc_x.load();
- uint16_t y = state->tc_y.load();
- // pressure: a small non-zero value keeps z below the 500-palm-reject threshold
- // in touch.c (z = (pressure_lo|pressure_hi<<8) << 6 / (mod+0x40)).
- uint16_t pressure = (op == FTS4_EV_MULTI_TOUCH_LEAVE) ? 0 : 0x10;
- push_event(op, state->tc_finger_id, x, y, pressure);
+ EmuState::TouchEvent ev;
+ while (ev_stack.size() < 32 && state->touch_take(&ev)) {
+ // pressure: a small non-zero value keeps z below the 500-palm-reject
+ // threshold in touch.c (z = (pressure_lo|pressure_hi<<8) << 6 / (mod+0x40)).
+ uint16_t pressure = (ev.op == FTS4_EV_MULTI_TOUCH_LEAVE) ? 0 : 0x10;
+ push_event(ev.op, state->tc_finger_id, ev.x, ev.y, pressure);
+ }
}
// Pop oldest event into 8-byte buffer; on empty, return NO_EVENT.
@@ -307,6 +305,24 @@ uint32_t pull_rx_word() {
} // namespace
+void i2c3_reset(EmuState *state) {
+ slave_addr = 0;
+ dir_read = false;
+ cmd_data[0] = cmd_data[1] = 0;
+ last_cnfg = 0;
+ pkt_state = PKT_HDR_W1;
+ pkt_size = pkt_recv = 0;
+ pkt_is_combined = false;
+ tx_buf.clear();
+ rx_buf.clear();
+ rx_pos = 0;
+ ev_stack.clear();
+ EmuState::TouchEvent ev;
+ while (state->touch_take(&ev)) {
+ }
+ state->tc_pressed = false;
+}
+
uint32_t i2c3_read(EmuState *state, uint64_t addr) {
uint32_t offset = (uint32_t)(addr - I2C3_BASE);
switch (offset) {
diff --git a/t210/i2c3.h b/t210/i2c3.h
index 4ae7aa1..8ab53dc 100644
--- a/t210/i2c3.h
+++ b/t210/i2c3.h
@@ -12,4 +12,8 @@ struct EmuState;
uint32_t i2c3_read(EmuState *state, uint64_t addr);
void i2c3_write(EmuState *state, uint64_t addr, uint32_t val);
+// Soft reboot: controller and touch controller back to power-on, with no
+// events left over from the previous run.
+void i2c3_reset(EmuState *state);
+
#endif
diff --git a/t210/memory_map.h b/t210/memory_map.h
index 90774d6..891aac9 100644
--- a/t210/memory_map.h
+++ b/t210/memory_map.h
@@ -1,243 +1,266 @@
-#ifndef T210_MEMORY_MAP_H
-#define T210_MEMORY_MAP_H
-
-#include
-
-/*
- * Tegra X1 (T210) Memory Map for RCM Payload Emulation
- *
- * RCM payloads (hekate, etc.) run ARM32 code on the BPMP.
- * They primarily use IRAM and access hardware via MMIO registers.
- */
-
-// ==================== RAM Regions ====================
-
-// IRAM (Internal SRAM) - 256KB
-constexpr uint64_t IRAM_BASE = 0x40000000;
-constexpr uint64_t IRAM_SIZE = (16 * 1024 * 1024); // 16 MB mapped (actual 512 KB, but hekate needs relocation space)
-
-// DRAM - We allocate a modest amount for framebuffer + heap
-constexpr uint64_t DRAM_BASE = 0x80000000;
-// Size of the contiguous DRAM window we map. The BPMP is a 32-bit core, so
-// everything it can address above DRAM_BASE ends at 0x100000000 - that upper
-// bound, not the console's physical 4 GB, is what a BPMP-side payload can
-// actually walk. MC_EMEM_CFG still reports the true 4096 MB.
-constexpr uint64_t DRAM_WINDOW_SIZE = 0x80000000ULL; // 2 GB
-constexpr uint64_t DRAM_SIZE = 0x80000000; // 2GB (Full T210 DRAM space for FatFs buffers)
-
-// Payload load address within IRAM
-constexpr uint64_t IPL_LOAD_ADDR = 0x40010000;
-
-// Stack addresses used by hekate
-constexpr uint64_t IPL_STACK_ADDR = 0x4003FF00;
-
-// Heap (in DRAM)
-constexpr uint64_t IPL_HEAP_START = 0x90000000;
-constexpr uint64_t IPL_HEAP_SIZE = 0x02000000; // 32MB
-
-// ==================== MMIO Regions ====================
-// All MMIO is in the 0x50000000-0x7FFFFFFF range on T210
-
-// Clock and Reset Controller
-constexpr uint64_t CLK_RST_BASE = 0x60006000;
-constexpr uint64_t CLK_RST_SIZE = 0x1000;
-
-// Timer (TMR)
-constexpr uint64_t TMR_BASE = 0x60005000;
-constexpr uint64_t TMR_SIZE = 0x1000;
-
-// GPIO
-constexpr uint64_t GPIO_BASE = 0x6000D000;
-constexpr uint64_t GPIO_SIZE = 0x1000;
-
-// PINMUX
-constexpr uint64_t PINMUX_BASE = 0x70003000;
-constexpr uint64_t PINMUX_SIZE = 0x1000;
-
-// UART
-constexpr uint64_t UART_A_BASE = 0x70006000;
-constexpr uint64_t UART_SIZE = 0x1000;
-
-// I2C controllers
-// Note: Tegra X1 base offsets per Hekate bdk/soc/i2c.c _i2c_base_offsets[]:
-// I2C1=0x0, I2C2=0x400, I2C3=0x500, I2C4=0x700, I2C5=0x1000, I2C6=0x1100
-// All measured from APB I2C base 0x7000C000.
-constexpr uint64_t I2C1_BASE = 0x7000C000;
-constexpr uint64_t I2C2_BASE = 0x7000C400; // GEN2_I2C, Rohm BH1730 ALS at slave 0x29
-constexpr uint64_t I2C2_SIZE = 0x100;
-constexpr uint64_t I2C3_BASE = 0x7000C500; // GEN3_I2C, used by STMFTS touchscreen at slave 0x49
-constexpr uint64_t I2C5_BASE = 0x7000D000;
-constexpr uint64_t I2C_SIZE = 0x1000;
-constexpr uint64_t I2C3_SIZE = 0x100;
-
-// PWM
-constexpr uint64_t PWM_BASE = 0x7000A000;
-constexpr uint64_t PWM_SIZE = 0x1000;
-
-// RTC
-constexpr uint64_t RTC_BASE = 0x7000E000;
-// 0x400, NOT 0x1000: the PMC block starts at 0x7000E400, immediately after the
-// RTC. A 0x1000-long RTC window swallowed the whole PMC range, and because the
-// RTC branch is tested first in the MMIO dispatch, every PMC access (reset
-// status, scratch registers, and the MAIN_RST reboot write) silently went to
-// the RTC handler instead.
-constexpr uint64_t RTC_SIZE = 0x400;
-
-// PMC (Power Management Controller)
-constexpr uint64_t PMC_BASE = 0x7000E400;
-constexpr uint64_t PMC_SIZE = 0x0C00;
-
-// Fuse Controller
-constexpr uint64_t FUSE_BASE = 0x7000F800;
-constexpr uint64_t FUSE_SIZE = 0x0400;
-
-// EMC (External Memory Controller). EMC_BASE is the broadcast/control bank;
-// EMC0/EMC1 are the per-channel banks used to read mode-register responses
-// (sdram_read_mrx splits the 16-bit MRR into low byte = ch0, high byte = ch1).
-constexpr uint64_t EMC_BASE = 0x7001B000;
-constexpr uint64_t EMC_SIZE = 0x1000;
-constexpr uint64_t EMC0_BASE = 0x7001E000;
-constexpr uint64_t EMC1_BASE = 0x7001F000;
-
-// MC (Memory Controller)
-constexpr uint64_t MC_BASE = 0x70019000;
-constexpr uint64_t MC_SIZE = 0x1000;
-
-// Display Controller (DC/DSI)
-constexpr uint64_t DISPLAY_A_BASE = 0x54200000;
-constexpr uint64_t DISPLAY_SIZE = 0x40000;
-
-// DSI Controller
-constexpr uint64_t DSI_BASE = 0x54300000;
-constexpr uint64_t DSI_SIZE = 0x1000;
-
-// SOC_THERM - on-die thermal sensors (tCPU0-3, tMEM0/1, tGPU, tPLLX).
-// Distinct from the TMP451 (I2C) board sensor: these are the Tegra's own
-// internal sensors, calibrated by fuses, that HOS/HW tests read to spot bad
-// factory thermal-cal fuses.
-constexpr uint64_t SOC_THERM_BASE = 0x700E2000;
-constexpr uint64_t SOC_THERM_SIZE = 0x1000;
-
-// MIPI CAL
-constexpr uint64_t MIPI_CAL_BASE = 0x700E3000;
-constexpr uint64_t MIPI_CAL_SIZE = 0x1000;
-
-// SOR (Serial Output Resource) / HDMI
-constexpr uint64_t SOR_BASE = 0x54540000;
-constexpr uint64_t SOR_SIZE = 0x1000;
-
-// SDMMC controllers
-constexpr uint64_t SDMMC1_BASE = 0x700B0000; // SD Card
-constexpr uint64_t SDMMC4_BASE = 0x700B0600; // eMMC
-constexpr uint64_t SDMMC_SIZE = 0x1000;
-
-// APB Misc
-constexpr uint64_t APB_MISC_BASE = 0x70000000;
-constexpr uint64_t APB_MISC_SIZE = 0x1000;
-
-// VIC (Video Image Compositor)
-constexpr uint64_t VIC_BASE = 0x54340000;
-constexpr uint64_t VIC_SIZE = 0x40000;
-
-// Host1x (display sync)
-constexpr uint64_t HOST1X_BASE = 0x50000000;
-constexpr uint64_t HOST1X_SIZE = 0x40000;
-
-// BPMP Cache
-constexpr uint64_t BPMP_CACHE_BASE = 0x50040000;
-constexpr uint64_t BPMP_CACHE_SIZE = 0x1000;
-
-// System Registers (SYSREG)
-constexpr uint64_t SYSREG_BASE = 0x6000C000;
-constexpr uint64_t SYSREG_SIZE = 0x1000;
-
-// I2S (Audio)
-constexpr uint64_t I2S_BASE = 0x702D1000;
-constexpr uint64_t I2S_SIZE = 0x1000;
-
-// APE audio hub: ADMAIF (+0x000) and the AXBAR crossbar (+0x800) share one
-// 4 KB page directly below I2S. Modelling it is not optional for hwtest: its
-// speaker probe pushes ~224k samples through the ADMAIF PIO FIFO one 32-bit
-// write at a time, and every write reaching the write-chain's fall-through
-// arm costs a printf + fflush. Unmodelled, the melody alone emits a quarter
-// of a million log lines and the run never reaches the Display / Inputs /
-// Raw state / Diagnostics pages.
-constexpr uint64_t ADMAIF_BASE = 0x702D0000;
-constexpr uint64_t ADMAIF_SIZE = 0x1000;
-
-// ADMA, the audio DMA engine. hwtest resets and enables it but never runs a
-// channel (the tone goes in by PIO), so only the soft-reset handshake has to
-// be believable.
-constexpr uint64_t ADMA_BASE = 0x702E2000;
-constexpr uint64_t ADMA_SIZE = 0x1000;
-
-// SE (Security Engine)
-constexpr uint64_t SE_BASE = 0x70012000;
-constexpr uint64_t SE_SIZE = 0x2000;
-
-// MSELECT: the fabric between every master (CCPLEX and BPMP alike) and the
-// AXI slaves, PCIe among them. Modelled because leaving it in reset is the
-// difference between a register read and a permanently hung console.
-constexpr uint64_t MSELECT_BASE = 0x50060000;
-constexpr uint64_t MSELECT_SIZE = 0x1000;
-
-// XUSB pad controller. Owns the UPHY SERDES lanes shared by PCIe (pcie-0..4)
-// and USB 3.0 SuperSpeed (pcie-5/6 on this board), plus UPHY PLL P0.
-constexpr uint64_t XUSB_PADCTL_BASE = 0x7009F000;
-constexpr uint64_t XUSB_PADCTL_SIZE = 0x1000;
-
-// ==================== PCIe ====================
-//
-// Unlike every other peripheral here, the PCIe apertures live BELOW the
-// 0x50000000 MMIO band - T210 puts the whole root complex in the bottom of
-// the address map (tegra210.dtsi pcie@1003000). The BPMP can address it:
-// bdk's MMU table defines DRAM and IRAM entries only and leaves the fallback
-// entry RWX, so PCIe space is reachable and uncached.
-//
-// Only the windows a payload actually touches are mapped: 16 KiB covering
-// both root ports plus PADS and AFI, 128 KiB of configuration aperture (bus
-// 0 and bus 1 are all that exist), and one 4 KiB page of downstream memory
-// for the endpoint's BAR0 register window. Mapping the architectural sizes
-// (256 MiB of config, 208 MiB of memory) would cost the host gigabytes for
-// address ranges nothing ever reads.
-constexpr uint64_t PCIE_RP0_BASE = 0x01000000; // root port 0 registers
-constexpr uint64_t PCIE_RP1_BASE = 0x01001000; // root port 1 registers
-constexpr uint64_t PCIE_PADS_BASE = 0x01003000;
-constexpr uint64_t PCIE_AFI_BASE = 0x01003800;
-constexpr uint64_t PCIE_BLOCK_BASE = 0x01000000;
-constexpr uint64_t PCIE_BLOCK_SIZE = 0x4000;
-constexpr uint64_t PCIE_CS_BASE = 0x02000000; // type-1 extended config
-constexpr uint64_t PCIE_CS_MODEL_SIZE = 0x20000; // buses 0 and 1 only
-constexpr uint64_t PCIE_MEM_BASE = 0x13000000; // non-prefetchable window
-constexpr uint64_t PCIE_MEM_MODEL_SIZE = 0x1000;
-
-// TSEC (Falcon control regs are in the 0x1000–0x11FF window within TSEC_BASE)
-constexpr uint64_t TSEC_BASE = 0x54500000;
-constexpr uint64_t TSEC_SIZE = 0x2000;
-
-// TZRAM
-constexpr uint64_t TZRAM_BASE = 0x7C010000;
-constexpr uint64_t TZRAM_SIZE = 0x10000; // 64KB
-
-// System Registers (SYSCTR0)
-constexpr uint64_t SYSCTR0_BASE = 0x700F0000;
-constexpr uint64_t SYSCTR0_SIZE = 0x1000;
-
-// ==================== Framebuffer ====================
-
-// hekate uses a display window within DRAM for framebuffer
-// The display init code sets up a linear framebuffer at predefined addresses.
-// IPL_FB_ADDRESS is 0xF5A00000, NYX is 0xF6200000.
-// We allocate a 16MB block covering 0xF5A00000 - 0xF6A00000
-constexpr uint64_t FB_BASE = 0xF5A00000;
-constexpr uint64_t FB_SIZE = 0x01000000; // 16MB
-
-// Display dimensions (hekate: 720 width, 1280 height in portrait)
-constexpr int DISPLAY_WIDTH = 720;
-constexpr int DISPLAY_HEIGHT = 1280;
-
-// Landscape dimensions for SDL window
-constexpr int WINDOW_WIDTH = 720;
-constexpr int WINDOW_HEIGHT = 1280;
-
-#endif // T210_MEMORY_MAP_H
+#ifndef T210_MEMORY_MAP_H
+#define T210_MEMORY_MAP_H
+
+#include
+
+/*
+ * Tegra X1 (T210) Memory Map for RCM Payload Emulation
+ *
+ * RCM payloads (hekate, etc.) run ARM32 code on the BPMP.
+ * They primarily use IRAM and access hardware via MMIO registers.
+ */
+
+// ==================== RAM Regions ====================
+
+// IRAM (Internal SRAM) - 256KB
+constexpr uint64_t IRAM_BASE = 0x40000000;
+constexpr uint64_t IRAM_SIZE = (16 * 1024 * 1024); // 16 MB mapped (actual 512 KB, but hekate needs relocation space)
+
+// DRAM - We allocate a modest amount for framebuffer + heap
+constexpr uint64_t DRAM_BASE = 0x80000000;
+// Size of the contiguous DRAM window we map. The BPMP is a 32-bit core, so
+// everything it can address above DRAM_BASE ends at 0x100000000 - that upper
+// bound, not the console's physical 4 GB, is what a BPMP-side payload can
+// actually walk. MC_EMEM_CFG still reports the true 4096 MB.
+constexpr uint64_t DRAM_WINDOW_SIZE = 0x80000000ULL; // 2 GB
+constexpr uint64_t DRAM_SIZE = 0x80000000; // 2GB (Full T210 DRAM space for FatFs buffers)
+
+// Payload load address within IRAM
+constexpr uint64_t IPL_LOAD_ADDR = 0x40010000;
+
+// Stack addresses used by hekate
+constexpr uint64_t IPL_STACK_ADDR = 0x4003FF00;
+
+// Heap (in DRAM)
+constexpr uint64_t IPL_HEAP_START = 0x90000000;
+constexpr uint64_t IPL_HEAP_SIZE = 0x02000000; // 32MB
+
+// ==================== MMIO Regions ====================
+// All MMIO is in the 0x50000000-0x7FFFFFFF range on T210
+
+// Clock and Reset Controller
+constexpr uint64_t CLK_RST_BASE = 0x60006000;
+constexpr uint64_t CLK_RST_SIZE = 0x1000;
+
+// Timer (TMR)
+constexpr uint64_t TMR_BASE = 0x60005000;
+constexpr uint64_t TMR_SIZE = 0x1000;
+
+// GPIO
+constexpr uint64_t GPIO_BASE = 0x6000D000;
+constexpr uint64_t GPIO_SIZE = 0x1000;
+
+// PINMUX
+constexpr uint64_t PINMUX_BASE = 0x70003000;
+constexpr uint64_t PINMUX_SIZE = 0x1000;
+
+// UART
+constexpr uint64_t UART_A_BASE = 0x70006000;
+constexpr uint64_t UART_SIZE = 0x1000;
+
+// I2C controllers
+// Note: Tegra X1 base offsets per Hekate bdk/soc/i2c.c _i2c_base_offsets[]:
+// I2C1=0x0, I2C2=0x400, I2C3=0x500, I2C4=0x700, I2C5=0x1000, I2C6=0x1100
+// All measured from APB I2C base 0x7000C000.
+constexpr uint64_t I2C1_BASE = 0x7000C000;
+constexpr uint64_t I2C2_BASE = 0x7000C400; // GEN2_I2C, Rohm BH1730 ALS at slave 0x29
+constexpr uint64_t I2C2_SIZE = 0x100;
+constexpr uint64_t I2C3_BASE = 0x7000C500; // GEN3_I2C, used by STMFTS touchscreen at slave 0x49
+constexpr uint64_t I2C5_BASE = 0x7000D000;
+constexpr uint64_t I2C_SIZE = 0x1000; // the MMIO page: I2C5, I2C6, SPI2B
+constexpr uint64_t I2C_CTRL_SIZE = 0x100; // one controller's registers
+constexpr uint64_t I2C4_BASE = 0x7000C700;
+constexpr uint64_t I2C6_BASE = 0x7000D100;
+constexpr uint64_t I2C3_SIZE = 0x100;
+
+// PWM
+constexpr uint64_t PWM_BASE = 0x7000A000;
+constexpr uint64_t PWM_SIZE = 0x1000;
+
+// RTC
+constexpr uint64_t RTC_BASE = 0x7000E000;
+// 0x400, NOT 0x1000: the PMC block starts at 0x7000E400, immediately after the
+// RTC. A 0x1000-long RTC window swallowed the whole PMC range, and because the
+// RTC branch is tested first in the MMIO dispatch, every PMC access (reset
+// status, scratch registers, and the MAIN_RST reboot write) silently went to
+// the RTC handler instead.
+constexpr uint64_t RTC_SIZE = 0x400;
+
+// PMC (Power Management Controller)
+constexpr uint64_t PMC_BASE = 0x7000E400;
+constexpr uint64_t PMC_SIZE = 0x0C00;
+
+// Fuse Controller
+constexpr uint64_t FUSE_BASE = 0x7000F800;
+constexpr uint64_t FUSE_SIZE = 0x0400;
+
+// EMC (External Memory Controller). EMC_BASE is the broadcast/control bank;
+// EMC0/EMC1 are the per-channel banks used to read mode-register responses
+// (sdram_read_mrx splits the 16-bit MRR into low byte = ch0, high byte = ch1).
+constexpr uint64_t EMC_BASE = 0x7001B000;
+constexpr uint64_t EMC_SIZE = 0x1000;
+constexpr uint64_t EMC0_BASE = 0x7001E000;
+constexpr uint64_t EMC1_BASE = 0x7001F000;
+
+// MC (Memory Controller)
+constexpr uint64_t MC_BASE = 0x70019000;
+constexpr uint64_t MC_SIZE = 0x1000;
+
+// Display Controller (DC/DSI)
+constexpr uint64_t DISPLAY_A_BASE = 0x54200000;
+constexpr uint64_t DISPLAY_SIZE = 0x40000;
+
+// DSI Controller
+constexpr uint64_t DSI_BASE = 0x54300000;
+constexpr uint64_t DSI_SIZE = 0x1000;
+
+// SOC_THERM - on-die thermal sensors (tCPU0-3, tMEM0/1, tGPU, tPLLX).
+// Distinct from the TMP451 (I2C) board sensor: these are the Tegra's own
+// internal sensors, calibrated by fuses, that HOS/HW tests read to spot bad
+// factory thermal-cal fuses.
+constexpr uint64_t SOC_THERM_BASE = 0x700E2000;
+constexpr uint64_t SOC_THERM_SIZE = 0x1000;
+
+// MIPI CAL
+constexpr uint64_t MIPI_CAL_BASE = 0x700E3000;
+constexpr uint64_t MIPI_CAL_SIZE = 0x1000;
+
+// SOR (Serial Output Resource) / HDMI
+constexpr uint64_t SOR_BASE = 0x54540000;
+constexpr uint64_t SOR_SIZE = 0x1000;
+
+// SDMMC controllers
+constexpr uint64_t SDMMC1_BASE = 0x700B0000; // SD Card
+constexpr uint64_t SDMMC4_BASE = 0x700B0600; // eMMC
+constexpr uint64_t SDMMC_SIZE = 0x1000;
+
+// APB Misc
+constexpr uint64_t APB_MISC_BASE = 0x70000000;
+constexpr uint64_t APB_MISC_SIZE = 0x1000;
+
+// VIC (Video Image Compositor)
+constexpr uint64_t VIC_BASE = 0x54340000;
+constexpr uint64_t VIC_SIZE = 0x40000;
+
+// Host1x (display sync)
+constexpr uint64_t HOST1X_BASE = 0x50000000;
+constexpr uint64_t HOST1X_SIZE = 0x40000;
+
+// BPMP Cache
+constexpr uint64_t BPMP_CACHE_BASE = 0x50040000;
+constexpr uint64_t BPMP_CACHE_SIZE = 0x1000;
+
+// System Registers (SYSREG). SB (secure boot) sits at +0x200 and holds the
+// CCPLEX's AArch64 reset vector (SB_AA64_RESET_LOW/HIGH, +0x230/+0x234).
+constexpr uint64_t SYSREG_BASE = 0x6000C000;
+constexpr uint64_t SYSREG_SIZE = 0x1000;
+
+// Flow controller: BPMP/CPU halt events, cluster control, RAM repair.
+constexpr uint64_t FLOW_CTLR_BASE = 0x60007000;
+constexpr uint64_t FLOW_CTLR_SIZE = 0x1000;
+
+// Exception vectors, incl. EVP_CPU_RESET_VECTOR (+0x100) for AArch32 boot.
+constexpr uint64_t EXCP_VEC_BASE = 0x6000F000;
+constexpr uint64_t EXCP_VEC_SIZE = 0x1000;
+
+// I2S (Audio)
+constexpr uint64_t I2S_BASE = 0x702D1000;
+constexpr uint64_t I2S_SIZE = 0x1000;
+
+// APE audio hub: ADMAIF (+0x000) and the AXBAR crossbar (+0x800) share one
+// 4 KB page directly below I2S. Modelling it is not optional for hwtest: its
+// speaker probe pushes ~224k samples through the ADMAIF PIO FIFO one 32-bit
+// write at a time, and every write reaching the write-chain's fall-through
+// arm costs a printf + fflush. Unmodelled, the melody alone emits a quarter
+// of a million log lines and the run never reaches the Display / Inputs /
+// Raw state / Diagnostics pages.
+constexpr uint64_t ADMAIF_BASE = 0x702D0000;
+constexpr uint64_t ADMAIF_SIZE = 0x1000;
+
+// ADMA, the audio DMA engine. hwtest resets and enables it but never runs a
+// channel (the tone goes in by PIO), so only the soft-reset handshake has to
+// be believable.
+constexpr uint64_t ADMA_BASE = 0x702E2000;
+constexpr uint64_t ADMA_SIZE = 0x1000;
+
+// SE (Security Engine)
+constexpr uint64_t SE_BASE = 0x70012000;
+constexpr uint64_t SE_SIZE = 0x2000;
+
+// MSELECT: the fabric between every master (CCPLEX and BPMP alike) and the
+// AXI slaves, PCIe among them. Modelled because leaving it in reset is the
+// difference between a register read and a permanently hung console.
+constexpr uint64_t MSELECT_BASE = 0x50060000;
+constexpr uint64_t MSELECT_SIZE = 0x1000;
+
+// USB2 controller USB1 ("OTG"): the device controller bdk's usbd.c drives on
+// Erista. Registers, the UTMI PHY at +0x400/+0x800, queue heads at +0x1000.
+constexpr uint64_t USB_OTG_BASE = 0x7D000000;
+constexpr uint64_t USB_OTG_SIZE = 0x4000;
+
+// XUSB device controller: bdk's xusbd.c on Mariko. XHCI registers, then its
+// PCI configuration space at +0x8000 and device registers at +0x9000.
+constexpr uint64_t XUSB_DEV_BASE = 0x700D0000;
+constexpr uint64_t XUSB_DEV_SIZE = 0xA000;
+
+// XUSB pad controller. Owns the UPHY SERDES lanes shared by PCIe (pcie-0..4)
+// and USB 3.0 SuperSpeed (pcie-5/6 on this board), plus UPHY PLL P0.
+constexpr uint64_t XUSB_PADCTL_BASE = 0x7009F000;
+constexpr uint64_t XUSB_PADCTL_SIZE = 0x1000;
+
+// ==================== PCIe ====================
+//
+// Unlike every other peripheral here, the PCIe apertures live BELOW the
+// 0x50000000 MMIO band - T210 puts the whole root complex in the bottom of
+// the address map (tegra210.dtsi pcie@1003000). The BPMP can address it:
+// bdk's MMU table defines DRAM and IRAM entries only and leaves the fallback
+// entry RWX, so PCIe space is reachable and uncached.
+//
+// These are MMIO windows (callbacks, no backing memory), so they are mapped
+// at their architectural sizes: the whole 256 MiB configuration aperture -
+// extended registers sit at AXI[27:24] - and the non-prefetchable memory
+// window to the end of PCIE_A2, wherever software places the endpoint's BARs.
+// A smaller map left a CPU0 access to, say, config offset 0x100 or BAR0 +
+// 0x2000 unmapped: nothing answered and the core wedged, where silicon
+// returns data or all-ones.
+constexpr uint64_t PCIE_RP0_BASE = 0x01000000; // root port 0 registers
+constexpr uint64_t PCIE_RP1_BASE = 0x01001000; // root port 1 registers
+constexpr uint64_t PCIE_PADS_BASE = 0x01003000;
+constexpr uint64_t PCIE_AFI_BASE = 0x01003800;
+constexpr uint64_t PCIE_BLOCK_BASE = 0x01000000;
+constexpr uint64_t PCIE_BLOCK_SIZE = 0x4000;
+constexpr uint64_t PCIE_CS_BASE = 0x02000000; // type-1 extended config
+constexpr uint64_t PCIE_CS_MODEL_SIZE = 0x10000000; // all of it: 256 MiB
+constexpr uint64_t PCIE_MEM_BASE = 0x13000000; // non-prefetchable window
+constexpr uint64_t PCIE_MEM_MODEL_SIZE = 0x0D000000; // up to the end of A2
+
+// TSEC (Falcon control regs are in the 0x1000–0x11FF window within TSEC_BASE)
+constexpr uint64_t TSEC_BASE = 0x54500000;
+constexpr uint64_t TSEC_SIZE = 0x2000;
+
+// TZRAM
+constexpr uint64_t TZRAM_BASE = 0x7C010000;
+constexpr uint64_t TZRAM_SIZE = 0x10000; // 64KB
+
+// System Registers (SYSCTR0)
+constexpr uint64_t SYSCTR0_BASE = 0x700F0000;
+constexpr uint64_t SYSCTR0_SIZE = 0x1000;
+
+// ==================== Framebuffer ====================
+
+// hekate uses a display window within DRAM for framebuffer
+// The display init code sets up a linear framebuffer at predefined addresses.
+// IPL_FB_ADDRESS is 0xF5A00000, NYX is 0xF6200000.
+// We allocate a 16MB block covering 0xF5A00000 - 0xF6A00000
+constexpr uint64_t FB_BASE = 0xF5A00000;
+constexpr uint64_t FB_SIZE = 0x01000000; // 16MB
+
+// Display dimensions (hekate: 720 width, 1280 height in portrait)
+constexpr int DISPLAY_WIDTH = 720;
+constexpr int DISPLAY_HEIGHT = 1280;
+
+// Landscape dimensions for SDL window
+constexpr int WINDOW_WIDTH = 720;
+constexpr int WINDOW_HEIGHT = 1280;
+
+#endif // T210_MEMORY_MAP_H
diff --git a/t210/mmio.cpp b/t210/mmio.cpp
index be5d5c3..72c6d02 100644
--- a/t210/mmio.cpp
+++ b/t210/mmio.cpp
@@ -1,9 +1,15 @@
#include "mmio.h"
+#include "block_linear.h"
#include "trace.h"
#include "../emu_state.h"
+#include "../platform.h"
#include "i2c3.h"
#include "memory_map.h"
+#include "bpmp.h"
+#include "ccplex.h"
#include "pcie.h"
+#include "usb.h"
+#include "regcache.h"
#include "se_engine.h"
#include "tegra_bl.h"
@@ -14,35 +20,27 @@
#include
#include
#include