mirror of
https://github.com/Creased/RCM-Emulator.git
synced 2026-12-06 02:48:11 +01:00
Merge pull request #1 from Creased/claude/focused-noether-5orhms
Run CCPLEX CPU0 so hwtest's PCIe probe completes, and speed up the core
This commit is contained in:
54 files changed
+10742
-2204
No files matched your search
@@ -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:
|
||||
|
||||
@@ -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
|
||||
@@ -10,19 +10,25 @@ them. Read [README.md](README.md) first for usage.
|
||||
flowchart TB
|
||||
main["<b>main.cpp</b><br/>arg parsing, payload load, CLI<br/>emulation loop, auto-script state"]
|
||||
|
||||
main -->|uc_emu_start| uc["<b>Unicorn Engine</b><br/>ARM32, T210<br/>IRAM / DRAM / MMIO"]
|
||||
main -->|sdl_display_*| sdl["<b>display/sdl_display</b><br/>block-linear de-swizzle<br/>rotate, blit"]
|
||||
main -->|bpmp_run| uc["<b>Unicorn Engine</b><br/>ARM32 BPMP<br/>IRAM / DRAM / MMIO"]
|
||||
main -->|ccplex_run| a57["<b>t210/ccplex</b><br/>2nd Unicorn engine, AArch64<br/>CCPLEX CPU0 (Cortex-A57)"]
|
||||
a57 -->|MMIO callbacks| mmio
|
||||
a57 -.->|shares| uc
|
||||
main -->|sdl_display_*| sdl["<b>display/sdl_display</b><br/>DC window scan-out<br/>blend, turn, blit"]
|
||||
main -->|config_window_*| cfg["<b>display/config_window</b><br/>2nd SDL window + ImGui<br/>live hardware tweaks"]
|
||||
main -->|console_window_*| con["<b>display/console_window</b><br/>3rd SDL window + ImGui<br/>per-port UART TX log + RX inject"]
|
||||
|
||||
uc -->|MMIO trap| mmio["<b>t210/mmio.cpp</b><br/>central read/write dispatch<br/>by address range"]
|
||||
uc -->|MMIO callbacks| mmio["<b>t210/mmio.cpp</b><br/>mmio_bus_read / mmio_bus_write<br/>shared by both masters"]
|
||||
|
||||
mmio --> sdmmc["<b>sdmmc</b><br/>SDMMC1 / SDMMC4<br/>CMD0..18, EXT_CSD, ADMA2"]
|
||||
mmio --> se["<b>se_engine</b><br/>AES-128, SHA-256<br/>BIS keyslot override"]
|
||||
mmio --> sdmmc["<b>sdmmc</b><br/>SDMMC1 / SDMMC4<br/>CMD0..21, EXT_CSD, ADMA2<br/>SD UHS-I, eMMC HS400"]
|
||||
mmio --> se["<b>se_engine</b><br/>AES-128, SHA-256, RSA, RNG<br/>BIS keyslot override"]
|
||||
mmio --> i2c["<b>i2c3</b><br/>STMFTS / FTS4 touch"]
|
||||
mmio --> i2c1["<b>I2C_1 slaves</b> (inline)<br/>MAX17050, TMP451,<br/>BQ24193, BM92T36"]
|
||||
mmio --> i2c5["<b>I2C_5 slaves</b> (inline)<br/>MAX77620, MAX77621"]
|
||||
mmio --> stubs["<b>inline stubs</b><br/>GPIO, PMC, TSEC, KFUSE,<br/>PWM, DC, CLK, TMR, FUSE, UART"]
|
||||
mmio --> dc["<b>DC + VIC</b> (inline)<br/>window registers A-D<br/>VIC compose, flip/transpose"]
|
||||
mmio --> stubs["<b>inline stubs</b><br/>GPIO, PMC, TSEC, KFUSE,<br/>PWM, CLK, TMR, FUSE, UART"]
|
||||
mmio --> pcie["<b>pcie</b><br/>AFI, root ports, CYW4356<br/>(CPU-complex master only)"]
|
||||
mmio --> usb["<b>usb</b><br/>USB2 + XUSB device controllers<br/>and the --usb-host PC"]
|
||||
|
||||
cfg -.->|writes atomics| state["<b>EmuState</b><br/>(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 (`<ms> TAP <x> <y>`, 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: <reason>` 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.
|
||||
|
||||
+21
-18
@@ -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"]
|
||||
@@ -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)
|
||||
@@ -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:<port>`. 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: `<ms> P\|U\|D [hold_ms]` presses POWER / VOL+ / VOL-, `<ms> TAP <x> <y> [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<br/>emu_state.h<br/>Makefile<br/>Dockerfile<br/>README.md / DESIGN.md"]
|
||||
root --> t210["t210/<br/>(SoC peripheral models)"]
|
||||
root --> display["display/"]
|
||||
root --> tests["tests/<br/>ccplex/, se/, usb/, display/, hwtest/"]
|
||||
|
||||
t210 --> mmio["mmio.{h,cpp}<br/>memory_map.h<br/>tegra_bl.h"]
|
||||
t210 --> sdmmc["sdmmc.{h,cpp}<br/>SDMMC1 / SDMMC4"]
|
||||
t210 --> se["se_engine.{h,cpp}<br/>AES-128, SHA-256"]
|
||||
t210 --> mmio["mmio.{h,cpp}<br/>memory_map.h<br/>regcache.h, tegra_bl.h"]
|
||||
t210 --> cpus["bpmp.{h,cpp} BPMP clock<br/>ccplex.{h,cpp} CPU0 (A57)"]
|
||||
t210 --> pcie["pcie.{h,cpp}<br/>root complex + CYW4356"]
|
||||
t210 --> se["se_engine.{h,cpp}<br/>AES-128, SHA-256, RSA, RNG"]
|
||||
t210 --> i2c["i2c3.{h,cpp}<br/>STMFTS / FTS4 touch"]
|
||||
t210 --> usb["usb.{h,cpp}<br/>USB device controllers + host PC"]
|
||||
|
||||
display --> sdl["sdl_display.{h,cpp}<br/>block-linear de-swizzle<br/>+ SDL2"]
|
||||
display --> sdl["sdl_display.{h,cpp}<br/>DC window scan-out<br/>+ 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
|
||||
|
||||
|
||||
@@ -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<uint16_t>("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<uint16_t>("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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
+455
-283
@@ -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 <SDL2/SDL.h>
|
||||
#include <cstdio>
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
@@ -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<uint32_t> 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<uint8_t> 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<uint64_t>(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<uint32_t> &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<uint32_t> 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<Win> 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<uint64_t> 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<uint64_t> last_shape, last_where;
|
||||
static std::vector<uint8_t> 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<uint32_t> panel;
|
||||
panel.assign((size_t)kPanelW * kPanelH, 0xFF000000u); // black background
|
||||
for (const Win &w : wins)
|
||||
draw_window(w, panel);
|
||||
|
||||
std::vector<uint8_t> buf(fb_size);
|
||||
if (uc_mem_read(uc, eff_addr, buf.data(), fb_size) == UC_ERR_OK) {
|
||||
std::vector<uint32_t> 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 {
|
||||
|
||||
+99
-23
@@ -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<uint16_t> tc_x{0};
|
||||
std::atomic<uint16_t> 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<uint32_t> tc_q_head{0}; // next slot the producer fills
|
||||
std::atomic<uint32_t> tc_q_tail{0}; // next slot the consumer takes
|
||||
std::atomic<bool> tc_pressed{false};
|
||||
std::atomic<bool> tc_event_pending{false};
|
||||
std::atomic<uint8_t> 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<uint32_t> last_rot{0};
|
||||
std::atomic<uint32_t> last_auto_rot{0}; // what auto-detect picked, before any override
|
||||
std::atomic<uint32_t> last_out_w{1280};
|
||||
std::atomic<uint32_t> 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<bool> display_dirty{false};
|
||||
std::atomic<bool> display_initialized{false};
|
||||
int32_t manual_offset = 0;
|
||||
@@ -141,6 +199,14 @@ struct EmuState {
|
||||
std::atomic<bool> running{true};
|
||||
std::atomic<bool> paused{false};
|
||||
std::atomic<bool> 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<bool> 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<bool> 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<bool> 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<uint16_t> 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<uint32_t>& 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
|
||||
|
||||
+65
-3
@@ -12,6 +12,11 @@
|
||||
// VOL_UP | VOLUP | UP | U
|
||||
// hold_ms how long to hold the button, default 200 ms.
|
||||
//
|
||||
// <when> TAP <x> <y> [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 <algorithm>
|
||||
#include <cctype>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
@@ -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<Event> 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 '<when> TAP <x> <y> [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<uint32_t>(strtoul(tok[2].c_str(), nullptr, 10), 1279);
|
||||
uint32_t y = std::min<uint32_t>(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<bool> *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;
|
||||
}
|
||||
@@ -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);
|
||||
@@ -22,9 +22,11 @@
|
||||
#include <unicorn/unicorn.h>
|
||||
|
||||
#include "emu_state.h"
|
||||
#include <string>
|
||||
#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:<port>\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<bool> *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<bool> *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.
|
||||
|
||||
|
||||
+17
-4
@@ -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)
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
#include "platform.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <windows.h>
|
||||
#else
|
||||
#include <sys/mman.h>
|
||||
#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;
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
#ifndef RCM_PLATFORM_H
|
||||
#define RCM_PLATFORM_H
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <fcntl.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
// 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 <io.h>
|
||||
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 <unistd.h>
|
||||
#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
|
||||
@@ -0,0 +1,27 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
// 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));
|
||||
}
|
||||
+262
@@ -0,0 +1,262 @@
|
||||
#include "bpmp.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
#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;
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
#ifndef T210_BPMP_H
|
||||
#define T210_BPMP_H
|
||||
|
||||
#include <cstdint>
|
||||
#include <unicorn/unicorn.h>
|
||||
|
||||
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
|
||||
+620
@@ -0,0 +1,620 @@
|
||||
#include "ccplex.h"
|
||||
#include "bpmp.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
|
||||
#include <unicorn/unicorn.h>
|
||||
|
||||
#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<std::unique_ptr<CodePage>> 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<CodePage>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
#ifndef T210_CCPLEX_H
|
||||
#define T210_CCPLEX_H
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
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
|
||||
+26
-10
@@ -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) {
|
||||
|
||||
@@ -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
|
||||
+266
-243
@@ -1,243 +1,266 @@
|
||||
#ifndef T210_MEMORY_MAP_H
|
||||
#define T210_MEMORY_MAP_H
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
/*
|
||||
* 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 <cstdint>
|
||||
|
||||
/*
|
||||
* 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
|
||||
+2362
-1148
File diff suppressed because it is too large.
Load diff
+88
-45
@@ -1,45 +1,88 @@
|
||||
#ifndef T210_MMIO_H
|
||||
#define T210_MMIO_H
|
||||
|
||||
#include <cstdint>
|
||||
#include <unicorn/unicorn.h>
|
||||
|
||||
/*
|
||||
* Tegra X1 MMIO Handler
|
||||
*
|
||||
* Routes memory-mapped IO reads/writes to peripheral handlers.
|
||||
* Unknown registers return 0 / ignore writes (permissive stub).
|
||||
*/
|
||||
|
||||
// Forward declarations for peripheral modules.
|
||||
struct EmuState;
|
||||
|
||||
// Initialize all MMIO hooks on the Unicorn engine.
|
||||
void mmio_init(uc_engine *uc, EmuState *state);
|
||||
|
||||
// Individual peripheral handlers.
|
||||
uint32_t timer_read(EmuState *state, uint64_t addr);
|
||||
void timer_write(EmuState *state, uint64_t addr, uint32_t val);
|
||||
|
||||
uint32_t gpio_read(EmuState *state, uint64_t addr);
|
||||
void gpio_write(EmuState *state, uint64_t addr, uint32_t val);
|
||||
|
||||
uint32_t i2c_read(EmuState *state, uint64_t addr);
|
||||
void i2c_write(EmuState *state, uint64_t addr, uint32_t val);
|
||||
|
||||
uint32_t display_read(EmuState *state, uint64_t addr);
|
||||
void display_write(EmuState *state, uint64_t addr, uint32_t val);
|
||||
|
||||
uint32_t pmc_read(EmuState *state, uint64_t addr);
|
||||
void pmc_write(EmuState *state, uint64_t addr, uint32_t val);
|
||||
|
||||
uint32_t clk_rst_read(EmuState *state, uint64_t addr);
|
||||
void clk_rst_write(EmuState *state, uint64_t addr, uint32_t val);
|
||||
|
||||
uint32_t fuse_read(EmuState *state, uint64_t addr);
|
||||
void fuse_write(EmuState *state, uint64_t addr, uint32_t val);
|
||||
|
||||
uint32_t misc_read(EmuState *state, uint64_t addr);
|
||||
void misc_write(uc_engine *uc, EmuState *state, uint64_t addr, int64_t value, int size);
|
||||
|
||||
#endif // T210_MMIO_H
|
||||
#ifndef T210_MMIO_H
|
||||
#define T210_MMIO_H
|
||||
|
||||
#include <cstdint>
|
||||
#include <unicorn/unicorn.h>
|
||||
|
||||
/*
|
||||
* Tegra X1 MMIO Handler
|
||||
*
|
||||
* Routes memory-mapped IO reads/writes to peripheral handlers.
|
||||
* Unknown registers return 0 / ignore writes (permissive stub).
|
||||
*/
|
||||
|
||||
// Forward declarations for peripheral modules.
|
||||
struct EmuState;
|
||||
|
||||
// Which processor issued the access being dispatched. Two masters share one
|
||||
// register model: the BPMP (the ARM7 every RCM payload runs on) and CPU0 of
|
||||
// the CCPLEX (Cortex-A57), which a payload can boot through bdk's
|
||||
// ccplex_boot_cpu0(). They do not see the same bus - PCIe and MSELECT answer
|
||||
// a CPU-complex master only (Tegra X1 TRM ch.16/ch.19) - so the few models
|
||||
// that care consult this. Both cores run on the emulator's one thread, one
|
||||
// slice at a time, so a global is exact: whoever is running is the master.
|
||||
enum BusMaster : uint8_t {
|
||||
BUS_BPMP = 0,
|
||||
BUS_CPU0 = 1,
|
||||
};
|
||||
extern BusMaster g_bus_master;
|
||||
|
||||
// Initialize all MMIO hooks on the Unicorn engine.
|
||||
void mmio_init(uc_engine *uc, EmuState *state);
|
||||
|
||||
// Map the same peripheral windows into another engine (CPU0's), backed by the
|
||||
// same register models. Everything in the 0x50000000..0x7FFFFFFF band plus
|
||||
// the PCIe apertures low in the map.
|
||||
void mmio_map_bus(uc_engine *uc, EmuState *state);
|
||||
// Forget the windows mapped into `uc`, before that engine is closed.
|
||||
void mmio_unmap_bus(uc_engine *uc);
|
||||
|
||||
// The shared dispatch both engines' MMIO callbacks funnel into. `size` is the
|
||||
// access width in bytes (1, 2 or 4).
|
||||
uint32_t mmio_bus_read(EmuState *state, uint64_t addr, unsigned size);
|
||||
void mmio_bus_write(EmuState *state, uint64_t addr, unsigned size,
|
||||
uint64_t value);
|
||||
|
||||
// Reset the per-run peripheral state that a soft reboot must not carry over.
|
||||
// `power_cycle`: the PMIC reset too (its register files return to their
|
||||
// seeds); otherwise only the SoC reset (PMC MAIN_RST) and the PMIC keeps
|
||||
// its rails.
|
||||
void mmio_soft_reset(EmuState *state, bool power_cycle);
|
||||
|
||||
// PMC power-partition state (APBDEV_PMC_PWRGATE_STATUS bit `part`).
|
||||
bool pmc_partition_on(int part);
|
||||
|
||||
// APBDEV_PMC_SECURE_SCRATCH`n` (n = 0..7), written by hardware: the SE
|
||||
// deposits its context-save key there.
|
||||
void pmc_secure_scratch_write(unsigned n, uint32_t value);
|
||||
|
||||
// True when the CCPLEX CPU rail is up: the MAX77621 on Erista (enabled, and
|
||||
// its EN pin driven by MAX77620 GPIO5), the MAX77812 M4 phase on Mariko.
|
||||
bool cpu_rail_on(EmuState *state);
|
||||
|
||||
// Individual peripheral handlers.
|
||||
uint32_t timer_read(EmuState *state, uint64_t addr);
|
||||
void timer_write(EmuState *state, uint64_t addr, uint32_t val);
|
||||
|
||||
uint32_t gpio_read(EmuState *state, uint64_t addr);
|
||||
void gpio_write(EmuState *state, uint64_t addr, uint32_t val);
|
||||
|
||||
uint32_t i2c_read(EmuState *state, uint64_t addr);
|
||||
void i2c_write(EmuState *state, uint64_t addr, uint32_t val);
|
||||
|
||||
uint32_t display_read(EmuState *state, uint64_t addr);
|
||||
void display_write(EmuState *state, uint64_t addr, uint32_t val);
|
||||
|
||||
uint32_t pmc_read(EmuState *state, uint64_t addr);
|
||||
void pmc_write(EmuState *state, uint64_t addr, uint32_t val);
|
||||
|
||||
uint32_t clk_rst_read(EmuState *state, uint64_t addr);
|
||||
void clk_rst_write(EmuState *state, uint64_t addr, uint32_t val);
|
||||
|
||||
uint32_t fuse_read(EmuState *state, uint64_t addr);
|
||||
void fuse_write(EmuState *state, uint64_t addr, uint32_t val);
|
||||
|
||||
uint32_t misc_read(EmuState *state, uint64_t addr);
|
||||
void misc_write(uc_engine *uc, EmuState *state, uint64_t addr, int64_t value, int size);
|
||||
|
||||
#endif // T210_MMIO_H
|
||||
+397
@@ -0,0 +1,397 @@
|
||||
// A one-client NBD server for the emulated USB host (see nbd.h).
|
||||
//
|
||||
// The handshake is the fixed newstyle one every current client speaks
|
||||
// (nbd-client, qemu-nbd, nbdfuse, libnbd):
|
||||
//
|
||||
// server "NBDMAGIC" "IHAVEOPT" handshake flags
|
||||
// client its flags, then options: "IHAVEOPT", option, length, data
|
||||
// server answers each option; EXPORT_NAME or GO hands over the disk
|
||||
//
|
||||
// then requests (magic 0x25609513, flags, type, handle, offset, length,
|
||||
// and a WRITE's data) each answered by a simple reply (magic 0x67446698,
|
||||
// error, handle, and a READ's data). The export has one name - any name
|
||||
// the client asks for - and takes READ, WRITE, FLUSH and DISC; structured
|
||||
// replies and the other extensions are refused, which clients handle.
|
||||
|
||||
#include "nbd.h"
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
#else
|
||||
#include <arpa/inet.h>
|
||||
#include <cerrno>
|
||||
#include <fcntl.h>
|
||||
#include <netinet/in.h>
|
||||
#include <netinet/tcp.h>
|
||||
#include <sys/select.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr uint64_t NBDMAGIC = 0x4E42444D41474943ull; // "NBDMAGIC"
|
||||
constexpr uint64_t IHAVEOPT = 0x49484156454F5054ull; // "IHAVEOPT"
|
||||
constexpr uint64_t REPLY_MAGIC = 0x0003E889045565A9ull; // option replies
|
||||
constexpr uint32_t REQUEST_MAGIC = 0x25609513;
|
||||
constexpr uint32_t SIMPLE_REPLY_MAGIC = 0x67446698;
|
||||
|
||||
constexpr uint16_t FLAG_FIXED_NEWSTYLE = 1 << 0, FLAG_NO_ZEROES = 1 << 1;
|
||||
constexpr uint16_t FLAG_HAS_FLAGS = 1 << 0, FLAG_READ_ONLY = 1 << 1,
|
||||
FLAG_SEND_FLUSH = 1 << 2;
|
||||
|
||||
constexpr uint32_t OPT_EXPORT_NAME = 1, OPT_ABORT = 2, OPT_LIST = 3,
|
||||
OPT_INFO = 6, OPT_GO = 7;
|
||||
constexpr uint32_t REP_ACK = 1, REP_SERVER = 2, REP_INFO = 3,
|
||||
REP_ERR_UNSUP = 0x80000001, REP_ERR_INVALID = 0x80000003;
|
||||
constexpr uint16_t INFO_EXPORT = 0, INFO_BLOCK_SIZE = 3;
|
||||
|
||||
#ifdef _WIN32
|
||||
using sock_t = SOCKET;
|
||||
const sock_t BAD_SOCK = INVALID_SOCKET;
|
||||
bool net_init() {
|
||||
static bool ok = [] {
|
||||
WSADATA d;
|
||||
return WSAStartup(MAKEWORD(2, 2), &d) == 0;
|
||||
}();
|
||||
return ok;
|
||||
}
|
||||
void close_sock(sock_t s) { closesocket(s); }
|
||||
bool would_block() { return WSAGetLastError() == WSAEWOULDBLOCK; }
|
||||
bool set_nonblocking(sock_t s) {
|
||||
u_long on = 1;
|
||||
return ioctlsocket(s, FIONBIO, &on) == 0;
|
||||
}
|
||||
const char *sock_error() {
|
||||
static char buf[32];
|
||||
snprintf(buf, sizeof(buf), "winsock error %d", WSAGetLastError());
|
||||
return buf;
|
||||
}
|
||||
#else
|
||||
using sock_t = int;
|
||||
const sock_t BAD_SOCK = -1;
|
||||
bool net_init() { return true; }
|
||||
void close_sock(sock_t s) { ::close(s); }
|
||||
bool would_block() {
|
||||
#if EWOULDBLOCK != EAGAIN
|
||||
if (errno == EWOULDBLOCK)
|
||||
return true;
|
||||
#endif
|
||||
return errno == EAGAIN || errno == EINTR;
|
||||
}
|
||||
bool set_nonblocking(sock_t s) {
|
||||
int fl = fcntl(s, F_GETFL, 0);
|
||||
return fl >= 0 && fcntl(s, F_SETFL, fl | O_NONBLOCK) == 0;
|
||||
}
|
||||
const char *sock_error() { return strerror(errno); }
|
||||
#endif
|
||||
|
||||
#ifdef MSG_NOSIGNAL
|
||||
constexpr int SEND_FLAGS = MSG_NOSIGNAL; // a gone client is an error, not SIGPIPE
|
||||
#else
|
||||
constexpr int SEND_FLAGS = 0;
|
||||
#endif
|
||||
|
||||
sock_t sock(intptr_t s) { return (sock_t)s; }
|
||||
|
||||
// Wait up to 10 s for room to send.
|
||||
bool wait_writable(sock_t s) {
|
||||
fd_set w;
|
||||
FD_ZERO(&w);
|
||||
FD_SET(s, &w);
|
||||
timeval tv = {10, 0};
|
||||
return select((int)s + 1, nullptr, &w, nullptr, &tv) > 0;
|
||||
}
|
||||
|
||||
// Everything on the wire is big-endian.
|
||||
void put16(uint8_t *p, uint16_t v) {
|
||||
p[0] = v >> 8;
|
||||
p[1] = (uint8_t)v;
|
||||
}
|
||||
void put32(uint8_t *p, uint32_t v) {
|
||||
put16(p, v >> 16);
|
||||
put16(p + 2, (uint16_t)v);
|
||||
}
|
||||
void put64(uint8_t *p, uint64_t v) {
|
||||
put32(p, v >> 32);
|
||||
put32(p + 4, (uint32_t)v);
|
||||
}
|
||||
uint16_t get16(const uint8_t *p) { return (uint16_t)(p[0] << 8 | p[1]); }
|
||||
uint32_t get32(const uint8_t *p) {
|
||||
return (uint32_t)get16(p) << 16 | get16(p + 2);
|
||||
}
|
||||
uint64_t get64(const uint8_t *p) {
|
||||
return (uint64_t)get32(p) << 32 | get32(p + 4);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool NbdServer::listen(uint16_t port, uint64_t size, bool read_only) {
|
||||
close();
|
||||
if (!net_init()) {
|
||||
printf("[usb-host] NBD: no sockets (%s)\n", sock_error());
|
||||
return false;
|
||||
}
|
||||
sock_t s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
|
||||
if (s == BAD_SOCK) {
|
||||
printf("[usb-host] NBD: no socket (%s)\n", sock_error());
|
||||
return false;
|
||||
}
|
||||
#ifndef _WIN32
|
||||
// Windows' SO_REUSEADDR lets another process take a bound port; the
|
||||
// POSIX one only skips TIME_WAIT, so a restarted run gets its port back.
|
||||
int one = 1;
|
||||
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
|
||||
#endif
|
||||
sockaddr_in a;
|
||||
memset(&a, 0, sizeof(a));
|
||||
a.sin_family = AF_INET;
|
||||
a.sin_port = htons(port);
|
||||
a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
if (bind(s, (sockaddr *)&a, sizeof(a)) != 0 || ::listen(s, 1) != 0 ||
|
||||
!set_nonblocking(s)) {
|
||||
printf("[usb-host] NBD: cannot listen on 127.0.0.1:%u (%s)\n", port,
|
||||
sock_error());
|
||||
close_sock(s);
|
||||
return false;
|
||||
}
|
||||
listen_ = (intptr_t)s;
|
||||
size_ = size;
|
||||
read_only_ = read_only;
|
||||
state_ = Listening;
|
||||
return true;
|
||||
}
|
||||
|
||||
void NbdServer::close() {
|
||||
drop_client();
|
||||
if (listen_ != -1)
|
||||
close_sock(sock(listen_));
|
||||
listen_ = -1;
|
||||
state_ = Idle;
|
||||
}
|
||||
|
||||
void NbdServer::drop_client() {
|
||||
if (client_ != -1)
|
||||
close_sock(sock(client_));
|
||||
client_ = -1;
|
||||
in_.clear();
|
||||
peer_closed_ = false;
|
||||
state_ = listen_ != -1 ? Listening : Idle;
|
||||
}
|
||||
|
||||
uint16_t NbdServer::transmission_flags() const {
|
||||
return FLAG_HAS_FLAGS | FLAG_SEND_FLUSH | (read_only_ ? FLAG_READ_ONLY : 0);
|
||||
}
|
||||
|
||||
// Read what the client has sent. False once it has closed its end.
|
||||
bool NbdServer::fill() {
|
||||
static uint8_t buf[65536];
|
||||
// Room for the largest WRITE; a client pipelining more waits in the socket.
|
||||
while (in_.size() < NBD_MAX_PAYLOAD + sizeof(buf)) {
|
||||
int n = recv(sock(client_), (char *)buf, sizeof(buf), 0);
|
||||
if (n > 0) {
|
||||
in_.insert(in_.end(), buf, buf + n);
|
||||
continue;
|
||||
}
|
||||
return n < 0 && would_block();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool NbdServer::send_all(const void *p, size_t n) {
|
||||
const char *c = (const char *)p;
|
||||
while (n) {
|
||||
int k = send(sock(client_), c, (int)std::min<size_t>(n, 1u << 20),
|
||||
SEND_FLAGS);
|
||||
if (k > 0) {
|
||||
c += k;
|
||||
n -= (size_t)k;
|
||||
} else if (k < 0 && would_block()) {
|
||||
if (!wait_writable(sock(client_)))
|
||||
return false;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool NbdServer::option_reply(uint32_t opt, uint32_t type,
|
||||
const std::vector<uint8_t> &data) {
|
||||
uint8_t h[20];
|
||||
put64(h, REPLY_MAGIC);
|
||||
put32(h + 8, opt);
|
||||
put32(h + 12, type);
|
||||
put32(h + 16, (uint32_t)data.size());
|
||||
return send_all(h, sizeof(h)) &&
|
||||
(data.empty() || send_all(data.data(), data.size()));
|
||||
}
|
||||
|
||||
// One handshake option. False drops the client.
|
||||
bool NbdServer::option(uint32_t opt, const std::vector<uint8_t> &d) {
|
||||
switch (opt) {
|
||||
case OPT_EXPORT_NAME: {
|
||||
// No reply header: the export's size and flags, then (unless the
|
||||
// client opted out) 124 zero bytes, and the disk is the client's.
|
||||
uint8_t r[10 + 124] = {};
|
||||
put64(r, size_);
|
||||
put16(r + 8, transmission_flags());
|
||||
if (!send_all(r, no_zeroes_ ? 10 : sizeof(r)))
|
||||
return false;
|
||||
state_ = Transmission;
|
||||
break;
|
||||
}
|
||||
case OPT_ABORT:
|
||||
option_reply(opt, REP_ACK);
|
||||
return false;
|
||||
case OPT_LIST: {
|
||||
if (!d.empty())
|
||||
return option_reply(opt, REP_ERR_INVALID);
|
||||
std::vector<uint8_t> unnamed(4, 0); // one export, the default name
|
||||
return option_reply(opt, REP_SERVER, unnamed) && option_reply(opt, REP_ACK);
|
||||
}
|
||||
case OPT_INFO:
|
||||
case OPT_GO: {
|
||||
// Export name length, the name, the count of info requests, the
|
||||
// requests. Whatever the client asks for, it gets the size and flags
|
||||
// and the block sizes: 512-byte sectors, 4 KiB preferred.
|
||||
if (d.size() < 6)
|
||||
return option_reply(opt, REP_ERR_INVALID);
|
||||
uint32_t name_len = get32(&d[0]);
|
||||
if (name_len > d.size() - 6 ||
|
||||
d.size() != 6 + name_len + 2 * (size_t)get16(&d[4 + name_len]))
|
||||
return option_reply(opt, REP_ERR_INVALID);
|
||||
std::vector<uint8_t> e(12), b(14);
|
||||
put16(&e[0], INFO_EXPORT);
|
||||
put64(&e[2], size_);
|
||||
put16(&e[10], transmission_flags());
|
||||
put16(&b[0], INFO_BLOCK_SIZE);
|
||||
put32(&b[2], 512);
|
||||
put32(&b[6], 4096);
|
||||
put32(&b[10], NBD_MAX_PAYLOAD);
|
||||
if (!option_reply(opt, REP_INFO, e) || !option_reply(opt, REP_INFO, b) ||
|
||||
!option_reply(opt, REP_ACK))
|
||||
return false;
|
||||
if (opt == OPT_GO)
|
||||
state_ = Transmission;
|
||||
break;
|
||||
}
|
||||
default:
|
||||
return option_reply(opt, REP_ERR_UNSUP);
|
||||
}
|
||||
if (state_ == Transmission)
|
||||
printf("[usb-host] NBD client has the disk\n");
|
||||
return true;
|
||||
}
|
||||
|
||||
NbdEvent NbdServer::poll(NbdRequest *req) {
|
||||
if (state_ == Idle)
|
||||
return NbdEvent::None;
|
||||
if (state_ == Listening) {
|
||||
sock_t c = accept(sock(listen_), nullptr, nullptr);
|
||||
if (c == BAD_SOCK)
|
||||
return NbdEvent::None;
|
||||
set_nonblocking(c);
|
||||
int one = 1;
|
||||
setsockopt(c, IPPROTO_TCP, TCP_NODELAY, (const char *)&one, sizeof(one));
|
||||
#ifdef SO_NOSIGPIPE
|
||||
setsockopt(c, SOL_SOCKET, SO_NOSIGPIPE, &one, sizeof(one));
|
||||
#endif
|
||||
client_ = (intptr_t)c;
|
||||
in_.clear();
|
||||
peer_closed_ = no_zeroes_ = false;
|
||||
uint8_t hello[18];
|
||||
put64(hello, NBDMAGIC);
|
||||
put64(hello + 8, IHAVEOPT);
|
||||
put16(hello + 16, FLAG_FIXED_NEWSTYLE | FLAG_NO_ZEROES);
|
||||
if (!send_all(hello, sizeof(hello))) {
|
||||
drop_client();
|
||||
return NbdEvent::None;
|
||||
}
|
||||
state_ = ClientFlags;
|
||||
}
|
||||
if (!fill())
|
||||
peer_closed_ = true;
|
||||
|
||||
for (;;) {
|
||||
size_t n = in_.size();
|
||||
if (state_ == ClientFlags) {
|
||||
if (n < 4)
|
||||
break;
|
||||
uint32_t f = get32(&in_[0]);
|
||||
in_.erase(in_.begin(), in_.begin() + 4);
|
||||
no_zeroes_ = (f & FLAG_FIXED_NEWSTYLE) && (f & FLAG_NO_ZEROES);
|
||||
state_ = Options;
|
||||
} else if (state_ == Options) {
|
||||
if (n < 16)
|
||||
break;
|
||||
uint32_t opt = get32(&in_[8]), len = get32(&in_[12]);
|
||||
if (get64(&in_[0]) != IHAVEOPT || len > 65536) {
|
||||
printf("[usb-host] NBD: not an NBD client; dropped\n");
|
||||
drop_client();
|
||||
return NbdEvent::None;
|
||||
}
|
||||
if (n < 16 + (size_t)len)
|
||||
break;
|
||||
std::vector<uint8_t> data(in_.begin() + 16, in_.begin() + 16 + len);
|
||||
in_.erase(in_.begin(), in_.begin() + 16 + len);
|
||||
if (!option(opt, data)) {
|
||||
drop_client();
|
||||
return NbdEvent::None;
|
||||
}
|
||||
} else {
|
||||
if (n < 28)
|
||||
break;
|
||||
uint16_t type = get16(&in_[6]);
|
||||
uint32_t len = get32(&in_[24]);
|
||||
if (get32(&in_[0]) != REQUEST_MAGIC ||
|
||||
(type == NBD_CMD_WRITE && len > NBD_MAX_PAYLOAD)) {
|
||||
printf("[usb-host] NBD: malformed request; client dropped\n");
|
||||
drop_client();
|
||||
return NbdEvent::Closed;
|
||||
}
|
||||
size_t need = 28 + (type == NBD_CMD_WRITE ? len : 0);
|
||||
if (n < need)
|
||||
break;
|
||||
req->flags = get16(&in_[4]);
|
||||
req->type = type;
|
||||
req->handle = get64(&in_[8]);
|
||||
req->offset = get64(&in_[16]);
|
||||
req->len = len;
|
||||
req->data.assign(in_.begin() + 28, in_.begin() + need);
|
||||
in_.erase(in_.begin(), in_.begin() + need);
|
||||
if (type == NBD_CMD_DISC) {
|
||||
printf("[usb-host] NBD client disconnected\n");
|
||||
drop_client();
|
||||
return NbdEvent::Closed;
|
||||
}
|
||||
return NbdEvent::Request;
|
||||
}
|
||||
}
|
||||
|
||||
if (peer_closed_) {
|
||||
bool had_disk = state_ == Transmission;
|
||||
printf("[usb-host] NBD client %s\n",
|
||||
had_disk ? "went away without disconnecting" : "left");
|
||||
drop_client();
|
||||
return had_disk ? NbdEvent::Closed : NbdEvent::None;
|
||||
}
|
||||
return NbdEvent::None;
|
||||
}
|
||||
|
||||
void NbdServer::reply(uint64_t handle, uint32_t error, const uint8_t *data,
|
||||
size_t len) {
|
||||
if (state_ != Transmission)
|
||||
return;
|
||||
uint8_t h[16];
|
||||
put32(h, SIMPLE_REPLY_MAGIC);
|
||||
put32(h + 4, error);
|
||||
put64(h + 8, handle);
|
||||
if (!send_all(h, sizeof(h)) || (!error && len && !send_all(data, len)))
|
||||
peer_closed_ = true; // the next poll reports it gone
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
// A one-client NBD server - the network block device protocol, fixed
|
||||
// newstyle handshake - that the emulated USB host (usb.cpp) serves a mass
|
||||
// storage gadget's disk with, so the disk can be mounted on the machine the
|
||||
// emulator runs on. It listens on 127.0.0.1 only. Single-threaded and
|
||||
// non-blocking: poll() does whatever the socket allows and returns.
|
||||
|
||||
struct NbdRequest {
|
||||
uint16_t type = 0; // NBD_CMD_*
|
||||
uint16_t flags = 0;
|
||||
uint64_t handle = 0, offset = 0;
|
||||
uint32_t len = 0;
|
||||
std::vector<uint8_t> data; // what a WRITE carries
|
||||
};
|
||||
|
||||
constexpr uint16_t NBD_CMD_READ = 0, NBD_CMD_WRITE = 1, NBD_CMD_DISC = 2,
|
||||
NBD_CMD_FLUSH = 3;
|
||||
constexpr uint32_t NBD_EPERM = 1, NBD_EIO = 5, NBD_EINVAL = 22;
|
||||
|
||||
// The largest READ or WRITE a client may send (the protocol's default).
|
||||
constexpr uint32_t NBD_MAX_PAYLOAD = 32u << 20;
|
||||
|
||||
enum class NbdEvent {
|
||||
None, // nothing to do yet
|
||||
Request, // *req holds the next command
|
||||
Closed, // the client that was using the disk disconnected
|
||||
};
|
||||
|
||||
class NbdServer {
|
||||
public:
|
||||
~NbdServer() { close(); }
|
||||
|
||||
// Listen on 127.0.0.1:port for a client, exporting `size` bytes. False
|
||||
// (and logged) when the port cannot be had.
|
||||
bool listen(uint16_t port, uint64_t size, bool read_only);
|
||||
void close();
|
||||
bool active() const { return state_ != Idle; }
|
||||
|
||||
// Accept, run the handshake, read the next request. A client that goes
|
||||
// away before it has the disk (a listing, a failed negotiation) is not a
|
||||
// Closed event: the server just waits for the next one.
|
||||
NbdEvent poll(NbdRequest *req);
|
||||
|
||||
// Answer a request; a READ's data goes with a zero error.
|
||||
void reply(uint64_t handle, uint32_t error, const uint8_t *data = nullptr,
|
||||
size_t len = 0);
|
||||
|
||||
private:
|
||||
enum State { Idle, Listening, ClientFlags, Options, Transmission };
|
||||
State state_ = Idle;
|
||||
intptr_t listen_ = -1, client_ = -1; // sockets
|
||||
std::vector<uint8_t> in_;
|
||||
bool peer_closed_ = false, no_zeroes_ = false, read_only_ = false;
|
||||
uint64_t size_ = 0;
|
||||
|
||||
bool fill();
|
||||
bool send_all(const void *p, size_t n);
|
||||
bool option(uint32_t opt, const std::vector<uint8_t> &data);
|
||||
bool option_reply(uint32_t opt, uint32_t type,
|
||||
const std::vector<uint8_t> &data = {});
|
||||
void drop_client();
|
||||
uint16_t transmission_flags() const;
|
||||
};
|
||||
+91
-18
@@ -1,10 +1,12 @@
|
||||
#include "pcie.h"
|
||||
#include "ccplex.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
#include "../emu_state.h"
|
||||
#include "memory_map.h"
|
||||
#include "mmio.h"
|
||||
|
||||
// ==========================================================================
|
||||
// Register map (tegra210.dtsi pcie@1003000, U-Boot drivers/pci/pci_tegra.c)
|
||||
@@ -108,6 +110,15 @@
|
||||
static constexpr uint64_t T_VDD_TO_POR_US = 57000; // WL_REG_ON -> POR done
|
||||
static constexpr uint64_t T_REFCLK_STABLE_US = 10000; // refclk -> PERST# high
|
||||
|
||||
// Reset values, as a CPU-complex master reads them on real silicon.
|
||||
// MSELECT_CONFIG_0 is the TRM's documented reset value (16.3.1): the PCIe
|
||||
// aperture (bit 5) is already enabled. AFI_PCIE_CONFIG is what hwtest's CPU0
|
||||
// stub reads straight after the BPMP has cycled the AFI reset - xbar X4_X1 in
|
||||
// bits 23:20 and root port 1 disabled (bit 2) until software clears it.
|
||||
static constexpr uint32_t MSELECT_CONFIG_RESET = 0x07FF4020;
|
||||
static constexpr uint32_t MSELECT_CFG_ENABLE_PCIE_APERTURE = 1u << 5;
|
||||
static constexpr uint32_t AFI_PCIE_CONFIG_RESET = 0x00103025;
|
||||
|
||||
// Broadcom identity (brcm_hw_ids.h, brcmfmac/pcie.c).
|
||||
static constexpr uint32_t BRCM_4356_CFG0 = 0x43EC14E4;
|
||||
static constexpr uint32_t BRCM_BAR0_WINDOW = 0x80;
|
||||
@@ -158,7 +169,8 @@ struct PcieModel {
|
||||
bool mgmt_warned = false;
|
||||
bool plle = false;
|
||||
bool pllrefe = false;
|
||||
bool powergated = true;
|
||||
// The PCIE partition is already up at RCM entry (see pmc_pwrgate_status).
|
||||
bool powergated = false;
|
||||
|
||||
// XUSB pad controller.
|
||||
uint32_t padctl[0x1000 / 4] = {};
|
||||
@@ -177,9 +189,11 @@ PcieModel pcie;
|
||||
|
||||
// BAR sizing masks: a write of all-ones reads back ~(size-1) with the type
|
||||
// bits preserved, which is how any enumerator discovers how big a BAR is.
|
||||
// BAR0 is 32 KiB of registers, BAR2 the 2 MiB TCM; both are 64-bit
|
||||
// prefetchable, which is why brcmfmac calls them resource 0 and resource 2.
|
||||
constexpr uint32_t EP_BAR_TYPE = 0x0000000C; // 64-bit, prefetchable
|
||||
// BAR0 is 32 KiB of registers, BAR2 the 2 MiB TCM; both are 64-bit memory
|
||||
// BARs, which is why brcmfmac calls them resource 0 and resource 2. They are
|
||||
// NOT prefetchable: a real CYW4356 in ROM phase reads BAR0 = 0x00000004
|
||||
// (hwtest's healthy-console capture), i.e. type 64-bit, prefetch clear.
|
||||
constexpr uint32_t EP_BAR_TYPE = 0x00000004; // 64-bit, non-prefetchable
|
||||
constexpr uint32_t EP_BAR0_MASK = ~(0x8000u - 1);
|
||||
constexpr uint32_t EP_BAR2_MASK = ~(0x200000u - 1);
|
||||
|
||||
@@ -187,7 +201,7 @@ void ep_init() {
|
||||
memset(pcie.ep, 0, sizeof(pcie.ep));
|
||||
pcie.ep[0x00 / 4] = BRCM_4356_CFG0; // 14E4:43EC
|
||||
pcie.ep[0x04 / 4] = 0x00100000; // status: capability list
|
||||
pcie.ep[0x08 / 4] = 0x02800000; // network controller, other
|
||||
pcie.ep[0x08 / 4] = 0x02800003; // network controller, rev 03
|
||||
pcie.ep[0x0C / 4] = 0x00000000; // header type 0
|
||||
pcie.ep[0x10 / 4] = EP_BAR_TYPE; // BAR0 lo: 32 KiB registers
|
||||
pcie.ep[0x18 / 4] = EP_BAR_TYPE; // BAR2 lo: 2 MiB TCM
|
||||
@@ -215,9 +229,8 @@ bool radio_core_alive(EmuState *state) {
|
||||
// hardware this is the difference between a register read and a dead
|
||||
// console, so it is checked before every single access rather than folded
|
||||
// into the link-training preconditions.
|
||||
// Everything this emulator executes is BPMP code - Unicorn runs the ARM7,
|
||||
// there is no CCPLEX model - and the BPMP cannot reach PCIe on real silicon.
|
||||
// Measured on an Erista and a Mariko: with clocks, resets, power and PLLE all
|
||||
// The BPMP cannot reach PCIe on real silicon; only a CPU-complex master can
|
||||
// (CPU0, t210/ccplex.cpp). Measured on an Erista and a Mariko: with clocks, resets, power and PLLE all
|
||||
// correct, the AFI window reads 0xFFFFFFFF and every offset of MSELECT reads
|
||||
// one constant. The TRM agrees (ch.19: BPMP-Lite is an AHB master, PCIe is
|
||||
// not an AHB slave; ch.16: MSELECT is CPU-complex hardware), and so does the
|
||||
@@ -227,6 +240,9 @@ bool radio_core_alive(EmuState *state) {
|
||||
// which is how a probe that cannot work on hardware passed here for days.
|
||||
// Refusing them is the single most valuable thing this file does.
|
||||
static bool bpmp_pcie_denied(uint64_t addr) {
|
||||
// CPU0 (t210/ccplex.cpp) is a CPU-complex master and reaches all of it.
|
||||
if (g_bus_master == BUS_CPU0)
|
||||
return false;
|
||||
static bool warned = false;
|
||||
if (!warned) {
|
||||
warned = true;
|
||||
@@ -249,13 +265,29 @@ void mselect_complain(uint64_t addr) {
|
||||
pcie.mselect_warned = true;
|
||||
printf("[pcie] *** access to %08X with MSELECT still in reset ***\n",
|
||||
(unsigned)addr);
|
||||
printf("[pcie] *** on real silicon this STALLS THE BPMP for good: no ***\n");
|
||||
printf("[pcie] *** on real silicon this STALLS THE %s for good: no ***\n",
|
||||
g_bus_master == BUS_CPU0 ? "CPU0" : "BPMP");
|
||||
printf("[pcie] *** abort, no timeout, no reboot path. Clear ***\n");
|
||||
printf("[pcie] *** RST_DEV_V bit %d first (bdk ccplex.c:121). ***\n",
|
||||
CLK_V_MSELECT);
|
||||
fflush(stdout);
|
||||
}
|
||||
|
||||
// MSELECT_CONFIG bit 5, ENABLE_PCIE_APERTURE (TRM 16.3.1, set at reset):
|
||||
// with it clear MSELECT does not route the PCIe apertures at all.
|
||||
static bool pcie_aperture_enabled(uint64_t addr) {
|
||||
if (pcie.mselect[0] & MSELECT_CFG_ENABLE_PCIE_APERTURE)
|
||||
return true;
|
||||
static bool warned = false;
|
||||
if (!warned) {
|
||||
warned = true;
|
||||
printf("[pcie] access to %08X with MSELECT_CONFIG.ENABLE_PCIE_APERTURE "
|
||||
"clear: MSELECT does not route it\n", (unsigned)addr);
|
||||
fflush(stdout);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const char *link_blocked(EmuState *state, int port) {
|
||||
if (!mselect_up()) return "MSELECT still in reset";
|
||||
if (pcie.powergated) return "PCIE partition still gated";
|
||||
@@ -345,9 +377,13 @@ bool ep_reachable(EmuState *state) {
|
||||
void pcie_reset(EmuState *state) {
|
||||
pcie = PcieModel();
|
||||
ep_init();
|
||||
pcie.mselect[0] = MSELECT_CONFIG_RESET;
|
||||
pcie.afi[AFI_PCIE_CONFIG / 4] = AFI_PCIE_CONFIG_RESET;
|
||||
(void)state;
|
||||
}
|
||||
|
||||
bool pcie_mselect_up() { return mselect_up(); }
|
||||
|
||||
void pcie_set_powergate(bool ungated) {
|
||||
if (pcie.powergated == !ungated)
|
||||
return;
|
||||
@@ -374,7 +410,8 @@ void pcie_wl_reg_on(EmuState *state, bool level) {
|
||||
|
||||
// ---- clock and reset controller -----------------------------------------
|
||||
|
||||
void pcie_car_write(uint32_t offset, uint32_t val) {
|
||||
void pcie_car_write(EmuState *state, uint32_t offset, uint32_t val) {
|
||||
bool mselect_was_up = mselect_up();
|
||||
switch (offset) {
|
||||
case CAR_RST_DEVICES_U: pcie.rst_u = val; break;
|
||||
case CAR_CLK_OUT_ENB_U: pcie.enb_u = val; break;
|
||||
@@ -389,12 +426,17 @@ void pcie_car_write(uint32_t offset, uint32_t val) {
|
||||
case CAR_RST_DEVICES_V: pcie.rst_v = val; break;
|
||||
case CAR_RST_DEV_V_SET: pcie.rst_v |= val; break;
|
||||
case CAR_RST_DEV_V_CLR: pcie.rst_v &= ~val; break;
|
||||
case CAR_RST_DEVICES_W: pcie.rst_w = val; break;
|
||||
case CAR_RST_DEV_W_SET: pcie.rst_w |= val; break;
|
||||
case CAR_RST_DEV_W_CLR: pcie.rst_w &= ~val; break;
|
||||
case CAR_RST_DEVICES_Y: pcie.rst_y = val; break;
|
||||
case CAR_PLLE_BASE: pcie.plle = (val & PLLE_BASE_ENABLE) != 0; break;
|
||||
case CAR_PLLREFE_BASE: pcie.pllrefe = (val & PLLREFE_BASE_ENABLE) != 0; break;
|
||||
default: break;
|
||||
}
|
||||
// MSELECT out of reset is one of the things CPU0 waits on.
|
||||
if (!mselect_was_up && mselect_up())
|
||||
ccplex_preconditions_changed(state);
|
||||
}
|
||||
|
||||
// PLLE and PLLREFE do not follow the generic "ENABLE bit 30, LOCK bit 27 in
|
||||
@@ -447,6 +489,9 @@ uint32_t mselect_read(EmuState *state, uint64_t addr) {
|
||||
|
||||
void mselect_write(EmuState *state, uint64_t addr, uint32_t val) {
|
||||
(void)state;
|
||||
// Writes from the BPMP go nowhere either, as with the AFI window.
|
||||
if (bpmp_pcie_denied(addr))
|
||||
return;
|
||||
uint32_t off = (uint32_t)(addr - MSELECT_BASE) & 0xFFC;
|
||||
// Held in reset, MSELECT latches nothing - which is exactly the state a
|
||||
// payload is in when it thinks it configured the fabric and did not.
|
||||
@@ -469,7 +514,8 @@ uint32_t padctl_read(EmuState *state, uint64_t addr) {
|
||||
pcie.padctl_warned = true;
|
||||
printf("[pcie] *** read of XUSB_PADCTL %08X with the block still ***\n",
|
||||
(unsigned)addr);
|
||||
printf("[pcie] *** in reset. On real silicon this STALLS THE ***\n");
|
||||
printf("[pcie] *** in reset. On real silicon this STALLS THE %s ***\n",
|
||||
g_bus_master == BUS_CPU0 ? "CPU0" : "BPMP");
|
||||
printf("[pcie] *** BPMP for good. Clear RST_DEV_W bit %d first. ***\n",
|
||||
CLK_W_XUSB_PADCTL);
|
||||
fflush(stdout);
|
||||
@@ -614,6 +660,8 @@ uint32_t pcie_read(EmuState *state, uint64_t addr) {
|
||||
mselect_complain(addr);
|
||||
return 0xFFFFFFFF;
|
||||
}
|
||||
if (!pcie_aperture_enabled(addr))
|
||||
return 0xFFFFFFFF;
|
||||
|
||||
// Root port register windows, 0x01000000 and 0x01001000.
|
||||
if (addr >= PCIE_RP0_BASE && addr < PCIE_RP0_BASE + 0x2000) {
|
||||
@@ -637,8 +685,11 @@ uint32_t pcie_read(EmuState *state, uint64_t addr) {
|
||||
// speeds"), so speed = 1 and width = 1.
|
||||
if (!rp.link)
|
||||
return rp.reg[off / 4] & 0xFFFF;
|
||||
// LNKSTA 0x3011 on hardware: gen1, x1, Slot Clock
|
||||
// Configuration (bit 28 - the endpoint runs off the refclk the
|
||||
// root port drives) and Data Link Layer Link Active.
|
||||
return (rp.reg[off / 4] & 0xFFFF) | RP_LINK_DL_ACTIVE |
|
||||
(1u << 16) | (1u << 20);
|
||||
(1u << 28) | (1u << 16) | (1u << 20);
|
||||
default:
|
||||
return rp.reg[off / 4];
|
||||
}
|
||||
@@ -655,10 +706,14 @@ uint32_t pcie_read(EmuState *state, uint64_t addr) {
|
||||
if (addr >= PCIE_CS_BASE && addr < PCIE_CS_BASE + PCIE_CS_MODEL_SIZE) {
|
||||
uint32_t a = (uint32_t)(addr - PCIE_CS_BASE);
|
||||
uint32_t bus = (a >> 16) & 0xFF, dev = (a >> 11) & 0x1F;
|
||||
uint32_t fn = (a >> 8) & 0x7, reg = a & 0xFC;
|
||||
uint32_t fn = (a >> 8) & 0x7;
|
||||
// Register number: {AXI[27:24], AXI[7:0]} (TRM 34.3.3).
|
||||
uint32_t reg = ((a >> 16) & 0xF00) | (a & 0xFC);
|
||||
link_update(state, 1);
|
||||
if (bus != 1 || dev != 0 || fn != 0 || !ep_reachable(state))
|
||||
return 0xFFFFFFFF; // unsupported request -> all ones
|
||||
if (reg >= sizeof(pcie.ep))
|
||||
return 0; // no extended capabilities
|
||||
return pcie.ep[reg / 4];
|
||||
}
|
||||
|
||||
@@ -671,13 +726,24 @@ uint32_t pcie_read(EmuState *state, uint64_t addr) {
|
||||
return 0xFFFFFFFF;
|
||||
if (!(pcie.ep[0x04 / 4] & 0x2)) // MEM space disabled
|
||||
return 0xFFFFFFFF;
|
||||
if ((pcie.ep[0x10 / 4] & ~0xFu) != PCIE_MEM_BASE) // BAR0 unassigned
|
||||
// Decode against wherever software put the BARs: BAR0 is the 32 KiB
|
||||
// register window (backplane window in its first 4 KiB, core
|
||||
// registers above), BAR2 the 2 MiB TCM. Anything else is claimed by
|
||||
// no function: all ones.
|
||||
uint32_t a32 = (uint32_t)addr;
|
||||
uint32_t bar0 = pcie.ep[0x10 / 4] & EP_BAR0_MASK;
|
||||
uint32_t bar2 = pcie.ep[0x18 / 4] & EP_BAR2_MASK;
|
||||
bool in_bar0 = bar0 && (a32 & EP_BAR0_MASK) == bar0;
|
||||
bool in_bar2 = bar2 && (a32 & EP_BAR2_MASK) == bar2;
|
||||
if (!in_bar0 && !in_bar2)
|
||||
return 0xFFFFFFFF;
|
||||
if (!radio_core_alive(state))
|
||||
return 0xFFFFFFFF; // front-end answers, the die does not
|
||||
if (in_bar2 || (a32 - bar0) >= 0x1000)
|
||||
return 0; // modelled as quiet registers / RAM
|
||||
|
||||
uint32_t win = pcie.ep[BRCM_BAR0_WINDOW / 4] & ~0xFFFu;
|
||||
uint32_t bp = win + ((uint32_t)(addr - PCIE_MEM_BASE) & 0xFFF);
|
||||
uint32_t bp = win + ((a32 - bar0) & 0xFFF);
|
||||
if (bp == BRCM_SI_ENUM_BASE)
|
||||
return BRCM_4356_CHIPID;
|
||||
return 0;
|
||||
@@ -694,10 +760,15 @@ void pcie_write(EmuState *state, uint64_t addr, uint32_t val) {
|
||||
mselect_complain(addr);
|
||||
return;
|
||||
}
|
||||
if (!pcie_aperture_enabled(addr))
|
||||
return;
|
||||
|
||||
if (addr >= PCIE_RP0_BASE && addr < PCIE_RP0_BASE + 0x2000) {
|
||||
int port = (addr >= PCIE_RP1_BASE) ? 1 : 0;
|
||||
pcie.rp[port].reg[(uint32_t)(addr & 0xFFC) / 4] = val;
|
||||
uint32_t off = (uint32_t)(addr & 0xFFC);
|
||||
if (off == RP_VEND_XP)
|
||||
val &= ~RP_VEND_XP_DL_UP; // read-only: the link state
|
||||
pcie.rp[port].reg[off / 4] = val;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -714,8 +785,10 @@ void pcie_write(EmuState *state, uint64_t addr, uint32_t val) {
|
||||
if (addr >= PCIE_CS_BASE && addr < PCIE_CS_BASE + PCIE_CS_MODEL_SIZE) {
|
||||
uint32_t a = (uint32_t)(addr - PCIE_CS_BASE);
|
||||
uint32_t bus = (a >> 16) & 0xFF, dev = (a >> 11) & 0x1F;
|
||||
uint32_t fn = (a >> 8) & 0x7, reg = a & 0xFC;
|
||||
if (bus != 1 || dev != 0 || fn != 0 || !ep_reachable(state))
|
||||
uint32_t fn = (a >> 8) & 0x7;
|
||||
uint32_t reg = ((a >> 16) & 0xF00) | (a & 0xFC);
|
||||
if (bus != 1 || dev != 0 || fn != 0 || !ep_reachable(state) ||
|
||||
reg >= sizeof(pcie.ep))
|
||||
return;
|
||||
switch (reg) {
|
||||
case 0x04: // command: only the low half is RW
|
||||
|
||||
+15
-8
@@ -15,17 +15,20 @@ struct EmuState;
|
||||
* (0x02000000), the endpoint's BAR0 backplane window, and the UPHY PLL P0
|
||||
* calibration/lock state machine in the XUSB pad controller.
|
||||
*
|
||||
* The link only trains when the payload has satisfied every precondition
|
||||
* real silicon and the CYW4356 datasheet impose -- power partition, clocks,
|
||||
* resets, PLLE, UPHY, lane mux, IDDQ, and the refclk/PERST#/POR timing of
|
||||
* Table 62. A payload that skips one gets a link that stays down and a
|
||||
* `[pcie]` line on stdout naming what it missed.
|
||||
* The link only trains once the payload has satisfied the preconditions
|
||||
* this model checks -- power partition, AFI clock, resets, PLLE, UPHY, lane
|
||||
* mux, IDDQ, and the refclk/PERST#/POR timing of Table 62. A payload that
|
||||
* skips one gets a link that stays down and a `[pcie]` line on stdout naming
|
||||
* what it missed. Not every step of the TRM's bring-up (34.3) is checked:
|
||||
* the PCIe clock enable, PRSNT_MAP, PEX_BIAS_PWRD, the PEX_L1_RST_N pinmux
|
||||
* and the AUX_MUX_LP0 clamps are not, so a sequence that leaves one out can
|
||||
* train here and not on silicon.
|
||||
*/
|
||||
|
||||
void pcie_reset(EmuState *state);
|
||||
|
||||
// 0x01000000..0x01003FFF (root ports, PADS, AFI), 0x02000000 config
|
||||
// aperture, and the 0x13000000 BAR0 memory window.
|
||||
// 0x01000000..0x01003FFF (root ports, PADS, AFI), the 0x02000000 config
|
||||
// aperture and the 0x13000000 non-prefetchable memory window.
|
||||
uint32_t pcie_read(EmuState *state, uint64_t addr);
|
||||
void pcie_write(EmuState *state, uint64_t addr, uint32_t val);
|
||||
|
||||
@@ -40,9 +43,13 @@ void padctl_write(EmuState *state, uint64_t addr, uint32_t val);
|
||||
// Clock-and-reset forwarding. The PCIe model needs PLLE/PLLREFE lock and the
|
||||
// PCIE/AFI/PCIEXCLK/UPHY reset+enable bits, all of which live in CAR.
|
||||
// pcie_car_read returns true when it wants to override the CAR model's answer.
|
||||
void pcie_car_write(uint32_t offset, uint32_t val);
|
||||
void pcie_car_write(EmuState *state, uint32_t offset, uint32_t val);
|
||||
bool pcie_car_read(uint32_t offset, uint32_t *out);
|
||||
|
||||
// MSELECT clocked out of reset (RST_DEV_V bit 3 clear). The CCPLEX needs it
|
||||
// as much as PCIe does: it is the CPU cluster's path to every slave.
|
||||
bool pcie_mselect_up();
|
||||
|
||||
// The PCIE power partition, toggled through PMC_PWRGATE_TOGGLE.
|
||||
void pcie_set_powergate(bool ungated);
|
||||
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
#ifndef T210_REGCACHE_H
|
||||
#define T210_REGCACHE_H
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
#include <unordered_map>
|
||||
|
||||
// Last-written value of every MMIO address, for the registers whose model is
|
||||
// "read back what the payload wrote" (PINMUX, PWM, UART LCR, CLK_SOURCE_*...).
|
||||
//
|
||||
// This sits on the hottest path in the emulator - every MMIO write stores
|
||||
// into it and a good share of reads consult it - and it used to be a
|
||||
// std::map<uint64_t, uint32_t>: a red-black tree walk plus, for a new key, a
|
||||
// heap allocation per access. Profiling a hwtest sweep put the tree lookups
|
||||
// on par with the peripheral models themselves.
|
||||
//
|
||||
// Registers cluster into a few dozen 4 KiB pages, so this keeps one flat page
|
||||
// per touched page with a presence bitmap, and caches the last page looked
|
||||
// up. The interface is the subset of std::map the call sites use (count() and
|
||||
// operator[]), so they did not have to change. Keys stay byte-granular: a
|
||||
// byte store at 0x70006001 is its own entry, exactly as it was in the map.
|
||||
class RegCache {
|
||||
struct Page {
|
||||
uint32_t val[4096];
|
||||
uint64_t present[4096 / 64];
|
||||
};
|
||||
|
||||
std::unordered_map<uint64_t, std::unique_ptr<Page>> pages_;
|
||||
mutable uint64_t last_key_ = ~0ULL;
|
||||
mutable Page *last_ = nullptr;
|
||||
|
||||
Page *find(uint64_t key) const {
|
||||
if (key == last_key_)
|
||||
return last_;
|
||||
auto it = pages_.find(key);
|
||||
if (it == pages_.end())
|
||||
return nullptr;
|
||||
last_key_ = key;
|
||||
last_ = it->second.get();
|
||||
return last_;
|
||||
}
|
||||
|
||||
public:
|
||||
size_t count(uint64_t addr) const {
|
||||
const Page *p = find(addr >> 12);
|
||||
if (!p)
|
||||
return 0;
|
||||
uint32_t o = (uint32_t)(addr & 0xFFF);
|
||||
return (p->present[o >> 6] >> (o & 63)) & 1;
|
||||
}
|
||||
|
||||
uint32_t &operator[](uint64_t addr) {
|
||||
uint64_t key = addr >> 12;
|
||||
Page *p = find(key);
|
||||
if (!p) {
|
||||
auto page = std::make_unique<Page>();
|
||||
memset(page.get(), 0, sizeof(Page));
|
||||
p = page.get();
|
||||
pages_.emplace(key, std::move(page));
|
||||
last_key_ = key;
|
||||
last_ = p;
|
||||
}
|
||||
uint32_t o = (uint32_t)(addr & 0xFFF);
|
||||
p->present[o >> 6] |= 1ULL << (o & 63);
|
||||
return p->val[o];
|
||||
}
|
||||
|
||||
// Value if ever written, else `dflt`. One lookup instead of the
|
||||
// count()-then-operator[] pair.
|
||||
uint32_t get(uint64_t addr, uint32_t dflt = 0) const {
|
||||
const Page *p = find(addr >> 12);
|
||||
if (!p)
|
||||
return dflt;
|
||||
uint32_t o = (uint32_t)(addr & 0xFFF);
|
||||
return ((p->present[o >> 6] >> (o & 63)) & 1) ? p->val[o] : dflt;
|
||||
}
|
||||
|
||||
void clear() {
|
||||
pages_.clear();
|
||||
last_key_ = ~0ULL;
|
||||
last_ = nullptr;
|
||||
}
|
||||
};
|
||||
|
||||
#endif // T210_REGCACHE_H
|
||||
+487
-149
@@ -1,12 +1,14 @@
|
||||
#include "se_engine.h"
|
||||
#include "../emu_state.h"
|
||||
#include "memory_map.h"
|
||||
#include "mmio.h"
|
||||
|
||||
#include <unicorn/unicorn.h>
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <cstdlib>
|
||||
#include <vector>
|
||||
|
||||
// =============================================================================
|
||||
// Tegra X1 Security Engine (SE) emulation
|
||||
@@ -41,25 +43,20 @@ static const uint32_t K[64] = {
|
||||
|
||||
#define ROR32(x, n) (((x) >> (n)) | ((x) << (32 - (n))))
|
||||
|
||||
static void compute(const uint8_t *msg, uint32_t len, uint8_t out[32]) {
|
||||
uint32_t H[8] = {
|
||||
0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,
|
||||
0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19,
|
||||
};
|
||||
// Total padded length: msg + 0x80 + zeros + 8-byte length, multiple of 64
|
||||
uint64_t bitlen = (uint64_t)len * 8;
|
||||
uint32_t padded_len = ((len + 1 + 8 + 63) / 64) * 64;
|
||||
uint8_t *buf = (uint8_t*)std::calloc(1, padded_len);
|
||||
std::memcpy(buf, msg, len);
|
||||
buf[len] = 0x80;
|
||||
for (int i = 0; i < 8; i++) buf[padded_len - 1 - i] = (uint8_t)(bitlen >> (i * 8));
|
||||
for (uint32_t off = 0; off < padded_len; off += 64) {
|
||||
static const uint32_t H0[8] = {
|
||||
0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,
|
||||
0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19,
|
||||
};
|
||||
|
||||
// Compress `nblocks` 64-byte blocks into the running state H.
|
||||
static void blocks(uint32_t H[8], const uint8_t *p, size_t nblocks) {
|
||||
for (size_t blk = 0; blk < nblocks; blk++, p += 64) {
|
||||
uint32_t W[64];
|
||||
for (int i = 0; i < 16; i++) {
|
||||
W[i] = ((uint32_t)buf[off + i*4 + 0] << 24) |
|
||||
((uint32_t)buf[off + i*4 + 1] << 16) |
|
||||
((uint32_t)buf[off + i*4 + 2] << 8) |
|
||||
((uint32_t)buf[off + i*4 + 3]);
|
||||
W[i] = ((uint32_t)p[i*4 + 0] << 24) |
|
||||
((uint32_t)p[i*4 + 1] << 16) |
|
||||
((uint32_t)p[i*4 + 2] << 8) |
|
||||
((uint32_t)p[i*4 + 3]);
|
||||
}
|
||||
for (int i = 16; i < 64; i++) {
|
||||
uint32_t s0 = ROR32(W[i-15],7) ^ ROR32(W[i-15],18) ^ (W[i-15] >> 3);
|
||||
@@ -79,13 +76,23 @@ static void compute(const uint8_t *msg, uint32_t len, uint8_t out[32]) {
|
||||
H[0]+=a; H[1]+=b; H[2]+=c; H[3]+=d;
|
||||
H[4]+=e; H[5]+=f; H[6]+=g; H[7]+=h;
|
||||
}
|
||||
std::free(buf);
|
||||
for (int i = 0; i < 8; i++) {
|
||||
out[i*4 + 0] = (uint8_t)(H[i] >> 24);
|
||||
out[i*4 + 1] = (uint8_t)(H[i] >> 16);
|
||||
out[i*4 + 2] = (uint8_t)(H[i] >> 8);
|
||||
out[i*4 + 3] = (uint8_t)(H[i]);
|
||||
}
|
||||
}
|
||||
|
||||
// Hash the last `len` bytes of a message whose total length is `total_bits`,
|
||||
// padding as FIPS 180-4 requires. Whole blocks go straight through; only the
|
||||
// tail is copied.
|
||||
static void final(uint32_t H[8], const uint8_t *msg, size_t len,
|
||||
uint64_t total_bits) {
|
||||
size_t whole = len / 64;
|
||||
blocks(H, msg, whole);
|
||||
uint8_t tail[128] = {0};
|
||||
size_t rest = len - whole * 64;
|
||||
std::memcpy(tail, msg + whole * 64, rest);
|
||||
tail[rest] = 0x80;
|
||||
size_t tail_len = (rest + 1 + 8 <= 64) ? 64 : 128;
|
||||
for (int i = 0; i < 8; i++)
|
||||
tail[tail_len - 1 - i] = (uint8_t)(total_bits >> (i * 8));
|
||||
blocks(H, tail, tail_len / 64);
|
||||
}
|
||||
|
||||
#undef ROR32
|
||||
@@ -249,8 +256,40 @@ constexpr uint32_t SE_RNG_CONFIG_REG = 0x340;
|
||||
constexpr uint32_t SE_HASH_RESULT_REG = 0x030; // 16 dwords
|
||||
constexpr uint32_t SE_STATUS_REG = 0x800;
|
||||
constexpr uint32_t SE_ERR_STATUS_REG = 0x804;
|
||||
constexpr uint32_t SE_CONTEXT_SAVE_CONFIG_REG = 0x070;
|
||||
constexpr uint32_t SE_SHA_CONFIG_REG = 0x200;
|
||||
constexpr uint32_t SE_SHA_MSG_LENGTH_REG = 0x204; // 4 dwords, in bits
|
||||
constexpr uint32_t SE_SHA_MSG_LEFT_REG = 0x214; // 4 dwords, in bits
|
||||
constexpr uint32_t SE_RSA_CONFIG_REG = 0x400;
|
||||
constexpr uint32_t SE_RSA_KEY_SIZE_REG = 0x404;
|
||||
constexpr uint32_t SE_RSA_EXP_SIZE_REG = 0x408;
|
||||
constexpr uint32_t SE_RSA_KEYTABLE_ADDR_REG = 0x420;
|
||||
constexpr uint32_t SE_RSA_KEYTABLE_DATA_REG = 0x424;
|
||||
constexpr uint32_t SE_RSA_OUTPUT_REG = 0x428; // 64 dwords
|
||||
|
||||
constexpr uint32_t SE_INT_OP_DONE = 1u << 4;
|
||||
constexpr uint32_t SE_INT_ERR_STAT = 1u << 16;
|
||||
|
||||
constexpr uint32_t SE_OP_START = 1;
|
||||
constexpr uint32_t SE_OP_CTX_SAVE = 3;
|
||||
|
||||
constexpr uint32_t ALG_RNG = 2;
|
||||
constexpr uint32_t ALG_SHA = 3;
|
||||
constexpr uint32_t ALG_RSA = 4;
|
||||
constexpr uint32_t MODE_SHA256 = 5;
|
||||
constexpr uint32_t DST_SRK = 3;
|
||||
constexpr uint32_t DST_RSAREG = 4;
|
||||
constexpr uint32_t SHA_INIT_HASH = 1;
|
||||
|
||||
// SE_CONTEXT_SAVE_CONFIG: source in 31:29, AES key index in 11:8, word quad
|
||||
// in 1:0 (bdk se_t210.h).
|
||||
constexpr uint32_t CTX_SRC_AES_KEYTABLE = 2;
|
||||
constexpr uint32_t CTX_SRC_SRK = 6;
|
||||
|
||||
// A linked-list entry's size field is 24 bits (bdk masks it the same way),
|
||||
// which also bounds how much one operation can move: 16 MiB, 2^20 blocks.
|
||||
constexpr uint32_t LL_SIZE_MASK = 0xFFFFFF;
|
||||
constexpr uint32_t MAX_AES_BLOCKS = (LL_SIZE_MASK + 1) / 16;
|
||||
|
||||
constexpr uint32_t ALG_NOP = 0;
|
||||
constexpr uint32_t ALG_AES_DEC = 1;
|
||||
@@ -312,106 +351,333 @@ static uint32_t reg_err_status = 0;
|
||||
static uint32_t reg_rng_config = 0;
|
||||
static uint32_t spare_regs[256] = {0}; // catch-all for less critical regs
|
||||
|
||||
// The two RSA keyslots, as bdk's se_rsa_key_set() loads them: 32-bit words,
|
||||
// least significant first (it writes the big-endian key backwards, each word
|
||||
// byte-swapped). SE_RSA_KEYTABLE_ADDR picks the word: PKT in 5:0, EXP (0) or
|
||||
// MOD (1) in bit 6, the slot in bit 7.
|
||||
constexpr int kRsaWords = 64; // 2048 bits
|
||||
struct RsaKey { uint32_t exp[kRsaWords]; uint32_t mod[kRsaWords]; };
|
||||
static RsaKey rsa_keys[2];
|
||||
static uint32_t rsa_config = 0;
|
||||
static uint32_t rsa_key_size = 0;
|
||||
static uint32_t rsa_exp_size = 0;
|
||||
static uint32_t rsa_keytable_addr = 0;
|
||||
static uint32_t rsa_output[kRsaWords] = {0};
|
||||
|
||||
// The random number generator's state. The SE's DRBG is seeded from an
|
||||
// entropy source; this one starts from a constant, so runs repeat.
|
||||
static uint64_t rng_state = 0;
|
||||
|
||||
// Secure random key for context save, and the CBC chain the saved blocks
|
||||
// are encrypted under. See ctx_save().
|
||||
static uint8_t srk[16] = {0};
|
||||
static uint8_t ctx_chain[16] = {0};
|
||||
|
||||
// LL descriptor: { num, addr, size }. Hekate often uses num=0 (single descriptor).
|
||||
struct LLDesc { uint32_t num, addr, size; };
|
||||
|
||||
static bool read_ll(uc_engine *uc, uint32_t ll_addr, LLDesc *out) {
|
||||
if (!ll_addr) return false;
|
||||
if (uc_mem_read(uc, ll_addr, out, sizeof(LLDesc)) != UC_ERR_OK) return false;
|
||||
out->size &= LL_SIZE_MASK;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Encrypt/decrypt a buffer in-place using the keyslot's key (assumes 128-bit).
|
||||
// The operation touched memory it cannot reach: finish with an error, which
|
||||
// bdk's _se_op_wait() reports instead of handing back a buffer of zeros.
|
||||
static void op_fail(const char *what, uint32_t addr) {
|
||||
std::printf("[se] %s: cannot access 0x%08X - operation failed\n", what, addr);
|
||||
reg_int_status |= SE_INT_OP_DONE | SE_INT_ERR_STAT;
|
||||
}
|
||||
|
||||
static inline void xor16(uint8_t *d, const uint8_t *s) {
|
||||
for (int j = 0; j < 16; ++j) d[j] ^= s[j];
|
||||
}
|
||||
|
||||
// SE_CRYPTO_LINEAR_CTR holds the counter as the driver wrote it, bytes in
|
||||
// memory order; it counts as one big-endian 128-bit number.
|
||||
static void ctr_add(uint32_t n) {
|
||||
uint8_t *p = (uint8_t *)linear_ctr;
|
||||
for (int j = 15; j >= 0 && n; --j) {
|
||||
uint32_t v = p[j] + (n & 0xFF);
|
||||
p[j] = (uint8_t)v;
|
||||
n = (n >> 8) + (v >> 8);
|
||||
}
|
||||
}
|
||||
|
||||
// One AES operation over `blocks` 16-byte blocks, chained the way the SE
|
||||
// datapath chains them. The configurations bdk's sec/se.c uses:
|
||||
//
|
||||
// ECB INPUT_MEMORY XOR_BYPASS out = AES(in)
|
||||
// CBC enc INPUT_MEMORY XOR_TOP VCTRAM_AESOUT out = AES(in ^ v); v = out
|
||||
// CBC dec INPUT_MEMORY XOR_BOTTOM VCTRAM_PREVMEM out = AES(in) ^ v; v = in
|
||||
// OFB INPUT_AESOUT XOR_BOTTOM v = AES(v); out = v ^ in
|
||||
// CTR INPUT_LNR_CTR XOR_BOTTOM out = AES(ctr) ^ in; ctr += n
|
||||
//
|
||||
// v, the vector RAM, starts from the slot's original or updated IV (IV_SEL).
|
||||
// When the mode chains, the final v is left in the slot's UPDATED_IV: that is
|
||||
// how bdk continues a chain into a trailing partial block, and how its CMAC
|
||||
// feeds the last block after the others. With HASH enabled (CMAC) the last
|
||||
// AES output goes to SE_HASH_RESULT.
|
||||
static void run_aes_blocks(uint32_t slot, bool encrypt,
|
||||
const uint8_t *in, uint8_t *out, size_t blocks,
|
||||
uint32_t xor_pos, uint32_t input_sel,
|
||||
uint32_t vctram_sel, uint32_t iv_sel,
|
||||
bool ctr_mode, bool hash_mode) {
|
||||
uint32_t ctr_step, bool hash_mode) {
|
||||
uint8_t rk[176];
|
||||
aes::key_expand(ks_table[slot].key, rk);
|
||||
|
||||
// Pick which IV to use for chaining. Hekate typically uses ORIGINAL_IV for
|
||||
// CBC starts and switches to UPDATED_IV mid-CMAC; we honour that.
|
||||
uint8_t chain[16];
|
||||
if (iv_sel == IV_UPDATED) std::memcpy(chain, ks_table[slot].iv_upd, 16);
|
||||
else std::memcpy(chain, ks_table[slot].iv_orig, 16);
|
||||
|
||||
uint8_t prev_in[16] = {0};
|
||||
uint8_t hash_state[16] = {0}; // accumulator for HASH=1 (CMAC) — XOR top, encrypt
|
||||
if (hash_mode) std::memcpy(hash_state, chain, 16);
|
||||
uint8_t v[16];
|
||||
std::memcpy(v, iv_sel == IV_UPDATED ? ks_table[slot].iv_upd
|
||||
: ks_table[slot].iv_orig, 16);
|
||||
uint8_t aes_out[16] = {0};
|
||||
|
||||
for (size_t i = 0; i < blocks; ++i) {
|
||||
uint8_t in_block[16];
|
||||
uint8_t out_block[16];
|
||||
const uint8_t *mem = in + i * 16;
|
||||
uint8_t a[16];
|
||||
if (input_sel == INPUT_LNR_CTR) std::memcpy(a, linear_ctr, 16);
|
||||
else if (input_sel == INPUT_AESOUT) std::memcpy(a, v, 16);
|
||||
else std::memcpy(a, mem, 16);
|
||||
|
||||
if (input_sel == INPUT_LNR_CTR) {
|
||||
// CTR mode input is the linear counter (big-endian 128-bit), per-block.
|
||||
// Our linear_ctr[] is stored as 4 dwords little-endian; assemble.
|
||||
uint8_t ctr_be[16];
|
||||
for (int j = 0; j < 4; ++j) {
|
||||
uint32_t w = linear_ctr[j];
|
||||
ctr_be[j*4 + 0] = (w >> 0) & 0xFF;
|
||||
ctr_be[j*4 + 1] = (w >> 8) & 0xFF;
|
||||
ctr_be[j*4 + 2] = (w >> 16) & 0xFF;
|
||||
ctr_be[j*4 + 3] = (w >> 24) & 0xFF;
|
||||
}
|
||||
std::memcpy(in_block, ctr_be, 16);
|
||||
} else if (input_sel == INPUT_AESOUT) {
|
||||
// Re-feeding previous AES output (used in some chained constructions).
|
||||
std::memcpy(in_block, prev_in, 16);
|
||||
} else {
|
||||
std::memcpy(in_block, in + i*16, 16);
|
||||
if (xor_pos == XOR_TOP) xor16(a, v);
|
||||
if (encrypt) aes::encrypt_block(a, aes_out, rk);
|
||||
else aes::decrypt_block(a, aes_out, rk);
|
||||
|
||||
uint8_t *o = out + i * 16;
|
||||
std::memcpy(o, aes_out, 16);
|
||||
// After the core: CBC decrypt XORs the vector; OFB and CTR XOR the data.
|
||||
if (xor_pos == XOR_BOTTOM) xor16(o, input_sel == INPUT_MEMORY ? v : mem);
|
||||
|
||||
if (input_sel == INPUT_AESOUT || vctram_sel == VCTRAM_AESOUT)
|
||||
std::memcpy(v, aes_out, 16);
|
||||
else if (vctram_sel == VCTRAM_PREVMEM)
|
||||
std::memcpy(v, mem, 16);
|
||||
|
||||
if (input_sel == INPUT_LNR_CTR) ctr_add(ctr_step);
|
||||
}
|
||||
|
||||
if (hash_mode) std::memcpy(hash_result, aes_out, 16);
|
||||
bool chained = input_sel == INPUT_AESOUT || vctram_sel == VCTRAM_AESOUT ||
|
||||
vctram_sel == VCTRAM_PREVMEM;
|
||||
if (chained && blocks) std::memcpy(ks_table[slot].iv_upd, v, 16);
|
||||
}
|
||||
|
||||
// ---- RSA: x^e mod n, Montgomery multiplication on 32-bit words -------------
|
||||
//
|
||||
// Numbers are arrays of words, least significant first, n words long.
|
||||
|
||||
static bool big_geq(const uint32_t *a, const uint32_t *b, int n) {
|
||||
for (int i = n - 1; i >= 0; --i)
|
||||
if (a[i] != b[i]) return a[i] > b[i];
|
||||
return true;
|
||||
}
|
||||
|
||||
static void big_sub(uint32_t *a, const uint32_t *b, int n) {
|
||||
uint64_t borrow = 0;
|
||||
for (int i = 0; i < n; ++i) {
|
||||
uint64_t d = (uint64_t)a[i] - b[i] - borrow;
|
||||
a[i] = (uint32_t)d;
|
||||
borrow = d >> 63;
|
||||
}
|
||||
}
|
||||
|
||||
// x = (2x + bit) mod m, for x < m.
|
||||
static void big_shl1_mod(uint32_t *x, uint32_t bit, const uint32_t *m, int n) {
|
||||
uint32_t carry = bit;
|
||||
for (int i = 0; i < n; ++i) {
|
||||
uint32_t top = x[i] >> 31;
|
||||
x[i] = x[i] << 1 | carry;
|
||||
carry = top;
|
||||
}
|
||||
if (carry || big_geq(x, m, n)) big_sub(x, m, n);
|
||||
}
|
||||
|
||||
// r = a mod m, a being na words long.
|
||||
static void big_mod(const uint32_t *a, int na, const uint32_t *m, int n,
|
||||
uint32_t *r) {
|
||||
std::memset(r, 0, n * sizeof(uint32_t));
|
||||
for (int i = na * 32 - 1; i >= 0; --i)
|
||||
big_shl1_mod(r, a[i / 32] >> (i % 32) & 1, m, n);
|
||||
}
|
||||
|
||||
// t = a * b / 2^(32n) mod m, for a, b < m and m odd (CIOS).
|
||||
static void mont_mul(const uint32_t *a, const uint32_t *b, const uint32_t *m,
|
||||
uint32_t minv, int n, uint32_t *out) {
|
||||
uint32_t t[kRsaWords + 2] = {0};
|
||||
for (int i = 0; i < n; ++i) {
|
||||
uint64_t c = 0;
|
||||
for (int j = 0; j < n; ++j) {
|
||||
uint64_t s = (uint64_t)t[j] + (uint64_t)a[j] * b[i] + c;
|
||||
t[j] = (uint32_t)s;
|
||||
c = s >> 32;
|
||||
}
|
||||
|
||||
// VCTRAM source: the value XORed at XOR_TOP / XOR_BOTTOM.
|
||||
uint8_t vctram[16];
|
||||
if (vctram_sel == VCTRAM_AESOUT) std::memcpy(vctram, prev_in, 16);
|
||||
else if (vctram_sel == VCTRAM_PREVMEM) std::memcpy(vctram, (i==0)? chain : (in + (i-1)*16), 16);
|
||||
else std::memcpy(vctram, chain, 16);
|
||||
|
||||
if (xor_pos == XOR_TOP) {
|
||||
for (int j = 0; j < 16; ++j) in_block[j] ^= vctram[j];
|
||||
uint64_t s = (uint64_t)t[n] + c;
|
||||
t[n] = (uint32_t)s;
|
||||
t[n + 1] = (uint32_t)(s >> 32);
|
||||
uint32_t u = t[0] * minv;
|
||||
c = ((uint64_t)t[0] + (uint64_t)u * m[0]) >> 32;
|
||||
for (int j = 1; j < n; ++j) {
|
||||
s = (uint64_t)t[j] + (uint64_t)u * m[j] + c;
|
||||
t[j - 1] = (uint32_t)s;
|
||||
c = s >> 32;
|
||||
}
|
||||
s = (uint64_t)t[n] + c;
|
||||
t[n - 1] = (uint32_t)s;
|
||||
t[n] = t[n + 1] + (uint32_t)(s >> 32);
|
||||
}
|
||||
if (t[n] || big_geq(t, m, n)) big_sub(t, m, n);
|
||||
std::memcpy(out, t, n * sizeof(uint32_t));
|
||||
}
|
||||
|
||||
if (encrypt) aes::encrypt_block(in_block, out_block, rk);
|
||||
else aes::decrypt_block(in_block, out_block, rk);
|
||||
// out = x^e mod m. m must be odd (every RSA modulus is); false if it is not.
|
||||
static bool mod_exp(const uint32_t *x, const uint32_t *e, int ne,
|
||||
const uint32_t *m, int n, uint32_t *out) {
|
||||
if (!(m[0] & 1)) return false;
|
||||
// -1/m mod 2^32 by Newton's iteration; m0 is its own inverse mod 8.
|
||||
uint32_t inv = m[0];
|
||||
for (int i = 0; i < 4; ++i) inv *= 2 - m[0] * inv;
|
||||
uint32_t minv = 0u - inv;
|
||||
|
||||
if (xor_pos == XOR_BOTTOM) {
|
||||
// Output XOR with chain (CTR keystream XOR plaintext, etc.)
|
||||
const uint8_t *xb = (input_sel == INPUT_LNR_CTR)
|
||||
? (in + i*16) // CTR: XOR with plaintext from memory
|
||||
: vctram;
|
||||
for (int j = 0; j < 16; ++j) out_block[j] ^= xb[j];
|
||||
}
|
||||
// R^2 mod m, R = 2^(32n): 1 doubled 64n times.
|
||||
uint32_t r2[kRsaWords] = {0}, one[kRsaWords] = {0};
|
||||
one[0] = 1;
|
||||
big_mod(one, 1, m, n, r2);
|
||||
for (int i = 0; i < 64 * n; ++i) big_shl1_mod(r2, 0, m, n);
|
||||
|
||||
if (out) std::memcpy(out + i*16, out_block, 16);
|
||||
uint32_t xm[kRsaWords], acc[kRsaWords];
|
||||
big_mod(x, n, m, n, xm);
|
||||
mont_mul(xm, r2, m, minv, n, xm); // x in Montgomery form
|
||||
mont_mul(one, r2, m, minv, n, acc); // 1 in Montgomery form
|
||||
for (int i = ne * 32 - 1; i >= 0; --i) {
|
||||
mont_mul(acc, acc, m, minv, n, acc);
|
||||
if (e[i / 32] >> (i % 32) & 1) mont_mul(acc, xm, m, minv, n, acc);
|
||||
}
|
||||
mont_mul(acc, one, m, minv, n, out);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Advance chain for next block.
|
||||
if (xor_pos == XOR_BOTTOM && input_sel != INPUT_LNR_CTR) {
|
||||
// CBC encrypt: chain = ciphertext = out_block
|
||||
std::memcpy(chain, out_block, 16);
|
||||
} else if (xor_pos == XOR_TOP) {
|
||||
// CBC decrypt: chain = ciphertext (the input block we read)
|
||||
std::memcpy(chain, in + i*16, 16);
|
||||
}
|
||||
std::memcpy(prev_in, out_block, 16);
|
||||
// SE_OP_START with ALG_RSA, as bdk's se_rsa_exp_mod() drives it: the input
|
||||
// arrives over DMA as a little-endian number the size of the modulus, the
|
||||
// key comes from the slot in SE_RSA_CONFIG, KEY_SIZE gives the modulus in
|
||||
// 512-bit steps and EXP_SIZE the exponent in words. The result goes to
|
||||
// SE_RSA_OUTPUT (least significant word first), or to memory.
|
||||
static void rsa_op(EmuState *state, uint32_t dst_kind) {
|
||||
const RsaKey &k = rsa_keys[(rsa_config >> 24) & 1];
|
||||
int n = (int)((rsa_key_size & 3) + 1) * 16;
|
||||
int ne = (int)(rsa_exp_size > (uint32_t)kRsaWords ? kRsaWords : rsa_exp_size);
|
||||
|
||||
if (ctr_mode) {
|
||||
// Increment linear counter (big-endian 128-bit).
|
||||
for (int j = 15; j >= 0; --j) {
|
||||
uint8_t *p = (uint8_t*)linear_ctr;
|
||||
p[j]++;
|
||||
if (p[j]) break;
|
||||
}
|
||||
uint32_t x[kRsaWords] = {0};
|
||||
LLDesc in_ll{};
|
||||
if (read_ll(state->uc, reg_in_ll_addr, &in_ll) && in_ll.size) {
|
||||
uint32_t copy = in_ll.size < (uint32_t)n * 4 ? in_ll.size : n * 4;
|
||||
if (uc_mem_read(state->uc, in_ll.addr, x, copy) != UC_ERR_OK) {
|
||||
op_fail("RSA input", in_ll.addr);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (hash_mode) {
|
||||
// For HASH paths the final cipher block is exposed via SE_HASH_RESULT_REG.
|
||||
std::memcpy(hash_result, prev_in, 16);
|
||||
std::memset(rsa_output, 0, sizeof(rsa_output));
|
||||
if (!mod_exp(x, k.exp, ne, k.mod, n, rsa_output)) {
|
||||
std::printf("[se] RSA-%d: even modulus, no result\n", n * 32);
|
||||
reg_int_status |= SE_INT_OP_DONE | SE_INT_ERR_STAT;
|
||||
return;
|
||||
}
|
||||
// Save updated IV (chain) for next call's IV_UPDATED.
|
||||
std::memcpy(ks_table[slot].iv_upd, chain, 16);
|
||||
std::printf("[se] RSA-%d exp mod, %d-bit exponent -> ...%08X\n", n * 32,
|
||||
ne * 32, rsa_output[0]);
|
||||
|
||||
if (dst_kind == DST_MEMORY) {
|
||||
LLDesc out_ll{};
|
||||
if (read_ll(state->uc, reg_out_ll_addr, &out_ll) && out_ll.size) {
|
||||
uint32_t copy = out_ll.size < (uint32_t)n * 4 ? out_ll.size : n * 4;
|
||||
if (uc_mem_write(state->uc, out_ll.addr, rsa_output, copy) != UC_ERR_OK) {
|
||||
op_fail("RSA output", out_ll.addr);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
reg_int_status |= SE_INT_OP_DONE;
|
||||
}
|
||||
|
||||
// SplitMix64: small, and its output has no visible pattern.
|
||||
static uint64_t rng_next() {
|
||||
uint64_t z = (rng_state += 0x9E3779B97F4A7C15ull);
|
||||
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull;
|
||||
z = (z ^ (z >> 27)) * 0x94D049BB133111EBull;
|
||||
return z ^ (z >> 31);
|
||||
}
|
||||
|
||||
static void rng_fill(uint8_t *p, size_t len) {
|
||||
for (size_t i = 0; i < len; i += 8) {
|
||||
uint64_t v = rng_next();
|
||||
std::memcpy(p + i, &v, len - i < 8 ? len - i : 8);
|
||||
}
|
||||
}
|
||||
|
||||
// SE_OP_START with ALG_RNG into memory or a keyslot: bdk's se_rng_pseudo()
|
||||
// and TegraExplorer's se_generate_random() fill a buffer, SE_CRYPTO_LAST_BLOCK
|
||||
// + 1 blocks of it; Atmosphère-style drivers fill a key quad.
|
||||
static void rng_op(EmuState *state, uint32_t dst_kind) {
|
||||
uint32_t blocks = (reg_block_count % MAX_AES_BLOCKS) + 1;
|
||||
if (dst_kind == DST_KEYTABLE) {
|
||||
Keyslot &k = ks_table[(reg_keytable_dst >> 8) & 0xF];
|
||||
uint8_t *target[4] = {k.key, k.key + 16, k.iv_orig, k.iv_upd};
|
||||
rng_fill(target[reg_keytable_dst & 0x3], 16);
|
||||
} else if (dst_kind == DST_MEMORY) {
|
||||
LLDesc out_ll{};
|
||||
if (read_ll(state->uc, reg_out_ll_addr, &out_ll) && out_ll.size) {
|
||||
uint32_t len = out_ll.size < blocks * 16 ? out_ll.size : blocks * 16;
|
||||
std::vector<uint8_t> buf(len);
|
||||
rng_fill(buf.data(), len);
|
||||
if (uc_mem_write(state->uc, out_ll.addr, buf.data(), len) != UC_ERR_OK) {
|
||||
op_fail("RNG output", out_ll.addr);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
reg_int_status |= SE_INT_OP_DONE;
|
||||
}
|
||||
|
||||
// SHA-256, one-shot or in parts (bdk _se_sha_hash_256). SHA_INIT_HASH starts
|
||||
// from the standard initial state, SHA_CONTINUE from the state the previous
|
||||
// part left in SE_HASH_RESULT - which is where the hardware keeps it, too.
|
||||
// SE_SHA_MSG_LEFT says whether this is the last part: bdk passes one byte
|
||||
// more than it feeds for any part but the last, so the engine pads the part
|
||||
// only when LEFT equals the data it has, using the total from
|
||||
// SE_SHA_MSG_LENGTH. HASH_RESULT holds the state as 8 dwords, most
|
||||
// significant byte first; the driver byte-swaps them into the digest.
|
||||
static void sha_op(EmuState *state) {
|
||||
LLDesc in_ll{};
|
||||
if (!read_ll(state->uc, reg_in_ll_addr, &in_ll) || !in_ll.size) {
|
||||
reg_int_status |= SE_INT_OP_DONE;
|
||||
return;
|
||||
}
|
||||
std::vector<uint8_t> buf(in_ll.size);
|
||||
if (uc_mem_read(state->uc, in_ll.addr, buf.data(), in_ll.size) != UC_ERR_OK) {
|
||||
op_fail("SHA-256 input", in_ll.addr);
|
||||
return;
|
||||
}
|
||||
auto reg64 = [](uint32_t off) {
|
||||
return (uint64_t)spare_regs[off / 4] | ((uint64_t)spare_regs[off / 4 + 1] << 32);
|
||||
};
|
||||
uint64_t total_bits = reg64(SE_SHA_MSG_LENGTH_REG);
|
||||
uint64_t left_bits = reg64(SE_SHA_MSG_LEFT_REG);
|
||||
bool init = (spare_regs[SE_SHA_CONFIG_REG / 4] & 1) == SHA_INIT_HASH;
|
||||
|
||||
uint32_t H[8];
|
||||
if (init) std::memcpy(H, sha256::H0, sizeof(H));
|
||||
else std::memcpy(H, hash_result, sizeof(H));
|
||||
|
||||
bool last = left_bits <= (uint64_t)in_ll.size * 8;
|
||||
if (last)
|
||||
sha256::final(H, buf.data(), in_ll.size, total_bits);
|
||||
else
|
||||
sha256::blocks(H, buf.data(), in_ll.size / 64);
|
||||
std::memcpy(hash_result, H, sizeof(H));
|
||||
|
||||
std::printf("[se] SHA-256 %s%s over %u bytes @0x%X -> %08X...\n",
|
||||
init ? "" : "continued ", last ? "final" : "part",
|
||||
in_ll.size, in_ll.addr, H[0]);
|
||||
reg_int_status |= SE_INT_OP_DONE;
|
||||
}
|
||||
|
||||
static void op_start(EmuState *state) {
|
||||
@@ -423,39 +689,27 @@ static void op_start(EmuState *state) {
|
||||
bool dec = (dec_alg == ALG_AES_DEC) && (enc_alg == ALG_NOP);
|
||||
bool enc = (enc_alg == ALG_AES_ENC) && (dec_alg == ALG_NOP);
|
||||
|
||||
// ---- SHA-256 path ----
|
||||
// ALG_SHA=3, MODE_SHA256=5, DST=DST_HASHREG. Driver flow: writes
|
||||
// SE_SHA_MSG_LENGTH/LEFT, sets up IN_LL pointing at src/src_size, then
|
||||
// OP_START. Output 32 bytes go into HASH_RESULT_REG as 8 big-endian dwords
|
||||
// (driver byte_swap_32's each on read). We currently only model the
|
||||
// oneshot case (SHA_INIT_HASH); save_process_header uses oneshot.
|
||||
if (enc_alg == 3 /*ALG_SHA*/ && dst_kind == DST_HASHREG && enc_mode == 5 /*MODE_SHA256*/) {
|
||||
LLDesc in_ll{};
|
||||
bool got_in = read_ll(state->uc, reg_in_ll_addr, &in_ll);
|
||||
if (!got_in || !in_ll.size) {
|
||||
reg_int_status |= SE_INT_OP_DONE;
|
||||
return;
|
||||
}
|
||||
std::vector<uint8_t> buf(in_ll.size, 0);
|
||||
uc_mem_read(state->uc, in_ll.addr, buf.data(), in_ll.size);
|
||||
uint8_t digest[32];
|
||||
sha256::compute(buf.data(), in_ll.size, digest);
|
||||
// Pack into HASH_RESULT_REG as 8 big-endian dwords (driver byteswaps).
|
||||
for (int i = 0; i < 8; i++) {
|
||||
hash_result[i] = ((uint32_t)digest[i*4 + 0] << 24) |
|
||||
((uint32_t)digest[i*4 + 1] << 16) |
|
||||
((uint32_t)digest[i*4 + 2] << 8) |
|
||||
((uint32_t)digest[i*4 + 3]);
|
||||
}
|
||||
std::printf("[se] SHA-256 over %u bytes @0x%X -> %02X%02X%02X%02X...\n",
|
||||
in_ll.size, in_ll.addr, digest[0], digest[1], digest[2], digest[3]);
|
||||
if (enc_alg == ALG_SHA && dst_kind == DST_HASHREG && enc_mode == MODE_SHA256) {
|
||||
sha_op(state);
|
||||
return;
|
||||
}
|
||||
|
||||
// RNG into the secure random key: the start of a context save. The key is
|
||||
// fixed rather than random so runs stay reproducible.
|
||||
if (enc_alg == ALG_RNG && dst_kind == DST_SRK) {
|
||||
for (int i = 0; i < 16; ++i) srk[i] = (uint8_t)(0xA5 ^ (i * 0x1D));
|
||||
std::memset(ctx_chain, 0, sizeof(ctx_chain));
|
||||
reg_int_status |= SE_INT_OP_DONE;
|
||||
return;
|
||||
}
|
||||
|
||||
if (dst_kind == 4 /* DST_RSAREG */) {
|
||||
// RSA not implemented — leave output zero.
|
||||
reg_int_status |= SE_INT_OP_DONE;
|
||||
if (enc_alg == ALG_RNG) {
|
||||
rng_op(state, dst_kind);
|
||||
return;
|
||||
}
|
||||
|
||||
if (enc_alg == ALG_RSA) {
|
||||
rsa_op(state, dst_kind);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -470,46 +724,51 @@ static void op_start(EmuState *state) {
|
||||
uint32_t iv_sel = (reg_crypto_config >> 7) & 0x1;
|
||||
uint32_t core_sel = (reg_crypto_config >> 8) & 0x1;
|
||||
bool hash_en = (reg_crypto_config >> 0) & 0x1;
|
||||
uint32_t ctr_cnt = (reg_crypto_config >> 11) & 0x1;
|
||||
uint32_t ctr_step = (reg_crypto_config >> 11) & 0xFF;
|
||||
uint32_t key_index = (reg_crypto_config >> 24) & 0xF;
|
||||
|
||||
bool encrypt = (core_sel == CORE_ENCRYPT);
|
||||
|
||||
uint32_t blocks = reg_block_count + 1;
|
||||
// SE_CRYPTO_LAST_BLOCK is the index of the last block. Bounded by what one
|
||||
// linked-list entry can describe, so a wild value cannot overflow the
|
||||
// buffer size below.
|
||||
uint32_t blocks = (reg_block_count % MAX_AES_BLOCKS) + 1;
|
||||
uint32_t total_bytes = blocks * 16;
|
||||
|
||||
// Read input via IN_LL.
|
||||
std::vector<uint8_t> in_buf, out_buf;
|
||||
in_buf.resize(total_bytes, 0);
|
||||
out_buf.resize(total_bytes, 0);
|
||||
std::vector<uint8_t> in_buf(total_bytes, 0), out_buf(total_bytes, 0);
|
||||
|
||||
LLDesc in_ll{}, out_ll{};
|
||||
bool got_in = read_ll(state->uc, reg_in_ll_addr, &in_ll);
|
||||
bool got_out = read_ll(state->uc, reg_out_ll_addr, &out_ll);
|
||||
(void)got_out;
|
||||
|
||||
if (got_in && in_ll.size && input_sel == INPUT_MEMORY) {
|
||||
// Memory input is data for every mode: the block itself for ECB/CBC, what
|
||||
// the keystream is XORed with for OFB/CTR.
|
||||
if (got_in && in_ll.size) {
|
||||
uint32_t copy = (in_ll.size < total_bytes) ? in_ll.size : total_bytes;
|
||||
uc_mem_read(state->uc, in_ll.addr, in_buf.data(), copy);
|
||||
if (uc_mem_read(state->uc, in_ll.addr, in_buf.data(), copy) != UC_ERR_OK) {
|
||||
op_fail("AES input", in_ll.addr);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
run_aes_blocks(key_index, encrypt, in_buf.data(), out_buf.data(), blocks,
|
||||
xor_pos, input_sel, vctram_sel, iv_sel,
|
||||
(input_sel == INPUT_LNR_CTR) || ctr_cnt, hash_en);
|
||||
xor_pos, input_sel, vctram_sel, iv_sel, ctr_step, hash_en);
|
||||
|
||||
if (dst_kind == DST_MEMORY) {
|
||||
if (got_out && out_ll.size) {
|
||||
uint32_t copy = (out_ll.size < total_bytes) ? out_ll.size : total_bytes;
|
||||
uc_mem_write(state->uc, out_ll.addr, out_buf.data(), copy);
|
||||
if (uc_mem_write(state->uc, out_ll.addr, out_buf.data(), copy) != UC_ERR_OK) {
|
||||
op_fail("AES output", out_ll.addr);
|
||||
return;
|
||||
}
|
||||
}
|
||||
} else if (dst_kind == DST_KEYTABLE) {
|
||||
// Unwrap-key path: store the (single-block) result in the destination slot.
|
||||
// Unwrap-key path: the (single-block) result lands in the destination
|
||||
// slot's selected word quad.
|
||||
uint32_t dst_slot = (reg_keytable_dst >> 8) & 0xF;
|
||||
uint32_t word_quad = reg_keytable_dst & 0x3;
|
||||
uint8_t *target = (word_quad == 1)
|
||||
? ks_table[dst_slot].key + 16
|
||||
: ks_table[dst_slot].key + 0;
|
||||
std::memcpy(target, out_buf.data(), 16);
|
||||
Keyslot &k = ks_table[dst_slot];
|
||||
uint8_t *target[4] = {k.key, k.key + 16, k.iv_orig, k.iv_upd};
|
||||
std::memcpy(target[reg_keytable_dst & 0x3], out_buf.data(), 16);
|
||||
}
|
||||
// DST_HASHREG: hash_result is already populated by run_aes_blocks.
|
||||
|
||||
@@ -522,6 +781,40 @@ static void op_start(EmuState *state) {
|
||||
got_in ? in_ll.addr : 0, got_out ? out_ll.addr : 0);
|
||||
}
|
||||
|
||||
// SE_OP_CTX_SAVE, as bdk's se_aes_ctx_get_keys() drives it to read keyslots
|
||||
// back: an RNG op seeds the secure random key (SRK); each save of an AES
|
||||
// keytable quad writes that quad to memory encrypted under the SRK, CBC-
|
||||
// chained from one save to the next; saving the SRK source deposits the key
|
||||
// in PMC SECURE_SCRATCH4..7. The driver then loads the SRK into a slot and
|
||||
// CBC-decrypts everything it saved in one pass with that slot's original IV,
|
||||
// which it never sets - zero from reset - so the chain starts from zero.
|
||||
static void ctx_save(EmuState *state) {
|
||||
uint32_t cfg = spare_regs[SE_CONTEXT_SAVE_CONFIG_REG / 4];
|
||||
uint32_t src = cfg >> 29;
|
||||
if ((reg_config >> 2 & 0x7) == DST_MEMORY && src == CTX_SRC_AES_KEYTABLE) {
|
||||
const Keyslot &k = ks_table[(cfg >> 8) & 0xF];
|
||||
const uint8_t *quad[4] = {k.key, k.key + 16, k.iv_orig, k.iv_upd};
|
||||
uint8_t blk[16], rk[176];
|
||||
std::memcpy(blk, quad[cfg & 0x3], 16);
|
||||
xor16(blk, ctx_chain);
|
||||
aes::key_expand(srk, rk);
|
||||
aes::encrypt_block(blk, ctx_chain, rk);
|
||||
LLDesc out_ll{};
|
||||
if (read_ll(state->uc, reg_out_ll_addr, &out_ll) && out_ll.size >= 16 &&
|
||||
uc_mem_write(state->uc, out_ll.addr, ctx_chain, 16) != UC_ERR_OK) {
|
||||
op_fail("context save output", out_ll.addr);
|
||||
return;
|
||||
}
|
||||
} else if (src == CTX_SRC_SRK && reg_config != 0) {
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
uint32_t w;
|
||||
std::memcpy(&w, srk + i * 4, 4);
|
||||
pmc_secure_scratch_write(4 + i, w);
|
||||
}
|
||||
}
|
||||
reg_int_status |= SE_INT_OP_DONE;
|
||||
}
|
||||
|
||||
// Keytable address layout: bits 4..7 = slot, bits 2..3 = quad, bits 0..1 = pkt
|
||||
static void keytable_write(uint32_t addr, uint32_t val) {
|
||||
uint32_t slot = (addr >> 4) & 0xF;
|
||||
@@ -541,14 +834,19 @@ static void keytable_write(uint32_t addr, uint32_t val) {
|
||||
// Lockpick's _derive_bis_keys may produce wrong values when our SE engine
|
||||
// doesn't faithfully model some part of the chain; the override is a
|
||||
// pragmatic shortcut that lets the BIS XTS layer succeed regardless.
|
||||
// Two writes are never BIS keys and are left alone: clearing a slot (all
|
||||
// zeros), and loading the context-save SRK (bdk puts it in slot 3).
|
||||
if (quad == 0 && pkt == 3 && slot < 6) {
|
||||
if (bis_override_present[slot]) {
|
||||
static const uint8_t zero[16] = {0};
|
||||
bool clear = std::memcmp(ks_table[slot].key, zero, 16) == 0;
|
||||
bool is_srk = std::memcmp(ks_table[slot].key, srk, 16) == 0;
|
||||
if (bis_override_present[slot] && !clear && !is_srk) {
|
||||
std::memcpy(ks_table[slot].key, bis_override_keys[slot], 16);
|
||||
std::printf("[se] slot %u BIS key overridden from prod.keys:", slot);
|
||||
for (int i = 0; i < 16; ++i) std::printf(" %02X", ks_table[slot].key[i]);
|
||||
std::printf("\n");
|
||||
} else {
|
||||
std::printf("[se] slot %u key loaded (derived):", slot);
|
||||
} else if (!clear) {
|
||||
std::printf("[se] slot %u key loaded:", slot);
|
||||
for (int i = 0; i < 16; ++i) std::printf(" %02X", ks_table[slot].key[i]);
|
||||
std::printf("\n");
|
||||
}
|
||||
@@ -572,9 +870,12 @@ static uint32_t keytable_read(uint32_t addr) {
|
||||
return v;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
static uint32_t &rsa_keytable_word() {
|
||||
RsaKey &k = rsa_keys[(rsa_keytable_addr >> 7) & 1];
|
||||
return ((rsa_keytable_addr >> 6) & 1 ? k.mod : k.exp)[rsa_keytable_addr & 0x3F];
|
||||
}
|
||||
|
||||
#include <vector>
|
||||
} // namespace
|
||||
|
||||
uint32_t se_engine_read(EmuState *state, uint64_t addr) {
|
||||
uint32_t off = (uint32_t)(addr - SE_BASE);
|
||||
@@ -584,6 +885,9 @@ uint32_t se_engine_read(EmuState *state, uint64_t addr) {
|
||||
if (off >= SE_CRYPTO_LINEAR_CTR_REG && off < SE_CRYPTO_LINEAR_CTR_REG + 16) {
|
||||
return linear_ctr[(off - SE_CRYPTO_LINEAR_CTR_REG) / 4];
|
||||
}
|
||||
if (off >= SE_RSA_OUTPUT_REG && off < SE_RSA_OUTPUT_REG + kRsaWords * 4) {
|
||||
return rsa_output[(off - SE_RSA_OUTPUT_REG) / 4];
|
||||
}
|
||||
switch (off) {
|
||||
case SE_OPERATION_REG: return reg_op;
|
||||
case SE_INT_ENABLE_REG: return reg_int_enable;
|
||||
@@ -599,6 +903,11 @@ uint32_t se_engine_read(EmuState *state, uint64_t addr) {
|
||||
case SE_RNG_CONFIG_REG: return reg_rng_config;
|
||||
case SE_STATUS_REG: return 0; // IDLE
|
||||
case SE_ERR_STATUS_REG: return reg_err_status;
|
||||
case SE_RSA_CONFIG_REG: return rsa_config;
|
||||
case SE_RSA_KEY_SIZE_REG: return rsa_key_size;
|
||||
case SE_RSA_EXP_SIZE_REG: return rsa_exp_size;
|
||||
case SE_RSA_KEYTABLE_ADDR_REG: return rsa_keytable_addr;
|
||||
case SE_RSA_KEYTABLE_DATA_REG: return rsa_keytable_word();
|
||||
default:
|
||||
if (off < sizeof(spare_regs)/sizeof(spare_regs[0])*4)
|
||||
return spare_regs[off / 4];
|
||||
@@ -616,10 +925,12 @@ void se_engine_write(EmuState *state, uint64_t addr, uint32_t val) {
|
||||
switch (off) {
|
||||
case SE_OPERATION_REG:
|
||||
reg_op = val;
|
||||
// SE_OP_START runs the configured AES op; other op codes (RESTART_*,
|
||||
// CTX_SAVE, ABORT) just need OP_DONE so the driver's _se_wait() exits.
|
||||
if ((val & 0x7) == 1 /*SE_OP_START*/) {
|
||||
// SE_OP_START runs the configured op and CTX_SAVE saves context;
|
||||
// the others (RESTART_*) just need OP_DONE so _se_op_wait() exits.
|
||||
if ((val & 0x7) == SE_OP_START) {
|
||||
op_start(state);
|
||||
} else if ((val & 0x7) == SE_OP_CTX_SAVE) {
|
||||
ctx_save(state);
|
||||
} else if ((val & 0x7) != 0 /*not ABORT*/) {
|
||||
reg_int_status |= SE_INT_OP_DONE;
|
||||
}
|
||||
@@ -639,6 +950,11 @@ void se_engine_write(EmuState *state, uint64_t addr, uint32_t val) {
|
||||
case SE_CRYPTO_KEYTABLE_DST: reg_keytable_dst = val; return;
|
||||
case SE_RNG_CONFIG_REG: reg_rng_config = val; return;
|
||||
case SE_ERR_STATUS_REG: reg_err_status &= ~val; return;
|
||||
case SE_RSA_CONFIG_REG: rsa_config = val; return;
|
||||
case SE_RSA_KEY_SIZE_REG: rsa_key_size = val; return;
|
||||
case SE_RSA_EXP_SIZE_REG: rsa_exp_size = val; return;
|
||||
case SE_RSA_KEYTABLE_ADDR_REG: rsa_keytable_addr = val; return;
|
||||
case SE_RSA_KEYTABLE_DATA_REG: rsa_keytable_word() = val; return;
|
||||
default:
|
||||
if (off < sizeof(spare_regs)/sizeof(spare_regs[0])*4)
|
||||
spare_regs[off / 4] = val;
|
||||
@@ -647,9 +963,31 @@ void se_engine_write(EmuState *state, uint64_t addr, uint32_t val) {
|
||||
(void)state;
|
||||
}
|
||||
|
||||
// Keys a prod.keys file pre-loaded, which a soft reboot puts back.
|
||||
static Keyslot ks_preload[16];
|
||||
|
||||
void se_engine_set_aes128_key(uint32_t slot, const uint8_t key[16]) {
|
||||
if (slot >= 16) return;
|
||||
std::memcpy(ks_table[slot].key, key, 16);
|
||||
std::memcpy(ks_preload[slot].key, key, 16);
|
||||
}
|
||||
|
||||
void se_engine_reset() {
|
||||
std::memcpy(ks_table, ks_preload, sizeof(ks_table));
|
||||
reg_config = reg_crypto_config = 0;
|
||||
reg_in_ll_addr = reg_out_ll_addr = 0;
|
||||
reg_block_count = reg_keytable_addr = reg_keytable_dst = 0;
|
||||
reg_op = reg_int_status = reg_int_enable = 0;
|
||||
reg_err_status = reg_rng_config = 0;
|
||||
std::memset(linear_ctr, 0, sizeof(linear_ctr));
|
||||
std::memset(hash_result, 0, sizeof(hash_result));
|
||||
std::memset(spare_regs, 0, sizeof(spare_regs));
|
||||
std::memset(srk, 0, sizeof(srk));
|
||||
std::memset(ctx_chain, 0, sizeof(ctx_chain));
|
||||
std::memset(rsa_keys, 0, sizeof(rsa_keys));
|
||||
std::memset(rsa_output, 0, sizeof(rsa_output));
|
||||
rsa_config = rsa_key_size = rsa_exp_size = rsa_keytable_addr = 0;
|
||||
rng_state = 0;
|
||||
}
|
||||
|
||||
// ---- prod.keys parser -------------------------------------------------------
|
||||
|
||||
+12
-7
@@ -10,17 +10,18 @@ struct EmuState;
|
||||
// operations against an emulated 16-slot keytable.
|
||||
//
|
||||
// Currently implemented:
|
||||
// * AES-128 ECB encrypt/decrypt (single + multi-block, DMA via LL descriptors)
|
||||
// * AES-128 CBC encrypt/decrypt
|
||||
// * AES-128 CTR mode
|
||||
// * AES-128 ECB, CBC, OFB and CTR, single and multi-block, with the IV
|
||||
// chained through UPDATED_IV the way bdk's partial-block path expects
|
||||
// * AES-CMAC (HASH_ENABLE into SE_HASH_RESULT)
|
||||
// * AES "unwrap" (decrypt and store result in destination keyslot)
|
||||
// * SHA-256, one-shot and in parts (SHA_INIT_HASH / SHA_CONTINUE)
|
||||
// * Context save of AES keyslots under a secure random key, as bdk's
|
||||
// se_aes_ctx_get_keys() reads keys back
|
||||
// * Keyslot programming (CRYPTO_KEYTABLE_ADDR/DATA)
|
||||
// * Pre-population of keyslots from a Switch prod.keys file
|
||||
//
|
||||
// Not implemented (returns zero / no-op):
|
||||
// * AES-CMAC (HASH+VCTRAM_AESOUT path)
|
||||
// * SHA / RNG / RSA
|
||||
// Each unimplemented op still completes (sets OP_DONE) so the boot doesn't hang.
|
||||
// Not implemented: RNG output, RSA, AES-192/256 key sizes. Those operations
|
||||
// still complete (set OP_DONE) so a payload does not hang on them.
|
||||
|
||||
uint32_t se_engine_read (EmuState *state, uint64_t addr);
|
||||
void se_engine_write(EmuState *state, uint64_t addr, uint32_t val);
|
||||
@@ -31,6 +32,10 @@ void se_engine_write(EmuState *state, uint64_t addr, uint32_t val);
|
||||
// AES, so this is enough.
|
||||
void se_engine_set_aes128_key(uint32_t slot, const uint8_t key[16]);
|
||||
|
||||
// Soft reboot: registers back to reset, keyslots back to what prod.keys
|
||||
// pre-loaded.
|
||||
void se_engine_reset();
|
||||
|
||||
// Parse a switch-style "prod.keys" file (lines of `name = hex_value`) and
|
||||
// pre-populate the well-known bootrom-derived keyslots (KS_TSEC=12,
|
||||
// KS_SECURE_BOOT=14, KS_TSEC_ROOT=13) so Lockpick / Hekate's derivation
|
||||
|
||||
+26
-26
@@ -1,26 +1,26 @@
|
||||
#ifndef T210_TEGRA_BL_H
|
||||
#define T210_TEGRA_BL_H
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
// Tegra X1-style block-linear byte offset for 32 bpp (RGBA8888 / XRGB in RAM).
|
||||
// Matches test_img.py "Block Linear / Tegra X1" mode.
|
||||
inline uint32_t tegra_bl_byte_off_rgba8888(uint32_t sx, uint32_t sy,
|
||||
uint32_t width_gobs,
|
||||
uint32_t block_height_gobs) {
|
||||
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 / block_height_gobs;
|
||||
uint32_t gob_in_block_y = gob_y % block_height_gobs;
|
||||
|
||||
uint32_t idx =
|
||||
(block_y * width_gobs * block_height_gobs * 128u) +
|
||||
(gob_x * block_height_gobs * 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);
|
||||
return idx * 4u;
|
||||
}
|
||||
|
||||
#endif
|
||||
#ifndef T210_TEGRA_BL_H
|
||||
#define T210_TEGRA_BL_H
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
// Tegra X1-style block-linear byte offset for 32 bpp (RGBA8888 / XRGB in RAM).
|
||||
// Matches test_img.py "Block Linear / Tegra X1" mode.
|
||||
inline uint32_t tegra_bl_byte_off_rgba8888(uint32_t sx, uint32_t sy,
|
||||
uint32_t width_gobs,
|
||||
uint32_t block_height_gobs) {
|
||||
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 / block_height_gobs;
|
||||
uint32_t gob_in_block_y = gob_y % block_height_gobs;
|
||||
|
||||
uint32_t idx =
|
||||
(block_y * width_gobs * block_height_gobs * 128u) +
|
||||
(gob_x * block_height_gobs * 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);
|
||||
return idx * 4u;
|
||||
}
|
||||
|
||||
#endif
|
||||
+1723
File diff suppressed because it is too large.
Load diff
+18
@@ -0,0 +1,18 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
struct EmuState;
|
||||
|
||||
// USB device mode (see usb.cpp): the Erista USB2 device controller, and the
|
||||
// PC a --usb-host run plugs into it.
|
||||
uint32_t usb2d_read(EmuState *state, uint64_t addr, unsigned size);
|
||||
void usb2d_write(EmuState *state, uint64_t addr, unsigned size, uint32_t val);
|
||||
|
||||
// The Mariko XUSB device controller (XHCI registers, PCI config at +0x8000,
|
||||
// the device block at +0x9000).
|
||||
uint32_t xusbd_read(EmuState *state, uint64_t addr, unsigned size);
|
||||
void xusbd_write(EmuState *state, uint64_t addr, unsigned size, uint32_t val);
|
||||
|
||||
// SoC reset: the controller back to its reset state, the host unplugged.
|
||||
void usb_reset(EmuState *state);
|
||||
@@ -0,0 +1,10 @@
|
||||
/* Loaded and entered at 0x40010000, like any RCM payload. */
|
||||
ENTRY(_start)
|
||||
SECTIONS {
|
||||
. = 0x40010000;
|
||||
.text : { KEEP(*(.text.start)) *(.text*) }
|
||||
.rodata : { *(.rodata*) }
|
||||
.data : { *(.data*) }
|
||||
.bss : { *(.bss*) *(COMMON) }
|
||||
/DISCARD/ : { *(.comment) *(.note*) *(.ARM.attributes) *(.ARM.exidx*) }
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
/*
|
||||
* CCPLEX regression payload.
|
||||
*
|
||||
* A freestanding BPMP payload (ARM mode, loaded at 0x40010000 like any RCM
|
||||
* payload) that drives the emulator's CPU0 model through the same register
|
||||
* sequence as bdk's ccplex_boot_cpu0(), and reports what happened on UART-B.
|
||||
* tests/ccplex/run.sh checks the emulator's log for the expected lines.
|
||||
*
|
||||
* 1. Release CPU0 from reset with nothing powered. The core must NOT run,
|
||||
* and the emulator must say which precondition is missing.
|
||||
* 2. Do the real bring-up - CPU rail (MAX77620 GPIO5 + MAX77621 VOUT on
|
||||
* I2C5), CRAIL/C0NC/CE0 partitions, CPUG + MSELECT clocks, MSELECT out
|
||||
* of reset, PLLX, RAM repair, SB_AA64_RESET_LOW - then release it. An
|
||||
* AArch64 blob copied to DRAM records CurrentEL and a TIMERUS delta in
|
||||
* a mailbox, writes a magic word last, and parks in WFE.
|
||||
* Released first with its clock stopped (CLK_CPUG_CMPLX), it must
|
||||
* stay still until the stop is cleared.
|
||||
* 3. Put CPU0 back into reset and power the console off.
|
||||
*
|
||||
* Built by `make test` with arm-none-eabi-gcc; no other toolchain needed, as
|
||||
* the AArch64 side is a handful of pre-assembled words.
|
||||
*/
|
||||
|
||||
typedef unsigned int u32;
|
||||
|
||||
#define REG(a) (*(volatile u32 *)(a))
|
||||
|
||||
#define TIMERUS 0x60005010u
|
||||
#define CAR 0x60006000u
|
||||
#define FLOW 0x60007000u
|
||||
#define SB 0x6000C200u
|
||||
#define UARTB_THR 0x70006040u
|
||||
#define PMC 0x7000E400u
|
||||
#define I2C5 0x7000D000u
|
||||
|
||||
#define CPU_ENTRY 0xA0000000u
|
||||
#define MBOX 0xA0030000u
|
||||
#define PCIE_MAGIC 0x50434945u
|
||||
|
||||
/* AArch64, entered at EL3 with the MMU off:
|
||||
* mov w1, #0xa0030000 ; mailbox
|
||||
* mrs x8, currentel
|
||||
* str w8, [x1, #4] ; [1] = CurrentEL
|
||||
* mov w4, #0x5010
|
||||
* movk w4, #0x6000, lsl #16 ; TIMERUS
|
||||
* ldr w5, [x4]
|
||||
* mov w6, #2000
|
||||
* 1:subs w6, w6, #1
|
||||
* b.ne 1b
|
||||
* ldr w7, [x4]
|
||||
* sub w7, w7, w5
|
||||
* str w7, [x1, #8] ; [2] = TIMERUS delta across the loop
|
||||
* mov w2, #0x4945
|
||||
* movk w2, #0x5043, lsl #16
|
||||
* str w2, [x1] ; [0] = 'PCIE', written last
|
||||
* 2:wfe
|
||||
* b 2b
|
||||
*/
|
||||
static const u32 cpu0_blob[] = {
|
||||
0x52b40061, 0xd5384248, 0xb9000428, 0x528a0204, 0x72ac0004, 0xb9400085,
|
||||
0x5280fa06, 0x710004c6, 0x54ffffe1, 0xb9400087, 0x4b0500e7, 0xb9000827,
|
||||
0x528928a2, 0x72aa0862, 0xb9000022, 0xd503205f, 0x17ffffff,
|
||||
};
|
||||
|
||||
static void putc_(char c) { REG(UARTB_THR) = (u32)(unsigned char)c; }
|
||||
|
||||
static void puts_(const char *s) {
|
||||
while (*s)
|
||||
putc_(*s++);
|
||||
}
|
||||
|
||||
static void puthex(u32 v) {
|
||||
for (int i = 28; i >= 0; i -= 4)
|
||||
putc_("0123456789ABCDEF"[(v >> i) & 0xF]);
|
||||
}
|
||||
|
||||
static void udelay(u32 us) {
|
||||
u32 start = REG(TIMERUS);
|
||||
while (REG(TIMERUS) - start < us)
|
||||
;
|
||||
}
|
||||
|
||||
/* bdk-style normal-mode I2C write: [reg, val] in CMD_DATA1, 2 bytes, GO. */
|
||||
static void i2c5_write(u32 dev, u32 reg, u32 val) {
|
||||
REG(I2C5 + 0x04) = dev << 1; /* CMD_ADDR0 */
|
||||
REG(I2C5 + 0x0C) = reg | (val << 8); /* CMD_DATA1 */
|
||||
REG(I2C5 + 0x00) = (1u << 1) | (1u << 9); /* CNFG: 2 bytes, write, GO */
|
||||
}
|
||||
|
||||
static void pwrgate_on(u32 part) {
|
||||
if (!(REG(PMC + 0x38) & (1u << part))) /* PWRGATE_STATUS */
|
||||
REG(PMC + 0x30) = part | (1u << 8); /* PWRGATE_TOGGLE */
|
||||
}
|
||||
|
||||
#define RST_CPU0 ((1u << 30) | (1u << 24) | (1u << 16) | (1u << 0))
|
||||
#define RST_NONCPU (1u << 29)
|
||||
|
||||
static void release_cpu0(void) {
|
||||
REG(SB + 0x30) = CPU_ENTRY | 1u; /* SB_AA64_RESET_LOW */
|
||||
REG(SB + 0x34) = 0; /* SB_AA64_RESET_HIGH */
|
||||
REG(CAR + 0x454) = RST_NONCPU; /* RST_CPUG_CMPLX_CLR */
|
||||
REG(CAR + 0x454) = RST_CPU0;
|
||||
}
|
||||
|
||||
static void hold_cpu0(void) {
|
||||
REG(CAR + 0x450) = RST_CPU0; /* RST_CPUG_CMPLX_SET */
|
||||
REG(CAR + 0x450) = RST_NONCPU;
|
||||
}
|
||||
|
||||
__attribute__((section(".text.start"), noreturn))
|
||||
void _start(void) {
|
||||
volatile u32 *mb = (volatile u32 *)MBOX;
|
||||
|
||||
puts_("ccplex test: start\n");
|
||||
for (u32 i = 0; i < sizeof(cpu0_blob) / sizeof(cpu0_blob[0]); i++)
|
||||
((volatile u32 *)CPU_ENTRY)[i] = cpu0_blob[i];
|
||||
for (u32 i = 0; i < 4; i++)
|
||||
mb[i] = 0;
|
||||
|
||||
/* 1. Nothing powered: the release must be refused. */
|
||||
release_cpu0();
|
||||
udelay(2000);
|
||||
puts_(mb[0] == PCIE_MAGIC ? "unpowered: CPU0 RAN (wrong)\n"
|
||||
: "unpowered: CPU0 stayed dark\n");
|
||||
hold_cpu0();
|
||||
|
||||
/* 2. The real bring-up, in ccplex_boot_cpu0() order. */
|
||||
i2c5_write(0x3C, 0x40, 0x1C); /* MAX77620 AME_GPIO: GPIO5 plain */
|
||||
i2c5_write(0x3C, 0x3B, 0x09); /* GPIO5: push-pull, out high */
|
||||
i2c5_write(0x1B, 0x00, 0x80 | 55); /* MAX77621 VOUT: on, 0.950 V */
|
||||
REG(CAR + 0x0E0) = (1u << 30) | (2u << 20) | (156u << 8) | 2u; /* PLLX */
|
||||
REG(CAR + 0x3B4) = 4u << 1; /* CLK_SOURCE_MSELECT */
|
||||
REG(CAR + 0x440) = 1u << 3; /* CLK_ENB_V_SET: MSELECT */
|
||||
REG(CAR + 0x020) = 0x20008888; /* CCLK_BURST: PLLX_OUT0_LJ */
|
||||
REG(CAR + 0x024) = 1u << 31; /* SUPER_CCLK_DIVIDER */
|
||||
REG(CAR + 0x440) = 1u << 0; /* CLK_ENB_V_SET: CPUG */
|
||||
pwrgate_on(0); /* CRAIL */
|
||||
pwrgate_on(15); /* C0NC */
|
||||
pwrgate_on(14); /* CE0 */
|
||||
REG(FLOW + 0x40) = 1; /* RAM_REPAIR_REQ */
|
||||
while (!(REG(FLOW + 0x40) & 2))
|
||||
;
|
||||
REG(CAR + 0x434) = 1u << 3; /* RST_DEV_V_CLR: MSELECT */
|
||||
|
||||
/* Released with its clock stopped, CPU0 must not run until the stop is
|
||||
* cleared; the strobes and the active-cluster reset view read back. */
|
||||
REG(CAR + 0x460) = 1u << 8; /* CLK_CPUG_CMPLX_SET: CPU0 */
|
||||
release_cpu0();
|
||||
udelay(5000);
|
||||
puts_(mb[0] == PCIE_MAGIC ? "clock stopped: CPU0 RAN (wrong)\n"
|
||||
: "clock stopped: CPU0 held still\n");
|
||||
puts_("clock stop reads ");
|
||||
puthex(REG(CAR + 0x378)); /* CLK_CPUG_CMPLX */
|
||||
putc_(' ');
|
||||
puthex(REG(CAR + 0x464)); /* CLK_CPUG_CMPLX_CLR */
|
||||
putc_('\n');
|
||||
puts_(REG(CAR + 0x340) == REG(CAR + 0x450) /* RST_CPU(G)_CMPLX_SET */
|
||||
? "reset view: RST_CPU_CMPLX matches RST_CPUG_CMPLX\n"
|
||||
: "reset view: RST_CPU_CMPLX differs\n");
|
||||
REG(CAR + 0x464) = 1u << 8; /* CLK_CPUG_CMPLX_CLR */
|
||||
|
||||
u32 start = REG(TIMERUS);
|
||||
while (mb[0] != PCIE_MAGIC && REG(TIMERUS) - start < 100000)
|
||||
udelay(100);
|
||||
puts_("powered: magic=");
|
||||
puthex(mb[0]);
|
||||
puts_(" el=");
|
||||
puthex(mb[1]);
|
||||
puts_(" dt=");
|
||||
puthex(mb[2]);
|
||||
putc_('\n');
|
||||
|
||||
/* Let CPU0 sit in its WFE park for a while: it must cost next to
|
||||
* nothing, which the retired-instruction count at reset shows. */
|
||||
udelay(50000);
|
||||
|
||||
/* 3. Back into reset, then power off. */
|
||||
hold_cpu0();
|
||||
puts_("ccplex test: done\n");
|
||||
i2c5_write(0x3C, 0x41, 0x02); /* MAX77620 ONOFFCNFG1: PWR_OFF */
|
||||
for (;;)
|
||||
;
|
||||
}
|
||||
Executable
+59
@@ -0,0 +1,59 @@
|
||||
#!/bin/sh
|
||||
# CCPLEX regression test: boot CPU0 from a BPMP payload and check what the
|
||||
# emulator and the payload report. Usage: tests/ccplex/run.sh [rcm_emu] [payload]
|
||||
EMU=${1:-./rcm_emu}
|
||||
PAYLOAD=${2:-tests/ccplex/payload.bin}
|
||||
LOG=${LOG:-tests/ccplex/out.log}
|
||||
|
||||
SDL_VIDEODRIVER=dummy RCM_EMU_NO_AUDIO=1 timeout 120 "$EMU" "$PAYLOAD" \
|
||||
> "$LOG" 2>&1
|
||||
status=$?
|
||||
|
||||
fail=0
|
||||
expect() {
|
||||
if grep -q -- "$1" "$LOG"; then
|
||||
echo " ok $2"
|
||||
else
|
||||
echo " FAIL $2 (missing: $1)"
|
||||
fail=1
|
||||
fi
|
||||
}
|
||||
|
||||
echo "ccplex test (emulator exit $status):"
|
||||
expect 'cannot run: CPU rail off' 'an unpowered release is refused, with the reason'
|
||||
expect 'unpowered: CPU0 stayed dark' 'and the core really did not execute'
|
||||
expect 'CPU0 released: AArch64 EL3, MMU off, entry 0xA0000000' 'a powered release boots CPU0 at the SB vector'
|
||||
expect 'clock stopped: CPU0 held still' 'a core released with its clock stopped does not run'
|
||||
expect 'clock stop reads 00000100 00000100' 'CLK_CPUG_CMPLX and its CLR strobe read back the stop'
|
||||
expect 'RST_CPU_CMPLX matches RST_CPUG_CMPLX' 'the active-cluster reset register reads the G cluster'
|
||||
expect 'powered: magic=50434945' 'CPU0 ran the blob and wrote the mailbox'
|
||||
expect 'el=0000000C' 'CPU0 came up at EL3'
|
||||
expect 'CPU0 stopped (held in reset)' 'RST_CPUG_CMPLX_SET stops the core'
|
||||
expect 'MAX77620 PWR_OFF received' 'the payload ran to its power-off'
|
||||
if [ "$status" -eq 0 ]; then
|
||||
echo " ok the emulator exited cleanly"
|
||||
else
|
||||
echo " FAIL the emulator exited with status $status (124 = timed out)"
|
||||
fail=1
|
||||
fi
|
||||
|
||||
# TIMERUS as CPU0 saw it must have moved across its busy loop.
|
||||
dt=$(sed -n 's/.*dt=\([0-9A-F]*\).*/\1/p' "$LOG" | head -1)
|
||||
if [ -n "$dt" ] && [ "$dt" != "00000000" ]; then
|
||||
echo " ok CPU0 sees time advance (TIMERUS delta 0x$dt)"
|
||||
else
|
||||
echo " FAIL CPU0's TIMERUS delta is zero or missing"
|
||||
fail=1
|
||||
fi
|
||||
|
||||
# Parked in WFE for ~50 ms, the core must retire next to nothing: the park
|
||||
# loop sleeps to the end of each slice instead of spinning.
|
||||
retired=$(sed -n 's/.*CPU0 stopped (held in reset) after \([0-9]*\) instructions.*/\1/p' "$LOG" | head -1)
|
||||
if [ -n "$retired" ] && [ "$retired" -lt 100000 ]; then
|
||||
echo " ok WFE parks the core ($retired instructions retired in total)"
|
||||
else
|
||||
echo " FAIL WFE did not park the core (retired: ${retired:-?})"
|
||||
fail=1
|
||||
fi
|
||||
|
||||
[ $fail -eq 0 ] && echo "ccplex test: PASS" || { echo "ccplex test: FAIL - see $LOG"; exit 1; }
|
||||
Executable
+76
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare the emulator's frame snapshot with what a display scenario drew.
|
||||
|
||||
Usage: check.py <scenario> <last_fb.rgba> <last_fb.meta>
|
||||
|
||||
last_fb.rgba is the host view, ARGB8888 little-endian, as last_fb.meta's
|
||||
"W H" gives it. The expected picture follows tests/display/payload.c.
|
||||
"""
|
||||
import sys
|
||||
from array import array
|
||||
|
||||
|
||||
def pat(x, y):
|
||||
return 0xFF000000 | ((x * 7) & 0xFF) << 16 | ((y * 3) & 0xFF) << 8 | ((x ^ y) & 0xFF)
|
||||
|
||||
|
||||
def patq(x, y):
|
||||
return 0xFF000000 | ((x * 5 + y) & 0xFF) << 16 | 0x4000 | ((y * 9) & 0xFF)
|
||||
|
||||
|
||||
def blend(s, d, k1):
|
||||
# BLEND_MATCH_SELECT SRC K1, DST NEG_K1 (1 - K1), per channel, opaque.
|
||||
out = 0xFF000000
|
||||
for sh in (0, 8, 16):
|
||||
c = (((s >> sh) & 0xFF) * k1 + ((d >> sh) & 0xFF) * (255 - k1)) // 255
|
||||
out |= min(c, 255) << sh
|
||||
return out
|
||||
|
||||
|
||||
def expected(scenario, w, h):
|
||||
if scenario == 1:
|
||||
return (720, 1280), lambda x, y: pat(x, y)
|
||||
if scenario in (2, 3, 4, 5):
|
||||
# The picture was drawn landscape and turned on its way to the
|
||||
# panel; the view turns it back.
|
||||
return (1280, 720), lambda x, y: pat(x, y)
|
||||
if scenario == 6:
|
||||
def f(x, y):
|
||||
a = pat(x, 1279 - y)
|
||||
if 100 <= x < 300 and 200 <= y < 500:
|
||||
return blend(patq(x - 100, y - 200), a, 128)
|
||||
return a
|
||||
return (720, 1280), f
|
||||
raise SystemExit("unknown scenario %d" % scenario)
|
||||
|
||||
|
||||
def main():
|
||||
scenario = int(sys.argv[1])
|
||||
w, h = map(int, open(sys.argv[3]).read().split())
|
||||
frame = array("I")
|
||||
with open(sys.argv[2], "rb") as fh:
|
||||
frame.frombytes(fh.read())
|
||||
(ew, eh), f = expected(scenario, w, h)
|
||||
if (w, h) != (ew, eh):
|
||||
print(" FAIL scenario %d: view is %dx%d, expected %dx%d" % (scenario, w, h, ew, eh))
|
||||
return 1
|
||||
bad = 0
|
||||
first = None
|
||||
for y in range(h):
|
||||
row = y * w
|
||||
for x in range(w):
|
||||
want = f(x, y)
|
||||
if frame[row + x] != want:
|
||||
bad += 1
|
||||
if first is None:
|
||||
first = (x, y, frame[row + x], want)
|
||||
if bad:
|
||||
x, y, got, want = first
|
||||
print(" FAIL scenario %d: %d of %d pixels differ; first at (%d,%d): %08X, expected %08X"
|
||||
% (scenario, bad, w * h, x, y, got, want))
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,10 @@
|
||||
/* Loaded and entered at 0x40010000, like any RCM payload. */
|
||||
ENTRY(_start)
|
||||
SECTIONS {
|
||||
. = 0x40010000;
|
||||
.text : { KEEP(*(.text.start)) *(.text*) }
|
||||
.rodata : { *(.rodata*) }
|
||||
.data : { *(.data*) }
|
||||
.bss : { *(.bss*) *(COMMON) }
|
||||
/DISCARD/ : { *(.comment) *(.note*) *(.ARM.attributes) *(.ARM.exidx*) }
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
/*
|
||||
* Display regression payload.
|
||||
*
|
||||
* A freestanding BPMP payload that drives the emulator's display controller
|
||||
* and VIC models the way bdk does - window registers through
|
||||
* DISPLAY_WINDOW_HEADER and STATE_CONTROL, VIC through its Falcon register
|
||||
* window and a vic_config_t in DRAM - then parks. tests/display/run.sh
|
||||
* compares the frame the emulator shows (last_fb.rgba) with the picture the
|
||||
* payload drew. Built once per scenario with -DSCENARIO=n:
|
||||
*
|
||||
* 1 a pitch window (hekate's TUI setup)
|
||||
* 2 VIC turns a 1280x720 picture 270 degrees into a pitch surface that
|
||||
* window A shows (Nyx's setup); the view undoes the turn
|
||||
* 3 as 2, but VIC writes a block-linear surface (16-GOB blocks)
|
||||
* 4 VIC copies the picture into a block-linear surface, and window A
|
||||
* shows it turned by the DC itself: SCAN_COLUMN | H_DIRECTION with
|
||||
* ADDR_H_OFFSET at the top-right pixel's last byte (HOS's setup)
|
||||
* 5 as 2, but VIC reads a block-linear source surface
|
||||
* 6 window A mirrored top-bottom (V_DIRECTION, ADDR_V_OFFSET at the
|
||||
* last line), with window D blended over it at K1 = 128
|
||||
*
|
||||
* Every surface holds pat(x, y), which differs between neighbouring
|
||||
* pixels in both directions, so a wrong stride, turn, flip or offset shows
|
||||
* up almost everywhere.
|
||||
*/
|
||||
|
||||
#ifndef SCENARIO
|
||||
#define SCENARIO 1
|
||||
#endif
|
||||
|
||||
typedef unsigned int u32;
|
||||
|
||||
#define REG(a) (*(volatile u32 *)(a))
|
||||
|
||||
#define UARTB_THR 0x70006040u
|
||||
#define DC 0x54200000u
|
||||
#define VIC 0x54340000u
|
||||
|
||||
#define DCR(i) REG(DC + (i) * 4u)
|
||||
/* bdk's _vic_write_priv() for registers with no low address bits. */
|
||||
#define VICP(r) REG(VIC + 0x1000u + ((r) >> 6))
|
||||
|
||||
#define SRC_L 0xC0000000u /* 1280x720 landscape picture, pitch */
|
||||
#define SURF_B 0xC0400000u /* block-linear intermediate */
|
||||
#define DST 0xC0800000u /* what window A scans out */
|
||||
#define SRC_P 0xC0C00000u /* 720x1280 portrait picture, pitch */
|
||||
#define SRC_Q 0xC1000000u /* 200x300 overlay for window D */
|
||||
#define CFG 0xC1400000u /* vic_config_t, 256-byte aligned */
|
||||
|
||||
/* DC window registers (word indices) and bits. */
|
||||
#define WINDOW_HEADER 0x042u
|
||||
#define STATE_CONTROL 0x041u
|
||||
#define WIN_OPTIONS 0x700u
|
||||
#define COLOR_DEPTH 0x703u
|
||||
#define POSITION 0x704u
|
||||
#define SIZE 0x705u
|
||||
#define PRESCALED 0x706u
|
||||
#define LINE_STRIDE 0x70Au
|
||||
#define BLEND_LAYER 0x716u
|
||||
#define BLEND_MATCH 0x717u
|
||||
#define START_ADDR 0x800u
|
||||
#define ADDR_H_OFFSET 0x806u
|
||||
#define ADDR_V_OFFSET 0x808u
|
||||
#define SURFACE_KIND 0x80Bu
|
||||
|
||||
#define H_DIRECTION BIT(0)
|
||||
#define V_DIRECTION BIT(2)
|
||||
#define SCAN_COLUMN BIT(4)
|
||||
#define WIN_ENABLE BIT(30)
|
||||
#define BIT(n) (1u << (n))
|
||||
|
||||
#define KIND_PITCH 0u
|
||||
#define KIND_BLOCK (2u | (4u << 4)) /* block linear, 16-GOB blocks */
|
||||
|
||||
static void puts_(const char *s) {
|
||||
while (*s)
|
||||
REG(UARTB_THR) = (u32)(unsigned char)*s++;
|
||||
}
|
||||
|
||||
static u32 pat(u32 x, u32 y) {
|
||||
return 0xFF000000u | ((x * 7u) & 0xFFu) << 16 | ((y * 3u) & 0xFFu) << 8 |
|
||||
((x ^ y) & 0xFFu);
|
||||
}
|
||||
|
||||
static u32 patq(u32 x, u32 y) {
|
||||
return 0xFF000000u | ((x * 5u + y) & 0xFFu) << 16 | 0x4000u |
|
||||
((y * 9u) & 0xFFu);
|
||||
}
|
||||
|
||||
static void fill(u32 base, u32 w, u32 h, u32 (*f)(u32, u32)) {
|
||||
volatile u32 *p = (volatile u32 *)base;
|
||||
for (u32 y = 0; y < h; y++)
|
||||
for (u32 x = 0; x < w; x++)
|
||||
p[y * w + x] = f(x, y);
|
||||
}
|
||||
|
||||
/* One u64 bitfield word of vic_config_t, written as two halves. */
|
||||
static void cfg64(u32 off, u32 lo, u32 hi) {
|
||||
REG(CFG + off) = lo;
|
||||
REG(CFG + off + 4) = hi;
|
||||
}
|
||||
|
||||
/*
|
||||
* One VIC compose of a sw x sh X8R8G8B8 surface (slot 0) into a target of
|
||||
* the same size, with bdk's vic_set_surface() field layout. kind: 0 pitch,
|
||||
* 1 block linear; gob: log2 GOBs per block.
|
||||
*/
|
||||
static void vic_compose(u32 src, u32 skind, u32 sgob, u32 dst, u32 okind,
|
||||
u32 ogob, u32 sw, u32 sh, u32 flip_x, u32 transpose) {
|
||||
for (u32 i = 0; i < 0x610; i += 4)
|
||||
REG(CFG + i) = 0;
|
||||
/* OutputConfig: FlipX b48, Transpose b50; TargetRect R b16, B b48. */
|
||||
cfg64(0x10, 0, (flip_x ? BIT(16) : 0) | (transpose ? BIT(18) : 0));
|
||||
cfg64(0x18, (sw - 1) << 16, (sh - 1) << 16);
|
||||
/* OutputSurfaceConfig: X8R8G8B8 (36), BlkKind b11, BlkHeight b15,
|
||||
* width - 1 b32, height - 1 b46. */
|
||||
cfg64(0x20, 36u | okind << 11 | ogob << 15, (sw - 1) | (sh - 1) << 14);
|
||||
/* Slot 0: enable; SourceRect in 16.16; DestRect. */
|
||||
cfg64(0x90, 1, 0);
|
||||
cfg64(0xB0, 0, (sw - 1) << 16);
|
||||
cfg64(0xB8, 0, (sh - 1) << 16);
|
||||
cfg64(0xC0, (sw - 1) << 16, (sh - 1) << 16);
|
||||
cfg64(0xD0, 36u | skind << 11 | sgob << 15, (sw - 1) | (sh - 1) << 14);
|
||||
|
||||
VICP(0x14000) = CFG >> 8; /* VIC_SC_PRAMBASE */
|
||||
VICP(0x14300) = src >> 8; /* VIC_SC_SFC0_BASE_LUMA(0) */
|
||||
VICP(0x22000) = dst >> 8; /* VIC_BL_TARGET_BASADR */
|
||||
VICP(0x10000) = 1; /* VIC_FC_COMPOSE */
|
||||
}
|
||||
|
||||
/* Program window w (0 = A .. 3 = D) and activate it. */
|
||||
static void window(u32 w, u32 opts, u32 pos, u32 width, u32 height,
|
||||
u32 stride, u32 kind, u32 addr, u32 h_off, u32 v_off,
|
||||
u32 blend_layer, u32 blend_match) {
|
||||
DCR(WINDOW_HEADER) = BIT(4 + w);
|
||||
DCR(WIN_OPTIONS) = 0;
|
||||
DCR(COLOR_DEPTH) = 0xC; /* B8G8R8A8 */
|
||||
DCR(POSITION) = pos;
|
||||
DCR(SIZE) = height << 16 | width;
|
||||
DCR(PRESCALED) = height << 16 | width * 4;
|
||||
DCR(LINE_STRIDE) = stride;
|
||||
DCR(SURFACE_KIND) = kind;
|
||||
DCR(START_ADDR) = addr;
|
||||
DCR(ADDR_H_OFFSET) = h_off;
|
||||
DCR(ADDR_V_OFFSET) = v_off;
|
||||
DCR(BLEND_LAYER) = blend_layer;
|
||||
DCR(BLEND_MATCH) = blend_match;
|
||||
DCR(WIN_OPTIONS) = opts | WIN_ENABLE;
|
||||
DCR(STATE_CONTROL) = BIT(8) | BIT(9 + w); /* GENERAL + WIN_x_UPDATE */
|
||||
DCR(STATE_CONTROL) = BIT(0) | BIT(1 + w); /* GENERAL + WIN_x_ACT_REQ */
|
||||
}
|
||||
|
||||
#define BYPASS 0x01000000u /* BLEND_LAYER_CONTROL reset: blending bypassed */
|
||||
|
||||
__attribute__((section(".text.start"), noreturn))
|
||||
void _start(void) {
|
||||
#if SCENARIO == 1
|
||||
fill(SRC_P, 720, 1280, pat);
|
||||
window(0, 0, 0, 720, 1280, 720 * 4, KIND_PITCH, SRC_P, 0, 0, BYPASS, 0);
|
||||
#elif SCENARIO == 2
|
||||
fill(SRC_L, 1280, 720, pat);
|
||||
vic_compose(SRC_L, 0, 0, DST, 0, 0, 1280, 720, 1, 1);
|
||||
window(0, 0, 0, 720, 1280, 720 * 4, KIND_PITCH, DST, 0, 0, BYPASS, 0);
|
||||
#elif SCENARIO == 3
|
||||
fill(SRC_L, 1280, 720, pat);
|
||||
vic_compose(SRC_L, 0, 0, DST, 1, 4, 1280, 720, 1, 1);
|
||||
window(0, 0, 0, 720, 1280, 720 * 4, KIND_BLOCK, DST, 0, 0, BYPASS, 0);
|
||||
#elif SCENARIO == 4
|
||||
fill(SRC_L, 1280, 720, pat);
|
||||
vic_compose(SRC_L, 0, 0, SURF_B, 1, 4, 1280, 720, 0, 0);
|
||||
window(0, SCAN_COLUMN | H_DIRECTION, 0, 720, 1280, 1280 * 4, KIND_BLOCK,
|
||||
SURF_B, 1280 * 4 - 1, 0, BYPASS, 0);
|
||||
#elif SCENARIO == 5
|
||||
fill(SRC_L, 1280, 720, pat);
|
||||
vic_compose(SRC_L, 0, 0, SURF_B, 1, 4, 1280, 720, 0, 0);
|
||||
vic_compose(SURF_B, 1, 4, DST, 0, 0, 1280, 720, 1, 1);
|
||||
window(0, 0, 0, 720, 1280, 720 * 4, KIND_PITCH, DST, 0, 0, BYPASS, 0);
|
||||
#elif SCENARIO == 6
|
||||
fill(SRC_P, 720, 1280, pat);
|
||||
fill(SRC_Q, 200, 300, patq);
|
||||
window(0, V_DIRECTION, 0, 720, 1280, 720 * 4, KIND_PITCH, SRC_P, 0, 1279,
|
||||
BYPASS, 0);
|
||||
/* K1 = 128, blending on, depth 0; SRC x K1 + DST x (1 - K1). */
|
||||
window(3, 0, 200u << 16 | 100u, 200, 300, 200 * 4, KIND_PITCH, SRC_Q,
|
||||
0, 0, 128u << 8, 0x72u);
|
||||
#endif
|
||||
puts_("display test: ready\n");
|
||||
for (;;)
|
||||
;
|
||||
}
|
||||
Executable
+59
@@ -0,0 +1,59 @@
|
||||
#!/bin/sh
|
||||
# Display regression test: run each scenario payload (tests/display/payload.c,
|
||||
# built with -DSCENARIO=n) and compare the frame the emulator shows with the
|
||||
# picture the payload drew.
|
||||
# Usage: tests/display/run.sh [rcm_emu] [payload dir]
|
||||
EMU=$(cd "$(dirname "${1:-./rcm_emu}")" && pwd)/$(basename "${1:-./rcm_emu}")
|
||||
DIR=$(cd "${2:-tests/display}" && pwd)
|
||||
HERE=$(cd "$(dirname "$0")" && pwd)
|
||||
LIMIT=${LIMIT:-60}
|
||||
|
||||
names="pitch window|VIC 270-degree turn into a pitch surface|VIC turn into a block-linear surface|DC column scan with an address offset|VIC block-linear source|V mirror with window D blended over"
|
||||
|
||||
run() {
|
||||
n=$1
|
||||
work=$(mktemp -d)
|
||||
# The frame snapshot lands in the working directory.
|
||||
(cd "$work" && SDL_VIDEODRIVER=dummy RCM_EMU_NO_AUDIO=1 \
|
||||
"$EMU" "$DIR/payload_$n.bin" > out.log 2>&1) &
|
||||
pid=$!
|
||||
t=0
|
||||
until grep -q 'display test: ready' "$work/out.log" 2>/dev/null; do
|
||||
sleep 1
|
||||
t=$((t + 1))
|
||||
[ $t -ge "$LIMIT" ] && break
|
||||
done
|
||||
# The renderer writes a snapshot about a second after the frame changes.
|
||||
sleep 3
|
||||
kill $pid 2>/dev/null
|
||||
wait $pid 2>/dev/null
|
||||
name=$(echo "$names" | cut -d'|' -f"$n")
|
||||
if [ ! -f "$work/last_fb.rgba" ]; then
|
||||
echo " FAIL $n: $name (no frame snapshot)"
|
||||
rc=1
|
||||
elif python3 "$HERE/check.py" "$n" "$work/last_fb.rgba" "$work/last_fb.meta"; then
|
||||
echo " ok $n: $name"
|
||||
rc=0
|
||||
else
|
||||
echo " FAIL $n: $name (log: $work/out.log)"
|
||||
rc=1
|
||||
fi
|
||||
[ $rc -eq 0 ] && rm -rf "$work"
|
||||
return $rc
|
||||
}
|
||||
|
||||
echo "display test:"
|
||||
fail=0
|
||||
pids=""
|
||||
for n in 1 2 3 4 5 6; do
|
||||
run "$n" > "$DIR/result_$n.txt" 2>&1 &
|
||||
pids="$pids $!"
|
||||
done
|
||||
n=0
|
||||
for p in $pids; do
|
||||
n=$((n + 1))
|
||||
wait "$p" || fail=1
|
||||
cat "$DIR/result_$n.txt"
|
||||
rm -f "$DIR/result_$n.txt"
|
||||
done
|
||||
[ $fail -eq 0 ] && echo "display test: PASS" || { echo "display test: FAIL"; exit 1; }
|
||||
Executable
+31
@@ -0,0 +1,31 @@
|
||||
#!/bin/sh
|
||||
# Build hwtest-rcm (https://github.com/Creased/hwtest-rcm) with distro
|
||||
# toolchains, CPU0 stub included. Usage: tests/hwtest/build.sh <workdir>
|
||||
# Produces <workdir>/hwtest-rcm/build/hwtest.bin.
|
||||
#
|
||||
# hwtest's Makefile only needs $(DEVKITARM)/base_rules to exist - it names
|
||||
# arm-none-eabi-gcc itself - so an empty file stands in for devkitARM, and
|
||||
# Debian/Ubuntu's gcc-aarch64-linux-gnu builds the AArch64 stub, which is
|
||||
# what hwtest's own CI does too.
|
||||
#
|
||||
# Pinned so a change on the hwtest side cannot turn this emulator's CI red
|
||||
# without a commit here; bump HWTEST_REF deliberately.
|
||||
set -e
|
||||
WORK=${1:-build-hwtest}
|
||||
HWTEST_REF=${HWTEST_REF:-3738e9a47e1833605fc5a30eeca0ea95caa3b936}
|
||||
|
||||
mkdir -p "$WORK"
|
||||
cd "$WORK"
|
||||
if [ ! -d hwtest-rcm/.git ]; then
|
||||
git init -q hwtest-rcm
|
||||
git -C hwtest-rcm remote add origin https://github.com/Creased/hwtest-rcm.git
|
||||
fi
|
||||
git -C hwtest-rcm fetch -q --depth 1 origin "$HWTEST_REF"
|
||||
git -C hwtest-rcm checkout -q FETCH_HEAD
|
||||
git -C hwtest-rcm submodule update -q --init --depth 1 third_party/hekate
|
||||
|
||||
mkdir -p devkitARM
|
||||
: > devkitARM/base_rules
|
||||
make -C hwtest-rcm -j"$(nproc)" DEVKITARM="$PWD/devkitARM" \
|
||||
A64_CC=aarch64-linux-gnu-gcc A64_OC=aarch64-linux-gnu-objcopy REQUIRE_A64=1
|
||||
ls -l hwtest-rcm/build/hwtest.bin
|
||||
Executable
+53
@@ -0,0 +1,53 @@
|
||||
#!/bin/sh
|
||||
# End-to-end: run hwtest's whole hardware sweep in the emulator, headless,
|
||||
# and check the CPU0-driven PCIe probe enumerated the Wi-Fi endpoint.
|
||||
# Usage: tests/hwtest/run.sh <rcm_emu> <hwtest.bin> [extra emulator args...]
|
||||
#
|
||||
# hwtest sits in its pager once the sweep is dumped, so the run is ended as
|
||||
# soon as the dump's last line appears (with a hard timeout behind it).
|
||||
EMU=${1:-./rcm_emu}
|
||||
BIN=${2:-build-hwtest/hwtest-rcm/build/hwtest.bin}
|
||||
# Anything after the two positional arguments goes to the emulator. (A bare
|
||||
# `shift 2` with fewer than two arguments makes dash exit on the spot.)
|
||||
[ $# -ge 2 ] && shift 2 || set --
|
||||
LOG=${LOG:-tests/hwtest/out.log}
|
||||
LIMIT=${LIMIT:-300}
|
||||
|
||||
# POWER at 3 s picks "Hardware test" on hwtest's launcher.
|
||||
SDL_VIDEODRIVER=dummy RCM_EMU_NO_AUDIO=1 "$EMU" "$BIN" --input-script "3000 P" "$@" \
|
||||
> "$LOG" 2>&1 &
|
||||
pid=$!
|
||||
t=0
|
||||
until grep -q 'end of dump' "$LOG" 2>/dev/null || ! kill -0 $pid 2>/dev/null; do
|
||||
sleep 1
|
||||
t=$((t + 1))
|
||||
if [ $t -ge "$LIMIT" ]; then
|
||||
echo "hwtest: no end of dump after ${LIMIT}s"
|
||||
break
|
||||
fi
|
||||
done
|
||||
kill $pid 2>/dev/null
|
||||
wait $pid 2>/dev/null
|
||||
echo "hwtest: sweep took ~${t}s of wall time"
|
||||
|
||||
fail=0
|
||||
expect() {
|
||||
if grep -q -- "$1" "$LOG"; then
|
||||
echo " ok $2"
|
||||
else
|
||||
echo " FAIL $2 (missing: $1)"
|
||||
fail=1
|
||||
fi
|
||||
}
|
||||
expect 'end of dump' 'the whole sweep ran to its end'
|
||||
expect '\[ccplex\] CPU0 released: AArch64 EL3' 'hwtest booted CPU0'
|
||||
expect 'CPU0 : ran to completion' 'the CPU0 stub ran to completion'
|
||||
expect 'AFI (CPU) : cfg=00103025 witness=A5A50000 -> APERTURE LIVE' 'the PCIe aperture decodes for CPU0'
|
||||
expect 'RP1 link : UP, DL active (LNKSTA=3011' 'root port 1 trained'
|
||||
expect 'EP config : 14E4:43EC' 'the CYW4356 endpoint enumerated'
|
||||
expect 'CPU0 : powergated' 'the cluster was powergated again'
|
||||
expect 'Wireless : pass' 'the Wireless verdict passed'
|
||||
expect '\[sdmmc\] SDMMC4 tuned: 128 iterations' 'the eMMC passed HS200 tuning'
|
||||
expect 'card_clock : 199.68 MHz' 'the eMMC runs at HS400 speed'
|
||||
|
||||
[ $fail -eq 0 ] && echo "hwtest: PASS" || { echo "hwtest: FAIL - see $LOG"; exit 1; }
|
||||
Executable
+55
@@ -0,0 +1,55 @@
|
||||
#!/usr/bin/env python3
|
||||
# Writes vectors.h for tests/se/payload.c: two RSA keys (e = 65537), a message
|
||||
# and its m^d mod n for each, and SHA-256 digests. Seeded, so the output is
|
||||
# the same every run; vectors.h is checked in and this only needs rerunning
|
||||
# to change the vectors.
|
||||
import hashlib, os, random
|
||||
rnd = random.Random(0x5E)
|
||||
def is_prime(n):
|
||||
if n < 2: return False
|
||||
for p in [2,3,5,7,11,13,17,19,23,29,31,37]:
|
||||
if n % p == 0: return n == p
|
||||
d, s = n-1, 0
|
||||
while d % 2 == 0: d//=2; s+=1
|
||||
for _ in range(40):
|
||||
a = rnd.randrange(2, n-2)
|
||||
x = pow(a, d, n)
|
||||
if x in (1, n-1): continue
|
||||
for _ in range(s-1):
|
||||
x = x*x % n
|
||||
if x == n-1: break
|
||||
else: return False
|
||||
return True
|
||||
def prime(bits):
|
||||
while True:
|
||||
p = rnd.getrandbits(bits) | (1 << (bits-1)) | (1 << (bits-2)) | 1
|
||||
if is_prime(p): return p
|
||||
def key(bits, e=65537):
|
||||
while True:
|
||||
p, q = prime(bits//2), prime(bits//2)
|
||||
phi = (p-1)*(q-1)
|
||||
if p != q and phi % e:
|
||||
n = p*q
|
||||
if n.bit_length() == bits:
|
||||
return n, pow(e, -1, phi)
|
||||
def arr(name, v, nbytes):
|
||||
b = v.to_bytes(nbytes, 'big')
|
||||
lines = ['static const unsigned char %s[%d] = {' % (name, nbytes)]
|
||||
for i in range(0, nbytes, 12):
|
||||
lines.append(' ' + ', '.join('0x%02X' % x for x in b[i:i+12]) + ',')
|
||||
lines.append('};')
|
||||
return '\n'.join(lines)
|
||||
out = []
|
||||
for bits, tag in ((2048, 'k2048'), (1024, 'k1024')):
|
||||
n, d = key(bits)
|
||||
m = int.from_bytes(hashlib.sha256(tag.encode()).digest() * (bits // 256), 'big') % n
|
||||
s = pow(m, d, n)
|
||||
assert pow(s, 65537, n) == m
|
||||
nb = bits // 8
|
||||
out += [arr(tag + '_mod', n, nb), arr(tag + '_exp', d, nb), arr(tag + '_msg', m, nb), arr(tag + '_sig', s, nb)]
|
||||
msg = bytes((i * 7 + 3) & 0xFF for i in range(200))
|
||||
out.append(arr('sha_msg', int.from_bytes(msg, 'big'), 200))
|
||||
out.append(arr('sha_msg_digest', int.from_bytes(hashlib.sha256(msg).digest(), 'big'), 32))
|
||||
out.append(arr('sha_abc_digest', int.from_bytes(hashlib.sha256(b'abc').digest(), 'big'), 32))
|
||||
open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'vectors.h'), 'w').write('/* Generated by gen_vectors.py: RSA keys (e = 65537) with\n * m^d mod n, and SHA-256 digests, computed with Python integers and hashlib. */\n\n' + '\n\n'.join(out) + '\n')
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
/* Loaded and entered at 0x40010000, like any RCM payload. */
|
||||
ENTRY(_start)
|
||||
SECTIONS {
|
||||
. = 0x40010000;
|
||||
.text : { KEEP(*(.text.start)) *(.text*) }
|
||||
.rodata : { *(.rodata*) }
|
||||
.data : { *(.data*) }
|
||||
.bss : { *(.bss*) *(COMMON) }
|
||||
/DISCARD/ : { *(.comment) *(.note*) *(.ARM.attributes) *(.ARM.exidx*) }
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
/*
|
||||
* Security Engine regression payload.
|
||||
*
|
||||
* A freestanding BPMP payload that drives the emulator's SE model with the
|
||||
* register sequences bdk uses, checks every result against vectors computed
|
||||
* outside the emulator (vectors.h, from gen_vectors.py), and reports on
|
||||
* UART-B. tests/se/run.sh checks the log.
|
||||
*
|
||||
* rsa se_rsa_key_set() / se_rsa_exp_mod() as Lockpick's bdk has them:
|
||||
* a 2048-bit and a 1024-bit key in the two slots, each signing with
|
||||
* its private exponent and verifying with e = 65537
|
||||
* sha SHA-256 one-shot, and in two parts (INIT, then CONTINUE)
|
||||
* aes AES-128 ECB, Lockpick's keyslot-access vector
|
||||
* rng se_rng_pseudo(): output that is not all zeros, differs from call
|
||||
* to call, and stops at the size asked for
|
||||
*/
|
||||
|
||||
typedef unsigned int u32;
|
||||
typedef unsigned char u8;
|
||||
|
||||
#define REG(a) (*(volatile u32 *)(a))
|
||||
|
||||
#define UARTB_THR 0x70006040u
|
||||
#define I2C5 0x7000D000u
|
||||
#define SE 0x70012000u
|
||||
#define SER(o) REG(SE + (o))
|
||||
|
||||
#define SE_OPERATION 0x008
|
||||
#define SE_INT_STATUS 0x010
|
||||
#define SE_CONFIG 0x014
|
||||
#define SE_IN_LL_ADDR 0x018
|
||||
#define SE_OUT_LL_ADDR 0x024
|
||||
#define SE_HASH_RESULT 0x030
|
||||
#define SE_SHA_CONFIG 0x200
|
||||
#define SE_SHA_MSG_LENGTH 0x204
|
||||
#define SE_SHA_MSG_LEFT 0x214
|
||||
#define SE_CRYPTO_CONFIG 0x304
|
||||
#define SE_LAST_BLOCK 0x318
|
||||
#define SE_KEYTABLE_ADDR 0x31C
|
||||
#define SE_KEYTABLE_DATA 0x320
|
||||
#define SE_RNG_CONFIG 0x340
|
||||
#define SE_RSA_CONFIG 0x400
|
||||
#define SE_RSA_KEY_SIZE 0x404
|
||||
#define SE_RSA_EXP_SIZE 0x408
|
||||
#define SE_RSA_KT_ADDR 0x420
|
||||
#define SE_RSA_KT_DATA 0x424
|
||||
#define SE_RSA_OUTPUT 0x428
|
||||
#define SE_ERR_STATUS 0x804
|
||||
|
||||
#define OP_DONE (1u << 4)
|
||||
#define ERR_STAT (1u << 16)
|
||||
|
||||
#define DST(x) ((x) << 2)
|
||||
#define DEC_ALG(x) ((x) << 8)
|
||||
#define ENC_ALG(x) ((x) << 12)
|
||||
#define ENC_MODE(x) ((x) << 24)
|
||||
#define DST_MEMORY 0
|
||||
#define DST_HASHREG 1
|
||||
#define DST_RSAREG 4
|
||||
#define ALG_AES 1
|
||||
#define ALG_RNG 2
|
||||
#define ALG_SHA 3
|
||||
#define ALG_RSA 4
|
||||
#define MODE_SHA256 5
|
||||
|
||||
#include "vectors.h"
|
||||
|
||||
static void puts_(const char *s) {
|
||||
while (*s)
|
||||
REG(UARTB_THR) = (u32)(unsigned char)*s++;
|
||||
}
|
||||
|
||||
static void i2c5_write(u32 dev, u32 reg, u32 val) {
|
||||
REG(I2C5 + 0x04) = dev << 1; /* CMD_ADDR0 */
|
||||
REG(I2C5 + 0x0C) = reg | (val << 8); /* CMD_DATA1 */
|
||||
REG(I2C5 + 0x00) = (1u << 1) | (1u << 9); /* CNFG: 2 bytes, write, GO */
|
||||
}
|
||||
|
||||
static int failed;
|
||||
|
||||
static void check(int ok, const char *what) {
|
||||
puts_(ok ? "se test: ok " : "se test: FAIL ");
|
||||
puts_(what);
|
||||
puts_("\n");
|
||||
if (!ok)
|
||||
failed = 1;
|
||||
}
|
||||
|
||||
static int same(const u8 *a, const u8 *b, u32 n) {
|
||||
for (u32 i = 0; i < n; i++)
|
||||
if (a[i] != b[i])
|
||||
return 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static u32 be32(const u8 *p) {
|
||||
return (u32)p[0] << 24 | (u32)p[1] << 16 | (u32)p[2] << 8 | p[3];
|
||||
}
|
||||
|
||||
static void put_be32(u8 *p, u32 v) {
|
||||
p[0] = v >> 24;
|
||||
p[1] = v >> 16;
|
||||
p[2] = v >> 8;
|
||||
p[3] = v;
|
||||
}
|
||||
|
||||
/* bdk's _se_execute_oneshot(): one linked-list entry each way. */
|
||||
static volatile u32 ll_in[3], ll_out[3];
|
||||
|
||||
static int se_exec(void *dst, u32 dst_size, const void *src, u32 src_size) {
|
||||
ll_in[0] = 0;
|
||||
ll_in[1] = (u32)src;
|
||||
ll_in[2] = src_size;
|
||||
ll_out[0] = 0;
|
||||
ll_out[1] = (u32)dst;
|
||||
ll_out[2] = dst_size;
|
||||
SER(SE_IN_LL_ADDR) = src ? (u32)ll_in : 0;
|
||||
SER(SE_OUT_LL_ADDR) = dst ? (u32)ll_out : 0;
|
||||
SER(SE_ERR_STATUS) = SER(SE_ERR_STATUS);
|
||||
SER(SE_INT_STATUS) = SER(SE_INT_STATUS);
|
||||
SER(SE_OPERATION) = 1; /* START */
|
||||
while (!(SER(SE_INT_STATUS) & OP_DONE))
|
||||
;
|
||||
return (SER(SE_INT_STATUS) & ERR_STAT) || SER(SE_ERR_STATUS);
|
||||
}
|
||||
|
||||
/* se_rsa_key_set(): the big-endian key goes in backwards, word by word. */
|
||||
static void rsa_key_set(u32 ks, const u8 *mod, u32 mod_size, const u8 *exp,
|
||||
u32 exp_size) {
|
||||
for (u32 i = 0; i < mod_size / 4; i++) {
|
||||
SER(SE_RSA_KT_ADDR) = ks << 7 | 1u << 6 | i; /* MOD */
|
||||
SER(SE_RSA_KT_DATA) = be32(mod + mod_size - 4 - 4 * i);
|
||||
}
|
||||
for (u32 i = 0; i < exp_size / 4; i++) {
|
||||
SER(SE_RSA_KT_ADDR) = ks << 7 | i; /* EXP */
|
||||
SER(SE_RSA_KT_DATA) = be32(exp + exp_size - 4 - 4 * i);
|
||||
}
|
||||
}
|
||||
|
||||
/* se_rsa_exp_mod(): the input reversed into a little-endian number, the
|
||||
* output read back from SE_RSA_OUTPUT into big-endian bytes. */
|
||||
static int rsa_exp_mod(u32 ks, u8 *dst, const u8 *src, u32 size,
|
||||
u32 exp_size) {
|
||||
static u8 buf[256];
|
||||
for (u32 i = 0; i < size; i++)
|
||||
buf[i] = src[size - 1 - i];
|
||||
SER(SE_CONFIG) = ENC_ALG(ALG_RSA) | DST(DST_RSAREG);
|
||||
SER(SE_RSA_CONFIG) = ks << 24;
|
||||
SER(SE_RSA_KEY_SIZE) = (size >> 6) - 1;
|
||||
SER(SE_RSA_EXP_SIZE) = exp_size >> 2;
|
||||
int res = se_exec(0, 0, buf, size);
|
||||
for (u32 i = 0; i < size / 4; i++)
|
||||
put_be32(dst + size - 4 - 4 * i, SER(SE_RSA_OUTPUT + 4 * i));
|
||||
return res;
|
||||
}
|
||||
|
||||
/* _se_sha_hash_256(): total 0 or equal to the part means INIT; a part
|
||||
* that is not the last says one byte more is left than it carries. */
|
||||
static int sha256(u8 *hash, u32 total, const u8 *src, u32 size) {
|
||||
u32 left = total < size ? size + 1 : size;
|
||||
SER(SE_CONFIG) = ENC_MODE(MODE_SHA256) | ENC_ALG(ALG_SHA) | DST(DST_HASHREG);
|
||||
SER(SE_SHA_MSG_LENGTH) = total << 3;
|
||||
SER(SE_SHA_MSG_LENGTH + 4) = total >> 29;
|
||||
SER(SE_SHA_MSG_LENGTH + 8) = 0;
|
||||
SER(SE_SHA_MSG_LENGTH + 12) = 0;
|
||||
SER(SE_SHA_MSG_LEFT) = left << 3;
|
||||
SER(SE_SHA_MSG_LEFT + 4) = left >> 29;
|
||||
SER(SE_SHA_MSG_LEFT + 8) = 0;
|
||||
SER(SE_SHA_MSG_LEFT + 12) = 0;
|
||||
SER(SE_SHA_CONFIG) = (total == size || !total) ? 1 : 0;
|
||||
int res = se_exec(0, 0, src, size);
|
||||
for (u32 i = 0; i < 8; i++)
|
||||
put_be32(hash + 4 * i, SER(SE_HASH_RESULT + 4 * i));
|
||||
return res;
|
||||
}
|
||||
|
||||
/* se_rng_pseudo() for a whole number of blocks. */
|
||||
static int rng(u8 *dst, u32 size) {
|
||||
SER(SE_CONFIG) = ENC_ALG(ALG_RNG) | DST(DST_MEMORY);
|
||||
SER(SE_CRYPTO_CONFIG) = 1u << 3; /* INPUT_RANDOM */
|
||||
SER(SE_RNG_CONFIG) = 1u << 2; /* SRC_ENTROPY, MODE_NORMAL */
|
||||
SER(SE_LAST_BLOCK) = (size >> 4) - 1;
|
||||
return se_exec(dst, size, 0, 0);
|
||||
}
|
||||
|
||||
static const u8 e65537[4] = {0x00, 0x01, 0x00, 0x01};
|
||||
|
||||
__attribute__((section(".text.start"), noreturn))
|
||||
void _start(void) {
|
||||
static u8 out[256], hash[32], blk[16], a[48], b[48];
|
||||
|
||||
puts_("se test: start\n");
|
||||
|
||||
/* RSA: both slots loaded before either is used. */
|
||||
rsa_key_set(0, k2048_mod, 256, k2048_exp, 256);
|
||||
rsa_key_set(1, k1024_mod, 128, k1024_exp, 128);
|
||||
check(!rsa_exp_mod(0, out, k2048_msg, 256, 256) &&
|
||||
same(out, k2048_sig, 256), "RSA-2048 m^d mod n");
|
||||
check(!rsa_exp_mod(1, out, k1024_msg, 128, 128) &&
|
||||
same(out, k1024_sig, 128), "RSA-1024 m^d mod n in slot 1");
|
||||
rsa_key_set(0, k2048_mod, 256, e65537, 4);
|
||||
check(!rsa_exp_mod(0, out, k2048_sig, 256, 4) &&
|
||||
same(out, k2048_msg, 256), "RSA-2048 s^e mod n gives m back");
|
||||
rsa_key_set(1, k1024_mod, 128, e65537, 4);
|
||||
check(!rsa_exp_mod(1, out, k1024_sig, 128, 4) &&
|
||||
same(out, k1024_msg, 128), "RSA-1024 s^e mod n gives m back");
|
||||
|
||||
/* SHA-256. */
|
||||
static const u8 abc[3] = {'a', 'b', 'c'};
|
||||
check(!sha256(hash, 3, abc, 3) && same(hash, sha_abc_digest, 32),
|
||||
"SHA-256 one-shot");
|
||||
check(!sha256(hash, 0, sha_msg, 128) &&
|
||||
!sha256(hash, 200, sha_msg + 128, 72) &&
|
||||
same(hash, sha_msg_digest, 32), "SHA-256 in two parts");
|
||||
|
||||
/* AES-128 ECB decrypt of a zero block under 00..0F. */
|
||||
static const u8 aes_exp[16] = {0x7B, 0x1D, 0x29, 0xA1, 0x6C, 0xF8,
|
||||
0xCC, 0xAB, 0x84, 0xF0, 0xB8, 0xA5,
|
||||
0x98, 0xE4, 0x2F, 0xA6};
|
||||
for (u32 i = 0; i < 4; i++) {
|
||||
SER(SE_KEYTABLE_ADDR) = 5u << 4 | i; /* slot 5, KEYS_0_3 */
|
||||
SER(SE_KEYTABLE_DATA) = (4 * i) | (4 * i + 1) << 8 |
|
||||
(4 * i + 2) << 16 | (u32)(4 * i + 3) << 24;
|
||||
}
|
||||
for (u32 i = 0; i < 16; i++)
|
||||
blk[i] = 0;
|
||||
SER(SE_CONFIG) = DEC_ALG(ALG_AES) | DST(DST_MEMORY);
|
||||
SER(SE_CRYPTO_CONFIG) = 5u << 24; /* KEY_INDEX 5, CORE_DECRYPT */
|
||||
SER(SE_LAST_BLOCK) = 0;
|
||||
check(!se_exec(blk, 16, blk, 16) && same(blk, aes_exp, 16),
|
||||
"AES-128 ECB decrypt");
|
||||
|
||||
/* RNG: 32 bytes twice, into zeroed buffers with a sentinel tail. */
|
||||
for (u32 i = 0; i < 48; i++)
|
||||
a[i] = b[i] = i < 32 ? 0 : 0x5A;
|
||||
int res = rng(a, 32) | rng(b, 32);
|
||||
int zero = 1, tail = 1;
|
||||
for (u32 i = 0; i < 32; i++)
|
||||
if (a[i])
|
||||
zero = 0;
|
||||
for (u32 i = 32; i < 48; i++)
|
||||
if (a[i] != 0x5A || b[i] != 0x5A)
|
||||
tail = 0;
|
||||
check(!res && !zero, "RNG fills the buffer");
|
||||
check(!same(a, b, 32), "RNG output changes between calls");
|
||||
check(tail, "RNG stops at the size asked for");
|
||||
|
||||
puts_(failed ? "se test: done, with failures\n" : "se test: done\n");
|
||||
i2c5_write(0x3C, 0x41, 0x02); /* MAX77620 ONOFFCNFG1: PWR_OFF */
|
||||
for (;;)
|
||||
;
|
||||
}
|
||||
Executable
+26
@@ -0,0 +1,26 @@
|
||||
#!/bin/sh
|
||||
# Security Engine regression test: run tests/se/payload.c and check what it
|
||||
# reports. Usage: tests/se/run.sh [rcm_emu] [payload]
|
||||
EMU=${1:-./rcm_emu}
|
||||
PAYLOAD=${2:-tests/se/payload.bin}
|
||||
LOG=${LOG:-tests/se/out.log}
|
||||
|
||||
SDL_VIDEODRIVER=dummy RCM_EMU_NO_AUDIO=1 timeout 60 "$EMU" "$PAYLOAD" \
|
||||
> "$LOG" 2>&1
|
||||
status=$?
|
||||
|
||||
echo "se test (emulator exit $status):"
|
||||
# The payload's lines arrive through the UART-B log, tagged [uartB].
|
||||
grep '^\[uartB\] se test: \(ok\|FAIL\) ' "$LOG" |
|
||||
sed -e 's/^.*se test: ok */ ok /' -e 's/^.*se test: FAIL */ FAIL /'
|
||||
fail=0
|
||||
grep -q 'se test: FAIL' "$LOG" && fail=1
|
||||
if ! grep -q '^\[uartB\] se test: done$' "$LOG"; then
|
||||
echo " FAIL the payload did not finish cleanly"
|
||||
fail=1
|
||||
fi
|
||||
if [ "$status" -ne 0 ]; then
|
||||
echo " FAIL the emulator exited with status $status (124 = timed out)"
|
||||
fail=1
|
||||
fi
|
||||
[ $fail -eq 0 ] && echo "se test: PASS" || { echo "se test: FAIL (log: $LOG)"; exit 1; }
|
||||
@@ -0,0 +1,190 @@
|
||||
/* Generated by gen_vectors.py: RSA keys (e = 65537) with
|
||||
* m^d mod n, and SHA-256 digests, computed with Python integers and hashlib. */
|
||||
|
||||
static const unsigned char k2048_mod[256] = {
|
||||
0xDB, 0x84, 0xB5, 0x8A, 0xA4, 0x6A, 0xC2, 0x45, 0x45, 0x22, 0x94, 0x72,
|
||||
0x4B, 0xAC, 0xC7, 0xB9, 0x34, 0x68, 0x99, 0xA8, 0x81, 0x91, 0x99, 0x8D,
|
||||
0xEF, 0x69, 0xA2, 0xFE, 0xAC, 0x99, 0xD5, 0x36, 0x8D, 0x80, 0x27, 0x17,
|
||||
0x39, 0xC2, 0x33, 0xE5, 0x12, 0x23, 0xF0, 0x81, 0x28, 0xD8, 0x30, 0x5B,
|
||||
0x20, 0x7E, 0x9B, 0xD2, 0xE1, 0xA0, 0xE4, 0xBB, 0x12, 0x9C, 0xB9, 0x44,
|
||||
0x45, 0x99, 0x02, 0xEF, 0xDE, 0x5E, 0x21, 0x9B, 0x5E, 0x3E, 0xBF, 0x91,
|
||||
0x9E, 0x07, 0xBA, 0x6D, 0xE1, 0x5E, 0xBB, 0x2D, 0x10, 0x26, 0x20, 0x97,
|
||||
0xFC, 0x7F, 0xD4, 0x51, 0xA7, 0x17, 0x94, 0xB1, 0x07, 0x56, 0xD5, 0x7E,
|
||||
0xE9, 0xBE, 0xD4, 0x8A, 0x0B, 0xA6, 0xF9, 0x2A, 0x7A, 0x78, 0xE6, 0xC0,
|
||||
0x36, 0xE7, 0x53, 0xD4, 0x77, 0x3D, 0x8A, 0x79, 0x7B, 0xAF, 0x72, 0x80,
|
||||
0x82, 0x37, 0x00, 0x7E, 0xE4, 0x40, 0xBB, 0x75, 0x85, 0xB1, 0x34, 0xC3,
|
||||
0x3B, 0xC4, 0xE7, 0xCF, 0xCA, 0x7B, 0xA3, 0x7B, 0xEF, 0x49, 0xC7, 0x52,
|
||||
0x15, 0x79, 0xDC, 0xF9, 0x6C, 0xAE, 0xFB, 0xDC, 0xA5, 0x7A, 0x5B, 0x35,
|
||||
0x4C, 0x74, 0xAD, 0x1F, 0x7A, 0xDB, 0x8A, 0x1E, 0x2B, 0xDC, 0xD4, 0x3B,
|
||||
0x65, 0x21, 0x15, 0x21, 0xB5, 0xD3, 0x20, 0x62, 0x94, 0xAC, 0x11, 0x9F,
|
||||
0x11, 0xEA, 0x8B, 0xB6, 0xE8, 0xCA, 0xD1, 0x54, 0x26, 0x16, 0xEB, 0xED,
|
||||
0xF4, 0x7A, 0xFB, 0x92, 0x5C, 0xD7, 0x72, 0xE8, 0x3B, 0xAF, 0x63, 0x58,
|
||||
0xCC, 0x8B, 0x2B, 0x8A, 0x1D, 0x78, 0x5F, 0xC2, 0xFA, 0xD9, 0xFB, 0x59,
|
||||
0x50, 0x43, 0x96, 0x1C, 0x03, 0x6C, 0x2D, 0x99, 0x8A, 0xE8, 0x92, 0xA2,
|
||||
0xE4, 0x62, 0x0A, 0x29, 0x35, 0x93, 0x02, 0x26, 0x31, 0x2D, 0x07, 0xE7,
|
||||
0x99, 0xE5, 0xDA, 0x37, 0x2B, 0xD4, 0xA4, 0x39, 0x9B, 0xC8, 0x2B, 0x8D,
|
||||
0x2A, 0x51, 0x34, 0x23,
|
||||
};
|
||||
|
||||
static const unsigned char k2048_exp[256] = {
|
||||
0xB3, 0xBD, 0x44, 0xDC, 0x41, 0x65, 0xBC, 0xAD, 0xF5, 0x3E, 0xAC, 0x27,
|
||||
0xAD, 0xB8, 0xCA, 0x4B, 0xE6, 0x12, 0xA3, 0x86, 0x2A, 0x99, 0x2A, 0x0E,
|
||||
0xE2, 0x72, 0x2F, 0x68, 0xB1, 0xB0, 0xBF, 0xB8, 0x8C, 0x41, 0xDB, 0x40,
|
||||
0x14, 0x25, 0xE4, 0x51, 0xF2, 0xF9, 0x84, 0x6A, 0x6D, 0x24, 0x1E, 0xEB,
|
||||
0xEE, 0x7E, 0x5C, 0x5E, 0x5E, 0x2A, 0x5C, 0x3E, 0xA4, 0xAD, 0xB8, 0xB0,
|
||||
0xA2, 0xFF, 0xF7, 0x3C, 0xAA, 0x69, 0x8E, 0xC0, 0xE5, 0x79, 0x21, 0x68,
|
||||
0x3C, 0xE9, 0xFD, 0x07, 0x0D, 0x5A, 0x80, 0x8E, 0x14, 0x43, 0xF3, 0xBA,
|
||||
0x1E, 0xA0, 0x18, 0x1B, 0xC7, 0x61, 0xF2, 0x78, 0xC5, 0x16, 0x9F, 0x76,
|
||||
0xEC, 0x33, 0x39, 0x59, 0xD2, 0xD2, 0xA3, 0xFF, 0xD9, 0x09, 0xF7, 0x7E,
|
||||
0x79, 0x36, 0x0E, 0x18, 0xD0, 0x8D, 0x8E, 0x3D, 0x8C, 0x3D, 0x8A, 0xD6,
|
||||
0x98, 0x48, 0x2A, 0xDA, 0xBB, 0x50, 0x19, 0x6C, 0x4B, 0x8B, 0x24, 0x84,
|
||||
0xF4, 0x28, 0x0B, 0xFA, 0x6E, 0x64, 0xC4, 0x63, 0xDC, 0x3C, 0xDF, 0x90,
|
||||
0xF4, 0x8D, 0x02, 0xEC, 0x58, 0xFB, 0x3E, 0xAE, 0x05, 0x3C, 0xFC, 0x20,
|
||||
0xB8, 0x93, 0x02, 0x8E, 0x62, 0x3B, 0x29, 0xDA, 0x3E, 0xF7, 0x8C, 0xCC,
|
||||
0x16, 0x30, 0x83, 0xF1, 0xFD, 0xA4, 0x56, 0x0C, 0xD1, 0x09, 0x77, 0x61,
|
||||
0x58, 0xC0, 0xCE, 0xE7, 0x5E, 0xA1, 0x0F, 0x66, 0x18, 0x81, 0x96, 0x06,
|
||||
0xD1, 0xCF, 0xCC, 0x5B, 0x1F, 0x9A, 0x1F, 0x25, 0x79, 0xCB, 0x66, 0x28,
|
||||
0x6A, 0xE1, 0x61, 0x60, 0x16, 0x0E, 0x73, 0x5A, 0x50, 0xDC, 0x9C, 0xE4,
|
||||
0xB3, 0x0E, 0xFD, 0x50, 0x90, 0xD3, 0x63, 0x2D, 0x9E, 0xDB, 0xEA, 0x61,
|
||||
0x90, 0x65, 0xB0, 0xE0, 0xB8, 0xFF, 0xE6, 0x9D, 0x78, 0xB3, 0x8F, 0x68,
|
||||
0x19, 0xFE, 0x45, 0x2B, 0x91, 0xD8, 0x0F, 0xB2, 0x2E, 0x90, 0x47, 0xA7,
|
||||
0x80, 0xA0, 0x73, 0xB9,
|
||||
};
|
||||
|
||||
static const unsigned char k2048_msg[256] = {
|
||||
0x7E, 0x8E, 0x33, 0x8D, 0x7B, 0xD2, 0xAE, 0x8D, 0x55, 0xB2, 0xFF, 0x7E,
|
||||
0x47, 0x6F, 0x6C, 0x3F, 0x8F, 0xAA, 0x20, 0x78, 0xEB, 0xF8, 0x6D, 0xA4,
|
||||
0x36, 0xF1, 0x6E, 0x98, 0x64, 0x00, 0xCC, 0x4A, 0x7E, 0x8E, 0x33, 0x8D,
|
||||
0x7B, 0xD2, 0xAE, 0x8D, 0x55, 0xB2, 0xFF, 0x7E, 0x47, 0x6F, 0x6C, 0x3F,
|
||||
0x8F, 0xAA, 0x20, 0x78, 0xEB, 0xF8, 0x6D, 0xA4, 0x36, 0xF1, 0x6E, 0x98,
|
||||
0x64, 0x00, 0xCC, 0x4A, 0x7E, 0x8E, 0x33, 0x8D, 0x7B, 0xD2, 0xAE, 0x8D,
|
||||
0x55, 0xB2, 0xFF, 0x7E, 0x47, 0x6F, 0x6C, 0x3F, 0x8F, 0xAA, 0x20, 0x78,
|
||||
0xEB, 0xF8, 0x6D, 0xA4, 0x36, 0xF1, 0x6E, 0x98, 0x64, 0x00, 0xCC, 0x4A,
|
||||
0x7E, 0x8E, 0x33, 0x8D, 0x7B, 0xD2, 0xAE, 0x8D, 0x55, 0xB2, 0xFF, 0x7E,
|
||||
0x47, 0x6F, 0x6C, 0x3F, 0x8F, 0xAA, 0x20, 0x78, 0xEB, 0xF8, 0x6D, 0xA4,
|
||||
0x36, 0xF1, 0x6E, 0x98, 0x64, 0x00, 0xCC, 0x4A, 0x7E, 0x8E, 0x33, 0x8D,
|
||||
0x7B, 0xD2, 0xAE, 0x8D, 0x55, 0xB2, 0xFF, 0x7E, 0x47, 0x6F, 0x6C, 0x3F,
|
||||
0x8F, 0xAA, 0x20, 0x78, 0xEB, 0xF8, 0x6D, 0xA4, 0x36, 0xF1, 0x6E, 0x98,
|
||||
0x64, 0x00, 0xCC, 0x4A, 0x7E, 0x8E, 0x33, 0x8D, 0x7B, 0xD2, 0xAE, 0x8D,
|
||||
0x55, 0xB2, 0xFF, 0x7E, 0x47, 0x6F, 0x6C, 0x3F, 0x8F, 0xAA, 0x20, 0x78,
|
||||
0xEB, 0xF8, 0x6D, 0xA4, 0x36, 0xF1, 0x6E, 0x98, 0x64, 0x00, 0xCC, 0x4A,
|
||||
0x7E, 0x8E, 0x33, 0x8D, 0x7B, 0xD2, 0xAE, 0x8D, 0x55, 0xB2, 0xFF, 0x7E,
|
||||
0x47, 0x6F, 0x6C, 0x3F, 0x8F, 0xAA, 0x20, 0x78, 0xEB, 0xF8, 0x6D, 0xA4,
|
||||
0x36, 0xF1, 0x6E, 0x98, 0x64, 0x00, 0xCC, 0x4A, 0x7E, 0x8E, 0x33, 0x8D,
|
||||
0x7B, 0xD2, 0xAE, 0x8D, 0x55, 0xB2, 0xFF, 0x7E, 0x47, 0x6F, 0x6C, 0x3F,
|
||||
0x8F, 0xAA, 0x20, 0x78, 0xEB, 0xF8, 0x6D, 0xA4, 0x36, 0xF1, 0x6E, 0x98,
|
||||
0x64, 0x00, 0xCC, 0x4A,
|
||||
};
|
||||
|
||||
static const unsigned char k2048_sig[256] = {
|
||||
0x84, 0xFE, 0x52, 0x90, 0x0E, 0x74, 0xA7, 0x53, 0xCC, 0xEB, 0x46, 0x40,
|
||||
0x2D, 0x8A, 0x38, 0xFC, 0x14, 0x52, 0xD7, 0x8E, 0xC9, 0xC8, 0x17, 0xB7,
|
||||
0xE3, 0x17, 0x8E, 0x8D, 0x4C, 0xB8, 0xB1, 0xDB, 0x2D, 0xCA, 0xD5, 0x34,
|
||||
0xDE, 0xEC, 0x4B, 0x60, 0x7A, 0x53, 0xBC, 0x96, 0x62, 0xCA, 0xA5, 0x26,
|
||||
0xB3, 0x35, 0x9C, 0x4F, 0x30, 0xB4, 0xAC, 0x6A, 0x74, 0xDB, 0x6E, 0x13,
|
||||
0x70, 0xC6, 0xE4, 0x7F, 0xB5, 0x76, 0x4A, 0x41, 0x9D, 0x2C, 0x86, 0xDA,
|
||||
0x9C, 0xE6, 0x87, 0x32, 0x62, 0x71, 0xB6, 0xE7, 0xDB, 0x79, 0xC2, 0x07,
|
||||
0xF4, 0x24, 0x33, 0xC4, 0x60, 0x3E, 0xC8, 0x10, 0x17, 0x69, 0xA0, 0x95,
|
||||
0xBE, 0x6F, 0xD8, 0x69, 0x79, 0x25, 0xB0, 0x4D, 0x20, 0x9B, 0x33, 0xF1,
|
||||
0x86, 0x56, 0x2F, 0x8D, 0x79, 0xB8, 0xB7, 0x78, 0x63, 0x84, 0xB5, 0x4E,
|
||||
0xBA, 0x6A, 0xB0, 0x4D, 0xA0, 0x7E, 0x48, 0xDF, 0xD4, 0xC0, 0x96, 0xAD,
|
||||
0x2E, 0x23, 0x06, 0x7A, 0xE5, 0xC0, 0x79, 0x57, 0xBB, 0x60, 0xF5, 0x15,
|
||||
0x02, 0xBA, 0xED, 0x65, 0x54, 0x7B, 0x9D, 0x20, 0x03, 0xEB, 0x76, 0xDF,
|
||||
0xB5, 0xE1, 0xD1, 0x3D, 0x90, 0xD3, 0x73, 0x80, 0xA6, 0x52, 0x27, 0x01,
|
||||
0x02, 0x72, 0x4D, 0xCA, 0xBA, 0x30, 0xA8, 0xEF, 0x01, 0xC8, 0xC3, 0x3E,
|
||||
0xFA, 0xC4, 0x12, 0x00, 0x2F, 0x02, 0x12, 0x0F, 0xC4, 0x11, 0x74, 0x30,
|
||||
0x30, 0x68, 0x4F, 0x16, 0x74, 0x38, 0xBE, 0x25, 0xDA, 0x44, 0xE7, 0xE4,
|
||||
0xFF, 0x92, 0x3A, 0x20, 0xC5, 0x32, 0xCB, 0x86, 0xAE, 0x10, 0x47, 0x9B,
|
||||
0x71, 0x43, 0xD8, 0x2C, 0x66, 0xE4, 0x13, 0x93, 0xF6, 0xBE, 0x60, 0x15,
|
||||
0x51, 0x02, 0x61, 0xD0, 0xAA, 0xAF, 0x13, 0xA1, 0x38, 0x50, 0xF7, 0x0E,
|
||||
0x66, 0x4C, 0x8B, 0xF7, 0x46, 0x8A, 0x76, 0xD6, 0xC1, 0x6F, 0x87, 0xC2,
|
||||
0x37, 0x5A, 0x47, 0xB9,
|
||||
};
|
||||
|
||||
static const unsigned char k1024_mod[128] = {
|
||||
0xA9, 0x97, 0xBA, 0xDB, 0x61, 0x4B, 0x0E, 0x12, 0x16, 0x22, 0xC5, 0xD9,
|
||||
0x65, 0xD3, 0x01, 0x6E, 0x08, 0xDF, 0x1B, 0x29, 0xFD, 0x01, 0x88, 0xAC,
|
||||
0xF3, 0x36, 0xE0, 0xA6, 0x21, 0xC2, 0xE5, 0xB9, 0x21, 0x33, 0xB4, 0x22,
|
||||
0x47, 0xEE, 0x31, 0x66, 0xF8, 0x57, 0x9D, 0xC7, 0x6F, 0x72, 0x7C, 0xD7,
|
||||
0x30, 0x9B, 0xE7, 0xDF, 0x2E, 0x81, 0xDF, 0xA5, 0x2D, 0x68, 0x0D, 0x5F,
|
||||
0xFC, 0x0C, 0xEF, 0xFF, 0x06, 0x27, 0x8A, 0xCF, 0xD5, 0xA2, 0x57, 0xB3,
|
||||
0xAB, 0xDE, 0xF6, 0x37, 0x0A, 0x63, 0xCF, 0xC2, 0xF5, 0x19, 0x03, 0x9D,
|
||||
0x1E, 0x3C, 0x61, 0xE0, 0x40, 0xAB, 0xAA, 0xC5, 0x39, 0x68, 0x05, 0x9F,
|
||||
0x6E, 0xE6, 0x8E, 0x0E, 0x08, 0x9F, 0x2C, 0x78, 0x11, 0xEA, 0xA6, 0x7E,
|
||||
0x16, 0xED, 0x58, 0xBF, 0x55, 0x0C, 0x6B, 0xB1, 0x4D, 0x3E, 0x64, 0x0A,
|
||||
0x49, 0x47, 0xB7, 0xE3, 0x8F, 0xCF, 0x91, 0x05,
|
||||
};
|
||||
|
||||
static const unsigned char k1024_exp[128] = {
|
||||
0x61, 0xE6, 0xE6, 0x86, 0xC8, 0x96, 0xB4, 0x6B, 0xBA, 0x7D, 0x9E, 0x6B,
|
||||
0x8E, 0xBD, 0x8D, 0xC0, 0xC0, 0xBC, 0x53, 0x09, 0x1D, 0x36, 0x6A, 0x79,
|
||||
0x34, 0xFA, 0x44, 0x1B, 0x83, 0xB7, 0xE8, 0x37, 0xC4, 0x33, 0xFD, 0xD4,
|
||||
0x20, 0x64, 0x1F, 0xFE, 0xCA, 0x74, 0x81, 0xEF, 0xE4, 0xA5, 0x59, 0xEE,
|
||||
0x3B, 0xF0, 0x74, 0x9D, 0xC1, 0x52, 0x56, 0x12, 0x1B, 0xB1, 0x4A, 0xAF,
|
||||
0x53, 0x69, 0x00, 0x8D, 0xEE, 0x06, 0x63, 0x28, 0xA0, 0x34, 0xF8, 0x70,
|
||||
0xB6, 0x78, 0x5C, 0x0C, 0x9C, 0x16, 0x7D, 0xED, 0x59, 0xA5, 0x05, 0xD4,
|
||||
0x4B, 0x82, 0x6A, 0x86, 0x09, 0x1B, 0xC3, 0x85, 0x98, 0xE9, 0x71, 0x38,
|
||||
0x5E, 0x07, 0x3A, 0xF4, 0x51, 0xE2, 0xAF, 0xB3, 0xA6, 0x9C, 0x66, 0x6D,
|
||||
0x0F, 0x5D, 0xFF, 0x61, 0xF4, 0x45, 0x3B, 0xAE, 0x59, 0xA9, 0xCA, 0xAE,
|
||||
0x87, 0x95, 0x91, 0x65, 0xB9, 0x87, 0xD5, 0x01,
|
||||
};
|
||||
|
||||
static const unsigned char k1024_msg[128] = {
|
||||
0x03, 0x64, 0xE7, 0xA2, 0x21, 0x6E, 0xB6, 0x96, 0x08, 0x46, 0xDD, 0x04,
|
||||
0xAB, 0xB9, 0xD7, 0x96, 0x2B, 0xCE, 0x7C, 0xE7, 0x11, 0xC9, 0x11, 0xD8,
|
||||
0xEB, 0x51, 0xFA, 0xA5, 0x21, 0xC3, 0xDC, 0x82, 0x03, 0x64, 0xE7, 0xA2,
|
||||
0x21, 0x6E, 0xB6, 0x96, 0x08, 0x46, 0xDD, 0x04, 0xAB, 0xB9, 0xD7, 0x96,
|
||||
0x2B, 0xCE, 0x7C, 0xE7, 0x11, 0xC9, 0x11, 0xD8, 0xEB, 0x51, 0xFA, 0xA5,
|
||||
0x21, 0xC3, 0xDC, 0x82, 0x03, 0x64, 0xE7, 0xA2, 0x21, 0x6E, 0xB6, 0x96,
|
||||
0x08, 0x46, 0xDD, 0x04, 0xAB, 0xB9, 0xD7, 0x96, 0x2B, 0xCE, 0x7C, 0xE7,
|
||||
0x11, 0xC9, 0x11, 0xD8, 0xEB, 0x51, 0xFA, 0xA5, 0x21, 0xC3, 0xDC, 0x82,
|
||||
0x03, 0x64, 0xE7, 0xA2, 0x21, 0x6E, 0xB6, 0x96, 0x08, 0x46, 0xDD, 0x04,
|
||||
0xAB, 0xB9, 0xD7, 0x96, 0x2B, 0xCE, 0x7C, 0xE7, 0x11, 0xC9, 0x11, 0xD8,
|
||||
0xEB, 0x51, 0xFA, 0xA5, 0x21, 0xC3, 0xDC, 0x82,
|
||||
};
|
||||
|
||||
static const unsigned char k1024_sig[128] = {
|
||||
0x36, 0xF0, 0x8F, 0xE4, 0xDD, 0x4A, 0x6C, 0x54, 0x6F, 0xC7, 0x87, 0xC5,
|
||||
0xD3, 0x5E, 0x08, 0x6F, 0x07, 0x65, 0xDA, 0xCD, 0xC2, 0x05, 0xE7, 0x83,
|
||||
0x6D, 0x92, 0x6A, 0xB5, 0x26, 0xBA, 0xB0, 0xED, 0xC3, 0x09, 0x11, 0x27,
|
||||
0xD0, 0x4C, 0x67, 0xF1, 0xC7, 0xF7, 0xA2, 0xA2, 0x46, 0x7E, 0xCB, 0x58,
|
||||
0x48, 0x21, 0xAB, 0x77, 0x85, 0x75, 0x17, 0xDF, 0xD6, 0xE6, 0xEC, 0x25,
|
||||
0x3D, 0x77, 0x45, 0x31, 0xAB, 0x0B, 0xD8, 0x6F, 0xF8, 0xCD, 0xD6, 0x11,
|
||||
0x7B, 0xEF, 0xA5, 0xBB, 0xFC, 0xE6, 0xCB, 0x97, 0x0F, 0x2A, 0xA4, 0x11,
|
||||
0x25, 0xDA, 0xAC, 0x16, 0x2F, 0x2A, 0x85, 0x28, 0x7C, 0x62, 0xBD, 0xAB,
|
||||
0x44, 0xC3, 0x34, 0x33, 0x0B, 0x8B, 0x0C, 0x77, 0xEB, 0xDE, 0x07, 0xF3,
|
||||
0xC3, 0xAA, 0x9C, 0xA6, 0xE3, 0x62, 0x97, 0xF1, 0xA1, 0x05, 0x3C, 0x78,
|
||||
0x37, 0x99, 0xDE, 0xB7, 0x08, 0x4F, 0x9F, 0x46,
|
||||
};
|
||||
|
||||
static const unsigned char sha_msg[200] = {
|
||||
0x03, 0x0A, 0x11, 0x18, 0x1F, 0x26, 0x2D, 0x34, 0x3B, 0x42, 0x49, 0x50,
|
||||
0x57, 0x5E, 0x65, 0x6C, 0x73, 0x7A, 0x81, 0x88, 0x8F, 0x96, 0x9D, 0xA4,
|
||||
0xAB, 0xB2, 0xB9, 0xC0, 0xC7, 0xCE, 0xD5, 0xDC, 0xE3, 0xEA, 0xF1, 0xF8,
|
||||
0xFF, 0x06, 0x0D, 0x14, 0x1B, 0x22, 0x29, 0x30, 0x37, 0x3E, 0x45, 0x4C,
|
||||
0x53, 0x5A, 0x61, 0x68, 0x6F, 0x76, 0x7D, 0x84, 0x8B, 0x92, 0x99, 0xA0,
|
||||
0xA7, 0xAE, 0xB5, 0xBC, 0xC3, 0xCA, 0xD1, 0xD8, 0xDF, 0xE6, 0xED, 0xF4,
|
||||
0xFB, 0x02, 0x09, 0x10, 0x17, 0x1E, 0x25, 0x2C, 0x33, 0x3A, 0x41, 0x48,
|
||||
0x4F, 0x56, 0x5D, 0x64, 0x6B, 0x72, 0x79, 0x80, 0x87, 0x8E, 0x95, 0x9C,
|
||||
0xA3, 0xAA, 0xB1, 0xB8, 0xBF, 0xC6, 0xCD, 0xD4, 0xDB, 0xE2, 0xE9, 0xF0,
|
||||
0xF7, 0xFE, 0x05, 0x0C, 0x13, 0x1A, 0x21, 0x28, 0x2F, 0x36, 0x3D, 0x44,
|
||||
0x4B, 0x52, 0x59, 0x60, 0x67, 0x6E, 0x75, 0x7C, 0x83, 0x8A, 0x91, 0x98,
|
||||
0x9F, 0xA6, 0xAD, 0xB4, 0xBB, 0xC2, 0xC9, 0xD0, 0xD7, 0xDE, 0xE5, 0xEC,
|
||||
0xF3, 0xFA, 0x01, 0x08, 0x0F, 0x16, 0x1D, 0x24, 0x2B, 0x32, 0x39, 0x40,
|
||||
0x47, 0x4E, 0x55, 0x5C, 0x63, 0x6A, 0x71, 0x78, 0x7F, 0x86, 0x8D, 0x94,
|
||||
0x9B, 0xA2, 0xA9, 0xB0, 0xB7, 0xBE, 0xC5, 0xCC, 0xD3, 0xDA, 0xE1, 0xE8,
|
||||
0xEF, 0xF6, 0xFD, 0x04, 0x0B, 0x12, 0x19, 0x20, 0x27, 0x2E, 0x35, 0x3C,
|
||||
0x43, 0x4A, 0x51, 0x58, 0x5F, 0x66, 0x6D, 0x74,
|
||||
};
|
||||
|
||||
static const unsigned char sha_msg_digest[32] = {
|
||||
0x2C, 0x7E, 0x18, 0xC9, 0x42, 0xEF, 0x06, 0x5B, 0x52, 0x6A, 0x2D, 0x4E,
|
||||
0x55, 0x46, 0x28, 0x37, 0x49, 0xCD, 0x3D, 0xDF, 0xB5, 0x1D, 0x8F, 0xC7,
|
||||
0x1F, 0x42, 0x71, 0x73, 0x63, 0x68, 0x5F, 0x46,
|
||||
};
|
||||
|
||||
static const unsigned char sha_abc_digest[32] = {
|
||||
0xBA, 0x78, 0x16, 0xBF, 0x8F, 0x01, 0xCF, 0xEA, 0x41, 0x41, 0x40, 0xDE,
|
||||
0x5D, 0xAE, 0x22, 0x23, 0xB0, 0x03, 0x61, 0xA3, 0x96, 0x17, 0x7A, 0x9C,
|
||||
0xB4, 0x10, 0xFF, 0x61, 0xF2, 0x00, 0x15, 0xAD,
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
/* Loaded and entered at 0x40010000, like any RCM payload. */
|
||||
ENTRY(_start)
|
||||
SECTIONS {
|
||||
. = 0x40010000;
|
||||
.text : { KEEP(*(.text.start)) *(.text*) }
|
||||
.rodata : { *(.rodata*) }
|
||||
.data : { *(.data*) }
|
||||
.bss : { *(.bss*) *(COMMON) }
|
||||
/DISCARD/ : { *(.comment) *(.note*) *(.ARM.attributes) *(.ARM.exidx*) }
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
#!/usr/bin/env python3
|
||||
"""NBD client for tests/usb/run.sh: talks to the disk the emulator's
|
||||
--usb-host nbd serves and checks what comes back.
|
||||
|
||||
Usage: nbd_check.py <port> <log> rw|ro
|
||||
|
||||
Waits for the host to say it is serving, negotiates with NBD_OPT_GO, reads
|
||||
the whole disk (tests/usb/payload.c fills it with a known pattern), checks
|
||||
that bad requests are refused, then - on a writable disk - writes two
|
||||
sectors, reads them back and flushes, or - on a write-protected one - checks
|
||||
that the write is refused. Two reads go out back to back to check that
|
||||
pipelined requests are answered in turn. Prints the CRC32 the disk should
|
||||
have once the client is done, then disconnects.
|
||||
"""
|
||||
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
import time
|
||||
import zlib
|
||||
|
||||
NBDMAGIC = 0x4E42444D41474943
|
||||
IHAVEOPT = 0x49484156454F5054
|
||||
REPLY_MAGIC = 0x0003E889045565A9
|
||||
OPT_GO, OPT_LIST = 7, 3
|
||||
REP_ACK, REP_SERVER, REP_INFO = 1, 2, 3
|
||||
CMD_READ, CMD_WRITE, CMD_DISC, CMD_FLUSH = 0, 1, 2, 3
|
||||
FLAG_READ_ONLY, FLAG_SEND_FLUSH = 1 << 1, 1 << 2
|
||||
EPERM, EINVAL = 1, 22
|
||||
|
||||
LBAS = 384
|
||||
failed = False
|
||||
|
||||
|
||||
def check(ok, what):
|
||||
global failed
|
||||
print((" ok " if ok else " FAIL ") + what)
|
||||
if not ok:
|
||||
failed = True
|
||||
|
||||
|
||||
def pattern():
|
||||
return bytes(((i * 7) ^ (i >> 9)) & 0xFF for i in range(LBAS * 512))
|
||||
|
||||
|
||||
def recv_all(s, n):
|
||||
b = b""
|
||||
while len(b) < n:
|
||||
c = s.recv(n - len(b))
|
||||
if not c:
|
||||
raise EOFError("server closed the connection")
|
||||
b += c
|
||||
return b
|
||||
|
||||
|
||||
def option(s, opt, data=b""):
|
||||
s.sendall(struct.pack(">QII", IHAVEOPT, opt, len(data)) + data)
|
||||
replies = []
|
||||
while True:
|
||||
magic, ropt, rtype, rlen = struct.unpack(">QIII", recv_all(s, 20))
|
||||
if magic != REPLY_MAGIC or ropt != opt:
|
||||
raise ValueError("bad option reply")
|
||||
replies.append((rtype, recv_all(s, rlen)))
|
||||
if rtype == REP_ACK or rtype & 0x80000000:
|
||||
return replies
|
||||
|
||||
|
||||
def request(s, cmd, handle, offset, length, data=b""):
|
||||
s.sendall(struct.pack(">IHHQQI", 0x25609513, 0, cmd, handle, offset,
|
||||
length) + data)
|
||||
|
||||
|
||||
def reply(s, want_handle, length=0):
|
||||
magic, err, handle = struct.unpack(">IIQ", recv_all(s, 16))
|
||||
if magic != 0x67446698 or handle != want_handle:
|
||||
raise ValueError("bad reply (magic %08X, handle %d)" % (magic, handle))
|
||||
return err, (recv_all(s, length) if not err and length else b"")
|
||||
|
||||
|
||||
def main():
|
||||
port, log, mode = int(sys.argv[1]), sys.argv[2], sys.argv[3]
|
||||
deadline = time.time() + 60
|
||||
while "serving the disk over NBD" not in open(log, errors="replace").read():
|
||||
if time.time() > deadline:
|
||||
check(False, "the host serves the disk over NBD")
|
||||
return 1
|
||||
time.sleep(0.1)
|
||||
|
||||
s = socket.create_connection(("127.0.0.1", port), timeout=30)
|
||||
magic, opt_magic, hflags = struct.unpack(">QQH", recv_all(s, 18))
|
||||
check(magic == NBDMAGIC and opt_magic == IHAVEOPT and hflags & 1,
|
||||
"NBD %s: fixed newstyle greeting" % mode)
|
||||
s.sendall(struct.pack(">I", 3)) # fixed newstyle, no zeroes
|
||||
|
||||
listing = option(s, OPT_LIST)
|
||||
check([r[0] for r in listing] == [REP_SERVER, REP_ACK],
|
||||
"NBD %s: NBD_OPT_LIST names one export" % mode)
|
||||
|
||||
go = option(s, OPT_GO, struct.pack(">IH", 0, 0))
|
||||
size = flags = None
|
||||
for rtype, data in go:
|
||||
if rtype == REP_INFO and struct.unpack(">H", data[:2])[0] == 0:
|
||||
size, flags = struct.unpack(">QH", data[2:12])
|
||||
check(go[-1][0] == REP_ACK and size == LBAS * 512,
|
||||
"NBD %s: NBD_OPT_GO, export of %s bytes" % (mode, size))
|
||||
check(bool(flags & FLAG_READ_ONLY) == (mode == "ro") and
|
||||
bool(flags & FLAG_SEND_FLUSH),
|
||||
"NBD %s: transmission flags %s" % (mode, flags and hex(flags)))
|
||||
|
||||
disk = bytearray(pattern())
|
||||
request(s, CMD_READ, 1, 0, len(disk))
|
||||
err, data = reply(s, 1, len(disk))
|
||||
check(err == 0 and data == disk,
|
||||
"NBD %s: reading the whole disk returns it" % mode)
|
||||
|
||||
request(s, CMD_READ, 2, 100, 512)
|
||||
check(reply(s, 2)[0] == EINVAL, "NBD %s: an unaligned read is refused" % mode)
|
||||
request(s, CMD_READ, 3, len(disk), 512)
|
||||
check(reply(s, 3)[0] == EINVAL, "NBD %s: a read past the end is refused" % mode)
|
||||
|
||||
new = bytes((i * 13 + 5) & 0xFF for i in range(1024))
|
||||
request(s, CMD_WRITE, 4, 10 * 512, len(new), new)
|
||||
err = reply(s, 4)[0]
|
||||
if mode == "rw":
|
||||
check(err == 0, "NBD rw: writing blocks 10-11")
|
||||
disk[10 * 512:12 * 512] = new
|
||||
else:
|
||||
check(err == EPERM, "NBD ro: a write is refused")
|
||||
|
||||
request(s, CMD_READ, 5, 8 * 512, 4 * 512)
|
||||
request(s, CMD_READ, 6, (LBAS - 1) * 512, 512)
|
||||
e5, d5 = reply(s, 5, 4 * 512)
|
||||
e6, d6 = reply(s, 6, 512)
|
||||
check(e5 == 0 and d5 == disk[8 * 512:12 * 512] and
|
||||
e6 == 0 and d6 == disk[(LBAS - 1) * 512:],
|
||||
"NBD %s: two pipelined reads%s" %
|
||||
(mode, ", the first seeing the write" if mode == "rw" else ""))
|
||||
|
||||
request(s, CMD_FLUSH, 7, 0, 0)
|
||||
check(reply(s, 7)[0] == 0, "NBD %s: flush" % mode)
|
||||
|
||||
request(s, CMD_DISC, 8, 0, 0)
|
||||
s.close()
|
||||
print("nbd check: disk crc32 %08X" % (zlib.crc32(disk) & 0xFFFFFFFF))
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
except (OSError, EOFError, ValueError) as e:
|
||||
print(" FAIL NBD client: %s" % e)
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,668 @@
|
||||
/*
|
||||
* USB device mode regression payload.
|
||||
*
|
||||
* A freestanding BPMP payload that brings up a small USB mass storage gadget
|
||||
* - one LUN, a 384-block RAM disk - on one of the two device controllers,
|
||||
* with the register sequences bdk's drivers use, and serves whatever the
|
||||
* emulator's --usb-host PC asks. Built once per scenario with -DSCENARIO=n:
|
||||
*
|
||||
* 1 the USB2 controller USB1 (bdk usbd.c, Erista): queue heads in the
|
||||
* controller at +0x1000, transfer descriptors in DRAM
|
||||
* 2 the XUSB device controller (bdk xusbd.c, Mariko): event ring,
|
||||
* transfer rings and endpoint contexts in IRAM
|
||||
* 3 the USB2 controller again, as a HID gadget: after the report
|
||||
* descriptor and SET_IDLE it sends three interrupt IN reports
|
||||
* 4 scenario 1 with the disk write-protected
|
||||
*
|
||||
* Either way the gadget answers the standard requests and GET_MAX_LUN, then
|
||||
* the Bulk-Only Transport: INQUIRY, TEST UNIT READY, REQUEST SENSE, READ
|
||||
* CAPACITY, MODE SENSE(6), READ(10), WRITE(10), SYNCHRONIZE CACHE, PREVENT
|
||||
* ALLOW MEDIUM REMOVAL and START STOP UNIT. When the host ejects, it stops
|
||||
* the controller and powers off. It prints the CRC32 of the disk ranges the
|
||||
* host reads, and of the whole disk after the eject, which tests/usb/run.sh
|
||||
* compares with what the host logs and what its NBD client wrote. Run without
|
||||
* --usb-host, scenario 1 sees no bus reset and says so.
|
||||
*/
|
||||
|
||||
#ifndef SCENARIO
|
||||
#define SCENARIO 1
|
||||
#endif
|
||||
|
||||
typedef unsigned int u32;
|
||||
typedef unsigned short u16;
|
||||
typedef unsigned char u8;
|
||||
|
||||
#define REG(a) (*(volatile u32 *)(a))
|
||||
#define B(a) (*(volatile u8 *)(a))
|
||||
|
||||
#define TIMERUS 0x60005010u
|
||||
#define UARTB_THR 0x70006040u
|
||||
#define I2C5 0x7000D000u
|
||||
|
||||
#define DISK 0xC0000000u /* 384 blocks of 512 bytes */
|
||||
#define DISK_LBAS 384u
|
||||
#define EP0BUF 0xC0110000u
|
||||
#define CMDBUF 0xC0111000u /* CBW / CSW / small replies */
|
||||
#define SCRATCH 0xC0120000u /* a rejected WRITE's data */
|
||||
#define READ_ONLY (SCENARIO == 4)
|
||||
|
||||
static void putc_(char c) { REG(UARTB_THR) = (u32)(unsigned char)c; }
|
||||
|
||||
static void puts_(const char *s) {
|
||||
while (*s)
|
||||
putc_(*s++);
|
||||
}
|
||||
|
||||
static void puthex(u32 v) {
|
||||
for (int i = 28; i >= 0; i -= 4)
|
||||
putc_("0123456789ABCDEF"[(v >> i) & 0xF]);
|
||||
}
|
||||
|
||||
#if SCENARIO != 3
|
||||
static void putdec(u32 v) {
|
||||
char b[10];
|
||||
int n = 0;
|
||||
do {
|
||||
b[n++] = (char)('0' + v % 10);
|
||||
v /= 10;
|
||||
} while (v);
|
||||
while (n)
|
||||
putc_(b[--n]);
|
||||
}
|
||||
#endif
|
||||
|
||||
static void i2c5_write(u32 dev, u32 reg, u32 val) {
|
||||
REG(I2C5 + 0x04) = dev << 1;
|
||||
REG(I2C5 + 0x0C) = reg | (val << 8);
|
||||
REG(I2C5 + 0x00) = (1u << 1) | (1u << 9);
|
||||
}
|
||||
|
||||
static __attribute__((noreturn)) void finish(const char *msg) {
|
||||
puts_(msg);
|
||||
i2c5_write(0x3C, 0x41, 0x02); /* MAX77620 ONOFFCNFG1: PWR_OFF */
|
||||
for (;;)
|
||||
;
|
||||
}
|
||||
|
||||
static void copy(u32 dst, const u8 *src, u32 n) {
|
||||
for (u32 i = 0; i < n; i++)
|
||||
B(dst + i) = src[i];
|
||||
}
|
||||
|
||||
#if SCENARIO != 3
|
||||
static void zero(u32 dst, u32 n) {
|
||||
for (u32 i = 0; i < n; i += 4)
|
||||
REG(dst + i) = 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
static u32 crc32(u32 addr, u32 n) {
|
||||
u32 c = 0xFFFFFFFFu;
|
||||
for (u32 i = 0; i < n; i++) {
|
||||
c ^= B(addr + i);
|
||||
for (int k = 0; k < 8; k++)
|
||||
c = (c >> 1) ^ (0xEDB88320u & (0u - (c & 1)));
|
||||
}
|
||||
return ~c;
|
||||
}
|
||||
|
||||
/* ---- Descriptors --------------------------------------------------------- */
|
||||
|
||||
static const u8 dev_desc[18] = {
|
||||
18, 1, 0x00, 0x02, 0, 0, 0, 64,
|
||||
0x09, 0x12, 0x57, 0x7E, /* 1209:7E57 */
|
||||
0x00, 0x01, 1, 2, 3, 1,
|
||||
};
|
||||
|
||||
#if SCENARIO == 3
|
||||
static const u8 hid_report[21] = {
|
||||
0x06, 0x00, 0xFF, 0x09, 0x01, 0xA1, 0x01, /* vendor page, application */
|
||||
0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x08,
|
||||
0x09, 0x01, 0x81, 0x02, 0xC0, /* 8 bytes of input */
|
||||
};
|
||||
|
||||
static const u8 cfg_desc[34] = {
|
||||
9, 2, 34, 0, 1, 1, 0, 0x80, 50,
|
||||
9, 4, 0, 0, 1, 0x03, 0x00, 0x00, 0, /* HID */
|
||||
9, 0x21, 0x11, 0x01, 0, 1, 0x22, 21, 0, /* HID descriptor */
|
||||
7, 5, 0x81, 3, 8, 0, 4, /* interrupt IN, 8 bytes */
|
||||
};
|
||||
#else
|
||||
static const u8 cfg_desc[32] = {
|
||||
9, 2, 32, 0, 1, 1, 0, 0x80, 50,
|
||||
9, 4, 0, 0, 2, 0x08, 0x06, 0x50, 0, /* mass storage, SCSI, BOT */
|
||||
7, 5, 0x81, 2, 0x00, 0x02, 0, /* bulk IN, 512 */
|
||||
7, 5, 0x01, 2, 0x00, 0x02, 0, /* bulk OUT, 512 */
|
||||
};
|
||||
#endif
|
||||
|
||||
static const u8 str_lang[4] = {4, 3, 0x09, 0x04};
|
||||
static const char *const strs[3] = {"RCM-Emulator", "USB test disk", "0001"};
|
||||
|
||||
#if SCENARIO != 3
|
||||
static const u8 inquiry[36] = {
|
||||
0x00, 0x80, 0x02, 0x02, 31, 0, 0, 0,
|
||||
'R', 'C', 'M', 'E', 'M', 'U', ' ', ' ',
|
||||
'T', 'e', 's', 't', ' ', 'd', 'i', 's', 'k', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
|
||||
'1', '.', '0', '0',
|
||||
};
|
||||
#endif
|
||||
|
||||
/* ---- Transport ------------------------------------------------------------ */
|
||||
/*
|
||||
* What the gadget needs from a controller:
|
||||
* poll_setup(pkt) a SETUP packet, if one came (1) or not (0)
|
||||
* ep0_in(len) send EP0BUF[0..len), then the status stage
|
||||
* ep0_status() a no-data request's status stage
|
||||
* ep0_stall() reject the request
|
||||
* set_address(a) after its status stage
|
||||
* configure() bring up the bulk endpoints
|
||||
* bulk(in, buf, len) one bulk transfer; returns bytes moved
|
||||
* stop() detach
|
||||
*/
|
||||
|
||||
#if SCENARIO != 2
|
||||
/* ---- USB2 controller USB1 (bdk usbd.c) ---- */
|
||||
|
||||
#define USB 0x7D000000u
|
||||
#define U(o) REG(USB + (o))
|
||||
#define USBCMD 0x130
|
||||
#define USBSTS 0x134
|
||||
#define DEVADDR 0x144
|
||||
#define EPLIST 0x148
|
||||
#define USBMODE 0x1F8
|
||||
#define SETUPST 0x208
|
||||
#define PRIME 0x20C
|
||||
#define FLUSH 0x210
|
||||
#define STATUS 0x214
|
||||
#define COMPL 0x218
|
||||
#define EPCTRL(n) (0x21C + 4 * (n))
|
||||
#define SUSP 0x400
|
||||
#define QHB (USB + 0x1000)
|
||||
#define QH(i) (QHB + 64 * (i))
|
||||
#define DTD 0xC0100000u /* 4 dTDs per queue head, 32 bytes each */
|
||||
|
||||
static void init(void) {
|
||||
U(SUSP) |= (1u << 12) | (1u << 11); /* UTMIP_PHY_ENB, UTMIP_RESET */
|
||||
U(SUSP) &= ~(1u << 11);
|
||||
while (!(U(SUSP) & (1u << 7))) /* PHY_CLK_VALID */
|
||||
;
|
||||
U(USBCMD) |= 1u << 1; /* RESET */
|
||||
while (U(USBCMD) & (1u << 1))
|
||||
;
|
||||
U(USBMODE) = 2; /* device */
|
||||
for (u32 i = 0; i < 4; i++) {
|
||||
for (u32 w = 0; w < 16; w++)
|
||||
REG(QH(i) + 4 * w) = 0;
|
||||
REG(QH(i) + 8) = 1; /* no dTD */
|
||||
}
|
||||
REG(QH(0)) = 64u << 16 | 1u << 15; /* EP0 OUT: 64, IOS */
|
||||
REG(QH(1)) = 64u << 16;
|
||||
U(EPLIST) = QHB;
|
||||
U(USBCMD) |= 1; /* RUN: attach */
|
||||
}
|
||||
|
||||
/* One transfer on queue head idx (2 * ep + in), in up to four 16 KiB dTDs as
|
||||
* bdk builds them. Returns the bytes moved, or -1 if it never completed. */
|
||||
static int xfer(u32 idx, u32 buf, u32 len) {
|
||||
u32 base = DTD + idx * 4 * 32, off = 0, n = 0;
|
||||
do {
|
||||
u32 d = base + n * 32, sz = len - off > 16384 ? 16384 : len - off;
|
||||
REG(d) = 1;
|
||||
REG(d + 4) = sz << 16 | 0x80; /* bytes, ACTIVE */
|
||||
for (u32 p = 0; p < 5; p++)
|
||||
REG(d + 8 + 4 * p) = buf ? buf + off + 4096 * p : 0;
|
||||
if (n)
|
||||
REG(base + (n - 1) * 32) = d;
|
||||
off += sz;
|
||||
n++;
|
||||
} while (off < len && n < 4);
|
||||
REG(QH(idx) + 8) = base;
|
||||
REG(QH(idx) + 0xC) = 0;
|
||||
u32 bit = idx & 1 ? 1u << (16 + idx / 2) : 1u << (idx / 2);
|
||||
U(PRIME) = bit;
|
||||
u32 start = REG(TIMERUS);
|
||||
while ((U(PRIME) | U(STATUS)) & bit)
|
||||
if (REG(TIMERUS) - start > 5000000)
|
||||
return -1;
|
||||
U(COMPL) = bit;
|
||||
u32 left = 0;
|
||||
for (u32 i = 0; i < n; i++)
|
||||
left += (REG(base + i * 32 + 4) >> 16) & 0x7FFF;
|
||||
return (int)(len - left);
|
||||
}
|
||||
|
||||
static int poll_setup(u8 *pkt) {
|
||||
u32 sts = U(USBSTS);
|
||||
U(USBSTS) = sts;
|
||||
if (sts & (1u << 6)) { /* bus reset */
|
||||
U(DEVADDR) = 0;
|
||||
U(SETUPST) = U(SETUPST);
|
||||
U(COMPL) = U(COMPL);
|
||||
U(FLUSH) = 0xFFFFFFFFu;
|
||||
}
|
||||
if (!(U(SETUPST) & 1))
|
||||
return 0;
|
||||
U(SETUPST) = 1;
|
||||
u32 lo = REG(QH(0) + 0x28), hi = REG(QH(0) + 0x2C);
|
||||
for (int i = 0; i < 4; i++) {
|
||||
pkt[i] = lo >> (8 * i);
|
||||
pkt[4 + i] = hi >> (8 * i);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void ep0_in(u32 len) {
|
||||
xfer(1, EP0BUF, len);
|
||||
xfer(0, 0, 0);
|
||||
}
|
||||
|
||||
static void ep0_status(void) { xfer(1, 0, 0); }
|
||||
|
||||
static void ep0_stall(void) { U(EPCTRL(0)) |= 1u | 1u << 16; }
|
||||
|
||||
static void set_address(u32 a) { U(DEVADDR) = a << 25; }
|
||||
|
||||
static void configure(void) {
|
||||
for (u32 i = 2; i < 4; i++) {
|
||||
for (u32 w = 0; w < 16; w++)
|
||||
REG(QH(i) + 4 * w) = 0;
|
||||
REG(QH(i)) = 512u << 16 | 1u << 29; /* 512, no ZLP, as bdk */
|
||||
REG(QH(i) + 8) = 1;
|
||||
}
|
||||
U(EPCTRL(1)) = 2u << 2 | 1u << 7 | 2u << 18 | 1u << 23; /* bulk RX/TX on */
|
||||
}
|
||||
|
||||
static int bulk(int in, u32 buf, u32 len) { return xfer(in ? 3 : 2, buf, len); }
|
||||
|
||||
static void stop(void) {
|
||||
U(USBCMD) &= ~1u;
|
||||
(void)U(USBCMD); /* let the host see it go */
|
||||
}
|
||||
|
||||
/* Without a host nothing resets the bus: say so after half a second. */
|
||||
static int bus_reset_seen(void) {
|
||||
u32 start = REG(TIMERUS);
|
||||
while (REG(TIMERUS) - start < 500000)
|
||||
if (U(USBSTS) & (1u << 6))
|
||||
return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
#else
|
||||
/* ---- XUSB device controller (bdk xusbd.c) ---- */
|
||||
|
||||
#define XU 0x700D0000u
|
||||
#define X(o) REG(XU + (o))
|
||||
#define X_DB 0x04
|
||||
#define X_ERSTSZ 0x08
|
||||
#define X_ERST0 0x10
|
||||
#define X_ERST1 0x18
|
||||
#define X_ERDP 0x20
|
||||
#define X_EREP 0x28
|
||||
#define X_CTRL 0x30
|
||||
#define X_ST 0x34
|
||||
#define X_IMOD 0x38
|
||||
#define X_PORTSC 0x3C
|
||||
#define X_ECP 0x40
|
||||
#define X_HALT 0x50
|
||||
#define X_RELOAD 0x58
|
||||
|
||||
#define XMEM 0x40030000u
|
||||
#define SEG0 (XMEM)
|
||||
#define SEG1 (XMEM + 0x100)
|
||||
#define CTX (XMEM + 0x500) /* four 64-byte endpoint contexts */
|
||||
|
||||
struct ring { u32 base, idx, pcs; };
|
||||
static struct ring rings[4]; /* by context index: 0 control, 2 OUT, 3 IN */
|
||||
static u32 evt_deq, ccs, seq;
|
||||
|
||||
static void ring_init(u32 dci, u32 base) {
|
||||
struct ring *r = &rings[dci];
|
||||
r->base = base;
|
||||
r->idx = 0;
|
||||
r->pcs = 1;
|
||||
zero(base, 16 * 16);
|
||||
REG(base + 15 * 16) = base; /* Link TRB back to the start */
|
||||
REG(base + 15 * 16 + 12) = 6u << 10 | 2; /* type LINK, toggle cycle */
|
||||
u32 ctx = CTX + 64 * dci;
|
||||
zero(ctx, 64);
|
||||
REG(ctx) = 1; /* EP_RUNNING */
|
||||
REG(ctx + 4) = (dci ? 512u : 64u) << 16; /* max packet size */
|
||||
REG(ctx + 8) = base | 1; /* dequeue pointer, DCS */
|
||||
}
|
||||
|
||||
static void queue(u32 dci, u32 w0, u32 w2, u32 w3) {
|
||||
struct ring *r = &rings[dci];
|
||||
u32 t = r->base + r->idx * 16;
|
||||
REG(t) = w0;
|
||||
REG(t + 4) = 0;
|
||||
REG(t + 8) = w2;
|
||||
REG(t + 12) = w3 | r->pcs;
|
||||
if (++r->idx == 15) {
|
||||
REG(r->base + 15 * 16 + 12) = 6u << 10 | 2 | r->pcs;
|
||||
r->idx = 0;
|
||||
r->pcs ^= 1;
|
||||
}
|
||||
X(X_DB) = dci << 8 | (dci ? 0 : seq << 16);
|
||||
}
|
||||
|
||||
static void init(void) {
|
||||
zero(XMEM, 0x600);
|
||||
X(X_ERST0) = SEG0;
|
||||
X(X_ERST1) = SEG1;
|
||||
X(X_ERSTSZ) = 16u << 16 | 16;
|
||||
X(X_EREP) = SEG0 | 1;
|
||||
X(X_ERDP) = SEG0;
|
||||
evt_deq = SEG0;
|
||||
ccs = 1;
|
||||
ring_init(0, XMEM + 0x200);
|
||||
X(X_CTRL) |= 1u << 4 | 1u << 1; /* IE, LSE */
|
||||
X(X_ECP) = CTX;
|
||||
X(X_IMOD) = 0;
|
||||
X(X_PORTSC) = (X(X_PORTSC) & ~(0xFu << 5)) | 1u << 16 | 5u << 5; /* RxDetect */
|
||||
X(X_CTRL) |= 1u << 31; /* ENABLE */
|
||||
}
|
||||
|
||||
/* The next event, if any. Polling ST lets the host run. */
|
||||
static int next_event(u32 *ev) {
|
||||
(void)X(X_ST);
|
||||
if ((REG(evt_deq + 12) & 1) != ccs)
|
||||
return 0;
|
||||
for (int i = 0; i < 4; i++)
|
||||
ev[i] = REG(evt_deq + 4 * i);
|
||||
if (evt_deq == SEG0 + 15 * 16)
|
||||
evt_deq = SEG1;
|
||||
else if (evt_deq == SEG1 + 15 * 16) {
|
||||
evt_deq = SEG0;
|
||||
ccs ^= 1;
|
||||
} else
|
||||
evt_deq += 16;
|
||||
X(X_ERDP) = evt_deq;
|
||||
X(X_ST) = 1u << 4; /* IP, write 1 to clear */
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void port_change(void) {
|
||||
u32 ps = X(X_PORTSC);
|
||||
X(X_PORTSC) = ps; /* write the change bits back */
|
||||
}
|
||||
|
||||
/* Wait for the Transfer event of endpoint dci; the bytes it left over. */
|
||||
static int wait_xfer(u32 dci) {
|
||||
u32 ev[4], start = REG(TIMERUS);
|
||||
for (;;) {
|
||||
if (REG(TIMERUS) - start > 5000000)
|
||||
return -1;
|
||||
if (!next_event(ev))
|
||||
continue;
|
||||
u32 type = ev[3] >> 10 & 0x3F;
|
||||
if (type == 34)
|
||||
port_change();
|
||||
else if (type == 32 && (ev[3] >> 16 & 0x1F) == dci)
|
||||
return (int)(ev[2] & 0xFFFFFF);
|
||||
}
|
||||
}
|
||||
|
||||
static int poll_setup(u8 *pkt) {
|
||||
u32 ev[4];
|
||||
if (!next_event(ev))
|
||||
return 0;
|
||||
u32 type = ev[3] >> 10 & 0x3F;
|
||||
if (type == 34) {
|
||||
port_change();
|
||||
return 0;
|
||||
}
|
||||
if (type != 63)
|
||||
return 0;
|
||||
for (int i = 0; i < 4; i++) {
|
||||
pkt[i] = ev[0] >> (8 * i);
|
||||
pkt[4 + i] = ev[1] >> (8 * i);
|
||||
}
|
||||
seq = ev[2] & 0xFFFF;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void ep0_in(u32 len) {
|
||||
queue(0, EP0BUF, len, 3u << 10 | 1u << 16 | 1u << 5); /* Data IN, IOC */
|
||||
wait_xfer(0);
|
||||
queue(0, 0, 0, 4u << 10 | 1u << 5); /* Status OUT */
|
||||
wait_xfer(0);
|
||||
}
|
||||
|
||||
static void ep0_status(void) {
|
||||
queue(0, 0, 0, 4u << 10 | 1u << 16 | 1u << 5); /* Status IN */
|
||||
wait_xfer(0);
|
||||
}
|
||||
|
||||
static void ep0_stall(void) { X(X_HALT) |= 1; }
|
||||
|
||||
static void set_address(u32 a) { X(X_CTRL) = (X(X_CTRL) & 0x80FFFFFFu) | a << 24; }
|
||||
|
||||
static void configure(void) {
|
||||
ring_init(2, XMEM + 0x300);
|
||||
ring_init(3, XMEM + 0x400);
|
||||
X(X_RELOAD) = 0xC;
|
||||
while (X(X_RELOAD) & 0xC)
|
||||
;
|
||||
X(X_HALT) &= ~0xCu;
|
||||
X(X_CTRL) |= 1; /* RUN */
|
||||
}
|
||||
|
||||
static int bulk(int in, u32 buf, u32 len) {
|
||||
u32 dci = in ? 3 : 2;
|
||||
queue(dci, buf, len, 1u << 10 | 1u << 5 | 1u << 2); /* Normal, IOC, ISP */
|
||||
int left = wait_xfer(dci);
|
||||
return left < 0 ? -1 : (int)(len - left);
|
||||
}
|
||||
|
||||
static void stop(void) {
|
||||
X(X_CTRL) = 0;
|
||||
(void)X(X_CTRL);
|
||||
}
|
||||
|
||||
static int bus_reset_seen(void) { return 1; }
|
||||
|
||||
#endif
|
||||
|
||||
/* ---- The gadget ----------------------------------------------------------- */
|
||||
|
||||
static int configured, lun_asked, report_asked, idle_set;
|
||||
|
||||
static void control(const u8 *p) {
|
||||
u32 bm = p[0], req = p[1], val = p[2] | p[3] << 8, len = p[6] | p[7] << 8;
|
||||
u32 n = 0;
|
||||
if (bm == 0x80 && req == 6) { /* GET_DESCRIPTOR */
|
||||
u32 type = val >> 8, idx = val & 0xFF;
|
||||
if (type == 1) {
|
||||
copy(EP0BUF, dev_desc, n = 18);
|
||||
} else if (type == 2) {
|
||||
copy(EP0BUF, cfg_desc, n = sizeof(cfg_desc));
|
||||
} else if (type == 3 && idx == 0) {
|
||||
copy(EP0BUF, str_lang, n = 4);
|
||||
} else if (type == 3 && idx <= 3) {
|
||||
const char *s = strs[idx - 1];
|
||||
n = 2;
|
||||
while (*s) {
|
||||
B(EP0BUF + n) = *s++;
|
||||
B(EP0BUF + n + 1) = 0;
|
||||
n += 2;
|
||||
}
|
||||
B(EP0BUF) = n;
|
||||
B(EP0BUF + 1) = 3;
|
||||
} else {
|
||||
ep0_stall();
|
||||
return;
|
||||
}
|
||||
ep0_in(n < len ? n : len);
|
||||
} else if (bm == 0x00 && req == 5) { /* SET_ADDRESS */
|
||||
ep0_status();
|
||||
set_address(val & 0x7F);
|
||||
} else if (bm == 0x00 && req == 9) { /* SET_CONFIGURATION */
|
||||
configure();
|
||||
ep0_status();
|
||||
configured = 1;
|
||||
puts_("usb test: configured\n");
|
||||
} else if (bm == 0xA1 && req == 0xFE) { /* GET_MAX_LUN */
|
||||
B(EP0BUF) = 0;
|
||||
ep0_in(1);
|
||||
lun_asked = 1;
|
||||
#if SCENARIO == 3
|
||||
} else if (bm == 0x81 && req == 6 && (val >> 8) == 0x22) { /* HID report */
|
||||
copy(EP0BUF, hid_report, n = sizeof(hid_report));
|
||||
ep0_in(n < len ? n : len);
|
||||
report_asked = 1;
|
||||
} else if (bm == 0x21 && req == 0x0A) { /* SET_IDLE */
|
||||
ep0_status();
|
||||
idle_set = 1;
|
||||
#endif
|
||||
} else {
|
||||
ep0_stall();
|
||||
}
|
||||
}
|
||||
|
||||
#if SCENARIO != 3
|
||||
static void put_be32(u32 a, u32 v) {
|
||||
B(a) = v >> 24;
|
||||
B(a + 1) = v >> 16;
|
||||
B(a + 2) = v >> 8;
|
||||
B(a + 3) = v;
|
||||
}
|
||||
|
||||
/* Serve Bulk-Only Transport commands until the host ejects the disk. */
|
||||
static void bot(void) {
|
||||
u32 sense = 6, asc = 0x29; /* a unit attention first, like a real disk */
|
||||
for (;;) {
|
||||
int n = bulk(0, CMDBUF, 512);
|
||||
if (n != 31 || REG(CMDBUF) != 0x43425355u) /* "USBC" */
|
||||
finish("usb test: FAIL bad CBW\n");
|
||||
u32 tag = REG(CMDBUF + 4), want = REG(CMDBUF + 8);
|
||||
u8 op = B(CMDBUF + 15);
|
||||
u32 cdb = CMDBUF + 15, status = 0, sent = 0, eject = 0;
|
||||
switch (op) {
|
||||
case 0x12: /* INQUIRY */
|
||||
copy(CMDBUF + 0x100, inquiry, 36);
|
||||
sent = bulk(1, CMDBUF + 0x100, want < 36 ? want : 36);
|
||||
break;
|
||||
case 0x00: /* TEST UNIT READY */
|
||||
status = sense ? 1 : 0;
|
||||
break;
|
||||
case 0x03: /* REQUEST SENSE */
|
||||
zero(CMDBUF + 0x100, 20);
|
||||
B(CMDBUF + 0x100) = 0x70;
|
||||
B(CMDBUF + 0x102) = sense;
|
||||
B(CMDBUF + 0x107) = 10;
|
||||
B(CMDBUF + 0x10C) = asc;
|
||||
sense = asc = 0;
|
||||
sent = bulk(1, CMDBUF + 0x100, want < 18 ? want : 18);
|
||||
break;
|
||||
case 0x25: /* READ CAPACITY(10) */
|
||||
put_be32(CMDBUF + 0x100, DISK_LBAS - 1);
|
||||
put_be32(CMDBUF + 0x104, 512);
|
||||
sent = bulk(1, CMDBUF + 0x100, 8);
|
||||
break;
|
||||
case 0x1A: /* MODE SENSE(6) */
|
||||
zero(CMDBUF + 0x100, 4); /* the header, no pages */
|
||||
B(CMDBUF + 0x100) = 3;
|
||||
B(CMDBUF + 0x102) = READ_ONLY ? 0x80 : 0; /* WP */
|
||||
sent = bulk(1, CMDBUF + 0x100, want < 4 ? want : 4);
|
||||
break;
|
||||
case 0x28: /* READ(10) */
|
||||
case 0x2A: { /* WRITE(10) */
|
||||
u32 lba = (u32)B(cdb + 2) << 24 | B(cdb + 3) << 16 | B(cdb + 4) << 8 |
|
||||
B(cdb + 5);
|
||||
u32 cnt = B(cdb + 7) << 8 | B(cdb + 8);
|
||||
int bad = lba + cnt > DISK_LBAS || cnt * 512 != want;
|
||||
if (op == 0x28) {
|
||||
/* In 32 KiB transfers, as bdk sends a read: the host has to
|
||||
* go on to the next one after a full-sized packet. */
|
||||
if (bad)
|
||||
status = 1;
|
||||
for (u32 off = 0; !bad && off < want; off += 32768) {
|
||||
u32 n = want - off > 32768 ? 32768 : want - off;
|
||||
if (bulk(1, DISK + lba * 512 + off, n) != (int)n)
|
||||
break;
|
||||
sent += n;
|
||||
}
|
||||
break;
|
||||
}
|
||||
/* The host sends the data whatever happens to it. */
|
||||
if (bad || READ_ONLY) {
|
||||
sent = bulk(0, SCRATCH, want);
|
||||
status = 1;
|
||||
break;
|
||||
}
|
||||
sent = bulk(0, DISK + lba * 512, want);
|
||||
status = sent != want;
|
||||
puts_("usb test: WRITE(10) blocks ");
|
||||
putdec(lba);
|
||||
putc_('-');
|
||||
putdec(lba + cnt - 1);
|
||||
putc_('\n');
|
||||
break;
|
||||
}
|
||||
case 0x35: /* SYNCHRONIZE CACHE(10) */
|
||||
puts_("usb test: SYNCHRONIZE CACHE\n");
|
||||
break;
|
||||
case 0x1E: /* PREVENT ALLOW MEDIUM REMOVAL */
|
||||
break;
|
||||
case 0x1B: /* START STOP UNIT */
|
||||
eject = B(cdb + 4) & 2;
|
||||
break;
|
||||
default:
|
||||
status = 1;
|
||||
break;
|
||||
}
|
||||
REG(CMDBUF + 0x200) = 0x53425355u; /* "USBS" */
|
||||
REG(CMDBUF + 0x204) = tag;
|
||||
REG(CMDBUF + 0x208) = want - sent;
|
||||
B(CMDBUF + 0x20C) = status;
|
||||
bulk(1, CMDBUF + 0x200, 13);
|
||||
if (eject)
|
||||
return;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
__attribute__((section(".text.start"), noreturn))
|
||||
void _start(void) {
|
||||
for (u32 i = 0; i < DISK_LBAS * 512; i++)
|
||||
B(DISK + i) = (u8)((i * 7) ^ (i >> 9));
|
||||
puts_("usb test: disk crc32 first ");
|
||||
puthex(crc32(DISK, 64 * 512));
|
||||
puts_(" last ");
|
||||
puthex(crc32(DISK + (DISK_LBAS - 8) * 512, 8 * 512));
|
||||
puts_(" all ");
|
||||
puthex(crc32(DISK, DISK_LBAS * 512));
|
||||
putc_('\n');
|
||||
|
||||
init();
|
||||
if (!bus_reset_seen()) {
|
||||
stop();
|
||||
finish("usb test: no bus reset, nothing on the cable\n");
|
||||
}
|
||||
u8 pkt[8];
|
||||
u32 start = REG(TIMERUS);
|
||||
while (!(configured && (SCENARIO == 3 ? report_asked && idle_set : lun_asked))) {
|
||||
if (poll_setup(pkt))
|
||||
control(pkt);
|
||||
if (REG(TIMERUS) - start > 10000000)
|
||||
finish("usb test: FAIL enumeration timed out\n");
|
||||
}
|
||||
#if SCENARIO == 3
|
||||
for (u32 k = 1; k <= 3; k++) {
|
||||
for (u32 i = 0; i < 8; i++)
|
||||
B(CMDBUF + i) = (u8)(k * 0x10 + i);
|
||||
if (bulk(1, CMDBUF, 8) != 8)
|
||||
finish("usb test: FAIL report not taken\n");
|
||||
}
|
||||
puts_("usb test: hid reports sent\n");
|
||||
#else
|
||||
bot();
|
||||
puts_("usb test: ejected; disk crc32 ");
|
||||
puthex(crc32(DISK, DISK_LBAS * 512));
|
||||
putc_('\n');
|
||||
#endif
|
||||
stop();
|
||||
finish("usb test: done\n");
|
||||
}
|
||||
Executable
+150
@@ -0,0 +1,150 @@
|
||||
#!/bin/sh
|
||||
# USB device mode regression test: tests/usb/payload.c brings up a mass
|
||||
# storage gadget on each device controller and the emulator's --usb-host PC
|
||||
# enumerates it, reads it back, writes its last sectors back unchanged and
|
||||
# ejects it; on a write-protected disk it leaves the write out. With
|
||||
# --usb-host nbd the disk is served over NBD instead, and nbd_check.py reads
|
||||
# and writes it. Without a host the gadget must see nothing on the cable.
|
||||
# Usage: tests/usb/run.sh [rcm_emu] [payload dir]
|
||||
EMU=${1:-./rcm_emu}
|
||||
DIR=${2:-tests/usb}
|
||||
fail=0
|
||||
|
||||
run() {
|
||||
log=$DIR/out_$1.log
|
||||
shift
|
||||
SDL_VIDEODRIVER=dummy RCM_EMU_NO_AUDIO=1 timeout 60 "$EMU" "$@" > "$log" 2>&1
|
||||
echo $?
|
||||
}
|
||||
|
||||
expect() {
|
||||
if grep -q -- "$2" "$1"; then
|
||||
echo " ok $3"
|
||||
else
|
||||
echo " FAIL $3 (missing: $2)"
|
||||
fail=1
|
||||
fi
|
||||
}
|
||||
|
||||
expect_not() {
|
||||
if grep -q -- "$2" "$1"; then
|
||||
echo " FAIL $3 (found: $2)"
|
||||
fail=1
|
||||
else
|
||||
echo " ok $3"
|
||||
fi
|
||||
}
|
||||
|
||||
crc() { sed -n "s/.*disk crc32 first [0-9A-F]* last [0-9A-F]* all \([0-9A-F]*\).*/\1/p" "$1"; }
|
||||
|
||||
# Enumeration and the reads, the same in every mass storage run.
|
||||
check_disk() {
|
||||
log=$1
|
||||
name=$2
|
||||
expect "$log" '\[usb-host\] device attached' "$name: the host sees the device attach"
|
||||
expect "$log" 'high-speed device 1209:7E57 "RCM-Emulator" "USB test disk" serial "0001", address 1' \
|
||||
"$name: enumerated, strings read, address set"
|
||||
expect "$log" 'configuration 1: mass storage, bulk-only (EP 81 IN, EP 01 OUT, 512-byte packets)' \
|
||||
"$name: configuration parsed"
|
||||
expect "$log" 'LUN 0: "RCMEMU Test disk ", removable' "$name: INQUIRY"
|
||||
expect "$log" 'TEST UNIT READY: sense key 6, ASC 29/00' "$name: unit attention, then REQUEST SENSE"
|
||||
expect "$log" '384 blocks of 512 bytes (192 KiB)' "$name: READ CAPACITY"
|
||||
}
|
||||
|
||||
check_end() {
|
||||
log=$1
|
||||
name=$2
|
||||
want=$3
|
||||
expect "$log" "usb test: ejected; disk crc32 $want" "$name: START STOP UNIT ejects, the disk as expected"
|
||||
expect "$log" '\[usb-host\] device detached' "$name: the host sees the device go"
|
||||
expect "$log" 'usb test: done' "$name: the payload ran to its end"
|
||||
}
|
||||
|
||||
check_host() {
|
||||
log=$1
|
||||
name=$2
|
||||
check_disk "$log" "$name"
|
||||
first=$(sed -n 's/.*disk crc32 first \([0-9A-F]*\) last.*/\1/p' "$log")
|
||||
last=$(sed -n 's/.*disk crc32 first [0-9A-F]* last \([0-9A-F]*\).*/\1/p' "$log")
|
||||
expect "$log" "read blocks 0-63 (crc32 $first)" "$name: READ(10) of blocks 0-63 returns the disk"
|
||||
expect "$log" "read blocks 376-383 (crc32 $last)" "$name: READ(10) of the last 8 blocks returns the disk"
|
||||
if [ "$3" = ro ]; then
|
||||
expect "$log" '\[usb-host\] write-protected' "$name: MODE SENSE reports write protection"
|
||||
expect "$log" 'write check skipped: the disk is write-protected' "$name: no write to a write-protected disk"
|
||||
expect_not "$log" 'usb test: WRITE(10)' "$name: the gadget sees no WRITE(10)"
|
||||
else
|
||||
expect "$log" '\[usb-host\] writable' "$name: MODE SENSE reports a writable disk"
|
||||
expect "$log" 'usb test: WRITE(10) blocks 376-383' "$name: WRITE(10) of the last 8 blocks"
|
||||
expect "$log" 'usb test: SYNCHRONIZE CACHE' "$name: SYNCHRONIZE CACHE"
|
||||
expect "$log" 'wrote blocks 376-383 back unchanged; read back: the same data' \
|
||||
"$name: the blocks read back as written"
|
||||
fi
|
||||
check_end "$log" "$name" "$(crc "$log")"
|
||||
}
|
||||
|
||||
# --usb-host nbd: nbd_check.py reads, writes (or is refused) and disconnects.
|
||||
check_nbd() {
|
||||
n=$1
|
||||
name=$2
|
||||
mode=$3
|
||||
shift 3
|
||||
port=$((PORT_BASE + n))
|
||||
log=$DIR/out_nbd$n.log
|
||||
SDL_VIDEODRIVER=dummy RCM_EMU_NO_AUDIO=1 timeout 60 "$EMU" "$@" --usb-host nbd:$port > "$log" 2>&1 &
|
||||
emu=$!
|
||||
python3 "$DIR/nbd_check.py" $port "$log" $mode > "$DIR/out_nbd${n}_client.log" 2>&1
|
||||
client=$?
|
||||
wait $emu
|
||||
st=$?
|
||||
cat "$DIR/out_nbd${n}_client.log"
|
||||
[ $client -eq 0 ] || { echo " FAIL $name: NBD client"; fail=1; }
|
||||
check_disk "$log" "$name"
|
||||
expect "$log" "serving the disk over NBD at 127.0.0.1:$port" "$name: serving over NBD"
|
||||
expect "$log" 'NBD client has the disk' "$name: the client negotiated"
|
||||
expect "$log" 'NBD client disconnected' "$name: the client disconnected"
|
||||
expect "$log" 'ejecting the disk' "$name: the disk is ejected on disconnect"
|
||||
want=$(sed -n 's/^nbd check: disk crc32 \([0-9A-F]*\)$/\1/p' "$DIR/out_nbd${n}_client.log")
|
||||
check_end "$log" "$name" "${want:-none}"
|
||||
[ "$st" -eq 0 ] || { echo " FAIL $name: emulator exit $st"; fail=1; }
|
||||
}
|
||||
|
||||
echo "usb test:"
|
||||
st=$(run 1 "$DIR/payload_1.bin" --usb-host)
|
||||
check_host "$DIR/out_1.log" "USB2 controller"
|
||||
[ "$st" -eq 0 ] || { echo " FAIL USB2 controller: emulator exit $st"; fail=1; }
|
||||
|
||||
st=$(run 2 "$DIR/payload_2.bin" --usb-host --oem mariko)
|
||||
check_host "$DIR/out_2.log" "XUSB controller"
|
||||
[ "$st" -eq 0 ] || { echo " FAIL XUSB controller: emulator exit $st"; fail=1; }
|
||||
|
||||
st=$(run 4 "$DIR/payload_4.bin" --usb-host)
|
||||
check_host "$DIR/out_4.log" "write-protected disk" ro
|
||||
[ "$st" -eq 0 ] || { echo " FAIL write-protected disk: emulator exit $st"; fail=1; }
|
||||
|
||||
st=$(run 3 "$DIR/payload_3.bin" --usb-host)
|
||||
log=$DIR/out_3.log
|
||||
expect "$log" 'configuration 1: HID (EP 81 IN, interrupt every 4)' "HID gadget: configuration parsed"
|
||||
expect "$log" 'HID report descriptor: 21 bytes' "HID gadget: report descriptor read"
|
||||
expect "$log" 'SET_IDLE done; polling EP 81 for reports' "HID gadget: SET_IDLE"
|
||||
expect "$log" 'HID report 1: 10 11 12 13 14 15 16 17' "HID gadget: first interrupt report"
|
||||
expect "$log" 'HID report 3: 30 31 32 33 34 35 36 37' "HID gadget: third interrupt report"
|
||||
expect "$log" '\[usb-host\] device detached' "HID gadget: the host sees the device go"
|
||||
[ "$st" -eq 0 ] || { echo " FAIL HID gadget: emulator exit $st"; fail=1; }
|
||||
|
||||
st=$(run 0 "$DIR/payload_1.bin")
|
||||
expect "$DIR/out_0.log" 'usb test: no bus reset, nothing on the cable' "no host: the gadget waits on an empty cable"
|
||||
if grep -q '\[usb-host\]' "$DIR/out_0.log"; then
|
||||
echo " FAIL no host: the host logged activity"
|
||||
fail=1
|
||||
fi
|
||||
|
||||
if command -v python3 > /dev/null; then
|
||||
PORT_BASE=${USB_TEST_NBD_PORT:-$((20000 + $$ % 20000))}
|
||||
check_nbd 1 "NBD, USB2 controller" rw "$DIR/payload_1.bin"
|
||||
check_nbd 2 "NBD, XUSB controller" rw "$DIR/payload_2.bin" --oem mariko
|
||||
check_nbd 4 "NBD, write-protected disk" ro "$DIR/payload_4.bin"
|
||||
else
|
||||
echo " skip NBD: no python3"
|
||||
fi
|
||||
|
||||
[ $fail -eq 0 ] && echo "usb test: PASS" || { echo "usb test: FAIL (logs: $DIR/out_*.log)"; exit 1; }
|
||||
Reference in new issue
Block a user