Fix defects found in a code sweep and a TRM cross-check

Security Engine: CTR ignored its input and returned the raw keystream;
CBC encrypt skipped the IV on the first block and saved the wrong
chaining value, so every CMAC over more than one block was wrong; OFB
was broken. The datapath now follows INPUT_SEL/XOR_POS/VCTRAM_SEL the
way bdk drives it, and matches OpenSSL for ECB, CBC, OFB, CTR and
CMAC. SHA-256 works in parts (SHA_CONTINUE), SE_OP_CTX_SAVE reads keys
back as se_aes_ctx_get_keys() expects, unwrap honours the word quad,
guest block counts and LL sizes are bounded, and unreachable buffers
end the op with an error.

Soft reboot now resets the whole SoC (GPIO/pinmux cache, UARTs, I2C,
PMC, CAR, flow controller, SE, touch, SDMMC, display, ACTMON, ...)
while keeping what hardware keeps (PMC SCRATCH0, the RTC, and the PMIC
unless the reboot is a power cycle). DRAM gets fresh zero pages
instead of a memset that made all 2 GB resident; stale BPMP
translations are dropped; CPSR returns to SVC; scripts restart.

Execution: a branch to address 0 no longer hangs the emulator
(until=0 made PC 0 an exit); bdk's reset-then-bpmp_halt() reboots
instead of exiting; an untimed halt with CPU0 running parks the BPMP
and lets CPU0 continue; CPU0 starts in the same batch it is released
in; CPU0 drops translations of pages the BPMP rewrote; shared models
no longer see time run backwards.

TRM cross-check: RST_CPUG_CMPLX resets to 0x2000feef and CPU0 runs on
CPURESET0/CORERESET0/L2RESET/NONCPURESET (bit names corrected); RAM
repair clears REQ and sets STS, and is no longer a run condition;
refused releases are re-evaluated; MSELECT ENABLE_PCIE_APERTURE gates
PCIe; RST_DEVICES_W/Y direct writes land; DL_UP is read-only; the
whole config aperture and memory window decode; OSC_CTRL reports
38.4 MHz; PLLE/PLLREFE no longer get bit 27 forced into a divider;
PMC is a R/W register file; RTC SECONDS counts; FLOW halt modes follow
17.2.2 and STOP_UNTIL_IRQ wakes on the armed TMR; UART IIR/IER/
loopback MSR; I2C NOACK code and empty I2C4/I2C6 buses; pinmux reset
values; the COP ACTMON counts halt time.

Peripherals: MAX77620 LDO power-good follows the rail (hwtest's
gamecard probe no longer fails), the Erista GPU MAX77621 answers at
0x1C, regulators ACK per generation, RTC CONTROL is binary/24h, PS3
card detect reads "slot empty", packet-mode I2C parses 4 bytes per
word, rawnand I/O splits at part boundaries, eMMC returns to its user
area on CMD0, ADMA2 descriptors decode per spec, SD CMD6/ACMD13 data
reaches the programmed buffer, ERR_INTERRUPT is reported, R1 follows
block commands.

Frontend and tooling: touch events queue instead of overwriting each
other, map through rotation overrides and bdk's edge offset, and use
finger ID 0; a scripted press is always seen before its release;
zeroed fuses persist in the ini; dropped UTF-8 paths open on Windows;
bad --input-script is an error; test scripts check exit status and
missing arguments; make_sd.py quotes names and picks a FAT32-valid
cluster size; the Dockerfile marks the mount safe for git.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb
This commit is contained in:
Claude committed 2026-09-25 17:45:02 +00:00
1 parent 11ad2e4d9f
commit 6753c5f3db
26 files changed
+1585 -558

No files matched your search

+84 -29
View File
@@ -131,28 +131,42 @@ of the spec is modelled for the Hekate, Lockpick and TE init paths:
Models the SE (Security Engine) register block at `0x70012000`. Supports: Models the SE (Security Engine) register block at `0x70012000`. Supports:
- **AES-128 ECB, CBC, CTR, CMAC.** The compact public-domain TinyAES core - **AES-128 ECB, CBC, OFB, CTR, CMAC.** The compact public-domain TinyAES
([kokke/tiny-AES-c](https://github.com/kokke/tiny-AES-c)) drives one block core ([kokke/tiny-AES-c](https://github.com/kokke/tiny-AES-c)) drives one
at a time, with chaining state taken from `IV_ORIGINAL` or `IV_UPDATED` per block at a time through the SE's datapath: `INPUT_SEL` picks memory, the
slot and `xor_pos` from `CRYPTO_CONFIG`. previous AES output (OFB) or the linear counter (CTR); `XOR_POS` puts the
- **SHA-256.** Implemented because the TE function `save_process_header` vector RAM before the core (CBC encrypt) or the vector / the memory data
validates the save container hash. Without it, `readsave()` returns after it (CBC decrypt, OFB, CTR); `VCTRAM_SEL` says what the vector becomes
`Error: Save header is invalid!`. Oneshot only: one IN_LL buffer at a time, next. The vector starts from the slot's `IV_ORIGINAL` or `IV_UPDATED`, and
written into the `HASH_RESULT` registers as 8 big-endian dwords (the BDK a chaining mode leaves its final value in `IV_UPDATED`, which is how bdk
driver byte-swaps on read). continues a chain into a trailing partial block and feeds the last block of
- **DST_KEYTABLE unwrap path.** When the destination is another keyslot, the a CMAC. Checked against OpenSSL for every mode bdk uses, including
result of a single block is written into the destination `KEYS_0_3` or multi-block CMAC and partial blocks.
`KEYS_4_7` register pair. - **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.
- **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 - **`--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 derived BIS (Boot Image Storage) key into slots 0..5, the value from the
user-supplied key file is substituted. This sidesteps the user-supplied key file is substituted. This sidesteps the
TSEC-firmware to `master_kek` to `master_key` derivation chain that is not 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 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. `key[32] / iv_orig[16] / iv_upd[16]`. RSA and RNG output are stubbed: they
They return `OP_DONE` without producing data, which is enough for current return `OP_DONE` without producing data. Block counts are bounded by what one
payloads. 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.
### Touchscreen (`t210/i2c3.cpp`) ### Touchscreen (`t210/i2c3.cpp`)
@@ -185,11 +199,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 caught on both the small CMD\_DATA1 path and the packet-mode TX_FIFO path
-- stops emulation and exits cleanly. -- stops emulation and exits cleanly.
- Same register with `SFT_RST` (bit 7) set requests a payload soft-reboot - 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 - `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 `power_set_state(REBOOT_RCM)` -- also requests a soft-reboot, so the user
can iterate on a payload without restarting `rcm_emu`. 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) ### I²C-attached chips (battery, charger, thermal, USB-PD, PMIC ID)
Modelled inline in `t210/mmio.cpp::i2c_read`. The bus is disambiguated by Modelled inline in `t210/mmio.cpp::i2c_read`. The bus is disambiguated by
@@ -359,6 +389,14 @@ needed. The 64 KB TX log trim happens in-place during the write hook.
- **Timer and RTC.** Backed by `EmuState::emu_usec`, derived from retired - **Timer and RTC.** Backed by `EmuState::emu_usec`, derived from retired
instructions (see [Determinism](#determinism-and-the-auto-script-flag)), so instructions (see [Determinism](#determinism-and-the-auto-script-flag)), so
timing is identical across runs. The auto-script feature relies on this. 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 - **Probe-magic constants.** Several reads return fixed values, not because
they are tweakable but because the chip-detection code expects exact they are tweakable but because the chip-detection code expects exact
cookies: `MAX17050.DevName=0x00AC`, `BQ24193.VendorPart=0x2F`, the BM92T36 cookies: `MAX17050.DevName=0x00AC`, `BQ24193.VendorPart=0x2F`, the BM92T36
@@ -426,10 +464,13 @@ 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 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. mailbox while the stub trains the link and enumerates the CYW4356.
**Release.** The model shadows the registers the boot sequence writes and **Release.** The model shadows the registers the boot sequence writes.
starts the core when `RST_CPUG_CMPLX_CLR` clears the last of CPU0's reset bits `RST_CPUG_CMPLX` starts at its TRM reset value, `0x2000feef`, and the core
(CPURESET0, DBGRESET0, CORERESET0, bit 30, NONCPURESET) - but only if the core runs once CPURESET0 (bit 0), CORERESET0 (16), L2RESET (24) and NONCPURESET
could actually run: (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 | | Precondition | Where it comes from |
| --- | --- | | --- | --- |
@@ -437,7 +478,6 @@ could actually run:
| CRAIL, C0NC, CE0 ungated | PMC PWRGATE_STATUS bits 0, 15, 14 | | 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 | | 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 | | MSELECT clocked and out of reset | CLK_ENB_V bit 3, RST_DEV_V bit 3 |
| RAM repair requested | FLOW_CTLR_RAM_REPAIR |
| An AArch64 vector in IRAM/DRAM | SB_AA64_RESET_LOW bit 0 + address, SB_AA64_RESET_HIGH | | 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 A release that misses one prints `[ccplex] CPU0 released from reset but
@@ -450,7 +490,7 @@ 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 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 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 current EL from PSTATE and rebuilds `hflags` for the target. So each boot
creates a fresh engine (no stale translations of a rewritten stub), writes creates a fresh engine, writes
PSTATE = SPSR_EL3 = EL3h with DAIF masked and ELR_EL3 = ELR_EL1 = the vector, 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 and starts it on a one-instruction `eret` trampoline in a page at 1 TiB that
only CPU0 maps. only CPU0 maps.
@@ -460,18 +500,33 @@ 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 access; the PCIe model refuses the BPMP (`0xFFFFFFFF`, and one warning
explaining why) and serves CPU0. MSELECT reads its TRM reset value explaining why) and serves CPU0. MSELECT reads its TRM reset value
`0x07FF4020`, AFI_PCIE_CONFIG `0x00103025`, and LNKSTA `0x3011` once the link `0x07FF4020`, AFI_PCIE_CONFIG `0x00103025`, and LNKSTA `0x3011` once the link
is up - the values hwtest's healthy-console capture shows. An access CPU0 is up - the values hwtest's healthy-console capture shows. The whole config
makes to an address nothing decodes wedges it, as on silicon; the BPMP's aperture and non-prefetchable window are decoded (extended registers read 0,
watchdog on the mailbox heartbeat is what reports it. 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 **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). 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 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 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 500 us the BPMP polls the mailbox at. During a CPU0 slice `emu_usec` is CPU0's
clock, so every register model timestamps with the right core's time. WFE / clock, so every register model timestamps with the right core's time - a
WFI park the core to the end of the slice: the stub's final `for(;;) wfe;` model timing CPU0's PERST#-after-refclk sequence must use the clock CPU0
would otherwise spin through a billion instructions per emulated second. 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 `make test` runs `tests/ccplex/`, a self-contained payload that checks the
refusal, the EL3 entry, the mailbox, WFE parking and the reset. refusal, the EL3 entry, the mailbox, WFE parking and the reset.
+4 -1
View File
@@ -15,4 +15,7 @@ WORKDIR /work
# Build command: docker run --rm -v $(pwd):/work rcm_emu # Build command: docker run --rm -v $(pwd):/work rcm_emu
# (init the imgui submodule if it's missing, then build) # (init the imgui submodule if it's missing, then build)
CMD ["sh", "-c", "git submodule update --init --recursive && make"] # 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"]
+5 -2
View File
@@ -217,11 +217,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())); fprintf(f, "radio=%s\n", wifi_radio_name(s->wifi_radio.load()));
// Fuses are dumped wholesale — small enough (256 × 4 bytes) and keeps the // 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"); fprintf(f, "\n[fuses]\n");
for (size_t i = 0; i < EmuState::FUSE_WORDS; i++) { for (size_t i = 0; i < EmuState::FUSE_WORDS; i++) {
uint32_t v = s->fuse_word[i].load(); 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); fclose(f);
@@ -889,6 +891,7 @@ void build_ui(EmuState *state) {
} }
ImGui::SameLine(); ImGui::SameLine();
if (ImGui::Button("Reboot")) { if (ImGui::Button("Reboot")) {
state->reboot_cold = true; // the user's reset is a power cycle
state->reboot_requested.store(true); state->reboot_requested.store(true);
} }
ImGui::Text("emu_usec: %llu", (unsigned long long)state->emu_usec); ImGui::Text("emu_usec: %llu", (unsigned long long)state->emu_usec);
+49 -32
View File
@@ -93,7 +93,8 @@ void sdl_display_update(EmuState *state, uc_engine *uc) {
return a >= FB_BASE && a < FB_BASE + FB_SIZE; return a >= FB_BASE && a < FB_BASE + FB_SIZE;
}; };
int rot = state->rotation_override; // Auto-detect first; a manual override is applied on top further down.
int rot = -1;
uint32_t sw = state->fb_swizzle; uint32_t sw = state->fb_swizzle;
uint32_t eff_stride = stride; uint32_t eff_stride = stride;
@@ -160,6 +161,7 @@ void sdl_display_update(EmuState *state, uc_engine *uc) {
// rot = 0 for Nyx and Hekate TUI surfaces; if the user pressed R/Shift+R // 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 // they expect the rotation to actually change, regardless of what the
// auto-detect picked. -1 means "use auto-detect", anything else overrides. // auto-detect picked. -1 means "use auto-detect", anything else overrides.
state->last_auto_rot.store((uint32_t)(rot & 3));
if (state->rotation_override != -1) if (state->rotation_override != -1)
rot = state->rotation_override & 3; rot = state->rotation_override & 3;
@@ -424,30 +426,45 @@ static bool window_to_panel(EmuState *state, int mx, int my,
if (tx >= out_w) tx = out_w - 1; if (tx >= out_w) tx = out_w - 1;
if (ty >= out_h) ty = out_h - 1; if (ty >= out_h) ty = out_h - 1;
// The rendered SDL view always represents the physical Switch screen in its // With the auto-detected rotation, the rendered SDL view represents the
// intended orientation (post-rotation, post-de-swizzle). Whatever the // physical Switch screen in its intended orientation (post-rotation, post-
// framebuffer's in-memory layout, what the user sees is what they would see // de-swizzle): what the user sees is what they would see looking at a
// looking at a Switch held landscape (long axis horizontal). The FTS4 panel // Switch held landscape. A manual override (R / Shift+R) turns that view
// sits behind that physical screen with its long axis (panel_x) along the // by a further quarter-turn or two, so undo exactly that extra turn first:
// long dimension and its short axis (panel_y) along the short. // 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)
// So we map the texture coord to panel coords by aspect: whichever of (tx, uint32_t delta = (state->last_rot.load() - state->last_auto_rot.load()) & 3;
// ty) lives on the longer rendered axis is the long-axis sample. uint32_t aw = (delta & 1) ? out_h : out_w; // auto-rotated view's size
bool landscape = (out_w >= out_h); uint32_t ah = (delta & 1) ? out_w : out_h;
uint32_t long_pix = landscape ? tx : ty; uint32_t ax = tx, ay = ty;
uint32_t long_max = landscape ? out_w : out_h; switch (delta) {
uint32_t short_pix = landscape ? ty : tx; case 1: ax = ty; ay = ah - 1 - tx; break;
uint32_t short_max = landscape ? out_h : out_w; 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 (long_max == 0) long_max = 1;
if (short_max == 0) short_max = 1; if (short_max == 0) short_max = 1;
uint32_t px = (long_pix * 1264u) / long_max; // FTS4 X_REAL_MAX = 1264 // bdk's touch.c clamps raw samples to EDGE_OFFSET..REAL_MAX (15..1264 and
uint32_t py = (short_pix * 704u) / short_max; // FTS4 Y_REAL_MAX = 704 // 15..704) and stretches that span over the 1280x720 screen, so the inverse
if (px > 1264) px = 1264; // starts at the edge offset, not at 0.
if (py > 704) py = 704; 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_x = (uint16_t)px;
*panel_y = (uint16_t)py; *panel_y = (uint16_t)py;
(void)state; // last_rot still cached for future use; current mapping is rotation-agnostic
return true; return true;
} }
@@ -485,11 +502,8 @@ bool sdl_display_poll_events(EmuState *state, uc_engine *uc) {
if (event.type == SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_LEFT) { if (event.type == SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_LEFT) {
uint16_t px = 0, py = 0; uint16_t px = 0, py = 0;
if (window_to_panel(state, event.button.x, event.button.y, &px, &py)) { 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_pressed.store(true);
state->tc_event_op.store(0x03); // FTS4_EV_MULTI_TOUCH_ENTER state->touch_post(0x03, px, py); // FTS4_EV_MULTI_TOUCH_ENTER
state->tc_event_pending.store(true);
printf("[touch] DOWN win=(%d,%d) panel=(%u,%u)\n", printf("[touch] DOWN win=(%d,%d) panel=(%u,%u)\n",
event.button.x, event.button.y, px, py); event.button.x, event.button.y, px, py);
} }
@@ -497,11 +511,8 @@ bool sdl_display_poll_events(EmuState *state, uc_engine *uc) {
if (event.type == SDL_MOUSEBUTTONUP && event.button.button == SDL_BUTTON_LEFT) { if (event.type == SDL_MOUSEBUTTONUP && event.button.button == SDL_BUTTON_LEFT) {
uint16_t px = 0, py = 0; uint16_t px = 0, py = 0;
if (window_to_panel(state, event.button.x, event.button.y, &px, &py)) { 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_pressed.store(false);
state->tc_event_op.store(0x04); // FTS4_EV_MULTI_TOUCH_LEAVE state->touch_post(0x04, px, py); // FTS4_EV_MULTI_TOUCH_LEAVE
state->tc_event_pending.store(true);
printf("[touch] UP win=(%d,%d) panel=(%u,%u)\n", printf("[touch] UP win=(%d,%d) panel=(%u,%u)\n",
event.button.x, event.button.y, px, py); event.button.x, event.button.y, px, py);
} }
@@ -509,10 +520,15 @@ bool sdl_display_poll_events(EmuState *state, uc_engine *uc) {
if (event.type == SDL_MOUSEMOTION && state->tc_pressed.load()) { if (event.type == SDL_MOUSEMOTION && state->tc_pressed.load()) {
uint16_t px = 0, py = 0; uint16_t px = 0, py = 0;
if (window_to_panel(state, event.motion.x, event.motion.y, &px, &py)) { if (window_to_panel(state, event.motion.x, event.motion.y, &px, &py)) {
state->tc_x.store(px); // A release outside the window never reaches it when mouse capture
state->tc_y.store(py); // is off (the ImGui backend turns SDL's auto-capture off process-
state->tc_event_op.store(0x05); // FTS4_EV_MULTI_TOUCH_MOTION // wide), so a motion with the button up ends the touch instead.
state->tc_event_pending.store(true); 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) { if (event.type == SDL_KEYDOWN) {
@@ -543,6 +559,7 @@ bool sdl_display_poll_events(EmuState *state, uc_engine *uc) {
if (!ctrl) { if (!ctrl) {
// Plain R: soft reboot. Same path as the config window's "Reboot" // Plain R: soft reboot. Same path as the config window's "Reboot"
// button — re-prime IRAM payload + WDT cookie, wipe DRAM, reset PC. // button — re-prime IRAM payload + WDT cookie, wipe DRAM, reset PC.
state->reboot_cold = true; // the user's reset is a power cycle
state->reboot_requested = true; state->reboot_requested = true;
printf("[diag] Reboot requested (R)\n"); printf("[diag] Reboot requested (R)\n");
} else { } else {
+40 -5
View File
@@ -102,15 +102,40 @@ struct EmuState {
// Updated by SDL mouse events; consumed by i2c3_*/STMFTS code on CPU thread. // 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) // Coordinates are in panel-raw space (X long axis 0..1264, Y short 0..704)
// matching what touch.c expects before its rescaling. // 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_pressed{false};
std::atomic<bool> tc_event_pending{false}; uint8_t tc_finger_id = 0; // raw FTS4 ID; bdk reports it + 1
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 // 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. // last_rot mirrors the rotation last applied by sdl_display_update.
// Read from the SDL event handler to invert the display→window transform. // Read from the SDL event handler to invert the display→window transform.
std::atomic<uint32_t> last_rot{0}; 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_w{1280};
std::atomic<uint32_t> last_out_h{720}; std::atomic<uint32_t> last_out_h{720};
@@ -141,6 +166,14 @@ struct EmuState {
std::atomic<bool> running{true}; std::atomic<bool> running{true};
std::atomic<bool> paused{false}; std::atomic<bool> paused{false};
std::atomic<bool> reboot_requested{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). // Payload kept around for soft reboot (re-write to IRAM and reset PC).
uint8_t *payload_ptr = nullptr; uint8_t *payload_ptr = nullptr;
@@ -328,6 +361,8 @@ struct EmuState {
std::atomic<uint32_t>& fuse_at(uint32_t offset) { return fuse_word[(offset & 0x3FC) / 4]; } std::atomic<uint32_t>& fuse_at(uint32_t offset) { return fuse_word[(offset & 0x3FC) / 4]; }
void init_fuse_defaults() { 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 // Names below mirror Hekate's bdk/soc/fuse.h. Values picked from a
// typical Erista golden-sample dump (any retail Switch is similar). // typical Erista golden-sample dump (any retail Switch is similar).
fuse_at(0x100).store(1); // FUSE_PRODUCTION_MODE fuse_at(0x100).store(1); // FUSE_PRODUCTION_MODE
+13
View File
@@ -280,6 +280,10 @@ void input_script_tick(EmuState &state) {
printf("[input-script] %s down @%llu us (%zu/%zu)\n", key_name(ev.key), printf("[input-script] %s down @%llu us (%zu/%zu)\n", key_name(ev.key),
(unsigned long long)now, i + 1, g_events.size()); (unsigned long long)now, i + 1, g_events.size());
fflush(stdout); 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) { if (ev.pressed && !ev.released && now >= ev.until_us) {
btn->store(false); btn->store(false);
@@ -293,3 +297,12 @@ void input_script_tick(EmuState &state) {
if (!ev.released) break; // keep this event current until it's let go 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;
}
+4
View File
@@ -23,3 +23,7 @@ bool input_script_active();
// Apply any events that are due at the current state.emu_usec. Call once per // 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. // emulator loop iteration; cheap no-op when no script is loaded.
void input_script_tick(EmuState &state); 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);
+119 -38
View File
@@ -34,10 +34,34 @@
#include "display/console_window.h" #include "display/console_window.h"
#include "input_script.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 ==================== // ==================== Payload Loading ====================
static uint8_t *load_payload(const char *path, size_t *out_size) { 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) { if (!f) {
fprintf(stderr, "[error] Cannot open payload: %s\n", path); fprintf(stderr, "[error] Cannot open payload: %s\n", path);
return nullptr; return nullptr;
@@ -149,18 +173,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 // through. One contiguous block removes the hole and matches what real
// hardware presents. // hardware presents.
// //
// Allocated host-side (calloc, so pages are lazily committed - the full // 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 // 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 // kept as a host pointer so a soft reboot can hand it back zeroed: Nyx
// and its file-static SD/eMMC caches would otherwise survive a reboot. // loads here and its file-static SD/eMMC caches would otherwise survive.
err = uc_mem_map_ptr(uc, DRAM_BASE, DRAM_WINDOW_SIZE, UC_PROT_ALL, state->dram_low_ptr = zeroed_alloc(DRAM_WINDOW_SIZE);
(state->dram_low_ptr = (uint8_t *)calloc(1, DRAM_WINDOW_SIZE)));
if (!state->dram_low_ptr) { if (!state->dram_low_ptr) {
fprintf(stderr, "[error] Failed to allocate %zu MB DRAM host buffer\n", fprintf(stderr, "[error] Failed to allocate %zu MB DRAM host buffer\n",
(size_t)(DRAM_WINDOW_SIZE / (1024 * 1024))); (size_t)(DRAM_WINDOW_SIZE / (1024 * 1024)));
uc_close(uc); uc_close(uc);
return nullptr; 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) { if (err != UC_ERR_OK) {
fprintf(stderr, "[error] Failed to map DRAM: %s\n", uc_strerror(err)); fprintf(stderr, "[error] Failed to map DRAM: %s\n", uc_strerror(err));
uc_close(uc); uc_close(uc);
@@ -178,13 +203,7 @@ static uc_engine *setup_emulation(EmuState *state, uint8_t *payload, size_t payl
// ---- Map Framebuffer pointer ---- // ---- Map Framebuffer pointer ----
state->fb_ptr = state->dram_low_ptr + (FB_BASE - DRAM_BASE); state->fb_ptr = state->dram_low_ptr + (FB_BASE - DRAM_BASE);
// Fill with hekate background color (0x1B1B1B) fill_fb_background(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
}
state->fb_addr = FB_BASE; state->fb_addr = FB_BASE;
printf("[emu] Defined FB: 0x%08llX - 0x%08llX (%u MB)\n", printf("[emu] Defined FB: 0x%08llX - 0x%08llX (%u MB)\n",
(unsigned long long)FB_BASE, (unsigned long long)FB_BASE,
@@ -193,8 +212,20 @@ static uc_engine *setup_emulation(EmuState *state, uint8_t *payload, size_t payl
// ---- Map low memory (16MB @ 0x0) ---- // ---- Map low memory (16MB @ 0x0) ----
// hekate seems to do a memset(0, ...) for clear screen if some ptr is NULL. // hekate seems to do a memset(0, ...) for clear screen if some ptr is NULL.
uint8_t *low_ptr = (uint8_t *)calloc(1, 0x01000000); // This covers the iROM range (0x100000, 96 KB) too, as zero-filled RAM:
uc_mem_map_ptr(uc, 0, 0x01000000, UC_PROT_ALL, low_ptr); // 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) ---- // ---- Nyx Storage (16MB @ 0xED000000) ----
// Already mapped as part of 2GB DRAM chunk // Already mapped as part of 2GB DRAM chunk
@@ -204,13 +235,11 @@ static uc_engine *setup_emulation(EmuState *state, uint8_t *payload, size_t payl
// which only worked because MMIO was a pair of address-range hooks over // which only worked because MMIO was a pair of address-range hooks over
// whatever happened to be mapped. // whatever happened to be mapped.
// BootROM (iROM) at 0x100000, 96 KB. We don't have the real BootROM // The IPATCH CAM at 0x6001DC00 is zero-mapped so the ipatches table
// contents, but mapping the region as zero-filled lets Hekate's "Bootrom // renders empty (which matches an unpatched SoC).
// Info" / "Dump Bootrom" features read it without faulting. The IPATCH err = uc_mem_map(uc, 0x6001D000, 0x1000, UC_PROT_ALL);
// CAM at 0x6001DC00 is also zero-mapped so the ipatches table renders if (err != UC_ERR_OK)
// empty (which matches an unpatched SoC). fprintf(stderr, "[warn] IPATCH page not mapped: %s\n", uc_strerror(err));
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
// ---- heap region (32MB @ 0x90000000) ---- // ---- heap region (32MB @ 0x90000000) ----
// Already mapped as part of 2GB DRAM chunk // Already mapped as part of 2GB DRAM chunk
@@ -374,8 +403,14 @@ int main(int argc, char *argv[]) {
else if (strcmp(argv[i], "--auto-te-script") == 0) auto_te_script = true; else if (strcmp(argv[i], "--auto-te-script") == 0) auto_te_script = true;
// Generic scripted button input, for menu-driven payloads that can't // Generic scripted button input, for menu-driven payloads that can't
// be driven any other way from a headless / CI run. // be driven any other way from a headless / CI run.
else if (strcmp(argv[i], "--input-script") == 0 && i + 1 < argc) else if (strcmp(argv[i], "--input-script") == 0 && i + 1 < argc) {
input_script_load(argv[++i]); // 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 // Default to sd.img in the working directory when --sd is not given, so the
@@ -464,31 +499,52 @@ int main(int argc, char *argv[]) {
// re-prime the WDT cookie so Hekate's early boot skips Minerva again. // re-prime the WDT cookie so Hekate's early boot skips Minerva again.
if (state.reboot_requested.exchange(false)) { if (state.reboot_requested.exchange(false)) {
uc_emu_stop(uc); uc_emu_stop(uc);
bool cold = state.reboot_cold.exchange(false);
// The SoC resets as a whole: CPU0 back into reset, the PCIe root // The SoC resets as a whole: CPU0 back into reset, the PCIe root
// complex back to power-on, the clock's half-counted block gone. // complex and every other block back to power-on, the clock's
mmio_soft_reset(&state); // half-counted block gone. A power cycle resets the PMIC too.
mmio_soft_reset(&state, cold);
bpmp_clock_reset(); bpmp_clock_reset();
// One contiguous block now; dram_ptr is a view into it. // Fresh zero pages rather than a memset, which made all 2 GB
memset(state.dram_low_ptr, 0, DRAM_WINDOW_SIZE); // resident.
zeroed_reset(state.dram_low_ptr, DRAM_WINDOW_SIZE);
fill_fb_background(&state);
size_t reload = state.payload_len; size_t reload = state.payload_len;
if (reload > IRAM_SIZE - (IPL_LOAD_ADDR - IRAM_BASE)) if (reload > IRAM_SIZE - (IPL_LOAD_ADDR - IRAM_BASE))
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); uc_mem_write(uc, IPL_LOAD_ADDR, state.payload_ptr, reload);
uint32_t wdt_magic = 0x544457; uint32_t wdt_magic = 0x544457;
uc_mem_write(uc, 0x4003FF18, &wdt_magic, sizeof(wdt_magic)); uc_mem_write(uc, 0x4003FF18, &wdt_magic, sizeof(wdt_magic));
// 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_pc = IPL_LOAD_ADDR;
uint32_t reset_sp = IPL_STACK_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); uc_reg_write(uc, UC_ARM_REG_CPSR, &reset_cpsr);
uc_reg_write(uc, UC_ARM_REG_SP, &reset_sp);
uc_reg_write(uc, UC_ARM_REG_PC, &reset_pc);
state.fb_addr = FB_BASE; // re-point display at the FB base state.fb_addr = FB_BASE; // re-point display at the FB base
state.emu_usec = 0; state.emu_usec = 0;
state.insn_count = 0; state.insn_count = 0;
state.bpmp_slept_us = 0; state.bpmp_slept_us = 0;
state.touch_phase = 0; state.touch_phase = 0;
state.paused = false; 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) { if (!state.paused) {
@@ -508,8 +564,8 @@ int main(int argc, char *argv[]) {
// idle so recover_pin's final btn_wait blocks on us — keeps the // idle so recover_pin's final btn_wait blocks on us — keeps the
// result text visible in the framebuffer when the run times out. // result text visible in the framebuffer when the run times out.
if (auto_pin_recovery) { if (auto_pin_recovery) {
static int pin_stage = 0; int &pin_stage = g_auto.pin_stage;
static uint64_t pin_t = 0; uint64_t &pin_t = g_auto.pin_t;
auto press_release = [&](std::atomic<bool> *btn, auto press_release = [&](std::atomic<bool> *btn,
uint64_t hold_us, uint64_t hold_us,
uint64_t cooldown_us) { uint64_t cooldown_us) {
@@ -528,7 +584,7 @@ int main(int argc, char *argv[]) {
printf("[emu] Auto PIN recovery armed at emu_usec=%llu\n", printf("[emu] Auto PIN recovery armed at emu_usec=%llu\n",
(unsigned long long)state.emu_usec); (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) { if (pin_stage != last_logged_stage) {
printf("[emu] Auto PIN stage %d at emu_usec=%llu\n", pin_stage, printf("[emu] Auto PIN stage %d at emu_usec=%llu\n", pin_stage,
(unsigned long long)state.emu_usec); (unsigned long long)state.emu_usec);
@@ -590,7 +646,7 @@ int main(int argc, char *argv[]) {
{22850000, 'P', true}, {23020000, 'P', false}, {22850000, 'P', true}, {23020000, 'P', false},
}; };
static const size_t te_n = sizeof(te_events)/sizeof(te_events[0]); 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) { while (te_idx < te_n && state.emu_usec >= te_events[te_idx].at_us) {
const InputEv &ev = te_events[te_idx]; const InputEv &ev = te_events[te_idx];
std::atomic<bool> *btn = (ev.btn == 'P') ? &state.btn_power std::atomic<bool> *btn = (ev.btn == 'P') ? &state.btn_power
@@ -605,6 +661,10 @@ int main(int argc, char *argv[]) {
te_idx++; te_idx++;
if (te_idx == te_n) if (te_idx == te_n)
printf("[auto-te] sequence complete; idling for output\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;
} }
} }
@@ -629,8 +689,28 @@ int main(int argc, char *argv[]) {
// to the same emulated time. Scripted input and the display are // to the same emulated time. Scripted input and the display are
// still serviced once per full batch, as before. // still serviced once per full batch, as before.
uint64_t batch_end = state.insn_count + BATCH_INSTRUCTIONS; uint64_t batch_end = state.insn_count + BATCH_INSTRUCTIONS;
uint64_t parked_left = BATCH_INSTRUCTIONS;
while (state.running && !state.paused && while (state.running && !state.paused &&
state.insn_count < batch_end) { 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; uint64_t budget = batch_end - state.insn_count;
if (ccplex_cpu0_running() && budget > CPU0_QUANTUM_INSTRUCTIONS) if (ccplex_cpu0_running() && budget > CPU0_QUANTUM_INSTRUCTIONS)
budget = CPU0_QUANTUM_INSTRUCTIONS; budget = CPU0_QUANTUM_INSTRUCTIONS;
@@ -690,8 +770,9 @@ int main(int argc, char *argv[]) {
uc_close(uc); uc_close(uc);
free(state.iram_ptr); free(state.iram_ptr);
free(g_low_ptr);
// dram_ptr is a view into dram_low_ptr's block; only free the base once. // 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); free(state.payload_ptr);
// fb_ptr points inside dram_ptr; do not free separately. // fb_ptr points inside dram_ptr; do not free separately.
+17 -4
View File
@@ -13,6 +13,7 @@ Usage:
""" """
import argparse import argparse
import os import os
import shlex
import subprocess import subprocess
import sys 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): if not os.path.isdir(src_dir):
print(f"[error] source folder not found: {src_dir}") print(f"[error] source folder not found: {src_dir}")
return 1 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) src_dir_abs = os.path.abspath(src_dir)
out_img_abs = os.path.abspath(out_img) 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)") print(f"[*] formatting + populating via Docker (alpine)")
fdisk_script = f"o\\nn\\np\\n1\\n2048\\n\\nt\\nc\\nw\\n" 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_cmd = [
"docker", "run", "--rm", "docker", "run", "--rm",
"-v", f"{work_dir}:/work", "-v", f"{work_dir}:/work",
@@ -53,10 +64,12 @@ def build_sd_image(src_dir: str, out_img: str, size_mb: int) -> int:
"alpine", "alpine",
"sh", "-c", "sh", "-c",
"apk add --no-cache dosfstools mtools util-linux >/dev/null && " "apk add --no-cache dosfstools mtools util-linux >/dev/null && "
f"mkfs.fat -F 32 -s 8 {fat_name} && " f"mkfs.fat -F 32 -s {spc} {q_fat} && "
f"mcopy -i {fat_name} -s /src/* :: && " # Every top-level entry, dotfiles included; an empty source is fine.
f"printf '{fdisk_script}' | fdisk {img_name} && " f"(cd /src && find . -mindepth 1 -maxdepth 1 "
f"dd if={fat_name} of={img_name} bs=1M seek=1 conv=notrunc status=none" 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: try:
subprocess.run(docker_cmd, check=True) subprocess.run(docker_cmd, check=True)
+81
View File
@@ -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;
}
+12
View File
@@ -1,7 +1,9 @@
#ifndef RCM_PLATFORM_H #ifndef RCM_PLATFORM_H
#define RCM_PLATFORM_H #define RCM_PLATFORM_H
#include <cstddef>
#include <cstdint> #include <cstdint>
#include <cstdio>
#include <fcntl.h> #include <fcntl.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <sys/types.h> #include <sys/types.h>
@@ -34,4 +36,14 @@ static inline int64_t file_size64(int fd) {
#endif #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 #endif // RCM_PLATFORM_H
+20 -4
View File
@@ -153,7 +153,16 @@ uint32_t count_insns(uc_engine *uc, const EmuState *s, uint64_t addr,
// A payload that jumps into zeroed memory executes `movs r0, r0` (Thumb // 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 // 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. // emits sixteen zero bytes at the start of a block, so that is the signal.
bool nop_slide(const EmuState *s, uint64_t addr) { // 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) || bool in_range = (addr >= 0x40030000 && addr < IRAM_BASE + IRAM_SIZE) ||
(addr >= DRAM_BASE && addr < DRAM_BASE + DRAM_WINDOW_SIZE); (addr >= DRAM_BASE && addr < DRAM_BASE + DRAM_WINDOW_SIZE);
if (!in_range) if (!in_range)
@@ -161,7 +170,6 @@ bool nop_slide(const EmuState *s, uint64_t addr) {
const uint8_t *p = code_ptr(s, addr, 16); const uint8_t *p = code_ptr(s, addr, 16);
if (!p) if (!p)
return false; return false;
static const uint8_t zero[16] = {0};
return memcmp(p, zero, sizeof(zero)) == 0; return memcmp(p, zero, sizeof(zero)) == 0;
} }
@@ -178,7 +186,7 @@ void hook_block(uc_engine *uc, uint64_t address, uint32_t size, void *ud) {
return; return;
} }
if (nop_slide(s, address)) { if (nop_slide(uc, s, address)) {
if (!clk.nop_slide_reported) { if (!clk.nop_slide_reported) {
clk.nop_slide_reported = true; clk.nop_slide_reported = true;
printf("\n[emu] NOP-slide detected at 0x%08llX (zeroed memory being " printf("\n[emu] NOP-slide detected at 0x%08llX (zeroed memory being "
@@ -220,7 +228,11 @@ uc_err bpmp_run(uc_engine *uc, EmuState *state, uint64_t begin,
uint64_t max_insns) { uint64_t max_insns) {
clk.limit = state->insn_count + (max_insns ? max_insns : 1); clk.limit = state->insn_count + (max_insns ? max_insns : 1);
clk.pending = 0; clk.pending = 0;
uc_err err = uc_emu_start(uc, begin, 0, 0, 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 // 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 // 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. // end - Unicorn only checks for a stop between blocks - so credit it.
@@ -244,3 +256,7 @@ uint32_t bpmp_timerus_read(EmuState *state) {
void bpmp_clock_jumped() { void bpmp_clock_jumped() {
clk.polling = false; clk.polling = false;
} }
void bpmp_yield() {
clk.limit = 0;
}
+6
View File
@@ -45,4 +45,10 @@ uint32_t bpmp_timerus_read(EmuState *state);
// halt): whatever poll loop was being paced is over. // halt): whatever poll loop was being paced is over.
void bpmp_clock_jumped(); 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 #endif // T210_BPMP_H
+103 -23
View File
@@ -1,7 +1,10 @@
#include "ccplex.h" #include "ccplex.h"
#include "bpmp.h"
#include <cstdio> #include <cstdio>
#include <cstring> #include <cstring>
#include <vector>
#include <memory>
#include <unicorn/unicorn.h> #include <unicorn/unicorn.h>
@@ -27,10 +30,14 @@
#define CLK_V_MSELECT 3 #define CLK_V_MSELECT 3
#define CAR_RST_CPUG_CMPLX_SET 0x450 #define CAR_RST_CPUG_CMPLX_SET 0x450
#define CAR_RST_CPUG_CMPLX_CLR 0x454 #define CAR_RST_CPUG_CMPLX_CLR 0x454
// The bits ccplex_boot_cpu0() clears for CPU0 - CPURESET0, DBGRESET0, // RST_CPUG_CMPLX (TRM 5.2.152, reset 0x2000feef). CPU0 runs once nCPUPORESET
// CORERESET0 and bit 30 - and NONCPURESET, which it clears first. The core // (CPURESET0, bit 0), nCORERESET (CORERESET0, bit 16), nL2RESET (bit 24) and
// runs once all five are clear. // the nonCPU region's reset (NONCPURESET, bit 29) are all released.
#define RST_CPU0_MASK ((1u << 0) | (1u << 16) | (1u << 24) | (1u << 30)) // 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) #define RST_NONCPU (1u << 29)
// SB block, SYSREG + 0x200. // SB block, SYSREG + 0x200.
@@ -94,7 +101,7 @@ namespace {
enum class Cpu0 { Off, Running, Hung }; enum class Cpu0 { Off, Running, Hung };
struct Model { struct Model {
uint32_t rst_cpug = 0xFFFFFFFFu; // everything held at power-on uint32_t rst_cpug = RST_CPUG_CMPLX_RESET;
uint32_t clk_enb_v = 0; uint32_t clk_enb_v = 0;
uint32_t cclk_burst = 0; uint32_t cclk_burst = 0;
uint32_t pllx_base = 0; uint32_t pllx_base = 0;
@@ -122,6 +129,15 @@ struct Model {
Model m; Model m;
EmuState *g_state = nullptr; 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; uc_hook h_block, h_unmapped, h_intr;
bool held() { return (m.rst_cpug & (RST_CPU0_MASK | RST_NONCPU)) != 0; } bool held() { return (m.rst_cpug & (RST_CPU0_MASK | RST_NONCPU)) != 0; }
@@ -162,8 +178,6 @@ const char *boot_blocked(EmuState *state) {
return "CCLK runs from PLLX but PLLX is disabled"; return "CCLK runs from PLLX but PLLX is disabled";
if (!(m.clk_enb_v & (1u << CLK_V_MSELECT))) return "MSELECT clock disabled"; if (!(m.clk_enb_v & (1u << CLK_V_MSELECT))) return "MSELECT clock disabled";
if (!pcie_mselect_up()) return "MSELECT still in reset"; if (!pcie_mselect_up()) return "MSELECT still in reset";
if (!flow_ram_repair_done())
return "fast-cluster RAM repair never requested (FLOW_CTLR_RAM_REPAIR)";
if (!(m.sb_rst_lo & SB_AA64_RST_AARCH64_MODE_EN)) 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)"; 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"; if (!entry_mapped(entry_vector())) return "reset vector outside IRAM/DRAM";
@@ -171,6 +185,8 @@ const char *boot_blocked(EmuState *state) {
} }
void destroy_engine() { void destroy_engine() {
code_pages.clear();
last_code_page = ~0ULL;
if (!m.uc) if (!m.uc)
return; return;
mmio_unmap_bus(m.uc); mmio_unmap_bus(m.uc);
@@ -199,6 +215,43 @@ void stop_cpu0(const char *why) {
// ---- CPU0 engine hooks --------------------------------------------------- // ---- 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() { void commit_pending() {
m.ns += m.pending * NS_PER_INSN; m.ns += m.pending * NS_PER_INSN;
m.retired += m.pending; m.retired += m.pending;
@@ -228,6 +281,7 @@ void hook_block(uc_engine *uc, uint64_t address, uint32_t size, void *) {
uc_emu_stop(uc); uc_emu_stop(uc);
return; return;
} }
note_code_page(address);
// Every A64 instruction is four bytes. // Every A64 instruction is four bytes.
m.pending = size >= 4 ? size / 4 : 1; m.pending = size >= 4 ? size / 4 : 1;
if (const uint8_t *p = host_ptr(address + size - 4, 4)) { if (const uint8_t *p = host_ptr(address + size - 4, 4)) {
@@ -288,8 +342,9 @@ bool start_cpu0(EmuState *state) {
// IRAM, DRAM and TZRAM are the same host memory the BPMP engine maps, so // 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 // a stub the BPMP copies into DRAM and the mailbox both cores poll are one
// set of bytes. CPU0's engine is new on every release, so it cannot hold // set of bytes. Stores from the other engine bypass this one's self-
// stale translations of code the BPMP has rewritten since the last boot. // 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); err = uc_mem_map_ptr(uc, IRAM_BASE, IRAM_SIZE, UC_PROT_ALL, state->iram_ptr);
if (err == UC_ERR_OK) if (err == UC_ERR_OK)
err = uc_mem_map_ptr(uc, DRAM_BASE, DRAM_WINDOW_SIZE, UC_PROT_ALL, err = uc_mem_map_ptr(uc, DRAM_BASE, DRAM_WINDOW_SIZE, UC_PROT_ALL,
@@ -330,6 +385,10 @@ bool start_cpu0(EmuState *state) {
m.bus_accesses = 0; m.bus_accesses = 0;
m.cpu0 = Cpu0::Running; m.cpu0 = Cpu0::Running;
m.boots++; 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 " printf("[ccplex] CPU0 released: AArch64 EL3, MMU off, entry 0x%08llX "
"(boot #%u)\n", (unsigned long long)entry, m.boots); "(boot #%u)\n", (unsigned long long)entry, m.boots);
fflush(stdout); fflush(stdout);
@@ -352,6 +411,14 @@ void try_release(EmuState *state) {
start_cpu0(state); 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 } // namespace
// ========================================================================== // ==========================================================================
@@ -375,10 +442,10 @@ void ccplex_reset(EmuState *state) {
void ccplex_car_write(EmuState *state, uint32_t offset, uint32_t val) { void ccplex_car_write(EmuState *state, uint32_t offset, uint32_t val) {
switch (offset) { switch (offset) {
case CAR_CCLK_BURST_POLICY: m.cclk_burst = val; break; case CAR_CCLK_BURST_POLICY: m.cclk_burst = val; maybe_release(state); break;
case CAR_PLLX_BASE: m.pllx_base = val; break; case CAR_PLLX_BASE: m.pllx_base = val; maybe_release(state); break;
case CAR_CLK_OUT_ENB_V: m.clk_enb_v = val; 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; break; case CAR_CLK_ENB_V_SET: m.clk_enb_v |= val; maybe_release(state); break;
case CAR_CLK_ENB_V_CLR: case CAR_CLK_ENB_V_CLR:
m.clk_enb_v &= ~val; m.clk_enb_v &= ~val;
if ((val & (1u << CLK_V_CPUG)) && m.cpu0 == Cpu0::Running) { if ((val & (1u << CLK_V_CPUG)) && m.cpu0 == Cpu0::Running) {
@@ -430,24 +497,23 @@ uint32_t ccplex_sb_read(uint32_t offset) {
} }
void ccplex_sb_write(EmuState *state, uint32_t offset, uint32_t val) { void ccplex_sb_write(EmuState *state, uint32_t offset, uint32_t val) {
(void)state;
switch (offset) { switch (offset) {
case SB_CSR: case SB_CSR:
// NS_RST_VEC_WR_DIS (bit 1) is sticky until reset. It only locks out // NS_RST_VEC_WR_DIS (bit 1) is sticky until reset. It only locks out
// non-secure writers; the BPMP is secure, so the vector stays writable // non-secure writers, and the vector write below does not check it.
// from here either way.
m.sb_csr |= val; m.sb_csr |= val;
break; break;
case SB_AA64_RESET_LOW: m.sb_rst_lo = 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; break; case SB_AA64_RESET_HIGH: m.sb_rst_hi = val & 0xFFF; maybe_release(state); break;
default: break; default: break;
} }
} }
void ccplex_partition_changed(EmuState *state, int part, bool on) { void ccplex_partition_changed(EmuState *state, int part, bool on) {
(void)state; if (on) {
if (on) maybe_release(state);
return; return;
}
if (part == POWER_RAIL_CRAIL) stop_cpu0("CRAIL partition powergated"); if (part == POWER_RAIL_CRAIL) stop_cpu0("CRAIL partition powergated");
if (part == POWER_RAIL_C0NC) stop_cpu0("C0NC partition powergated"); if (part == POWER_RAIL_C0NC) stop_cpu0("C0NC partition powergated");
if (part == POWER_RAIL_CE0) stop_cpu0("CE0 partition powergated"); if (part == POWER_RAIL_CE0) stop_cpu0("CE0 partition powergated");
@@ -456,14 +522,20 @@ void ccplex_partition_changed(EmuState *state, int part, bool on) {
void ccplex_rail_changed(EmuState *state) { void ccplex_rail_changed(EmuState *state) {
if (m.cpu0 != Cpu0::Off && !cpu_rail_on(state)) if (m.cpu0 != Cpu0::Off && !cpu_rail_on(state))
stop_cpu0("CPU rail switched off"); 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) { void ccplex_bus_tick(EmuState *state) {
m.ns += NS_PER_BUS_ACCESS; m.ns += NS_PER_BUS_ACCESS;
m.bus_accesses++; m.bus_accesses++;
state->emu_usec = m.ns / 1000; 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; } bool ccplex_cpu0_running() { return m.cpu0 == Cpu0::Running && m.uc; }
void ccplex_run(EmuState *state, uint64_t until_us) { void ccplex_run(EmuState *state, uint64_t until_us) {
@@ -474,8 +546,12 @@ void ccplex_run(EmuState *state, uint64_t until_us) {
return; return;
// While CPU0 runs, it is the bus master and "now" is its clock: every // 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, not the // register model reads state->emu_usec, and must see CPU0's time - a
// BPMP's. Both are put back afterwards. // 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; uint64_t bpmp_usec = state->emu_usec;
BusMaster prev = g_bus_master; BusMaster prev = g_bus_master;
g_bus_master = BUS_CPU0; g_bus_master = BUS_CPU0;
@@ -483,7 +559,11 @@ void ccplex_run(EmuState *state, uint64_t until_us) {
m.target_ns = target; m.target_ns = target;
m.in_run = true; m.in_run = true;
uc_err err = uc_emu_start(m.uc, m.pc, 0, 0, 0); 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(); commit_pending();
uc_reg_read(m.uc, UC_ARM64_REG_PC, &m.pc); uc_reg_read(m.uc, UC_ARM64_REG_PC, &m.pc);
+7
View File
@@ -44,6 +44,13 @@ void ccplex_sb_write(EmuState *state, uint32_t offset, uint32_t val);
void ccplex_partition_changed(EmuState *state, int part, bool on); void ccplex_partition_changed(EmuState *state, int part, bool on);
void ccplex_rail_changed(EmuState *state); 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 // Called by the MMIO front-end for every access CPU0 makes: charges the bus
// latency to CPU0's clock before the access is dispatched. // latency to CPU0's clock before the access is dispatched.
void ccplex_bus_tick(EmuState *state); void ccplex_bus_tick(EmuState *state);
+26 -10
View File
@@ -132,17 +132,15 @@ void push_controller_ready() {
if (ev_stack.size() < 32) ev_stack.push_back(ev); 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) { void try_emit_pending_touch(EmuState *state) {
bool was_pending = state->tc_event_pending.exchange(false); EmuState::TouchEvent ev;
if (!was_pending) return; while (ev_stack.size() < 32 && state->touch_take(&ev)) {
uint8_t op = state->tc_event_op.load(); // pressure: a small non-zero value keeps z below the 500-palm-reject
uint16_t x = state->tc_x.load(); // threshold in touch.c (z = (pressure_lo|pressure_hi<<8) << 6 / (mod+0x40)).
uint16_t y = state->tc_y.load(); uint16_t pressure = (ev.op == FTS4_EV_MULTI_TOUCH_LEAVE) ? 0 : 0x10;
// pressure: a small non-zero value keeps z below the 500-palm-reject threshold push_event(ev.op, state->tc_finger_id, ev.x, ev.y, pressure);
// 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);
} }
// Pop oldest event into 8-byte buffer; on empty, return NO_EVENT. // Pop oldest event into 8-byte buffer; on empty, return NO_EVENT.
@@ -307,6 +305,24 @@ uint32_t pull_rx_word() {
} // namespace } // 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 i2c3_read(EmuState *state, uint64_t addr) {
uint32_t offset = (uint32_t)(addr - I2C3_BASE); uint32_t offset = (uint32_t)(addr - I2C3_BASE);
switch (offset) { switch (offset) {
+4
View File
@@ -12,4 +12,8 @@ struct EmuState;
uint32_t i2c3_read(EmuState *state, uint64_t addr); uint32_t i2c3_read(EmuState *state, uint64_t addr);
void i2c3_write(EmuState *state, uint64_t addr, uint32_t val); 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 #endif
+13 -9
View File
@@ -67,7 +67,10 @@ constexpr uint64_t I2C2_BASE = 0x7000C400; // GEN2_I2C, Rohm BH1730 ALS at slave
constexpr uint64_t I2C2_SIZE = 0x100; constexpr uint64_t I2C2_SIZE = 0x100;
constexpr uint64_t I2C3_BASE = 0x7000C500; // GEN3_I2C, used by STMFTS touchscreen at slave 0x49 constexpr uint64_t I2C3_BASE = 0x7000C500; // GEN3_I2C, used by STMFTS touchscreen at slave 0x49
constexpr uint64_t I2C5_BASE = 0x7000D000; constexpr uint64_t I2C5_BASE = 0x7000D000;
constexpr uint64_t I2C_SIZE = 0x1000; 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; constexpr uint64_t I2C3_SIZE = 0x100;
// PWM // PWM
@@ -203,12 +206,13 @@ constexpr uint64_t XUSB_PADCTL_SIZE = 0x1000;
// bdk's MMU table defines DRAM and IRAM entries only and leaves the fallback // bdk's MMU table defines DRAM and IRAM entries only and leaves the fallback
// entry RWX, so PCIe space is reachable and uncached. // entry RWX, so PCIe space is reachable and uncached.
// //
// Only the windows a payload actually touches are mapped: 16 KiB covering // These are MMIO windows (callbacks, no backing memory), so they are mapped
// both root ports plus PADS and AFI, 128 KiB of configuration aperture (bus // at their architectural sizes: the whole 256 MiB configuration aperture -
// 0 and bus 1 are all that exist), and one 4 KiB page of downstream memory // extended registers sit at AXI[27:24] - and the non-prefetchable memory
// for the endpoint's BAR0 register window. Mapping the architectural sizes // window to the end of PCIE_A2, wherever software places the endpoint's BARs.
// (256 MiB of config, 208 MiB of memory) would cost the host gigabytes for // A smaller map left a CPU0 access to, say, config offset 0x100 or BAR0 +
// address ranges nothing ever reads. // 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_RP0_BASE = 0x01000000; // root port 0 registers
constexpr uint64_t PCIE_RP1_BASE = 0x01001000; // root port 1 registers constexpr uint64_t PCIE_RP1_BASE = 0x01001000; // root port 1 registers
constexpr uint64_t PCIE_PADS_BASE = 0x01003000; constexpr uint64_t PCIE_PADS_BASE = 0x01003000;
@@ -216,9 +220,9 @@ constexpr uint64_t PCIE_AFI_BASE = 0x01003800;
constexpr uint64_t PCIE_BLOCK_BASE = 0x01000000; constexpr uint64_t PCIE_BLOCK_BASE = 0x01000000;
constexpr uint64_t PCIE_BLOCK_SIZE = 0x4000; constexpr uint64_t PCIE_BLOCK_SIZE = 0x4000;
constexpr uint64_t PCIE_CS_BASE = 0x02000000; // type-1 extended config 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_CS_MODEL_SIZE = 0x10000000; // all of it: 256 MiB
constexpr uint64_t PCIE_MEM_BASE = 0x13000000; // non-prefetchable window constexpr uint64_t PCIE_MEM_BASE = 0x13000000; // non-prefetchable window
constexpr uint64_t PCIE_MEM_MODEL_SIZE = 0x1000; 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) // TSEC (Falcon control regs are in the 0x1000–0x11FF window within TSEC_BASE)
constexpr uint64_t TSEC_BASE = 0x54500000; constexpr uint64_t TSEC_BASE = 0x54500000;
+622 -227
View File
File diff suppressed because it is too large. Load diff
+7 -3
View File
@@ -44,13 +44,17 @@ void mmio_bus_write(EmuState *state, uint64_t addr, unsigned size,
uint64_t value); uint64_t value);
// Reset the per-run peripheral state that a soft reboot must not carry over. // Reset the per-run peripheral state that a soft reboot must not carry over.
void mmio_soft_reset(EmuState *state); // `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`). // PMC power-partition state (APBDEV_PMC_PWRGATE_STATUS bit `part`).
bool pmc_partition_on(int part); bool pmc_partition_on(int part);
// FLOW_CTLR_RAM_REPAIR has been requested (the fast cluster's RAMs repaired). // APBDEV_PMC_SECURE_SCRATCH`n` (n = 0..7), written by hardware: the SE
bool flow_ram_repair_done(); // 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 // 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. // its EN pin driven by MAX77620 GPIO5), the MAX77812 M4 phase on Mariko.
+59 -10
View File
@@ -1,4 +1,5 @@
#include "pcie.h" #include "pcie.h"
#include "ccplex.h"
#include <cstdio> #include <cstdio>
#include <cstring> #include <cstring>
@@ -115,6 +116,7 @@ static constexpr uint64_t T_REFCLK_STABLE_US = 10000; // refclk -> PERST# high
// stub reads straight after the BPMP has cycled the AFI reset - xbar X4_X1 in // 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. // 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_CONFIG_RESET = 0x07FF4020;
static constexpr uint32_t MSELECT_CFG_ENABLE_PCIE_APERTURE = 1u << 5;
static constexpr uint32_t AFI_PCIE_CONFIG_RESET = 0x00103025; static constexpr uint32_t AFI_PCIE_CONFIG_RESET = 0x00103025;
// Broadcom identity (brcm_hw_ids.h, brcmfmac/pcie.c). // Broadcom identity (brcm_hw_ids.h, brcmfmac/pcie.c).
@@ -227,9 +229,8 @@ bool radio_core_alive(EmuState *state) {
// hardware this is the difference between a register read and a dead // hardware this is the difference between a register read and a dead
// console, so it is checked before every single access rather than folded // console, so it is checked before every single access rather than folded
// into the link-training preconditions. // into the link-training preconditions.
// Everything this emulator executes is BPMP code - Unicorn runs the ARM7, // The BPMP cannot reach PCIe on real silicon; only a CPU-complex master can
// there is no CCPLEX model - and the BPMP cannot reach PCIe on real silicon. // (CPU0, t210/ccplex.cpp). Measured on an Erista and a Mariko: with clocks, resets, power and PLLE all
// 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 // 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 // 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 // not an AHB slave; ch.16: MSELECT is CPU-complex hardware), and so does the
@@ -272,6 +273,21 @@ void mselect_complain(uint64_t addr) {
fflush(stdout); 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) { const char *link_blocked(EmuState *state, int port) {
if (!mselect_up()) return "MSELECT still in reset"; if (!mselect_up()) return "MSELECT still in reset";
if (pcie.powergated) return "PCIE partition still gated"; if (pcie.powergated) return "PCIE partition still gated";
@@ -394,7 +410,8 @@ void pcie_wl_reg_on(EmuState *state, bool level) {
// ---- clock and reset controller ----------------------------------------- // ---- 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) { switch (offset) {
case CAR_RST_DEVICES_U: pcie.rst_u = val; break; case CAR_RST_DEVICES_U: pcie.rst_u = val; break;
case CAR_CLK_OUT_ENB_U: pcie.enb_u = val; break; case CAR_CLK_OUT_ENB_U: pcie.enb_u = val; break;
@@ -409,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_DEVICES_V: pcie.rst_v = val; break;
case CAR_RST_DEV_V_SET: 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_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_SET: pcie.rst_w |= val; break;
case CAR_RST_DEV_W_CLR: 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_PLLE_BASE: pcie.plle = (val & PLLE_BASE_ENABLE) != 0; break;
case CAR_PLLREFE_BASE: pcie.pllrefe = (val & PLLREFE_BASE_ENABLE) != 0; break; case CAR_PLLREFE_BASE: pcie.pllrefe = (val & PLLREFE_BASE_ENABLE) != 0; break;
default: 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 // PLLE and PLLREFE do not follow the generic "ENABLE bit 30, LOCK bit 27 in
@@ -467,6 +489,9 @@ uint32_t mselect_read(EmuState *state, uint64_t addr) {
void mselect_write(EmuState *state, uint64_t addr, uint32_t val) { void mselect_write(EmuState *state, uint64_t addr, uint32_t val) {
(void)state; (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; uint32_t off = (uint32_t)(addr - MSELECT_BASE) & 0xFFC;
// Held in reset, MSELECT latches nothing - which is exactly the state a // 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. // payload is in when it thinks it configured the fabric and did not.
@@ -635,6 +660,8 @@ uint32_t pcie_read(EmuState *state, uint64_t addr) {
mselect_complain(addr); mselect_complain(addr);
return 0xFFFFFFFF; return 0xFFFFFFFF;
} }
if (!pcie_aperture_enabled(addr))
return 0xFFFFFFFF;
// Root port register windows, 0x01000000 and 0x01001000. // Root port register windows, 0x01000000 and 0x01001000.
if (addr >= PCIE_RP0_BASE && addr < PCIE_RP0_BASE + 0x2000) { if (addr >= PCIE_RP0_BASE && addr < PCIE_RP0_BASE + 0x2000) {
@@ -679,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) { if (addr >= PCIE_CS_BASE && addr < PCIE_CS_BASE + PCIE_CS_MODEL_SIZE) {
uint32_t a = (uint32_t)(addr - PCIE_CS_BASE); uint32_t a = (uint32_t)(addr - PCIE_CS_BASE);
uint32_t bus = (a >> 16) & 0xFF, dev = (a >> 11) & 0x1F; 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); link_update(state, 1);
if (bus != 1 || dev != 0 || fn != 0 || !ep_reachable(state)) if (bus != 1 || dev != 0 || fn != 0 || !ep_reachable(state))
return 0xFFFFFFFF; // unsupported request -> all ones return 0xFFFFFFFF; // unsupported request -> all ones
if (reg >= sizeof(pcie.ep))
return 0; // no extended capabilities
return pcie.ep[reg / 4]; return pcie.ep[reg / 4];
} }
@@ -695,13 +726,24 @@ uint32_t pcie_read(EmuState *state, uint64_t addr) {
return 0xFFFFFFFF; return 0xFFFFFFFF;
if (!(pcie.ep[0x04 / 4] & 0x2)) // MEM space disabled if (!(pcie.ep[0x04 / 4] & 0x2)) // MEM space disabled
return 0xFFFFFFFF; 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; return 0xFFFFFFFF;
if (!radio_core_alive(state)) if (!radio_core_alive(state))
return 0xFFFFFFFF; // front-end answers, the die does not 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 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) if (bp == BRCM_SI_ENUM_BASE)
return BRCM_4356_CHIPID; return BRCM_4356_CHIPID;
return 0; return 0;
@@ -718,10 +760,15 @@ void pcie_write(EmuState *state, uint64_t addr, uint32_t val) {
mselect_complain(addr); mselect_complain(addr);
return; return;
} }
if (!pcie_aperture_enabled(addr))
return;
if (addr >= PCIE_RP0_BASE && addr < PCIE_RP0_BASE + 0x2000) { if (addr >= PCIE_RP0_BASE && addr < PCIE_RP0_BASE + 0x2000) {
int port = (addr >= PCIE_RP1_BASE) ? 1 : 0; 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; return;
} }
@@ -738,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) { if (addr >= PCIE_CS_BASE && addr < PCIE_CS_BASE + PCIE_CS_MODEL_SIZE) {
uint32_t a = (uint32_t)(addr - PCIE_CS_BASE); uint32_t a = (uint32_t)(addr - PCIE_CS_BASE);
uint32_t bus = (a >> 16) & 0xFF, dev = (a >> 11) & 0x1F; 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;
if (bus != 1 || dev != 0 || fn != 0 || !ep_reachable(state)) uint32_t reg = ((a >> 16) & 0xF00) | (a & 0xFC);
if (bus != 1 || dev != 0 || fn != 0 || !ep_reachable(state) ||
reg >= sizeof(pcie.ep))
return; return;
switch (reg) { switch (reg) {
case 0x04: // command: only the low half is RW case 0x04: // command: only the low half is RW
+11 -8
View File
@@ -15,17 +15,20 @@ struct EmuState;
* (0x02000000), the endpoint's BAR0 backplane window, and the UPHY PLL P0 * (0x02000000), the endpoint's BAR0 backplane window, and the UPHY PLL P0
* calibration/lock state machine in the XUSB pad controller. * calibration/lock state machine in the XUSB pad controller.
* *
* The link only trains when the payload has satisfied every precondition * The link only trains once the payload has satisfied the preconditions
* real silicon and the CYW4356 datasheet impose -- power partition, clocks, * this model checks -- power partition, AFI clock, resets, PLLE, UPHY, lane
* resets, PLLE, UPHY, lane mux, IDDQ, and the refclk/PERST#/POR timing of * mux, IDDQ, and the refclk/PERST#/POR timing of Table 62. A payload that
* Table 62. A payload that skips one gets a link that stays down and a * skips one gets a link that stays down and a `[pcie]` line on stdout naming
* `[pcie]` line on stdout naming what it missed. * 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); void pcie_reset(EmuState *state);
// 0x01000000..0x01003FFF (root ports, PADS, AFI), 0x02000000 config // 0x01000000..0x01003FFF (root ports, PADS, AFI), the 0x02000000 config
// aperture, and the 0x13000000 BAR0 memory window. // aperture and the 0x13000000 non-prefetchable memory window.
uint32_t pcie_read(EmuState *state, uint64_t addr); uint32_t pcie_read(EmuState *state, uint64_t addr);
void pcie_write(EmuState *state, uint64_t addr, uint32_t val); void pcie_write(EmuState *state, uint64_t addr, uint32_t val);
@@ -40,7 +43,7 @@ void padctl_write(EmuState *state, uint64_t addr, uint32_t val);
// Clock-and-reset forwarding. The PCIe model needs PLLE/PLLREFE lock and the // 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/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. // 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); 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 // MSELECT clocked out of reset (RST_DEV_V bit 3 clear). The CCPLEX needs it
+258 -145
View File
@@ -1,12 +1,14 @@
#include "se_engine.h" #include "se_engine.h"
#include "../emu_state.h" #include "../emu_state.h"
#include "memory_map.h" #include "memory_map.h"
#include "mmio.h"
#include <unicorn/unicorn.h> #include <unicorn/unicorn.h>
#include <cstdio> #include <cstdio>
#include <cstring> #include <cstring>
#include <cstdlib> #include <cstdlib>
#include <vector>
// ============================================================================= // =============================================================================
// Tegra X1 Security Engine (SE) emulation // 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)))) #define ROR32(x, n) (((x) >> (n)) | ((x) << (32 - (n))))
static void compute(const uint8_t *msg, uint32_t len, uint8_t out[32]) { static const uint32_t H0[8] = {
uint32_t H[8] = {
0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a, 0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,
0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19, 0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19,
}; };
// Total padded length: msg + 0x80 + zeros + 8-byte length, multiple of 64
uint64_t bitlen = (uint64_t)len * 8; // Compress `nblocks` 64-byte blocks into the running state H.
uint32_t padded_len = ((len + 1 + 8 + 63) / 64) * 64; static void blocks(uint32_t H[8], const uint8_t *p, size_t nblocks) {
uint8_t *buf = (uint8_t*)std::calloc(1, padded_len); for (size_t blk = 0; blk < nblocks; blk++, p += 64) {
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) {
uint32_t W[64]; uint32_t W[64];
for (int i = 0; i < 16; i++) { for (int i = 0; i < 16; i++) {
W[i] = ((uint32_t)buf[off + i*4 + 0] << 24) | W[i] = ((uint32_t)p[i*4 + 0] << 24) |
((uint32_t)buf[off + i*4 + 1] << 16) | ((uint32_t)p[i*4 + 1] << 16) |
((uint32_t)buf[off + i*4 + 2] << 8) | ((uint32_t)p[i*4 + 2] << 8) |
((uint32_t)buf[off + i*4 + 3]); ((uint32_t)p[i*4 + 3]);
} }
for (int i = 16; i < 64; i++) { for (int i = 16; i < 64; i++) {
uint32_t s0 = ROR32(W[i-15],7) ^ ROR32(W[i-15],18) ^ (W[i-15] >> 3); 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[0]+=a; H[1]+=b; H[2]+=c; H[3]+=d;
H[4]+=e; H[5]+=f; H[6]+=g; H[7]+=h; 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 #undef ROR32
@@ -249,8 +256,33 @@ constexpr uint32_t SE_RNG_CONFIG_REG = 0x340;
constexpr uint32_t SE_HASH_RESULT_REG = 0x030; // 16 dwords constexpr uint32_t SE_HASH_RESULT_REG = 0x030; // 16 dwords
constexpr uint32_t SE_STATUS_REG = 0x800; constexpr uint32_t SE_STATUS_REG = 0x800;
constexpr uint32_t SE_ERR_STATUS_REG = 0x804; 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_INT_OP_DONE = 1u << 4; 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 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_NOP = 0;
constexpr uint32_t ALG_AES_DEC = 1; constexpr uint32_t ALG_AES_DEC = 1;
@@ -312,106 +344,141 @@ static uint32_t reg_err_status = 0;
static uint32_t reg_rng_config = 0; static uint32_t reg_rng_config = 0;
static uint32_t spare_regs[256] = {0}; // catch-all for less critical regs static uint32_t spare_regs[256] = {0}; // catch-all for less critical regs
// 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). // LL descriptor: { num, addr, size }. Hekate often uses num=0 (single descriptor).
struct LLDesc { uint32_t num, addr, size; }; struct LLDesc { uint32_t num, addr, size; };
static bool read_ll(uc_engine *uc, uint32_t ll_addr, LLDesc *out) { static bool read_ll(uc_engine *uc, uint32_t ll_addr, LLDesc *out) {
if (!ll_addr) return false; if (!ll_addr) return false;
if (uc_mem_read(uc, ll_addr, out, sizeof(LLDesc)) != UC_ERR_OK) return false; if (uc_mem_read(uc, ll_addr, out, sizeof(LLDesc)) != UC_ERR_OK) return false;
out->size &= LL_SIZE_MASK;
return true; 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, static void run_aes_blocks(uint32_t slot, bool encrypt,
const uint8_t *in, uint8_t *out, size_t blocks, const uint8_t *in, uint8_t *out, size_t blocks,
uint32_t xor_pos, uint32_t input_sel, uint32_t xor_pos, uint32_t input_sel,
uint32_t vctram_sel, uint32_t iv_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]; uint8_t rk[176];
aes::key_expand(ks_table[slot].key, rk); aes::key_expand(ks_table[slot].key, rk);
// Pick which IV to use for chaining. Hekate typically uses ORIGINAL_IV for uint8_t v[16];
// CBC starts and switches to UPDATED_IV mid-CMAC; we honour that. std::memcpy(v, iv_sel == IV_UPDATED ? ks_table[slot].iv_upd
uint8_t chain[16]; : ks_table[slot].iv_orig, 16);
if (iv_sel == IV_UPDATED) std::memcpy(chain, ks_table[slot].iv_upd, 16); uint8_t aes_out[16] = {0};
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);
for (size_t i = 0; i < blocks; ++i) { for (size_t i = 0; i < blocks; ++i) {
uint8_t in_block[16]; const uint8_t *mem = in + i * 16;
uint8_t out_block[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) { if (xor_pos == XOR_TOP) xor16(a, v);
// CTR mode input is the linear counter (big-endian 128-bit), per-block. if (encrypt) aes::encrypt_block(a, aes_out, rk);
// Our linear_ctr[] is stored as 4 dwords little-endian; assemble. else aes::decrypt_block(a, aes_out, rk);
uint8_t ctr_be[16];
for (int j = 0; j < 4; ++j) { uint8_t *o = out + i * 16;
uint32_t w = linear_ctr[j]; std::memcpy(o, aes_out, 16);
ctr_be[j*4 + 0] = (w >> 0) & 0xFF; // After the core: CBC decrypt XORs the vector; OFB and CTR XOR the data.
ctr_be[j*4 + 1] = (w >> 8) & 0xFF; if (xor_pos == XOR_BOTTOM) xor16(o, input_sel == INPUT_MEMORY ? v : mem);
ctr_be[j*4 + 2] = (w >> 16) & 0xFF;
ctr_be[j*4 + 3] = (w >> 24) & 0xFF; if (input_sel == INPUT_AESOUT || vctram_sel == VCTRAM_AESOUT)
} std::memcpy(v, aes_out, 16);
std::memcpy(in_block, ctr_be, 16); else if (vctram_sel == VCTRAM_PREVMEM)
} else if (input_sel == INPUT_AESOUT) { std::memcpy(v, mem, 16);
// Re-feeding previous AES output (used in some chained constructions).
std::memcpy(in_block, prev_in, 16); if (input_sel == INPUT_LNR_CTR) ctr_add(ctr_step);
} else {
std::memcpy(in_block, in + i*16, 16);
} }
// VCTRAM source: the value XORed at XOR_TOP / XOR_BOTTOM. if (hash_mode) std::memcpy(hash_result, aes_out, 16);
uint8_t vctram[16]; bool chained = input_sel == INPUT_AESOUT || vctram_sel == VCTRAM_AESOUT ||
if (vctram_sel == VCTRAM_AESOUT) std::memcpy(vctram, prev_in, 16); vctram_sel == VCTRAM_PREVMEM;
else if (vctram_sel == VCTRAM_PREVMEM) std::memcpy(vctram, (i==0)? chain : (in + (i-1)*16), 16); if (chained && blocks) std::memcpy(ks_table[slot].iv_upd, v, 16);
else std::memcpy(vctram, chain, 16);
if (xor_pos == XOR_TOP) {
for (int j = 0; j < 16; ++j) in_block[j] ^= vctram[j];
} }
if (encrypt) aes::encrypt_block(in_block, out_block, rk); // SHA-256, one-shot or in parts (bdk _se_sha_hash_256). SHA_INIT_HASH starts
else aes::decrypt_block(in_block, out_block, rk); // 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;
if (xor_pos == XOR_BOTTOM) { uint32_t H[8];
// Output XOR with chain (CTR keystream XOR plaintext, etc.) if (init) std::memcpy(H, sha256::H0, sizeof(H));
const uint8_t *xb = (input_sel == INPUT_LNR_CTR) else std::memcpy(H, hash_result, sizeof(H));
? (in + i*16) // CTR: XOR with plaintext from memory
: vctram;
for (int j = 0; j < 16; ++j) out_block[j] ^= xb[j];
}
if (out) std::memcpy(out + i*16, out_block, 16); 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));
// Advance chain for next block. std::printf("[se] SHA-256 %s%s over %u bytes @0x%X -> %08X...\n",
if (xor_pos == XOR_BOTTOM && input_sel != INPUT_LNR_CTR) { init ? "" : "continued ", last ? "final" : "part",
// CBC encrypt: chain = ciphertext = out_block in_ll.size, in_ll.addr, H[0]);
std::memcpy(chain, out_block, 16); reg_int_status |= SE_INT_OP_DONE;
} 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);
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;
}
}
}
if (hash_mode) {
// For HASH paths the final cipher block is exposed via SE_HASH_RESULT_REG.
std::memcpy(hash_result, prev_in, 16);
}
// Save updated IV (chain) for next call's IV_UPDATED.
std::memcpy(ks_table[slot].iv_upd, chain, 16);
} }
static void op_start(EmuState *state) { static void op_start(EmuState *state) {
@@ -423,37 +490,21 @@ static void op_start(EmuState *state) {
bool dec = (dec_alg == ALG_AES_DEC) && (enc_alg == ALG_NOP); bool dec = (dec_alg == ALG_AES_DEC) && (enc_alg == ALG_NOP);
bool enc = (enc_alg == ALG_AES_ENC) && (dec_alg == ALG_NOP); bool enc = (enc_alg == ALG_AES_ENC) && (dec_alg == ALG_NOP);
// ---- SHA-256 path ---- if (enc_alg == ALG_SHA && dst_kind == DST_HASHREG && enc_mode == MODE_SHA256) {
// ALG_SHA=3, MODE_SHA256=5, DST=DST_HASHREG. Driver flow: writes sha_op(state);
// 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; return;
} }
std::vector<uint8_t> buf(in_ll.size, 0);
uc_mem_read(state->uc, in_ll.addr, buf.data(), in_ll.size); // RNG into the secure random key: the start of a context save. The key is
uint8_t digest[32]; // fixed rather than random so runs stay reproducible.
sha256::compute(buf.data(), in_ll.size, digest); if (enc_alg == ALG_RNG && dst_kind == DST_SRK) {
// Pack into HASH_RESULT_REG as 8 big-endian dwords (driver byteswaps). for (int i = 0; i < 16; ++i) srk[i] = (uint8_t)(0xA5 ^ (i * 0x1D));
for (int i = 0; i < 8; i++) { std::memset(ctx_chain, 0, sizeof(ctx_chain));
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]);
reg_int_status |= SE_INT_OP_DONE; reg_int_status |= SE_INT_OP_DONE;
return; return;
} }
if (dst_kind == 4 /* DST_RSAREG */) { if (dst_kind == DST_RSAREG) {
// RSA not implemented — leave output zero. // RSA not implemented — leave output zero.
reg_int_status |= SE_INT_OP_DONE; reg_int_status |= SE_INT_OP_DONE;
return; return;
@@ -470,46 +521,51 @@ static void op_start(EmuState *state) {
uint32_t iv_sel = (reg_crypto_config >> 7) & 0x1; uint32_t iv_sel = (reg_crypto_config >> 7) & 0x1;
uint32_t core_sel = (reg_crypto_config >> 8) & 0x1; uint32_t core_sel = (reg_crypto_config >> 8) & 0x1;
bool hash_en = (reg_crypto_config >> 0) & 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; uint32_t key_index = (reg_crypto_config >> 24) & 0xF;
bool encrypt = (core_sel == CORE_ENCRYPT); 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; uint32_t total_bytes = blocks * 16;
// Read input via IN_LL. std::vector<uint8_t> in_buf(total_bytes, 0), out_buf(total_bytes, 0);
std::vector<uint8_t> in_buf, out_buf;
in_buf.resize(total_bytes, 0);
out_buf.resize(total_bytes, 0);
LLDesc in_ll{}, out_ll{}; LLDesc in_ll{}, out_ll{};
bool got_in = read_ll(state->uc, reg_in_ll_addr, &in_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); 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; 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, run_aes_blocks(key_index, encrypt, in_buf.data(), out_buf.data(), blocks,
xor_pos, input_sel, vctram_sel, iv_sel, xor_pos, input_sel, vctram_sel, iv_sel, ctr_step, hash_en);
(input_sel == INPUT_LNR_CTR) || ctr_cnt, hash_en);
if (dst_kind == DST_MEMORY) { if (dst_kind == DST_MEMORY) {
if (got_out && out_ll.size) { if (got_out && out_ll.size) {
uint32_t copy = (out_ll.size < total_bytes) ? out_ll.size : total_bytes; 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) { } 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 dst_slot = (reg_keytable_dst >> 8) & 0xF;
uint32_t word_quad = reg_keytable_dst & 0x3; Keyslot &k = ks_table[dst_slot];
uint8_t *target = (word_quad == 1) uint8_t *target[4] = {k.key, k.key + 16, k.iv_orig, k.iv_upd};
? ks_table[dst_slot].key + 16 std::memcpy(target[reg_keytable_dst & 0x3], out_buf.data(), 16);
: ks_table[dst_slot].key + 0;
std::memcpy(target, out_buf.data(), 16);
} }
// DST_HASHREG: hash_result is already populated by run_aes_blocks. // DST_HASHREG: hash_result is already populated by run_aes_blocks.
@@ -522,6 +578,40 @@ static void op_start(EmuState *state) {
got_in ? in_ll.addr : 0, got_out ? out_ll.addr : 0); 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 // 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) { static void keytable_write(uint32_t addr, uint32_t val) {
uint32_t slot = (addr >> 4) & 0xF; uint32_t slot = (addr >> 4) & 0xF;
@@ -541,14 +631,19 @@ static void keytable_write(uint32_t addr, uint32_t val) {
// Lockpick's _derive_bis_keys may produce wrong values when our SE engine // 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 // doesn't faithfully model some part of the chain; the override is a
// pragmatic shortcut that lets the BIS XTS layer succeed regardless. // 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 (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::memcpy(ks_table[slot].key, bis_override_keys[slot], 16);
std::printf("[se] slot %u BIS key overridden from prod.keys:", slot); 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]); for (int i = 0; i < 16; ++i) std::printf(" %02X", ks_table[slot].key[i]);
std::printf("\n"); std::printf("\n");
} else { } else if (!clear) {
std::printf("[se] slot %u key loaded (derived):", slot); std::printf("[se] slot %u key loaded:", slot);
for (int i = 0; i < 16; ++i) std::printf(" %02X", ks_table[slot].key[i]); for (int i = 0; i < 16; ++i) std::printf(" %02X", ks_table[slot].key[i]);
std::printf("\n"); std::printf("\n");
} }
@@ -574,8 +669,6 @@ static uint32_t keytable_read(uint32_t addr) {
} // namespace } // namespace
#include <vector>
uint32_t se_engine_read(EmuState *state, uint64_t addr) { uint32_t se_engine_read(EmuState *state, uint64_t addr) {
uint32_t off = (uint32_t)(addr - SE_BASE); uint32_t off = (uint32_t)(addr - SE_BASE);
if (off >= SE_HASH_RESULT_REG && off < SE_HASH_RESULT_REG + 16*4) { if (off >= SE_HASH_RESULT_REG && off < SE_HASH_RESULT_REG + 16*4) {
@@ -616,10 +709,12 @@ void se_engine_write(EmuState *state, uint64_t addr, uint32_t val) {
switch (off) { switch (off) {
case SE_OPERATION_REG: case SE_OPERATION_REG:
reg_op = val; reg_op = val;
// SE_OP_START runs the configured AES op; other op codes (RESTART_*, // SE_OP_START runs the configured op and CTX_SAVE saves context;
// CTX_SAVE, ABORT) just need OP_DONE so the driver's _se_wait() exits. // the others (RESTART_*) just need OP_DONE so _se_op_wait() exits.
if ((val & 0x7) == 1 /*SE_OP_START*/) { if ((val & 0x7) == SE_OP_START) {
op_start(state); op_start(state);
} else if ((val & 0x7) == SE_OP_CTX_SAVE) {
ctx_save(state);
} else if ((val & 0x7) != 0 /*not ABORT*/) { } else if ((val & 0x7) != 0 /*not ABORT*/) {
reg_int_status |= SE_INT_OP_DONE; reg_int_status |= SE_INT_OP_DONE;
} }
@@ -647,9 +742,27 @@ void se_engine_write(EmuState *state, uint64_t addr, uint32_t val) {
(void)state; (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]) { void se_engine_set_aes128_key(uint32_t slot, const uint8_t key[16]) {
if (slot >= 16) return; if (slot >= 16) return;
std::memcpy(ks_table[slot].key, key, 16); 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));
} }
// ---- prod.keys parser ------------------------------------------------------- // ---- prod.keys parser -------------------------------------------------------
+12 -7
View File
@@ -10,17 +10,18 @@ struct EmuState;
// operations against an emulated 16-slot keytable. // operations against an emulated 16-slot keytable.
// //
// Currently implemented: // Currently implemented:
// * AES-128 ECB encrypt/decrypt (single + multi-block, DMA via LL descriptors) // * AES-128 ECB, CBC, OFB and CTR, single and multi-block, with the IV
// * AES-128 CBC encrypt/decrypt // chained through UPDATED_IV the way bdk's partial-block path expects
// * AES-128 CTR mode // * AES-CMAC (HASH_ENABLE into SE_HASH_RESULT)
// * AES "unwrap" (decrypt and store result in destination keyslot) // * 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) // * Keyslot programming (CRYPTO_KEYTABLE_ADDR/DATA)
// * Pre-population of keyslots from a Switch prod.keys file // * Pre-population of keyslots from a Switch prod.keys file
// //
// Not implemented (returns zero / no-op): // Not implemented: RNG output, RSA, AES-192/256 key sizes. Those operations
// * AES-CMAC (HASH+VCTRAM_AESOUT path) // still complete (set OP_DONE) so a payload does not hang on them.
// * SHA / RNG / RSA
// Each unimplemented op still completes (sets OP_DONE) so the boot doesn't hang.
uint32_t se_engine_read (EmuState *state, uint64_t addr); uint32_t se_engine_read (EmuState *state, uint64_t addr);
void se_engine_write(EmuState *state, uint64_t addr, uint32_t val); 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. // AES, so this is enough.
void se_engine_set_aes128_key(uint32_t slot, const uint8_t key[16]); 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 // Parse a switch-style "prod.keys" file (lines of `name = hex_value`) and
// pre-populate the well-known bootrom-derived keyslots (KS_TSEC=12, // pre-populate the well-known bootrom-derived keyslots (KS_TSEC=12,
// KS_SECURE_BOOT=14, KS_TSEC_ROOT=13) so Lockpick / Hekate's derivation // KS_SECURE_BOOT=14, KS_TSEC_ROOT=13) so Lockpick / Hekate's derivation
+6
View File
@@ -27,6 +27,12 @@ expect 'powered: magic=50434945' 'CPU0 ran the blob and wrote the ma
expect 'el=0000000C' 'CPU0 came up at EL3' expect 'el=0000000C' 'CPU0 came up at EL3'
expect 'CPU0 stopped (held in reset)' 'RST_CPUG_CMPLX_SET stops the core' 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' 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. # 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) dt=$(sed -n 's/.*dt=\([0-9A-F]*\).*/\1/p' "$LOG" | head -1)
+3 -1
View File
@@ -7,7 +7,9 @@
# soon as the dump's last line appears (with a hard timeout behind it). # soon as the dump's last line appears (with a hard timeout behind it).
EMU=${1:-./rcm_emu} EMU=${1:-./rcm_emu}
BIN=${2:-build-hwtest/hwtest-rcm/build/hwtest.bin} BIN=${2:-build-hwtest/hwtest-rcm/build/hwtest.bin}
shift 2 2>/dev/null # 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} LOG=${LOG:-tests/hwtest/out.log}
LIMIT=${LIMIT:-300} LIMIT=${LIMIT:-300}