diff --git a/DESIGN.md b/DESIGN.md index e194859..38f5fa7 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -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: -- **AES-128 ECB, CBC, CTR, CMAC.** The compact public-domain TinyAES core - ([kokke/tiny-AES-c](https://github.com/kokke/tiny-AES-c)) drives one block - at a time, with chaining state taken from `IV_ORIGINAL` or `IV_UPDATED` per - slot and `xor_pos` from `CRYPTO_CONFIG`. -- **SHA-256.** Implemented because the TE function `save_process_header` - validates the save container hash. Without it, `readsave()` returns - `Error: Save header is invalid!`. Oneshot only: one IN_LL buffer at a time, - written into the `HASH_RESULT` registers as 8 big-endian dwords (the BDK - driver byte-swaps on read). -- **DST_KEYTABLE unwrap path.** When the destination is another keyslot, the - result of a single block is written into the destination `KEYS_0_3` or - `KEYS_4_7` register pair. +- **AES-128 ECB, CBC, OFB, CTR, CMAC.** The compact public-domain TinyAES + core ([kokke/tiny-AES-c](https://github.com/kokke/tiny-AES-c)) drives one + block at a time through the SE's datapath: `INPUT_SEL` picks memory, the + previous AES output (OFB) or the linear counter (CTR); `XOR_POS` puts the + vector RAM before the core (CBC encrypt) or the vector / the memory data + after it (CBC decrypt, OFB, CTR); `VCTRAM_SEL` says what the vector becomes + next. The vector starts from the slot's `IV_ORIGINAL` or `IV_UPDATED`, and + a chaining mode leaves its final value in `IV_UPDATED`, which is how bdk + continues a chain into a trailing partial block and feeds the last block of + a CMAC. Checked against OpenSSL for every mode bdk uses, including + multi-block CMAC and partial blocks. +- **SHA-256**, one-shot and in parts. `SHA_INIT_HASH` starts from the + standard state, `SHA_CONTINUE` from the one the last part left in + `HASH_RESULT` (8 big-endian dwords; the BDK driver byte-swaps on read), and + the part is padded only when `SHA_MSG_LEFT` says it is the last. + Implemented because the TE function `save_process_header` validates the + save container hash. +- **DST_KEYTABLE unwrap path.** The result of a single block is written into + the destination slot's selected word quad. +- **Context save** (`SE_OP_CTX_SAVE`), as bdk's `se_aes_ctx_get_keys()` uses + it to read keyslots back: an RNG op seeds a secure random key (fixed, for + reproducibility), each saved keyslot quad is written out encrypted under it + in one CBC chain, and saving the SRK deposits it in PMC `SECURE_SCRATCH4..7` + for the driver to decrypt with. - **`--prod-keys` BIS override.** When Lockpick writes the last word of a derived BIS (Boot Image Storage) key into slots 0..5, the value from the user-supplied key file is substituted. This sidesteps the TSEC-firmware to `master_kek` to `master_key` derivation chain that is not - fully modelled. For other keyslots, the SE behaves normally. + fully modelled. Clearing a slot and loading the context-save SRK are left + alone. For other keyslots, the SE behaves normally. The 16 keyslots are stored in a flat `Keyslot ks_table[16]` with -`key[32] / iv_orig[16] / iv_upd[16]`. RSA, RNG, and chunked SHA are stubbed. -They return `OP_DONE` without producing data, which is enough for current -payloads. +`key[32] / iv_orig[16] / iv_upd[16]`. RSA and RNG output are stubbed: they +return `OP_DONE` without producing data. Block counts are bounded by what one +linked-list entry can describe (16 MiB), and an operation whose buffers are +unreachable finishes with `SE_INT_ERR_STAT` instead of computing on zeros. ### 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 -- stops emulation and exits cleanly. - Same register with `SFT_RST` (bit 7) set requests a payload soft-reboot - via `state->reboot_requested`. + via `state->reboot_requested`, as a power cycle (`reboot_cold`). - `APBDEV_PMC_CNTRL` (`0x00`) bit 4 (MAIN_RST) -- written by Hekate's `power_set_state(REBOOT_RCM)` -- also requests a soft-reboot, so the user can iterate on a payload without restarting `rcm_emu`. +Either request stops the BPMP on the spot: `power_set_state()` follows the +write with `bpmp_halt()`, which would otherwise end the run first. + +**What a reboot resets** (`mmio_soft_reset`). Everything on the SoC: the +register cache (GPIO, pinmux, clocks), UART modes and receive FIFOs, the I2C +controllers, the PMC's partitions, pad DPD and registers, CAR, the flow +controller, the SE (back to the `--prod-keys` preload), touch, SDMMC (the +eMMC back in its user area), the display controller, ACTMON, VIC, DSI, the +PCIe root complex and CPU0. What survives is what survives on hardware: PMC +SCRATCH0 and RST_STATUS, the RTC (still counting), and - unless the reboot +is a power cycle - the PMIC with its rails and the external regulators. DRAM +comes back as fresh zero pages (not a memset, which made all 2 GB resident), +the BPMP's translations of IRAM, DRAM and low memory are dropped so the old +run's code cannot run in place of the reloaded payload, the CPSR returns to +its power-on SVC mode, scripted input restarts and every button is released. + ### I²C-attached chips (battery, charger, thermal, USB-PD, PMIC ID) Modelled inline in `t210/mmio.cpp::i2c_read`. The bus is disambiguated by @@ -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 instructions (see [Determinism](#determinism-and-the-auto-script-flag)), so timing is identical across runs. The auto-script feature relies on this. + RTC SECONDS counts and is writable, and a MILLI_SECONDS read snapshots it + into SHADOW_SECONDS. TMR0..9 record when they were armed, so bdk's + `timer_usleep()` - TMR8 plus `FLOW_MODE_STOP_UNTIL_IRQ` - sleeps to the + timer's expiry. +- **Flow controller.** `HALT_COP_EVENTS` MODE 0/1 do not halt; a timed + WAITEVENT advances the clock; STOP_UNTIL_IRQ wakes on the first armed + timer; an untimed halt ends the run - unless CPU0 is running, in which case + the BPMP stays parked and CPU0 runs on (fusee's and hekate's L4T handoff). - **Probe-magic constants.** Several reads return fixed values, not because they are tweakable but because the chip-detection code expects exact cookies: `MAX17050.DevName=0x00AC`, `BQ24193.VendorPart=0x2F`, the BM92T36 @@ -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 mailbox while the stub trains the link and enumerates the CYW4356. -**Release.** The model shadows the registers the boot sequence writes and -starts the core when `RST_CPUG_CMPLX_CLR` clears the last of CPU0's reset bits -(CPURESET0, DBGRESET0, CORERESET0, bit 30, NONCPURESET) - but only if the core -could actually run: +**Release.** The model shadows the registers the boot sequence writes. +`RST_CPUG_CMPLX` starts at its TRM reset value, `0x2000feef`, and the core +runs once CPURESET0 (bit 0), CORERESET0 (16), L2RESET (24) and NONCPURESET +(29) are all clear. (bdk also clears PRESETDBG, bit 30, which only resets the +CoreSight debug logic; bits 15:4 are reserved on this SoC.) It must also be +able to run; a release that is refused is looked at again whenever one of +these changes, since silicon starts the moment the last one arrives: | Precondition | Where it comes from | | --- | --- | @@ -437,7 +478,6 @@ could actually run: | CRAIL, C0NC, CE0 ungated | PMC PWRGATE_STATUS bits 0, 15, 14 | | CPUG clock on, PLLX up if CCLK uses it | CLK_ENB_V bit 0, CCLK_BURST_POLICY, PLLX_BASE | | MSELECT clocked and out of reset | CLK_ENB_V bit 3, RST_DEV_V bit 3 | -| RAM repair requested | FLOW_CTLR_RAM_REPAIR | | An AArch64 vector in IRAM/DRAM | SB_AA64_RESET_LOW bit 0 + address, SB_AA64_RESET_HIGH | A release that misses one prints `[ccplex] CPU0 released from reset but @@ -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 exceptions, so no SMC can carry it up either. ERET can: its helper takes the current EL from PSTATE and rebuilds `hflags` for the target. So each boot -creates a fresh engine (no stale translations of a rewritten stub), writes +creates a fresh engine, writes PSTATE = SPSR_EL3 = EL3h with DAIF masked and ELR_EL3 = ELR_EL1 = the vector, and starts it on a one-instruction `eret` trampoline in a page at 1 TiB that only CPU0 maps. @@ -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 explaining why) and serves CPU0. MSELECT reads its TRM reset value `0x07FF4020`, AFI_PCIE_CONFIG `0x00103025`, and LNKSTA `0x3011` once the link -is up - the values hwtest's healthy-console capture shows. An access CPU0 -makes to an address nothing decodes wedges it, as on silicon; the BPMP's -watchdog on the mailbox heartbeat is what reports it. +is up - the values hwtest's healthy-console capture shows. The whole config +aperture and non-prefetchable window are decoded (extended registers read 0, +unclaimed addresses all-ones, BARs wherever software puts them), and +MSELECT_CONFIG.ENABLE_PCIE_APERTURE gates them. An access CPU0 makes to an +address nothing decodes wedges it, as on silicon; the BPMP's watchdog on the +mailbox heartbeat is what reports it. + +**Code the BPMP rewrites.** Stores from one engine never reach the other's +translation cache, so a stub loaded for a new job at the address of the last +one would run the old code. The pages CPU0 executes from are remembered with +a copy of their bytes, and before each slice any that changed have their +translations dropped (`uc_ctl_remove_cache`). A full `UC_CTL_TB_FLUSH` would +be simpler, but on Unicorn 2.0 it memsets the whole 1 GB code buffer. **Time.** CPU0 keeps its own clock: 1 ns per retired instruction (PLLX runs the A57 at ~1 GHz) plus 250 ns per bus access (MSELECT, the APC bridge, APB). While it runs, the main loop cuts the BPMP's batch into 250 us slices and runs CPU0 up to the BPMP's time after each - lockstep at a finer grain than the 500 us the BPMP polls the mailbox at. During a CPU0 slice `emu_usec` is CPU0's -clock, so every register model timestamps with the right core's time. 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. +clock, so every register model timestamps with the right core's time - a +model timing CPU0's PERST#-after-refclk sequence must use the clock CPU0 +waits on. CPU0 trails the BPMP by up to a slice, so a model both cores touch +(ACTMON, the Bluetooth chip) compares times rather than subtracting them. +Releasing CPU0 ends the BPMP's batch at the next block, so the first slice +starts at once. WFE / WFI park the core to the end of the slice: the stub's +final `for(;;) wfe;` would otherwise spin through a billion instructions per +emulated second. `make test` runs `tests/ccplex/`, a self-contained payload that checks the refusal, the EL3 entry, the mailbox, WFE parking and the reset. diff --git a/Dockerfile b/Dockerfile index 1b306df..2f87d35 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,18 +1,21 @@ -FROM ubuntu:24.04 - -# Build environment for RCM Payload Emulator. -# git is needed so the container can bootstrap the Dear ImGui submodule -# (third_party/imgui) from the bind-mounted source tree on first build. -RUN apt-get update && apt-get install -y --no-install-recommends \ - build-essential \ - pkg-config \ - git \ - libunicorn-dev \ - libsdl2-dev \ - && rm -rf /var/lib/apt/lists/* - -WORKDIR /work - -# Build command: docker run --rm -v $(pwd):/work rcm_emu -# (init the imgui submodule if it's missing, then build) -CMD ["sh", "-c", "git submodule update --init --recursive && make"] +FROM ubuntu:24.04 + +# Build environment for RCM Payload Emulator. +# git is needed so the container can bootstrap the Dear ImGui submodule +# (third_party/imgui) from the bind-mounted source tree on first build. +RUN apt-get update && apt-get install -y --no-install-recommends \ + build-essential \ + pkg-config \ + git \ + libunicorn-dev \ + libsdl2-dev \ + && rm -rf /var/lib/apt/lists/* + +WORKDIR /work + +# Build command: docker run --rm -v $(pwd):/work rcm_emu +# (init the imgui submodule if it's missing, then build) +# The source is bind-mounted and owned by the host user, not root: without +# safe.directory, git refuses to touch it ("dubious ownership") and make never +# runs. +CMD ["sh", "-c", "git config --global --add safe.directory /work && git submodule update --init --recursive && make"] diff --git a/display/config_window.cpp b/display/config_window.cpp index e1ef3ec..1e9cedc 100644 --- a/display/config_window.cpp +++ b/display/config_window.cpp @@ -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())); // Fuses are dumped wholesale — small enough (256 × 4 bytes) and keeps the - // load path branch-free. + // load path branch-free. Zero words too: loading layers the file over + // init_fuse_defaults(), so a fuse cleared in the UI and left out here + // came back at its default on the next start. fprintf(f, "\n[fuses]\n"); for (size_t i = 0; i < EmuState::FUSE_WORDS; i++) { uint32_t v = s->fuse_word[i].load(); - if (v) fprintf(f, "0x%03X=0x%08X\n", (unsigned)(i * 4), v); + fprintf(f, "0x%03X=0x%08X\n", (unsigned)(i * 4), v); } fclose(f); @@ -889,6 +891,7 @@ void build_ui(EmuState *state) { } ImGui::SameLine(); if (ImGui::Button("Reboot")) { + state->reboot_cold = true; // the user's reset is a power cycle state->reboot_requested.store(true); } ImGui::Text("emu_usec: %llu", (unsigned long long)state->emu_usec); diff --git a/display/sdl_display.cpp b/display/sdl_display.cpp index c91590f..5b2bd8d 100644 --- a/display/sdl_display.cpp +++ b/display/sdl_display.cpp @@ -93,7 +93,8 @@ void sdl_display_update(EmuState *state, uc_engine *uc) { 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 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 // they expect the rotation to actually change, regardless of what the // auto-detect picked. -1 means "use auto-detect", anything else overrides. + state->last_auto_rot.store((uint32_t)(rot & 3)); if (state->rotation_override != -1) 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 (ty >= out_h) ty = out_h - 1; - // The rendered SDL view always represents the physical Switch screen in its - // intended orientation (post-rotation, post-de-swizzle). Whatever the - // framebuffer's in-memory layout, what the user sees is what they would see - // looking at a Switch held landscape (long axis horizontal). The FTS4 panel - // sits behind that physical screen with its long axis (panel_x) along the - // long dimension and its short axis (panel_y) along the short. - // - // So we map the texture coord to panel coords by aspect: whichever of (tx, - // ty) lives on the longer rendered axis is the long-axis sample. - bool landscape = (out_w >= out_h); - uint32_t long_pix = landscape ? tx : ty; - uint32_t long_max = landscape ? out_w : out_h; - uint32_t short_pix = landscape ? ty : tx; - uint32_t short_max = landscape ? out_h : out_w; + // With the auto-detected rotation, the rendered SDL view represents the + // physical Switch screen in its intended orientation (post-rotation, post- + // de-swizzle): what the user sees is what they would see looking at a + // Switch held landscape. A manual override (R / Shift+R) turns that view + // by a further quarter-turn or two, so undo exactly that extra turn first: + // the render maps a source pixel (sx, sy) of a W x H image to + // 1: (H-1-sy, sx) 2: (W-1-sx, H-1-sy) 3: (sy, W-1-sx) + uint32_t delta = (state->last_rot.load() - state->last_auto_rot.load()) & 3; + uint32_t aw = (delta & 1) ? out_h : out_w; // auto-rotated view's size + uint32_t ah = (delta & 1) ? out_w : out_h; + uint32_t ax = tx, ay = ty; + switch (delta) { + case 1: ax = ty; ay = ah - 1 - tx; break; + case 2: ax = aw - 1 - tx; ay = ah - 1 - ty; break; + case 3: ax = aw - 1 - ty; ay = tx; break; + } + + // The FTS4 panel sits behind that physical screen with its long axis + // (panel_x) along the long dimension and its short axis (panel_y) along + // the short, so whichever of (ax, ay) lives on the longer axis is the + // long-axis sample. + bool landscape = (aw >= ah); + uint32_t long_pix = landscape ? ax : ay; + uint32_t long_max = landscape ? aw : ah; + uint32_t short_pix = landscape ? ay : ax; + uint32_t short_max = landscape ? ah : aw; if (long_max == 0) long_max = 1; if (short_max == 0) short_max = 1; - uint32_t px = (long_pix * 1264u) / long_max; // FTS4 X_REAL_MAX = 1264 - uint32_t py = (short_pix * 704u) / short_max; // FTS4 Y_REAL_MAX = 704 - if (px > 1264) px = 1264; - if (py > 704) py = 704; + // bdk's touch.c clamps raw samples to EDGE_OFFSET..REAL_MAX (15..1264 and + // 15..704) and stretches that span over the 1280x720 screen, so the inverse + // starts at the edge offset, not at 0. + constexpr uint32_t kEdge = 15, kXMax = 1264, kYMax = 704; + uint32_t px = kEdge + (long_pix * (kXMax - kEdge)) / long_max; + uint32_t py = kEdge + (short_pix * (kYMax - kEdge)) / short_max; + if (px > kXMax) px = kXMax; + if (py > kYMax) py = kYMax; *panel_x = (uint16_t)px; *panel_y = (uint16_t)py; - (void)state; // last_rot still cached for future use; current mapping is rotation-agnostic return true; } @@ -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) { uint16_t px = 0, py = 0; if (window_to_panel(state, event.button.x, event.button.y, &px, &py)) { - state->tc_x.store(px); - state->tc_y.store(py); state->tc_pressed.store(true); - state->tc_event_op.store(0x03); // FTS4_EV_MULTI_TOUCH_ENTER - state->tc_event_pending.store(true); + state->touch_post(0x03, px, py); // FTS4_EV_MULTI_TOUCH_ENTER printf("[touch] DOWN win=(%d,%d) panel=(%u,%u)\n", event.button.x, event.button.y, px, py); } @@ -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) { uint16_t px = 0, py = 0; if (window_to_panel(state, event.button.x, event.button.y, &px, &py)) { - state->tc_x.store(px); - state->tc_y.store(py); state->tc_pressed.store(false); - state->tc_event_op.store(0x04); // FTS4_EV_MULTI_TOUCH_LEAVE - state->tc_event_pending.store(true); + state->touch_post(0x04, px, py); // FTS4_EV_MULTI_TOUCH_LEAVE printf("[touch] UP win=(%d,%d) panel=(%u,%u)\n", event.button.x, event.button.y, px, py); } @@ -509,10 +520,15 @@ bool sdl_display_poll_events(EmuState *state, uc_engine *uc) { if (event.type == SDL_MOUSEMOTION && state->tc_pressed.load()) { uint16_t px = 0, py = 0; if (window_to_panel(state, event.motion.x, event.motion.y, &px, &py)) { - state->tc_x.store(px); - state->tc_y.store(py); - state->tc_event_op.store(0x05); // FTS4_EV_MULTI_TOUCH_MOTION - state->tc_event_pending.store(true); + // A release outside the window never reaches it when mouse capture + // is off (the ImGui backend turns SDL's auto-capture off process- + // wide), so a motion with the button up ends the touch instead. + if (!(event.motion.state & SDL_BUTTON_LMASK)) { + state->tc_pressed.store(false); + state->touch_post(0x04, px, py); // FTS4_EV_MULTI_TOUCH_LEAVE + } else { + state->touch_post(0x05, px, py); // FTS4_EV_MULTI_TOUCH_MOTION + } } } if (event.type == SDL_KEYDOWN) { @@ -543,6 +559,7 @@ bool sdl_display_poll_events(EmuState *state, uc_engine *uc) { if (!ctrl) { // Plain R: soft reboot. Same path as the config window's "Reboot" // button — re-prime IRAM payload + WDT cookie, wipe DRAM, reset PC. + state->reboot_cold = true; // the user's reset is a power cycle state->reboot_requested = true; printf("[diag] Reboot requested (R)\n"); } else { diff --git a/emu_state.h b/emu_state.h index d448634..cf18f04 100644 --- a/emu_state.h +++ b/emu_state.h @@ -102,15 +102,40 @@ struct EmuState { // Updated by SDL mouse events; consumed by i2c3_*/STMFTS code on CPU thread. // Coordinates are in panel-raw space (X long axis 0..1264, Y short 0..704) // matching what touch.c expects before its rescaling. - std::atomic tc_x{0}; - std::atomic tc_y{0}; + // + // Events queue up rather than overwrite each other: a click shorter than + // the payload's poll interval used to reach it as a bare LEAVE, the + // ENTER lost under it. Single producer (SDL), single consumer (I2C3). + struct TouchEvent { uint8_t op; uint16_t x, y; }; // op 3/4/5 = ENTER/LEAVE/MOTION + static constexpr uint32_t TC_QUEUE = 32; + TouchEvent tc_queue[TC_QUEUE] = {}; + std::atomic tc_q_head{0}; // next slot the producer fills + std::atomic tc_q_tail{0}; // next slot the consumer takes std::atomic tc_pressed{false}; - std::atomic tc_event_pending{false}; - std::atomic tc_event_op{0}; // 0x03=ENTER, 0x04=LEAVE, 0x05=MOTION - uint8_t tc_finger_id = 1; // FTS4 finger IDs are 1-indexed + uint8_t tc_finger_id = 0; // raw FTS4 ID; bdk reports it + 1 + + // Queue a touch event. MOTION is dropped when the queue is nearly full, + // so an ENTER or LEAVE always finds room. + void touch_post(uint8_t op, uint16_t x, uint16_t y) { + uint32_t head = tc_q_head.load(), tail = tc_q_tail.load(); + uint32_t used = head - tail; + if (used >= TC_QUEUE || (op == 0x05 && used >= TC_QUEUE - 4)) + return; + tc_queue[head % TC_QUEUE] = {op, x, y}; + tc_q_head.store(head + 1); + } + bool touch_take(TouchEvent *ev) { + uint32_t tail = tc_q_tail.load(); + if (tail == tc_q_head.load()) + return false; + *ev = tc_queue[tail % TC_QUEUE]; + tc_q_tail.store(tail + 1); + return true; + } // last_rot mirrors the rotation last applied by sdl_display_update. // Read from the SDL event handler to invert the display→window transform. std::atomic last_rot{0}; + std::atomic last_auto_rot{0}; // what auto-detect picked, before any override std::atomic last_out_w{1280}; std::atomic last_out_h{720}; @@ -141,6 +166,14 @@ struct EmuState { std::atomic running{true}; std::atomic paused{false}; std::atomic reboot_requested{false}; + // The reboot is a power cycle (PMIC software reset, the UI's Reboot): + // the regulators lose their state too. Otherwise it is a SoC reset + // (PMC MAIN_RST), which the PMIC, and its rails, sit out. + std::atomic reboot_cold{false}; + // The BPMP parked itself for good (bpmp_halt(): WAITEVENT with no timer) + // while CPU0 still runs - the handoff fusee and hekate's L4T launch do. + // Time keeps passing for CPU0; the BPMP executes nothing until reset. + bool bpmp_halted = false; // Payload kept around for soft reboot (re-write to IRAM and reset PC). uint8_t *payload_ptr = nullptr; @@ -328,6 +361,8 @@ struct EmuState { std::atomic& fuse_at(uint32_t offset) { return fuse_word[(offset & 0x3FC) / 4]; } void init_fuse_defaults() { + for (auto &w : fuse_word) + w.store(0); // Names below mirror Hekate's bdk/soc/fuse.h. Values picked from a // typical Erista golden-sample dump (any retail Switch is similar). fuse_at(0x100).store(1); // FUSE_PRODUCTION_MODE diff --git a/input_script.cpp b/input_script.cpp index db6588c..b4a5692 100644 --- a/input_script.cpp +++ b/input_script.cpp @@ -280,6 +280,10 @@ void input_script_tick(EmuState &state) { printf("[input-script] %s down @%llu us (%zu/%zu)\n", key_name(ev.key), (unsigned long long)now, i + 1, g_events.size()); fflush(stdout); + // Even if the release is already due - a FLOW_CTLR sleep can jump the + // clock past it within one batch - the payload has to run with the + // button down at least once, or it never sees the press. + break; } if (ev.pressed && !ev.released && now >= ev.until_us) { btn->store(false); @@ -293,3 +297,12 @@ void input_script_tick(EmuState &state) { if (!ev.released) break; // keep this event current until it's let go } } + +void input_script_restart(EmuState &state) { + for (Event &ev : g_events) + ev.pressed = ev.released = false; + g_done = 0; + state.btn_power = false; + state.btn_vol_up = false; + state.btn_vol_down = false; +} diff --git a/input_script.h b/input_script.h index 9778506..09cd068 100644 --- a/input_script.h +++ b/input_script.h @@ -23,3 +23,7 @@ bool input_script_active(); // Apply any events that are due at the current state.emu_usec. Call once per // emulator loop iteration; cheap no-op when no script is loaded. void input_script_tick(EmuState &state); + +// Soft reboot: the emulated clock starts again from 0, so every event is +// re-armed and any button the script was holding is let go. +void input_script_restart(EmuState &state); diff --git a/main.cpp b/main.cpp index d56121e..00a6487 100644 --- a/main.cpp +++ b/main.cpp @@ -34,10 +34,34 @@ #include "display/console_window.h" #include "input_script.h" +// Low 16 MB of the map (NULL-pointer writes land there); freed at exit. +static uint8_t *g_low_ptr = nullptr; + +// Scripted-navigation progress (--auto-pin-recovery, --auto-te-script). A +// soft reboot restarts both, as it restarts the emulated clock they run on. +struct AutoScripts { + int pin_stage = 0; + uint64_t pin_t = 0; + int pin_logged_stage = -1; + size_t te_idx = 0; +}; +static AutoScripts g_auto; + +// The IPL framebuffer starts out in hekate's background colour (0x1B1B1B), +// at power-on and again after a reboot has handed DRAM back zeroed. +static void fill_fb_background(EmuState *state) { + for (size_t i = 0; i < FB_SIZE; i += 4) { + state->fb_ptr[i + 0] = 0x1B; // B + state->fb_ptr[i + 1] = 0x1B; // G + state->fb_ptr[i + 2] = 0x1B; // R + state->fb_ptr[i + 3] = 0xFF; // A + } +} + // ==================== Payload Loading ==================== static uint8_t *load_payload(const char *path, size_t *out_size) { - FILE *f = fopen(path, "rb"); + FILE *f = platform_fopen(path, "rb"); if (!f) { fprintf(stderr, "[error] Cannot open payload: %s\n", path); return nullptr; @@ -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 // hardware presents. // - // Allocated host-side (calloc, so pages are lazily committed - the full - // 2 GB is only ever resident if a payload actually touches all of it) and - // kept as a host pointer so soft reboot can memset() it: Nyx loads here - // and its file-static SD/eMMC caches would otherwise survive a reboot. - err = uc_mem_map_ptr(uc, DRAM_BASE, DRAM_WINDOW_SIZE, UC_PROT_ALL, - (state->dram_low_ptr = (uint8_t *)calloc(1, DRAM_WINDOW_SIZE))); + // Allocated host-side as demand-zero pages (zeroed_alloc), so the full + // 2 GB is only ever resident if a payload actually touches all of it, and + // kept as a host pointer so a soft reboot can hand it back zeroed: Nyx + // loads here and its file-static SD/eMMC caches would otherwise survive. + state->dram_low_ptr = zeroed_alloc(DRAM_WINDOW_SIZE); if (!state->dram_low_ptr) { fprintf(stderr, "[error] Failed to allocate %zu MB DRAM host buffer\n", (size_t)(DRAM_WINDOW_SIZE / (1024 * 1024))); uc_close(uc); return nullptr; } + err = uc_mem_map_ptr(uc, DRAM_BASE, DRAM_WINDOW_SIZE, UC_PROT_ALL, + state->dram_low_ptr); if (err != UC_ERR_OK) { fprintf(stderr, "[error] Failed to map DRAM: %s\n", uc_strerror(err)); uc_close(uc); @@ -178,13 +203,7 @@ static uc_engine *setup_emulation(EmuState *state, uint8_t *payload, size_t payl // ---- Map Framebuffer pointer ---- state->fb_ptr = state->dram_low_ptr + (FB_BASE - DRAM_BASE); - // Fill with hekate background color (0x1B1B1B) - for (size_t i = 0; i < FB_SIZE; i += 4) { - state->fb_ptr[i + 0] = 0x1B; // B - state->fb_ptr[i + 1] = 0x1B; // G - state->fb_ptr[i + 2] = 0x1B; // R - state->fb_ptr[i + 3] = 0xFF; // A - } + fill_fb_background(state); state->fb_addr = FB_BASE; printf("[emu] Defined FB: 0x%08llX - 0x%08llX (%u MB)\n", (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) ---- // hekate seems to do a memset(0, ...) for clear screen if some ptr is NULL. - uint8_t *low_ptr = (uint8_t *)calloc(1, 0x01000000); - uc_mem_map_ptr(uc, 0, 0x01000000, UC_PROT_ALL, low_ptr); + // This covers the iROM range (0x100000, 96 KB) too, as zero-filled RAM: + // there are no BootROM contents to show, and Hekate's "Bootrom Info" / + // "Dump Bootrom" read it without faulting. (A read-only iROM map on top + // of this used to be attempted as well; it overlapped, so it always + // failed, unnoticed - and a read-only iROM would fault the NULL-pointer + // clear above.) + g_low_ptr = (uint8_t *)calloc(1, 0x01000000); + err = g_low_ptr ? uc_mem_map_ptr(uc, 0, 0x01000000, UC_PROT_ALL, g_low_ptr) + : UC_ERR_NOMEM; + if (err != UC_ERR_OK) { + fprintf(stderr, "[error] Failed to map low memory: %s\n", uc_strerror(err)); + uc_close(uc); + return nullptr; + } // ---- Nyx Storage (16MB @ 0xED000000) ---- // Already mapped as part of 2GB DRAM chunk @@ -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 // whatever happened to be mapped. - // BootROM (iROM) at 0x100000, 96 KB. We don't have the real BootROM - // contents, but mapping the region as zero-filled lets Hekate's "Bootrom - // Info" / "Dump Bootrom" features read it without faulting. The IPATCH - // CAM at 0x6001DC00 is also zero-mapped so the ipatches table renders - // empty (which matches an unpatched SoC). - uc_mem_map(uc, 0x00100000, 0x18000, UC_PROT_READ | UC_PROT_EXEC); // iROM - uc_mem_map(uc, 0x6001D000, 0x1000, UC_PROT_ALL); // IPATCH CAM page + // The IPATCH CAM at 0x6001DC00 is zero-mapped so the ipatches table + // renders empty (which matches an unpatched SoC). + err = uc_mem_map(uc, 0x6001D000, 0x1000, UC_PROT_ALL); + if (err != UC_ERR_OK) + fprintf(stderr, "[warn] IPATCH page not mapped: %s\n", uc_strerror(err)); // ---- heap region (32MB @ 0x90000000) ---- // Already mapped as part of 2GB DRAM chunk @@ -374,8 +403,14 @@ int main(int argc, char *argv[]) { else if (strcmp(argv[i], "--auto-te-script") == 0) auto_te_script = true; // Generic scripted button input, for menu-driven payloads that can't // be driven any other way from a headless / CI run. - else if (strcmp(argv[i], "--input-script") == 0 && i + 1 < argc) - input_script_load(argv[++i]); + else if (strcmp(argv[i], "--input-script") == 0 && i + 1 < argc) { + // A script that does not parse would leave a CI run idling until + // its timeout with nothing pressed; stop here instead. + if (!input_script_load(argv[++i])) { + fprintf(stderr, "[error] --input-script could not be loaded\n"); + return 1; + } + } } // Default to sd.img in the working directory when --sd is not given, so the @@ -464,31 +499,52 @@ int main(int argc, char *argv[]) { // re-prime the WDT cookie so Hekate's early boot skips Minerva again. if (state.reboot_requested.exchange(false)) { uc_emu_stop(uc); + bool cold = state.reboot_cold.exchange(false); // 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. - mmio_soft_reset(&state); + // complex and every other block back to power-on, the clock's + // half-counted block gone. A power cycle resets the PMIC too. + mmio_soft_reset(&state, cold); bpmp_clock_reset(); - // One contiguous block now; dram_ptr is a view into it. - memset(state.dram_low_ptr, 0, DRAM_WINDOW_SIZE); + // Fresh zero pages rather than a memset, which made all 2 GB + // resident. + zeroed_reset(state.dram_low_ptr, DRAM_WINDOW_SIZE); + fill_fb_background(&state); size_t reload = state.payload_len; if (reload > IRAM_SIZE - (IPL_LOAD_ADDR - IRAM_BASE)) reload = IRAM_SIZE - (IPL_LOAD_ADDR - IRAM_BASE); uc_mem_write(uc, IPL_LOAD_ADDR, state.payload_ptr, reload); uint32_t wdt_magic = 0x544457; 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_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_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.emu_usec = 0; state.insn_count = 0; state.bpmp_slept_us = 0; state.touch_phase = 0; state.paused = false; - printf("[emu] Soft reboot complete (DRAM wiped)\n"); + state.btn_power = false; + state.btn_vol_up = false; + state.btn_vol_down = false; + g_auto = AutoScripts(); + input_script_restart(state); + printf("[emu] Soft reboot complete (%s, DRAM wiped)\n", + cold ? "power cycle" : "SoC reset"); } if (!state.paused) { @@ -508,8 +564,8 @@ int main(int argc, char *argv[]) { // idle so recover_pin's final btn_wait blocks on us — keeps the // result text visible in the framebuffer when the run times out. if (auto_pin_recovery) { - static int pin_stage = 0; - static uint64_t pin_t = 0; + int &pin_stage = g_auto.pin_stage; + uint64_t &pin_t = g_auto.pin_t; auto press_release = [&](std::atomic *btn, uint64_t hold_us, uint64_t cooldown_us) { @@ -528,7 +584,7 @@ int main(int argc, char *argv[]) { printf("[emu] Auto PIN recovery armed at emu_usec=%llu\n", (unsigned long long)state.emu_usec); } - static int last_logged_stage = -1; + int &last_logged_stage = g_auto.pin_logged_stage; if (pin_stage != last_logged_stage) { printf("[emu] Auto PIN stage %d at emu_usec=%llu\n", pin_stage, (unsigned long long)state.emu_usec); @@ -590,7 +646,7 @@ int main(int argc, char *argv[]) { {22850000, 'P', true}, {23020000, 'P', false}, }; static const size_t te_n = sizeof(te_events)/sizeof(te_events[0]); - static size_t te_idx = 0; + size_t &te_idx = g_auto.te_idx; while (te_idx < te_n && state.emu_usec >= te_events[te_idx].at_us) { const InputEv &ev = te_events[te_idx]; std::atomic *btn = (ev.btn == 'P') ? &state.btn_power @@ -605,6 +661,10 @@ int main(int argc, char *argv[]) { te_idx++; if (te_idx == te_n) printf("[auto-te] sequence complete; idling for output\n"); + // A time jump (FLOW_CTLR sleep) can make the release due + // in the same tick; the payload must see the press first. + if (ev.down) + break; } } @@ -629,8 +689,28 @@ int main(int argc, char *argv[]) { // to the same emulated time. Scripted input and the display are // still serviced once per full batch, as before. uint64_t batch_end = state.insn_count + BATCH_INSTRUCTIONS; + uint64_t parked_left = BATCH_INSTRUCTIONS; while (state.running && !state.paused && state.insn_count < batch_end) { + if (state.bpmp_halted) { + // The BPMP parked itself for good after handing off to + // CPU0. It retires nothing; time runs on for CPU0 at the + // rate the BPMP's clock would have advanced it. + if (!ccplex_cpu0_running()) { + printf("[emu] BPMP halted and CPU0 stopped, shutting down emulator\n"); + state.running = false; + break; + } + if (parked_left < CPU0_QUANTUM_INSTRUCTIONS) + break; + parked_left -= CPU0_QUANTUM_INSTRUCTIONS; + state.emu_usec += CPU0_QUANTUM_INSTRUCTIONS / 10; + state.bpmp_slept_us += CPU0_QUANTUM_INSTRUCTIONS / 10; + ccplex_run(&state, state.emu_usec); + if (state.reboot_requested.load()) + break; + continue; + } uint64_t budget = batch_end - state.insn_count; if (ccplex_cpu0_running() && budget > CPU0_QUANTUM_INSTRUCTIONS) budget = CPU0_QUANTUM_INSTRUCTIONS; @@ -690,8 +770,9 @@ int main(int argc, char *argv[]) { uc_close(uc); free(state.iram_ptr); + free(g_low_ptr); // dram_ptr is a view into dram_low_ptr's block; only free the base once. - free(state.dram_low_ptr); + zeroed_free(state.dram_low_ptr, DRAM_WINDOW_SIZE); free(state.payload_ptr); // fb_ptr points inside dram_ptr; do not free separately. diff --git a/make_sd.py b/make_sd.py index 752ff64..49ef437 100644 --- a/make_sd.py +++ b/make_sd.py @@ -13,6 +13,7 @@ Usage: """ import argparse import os +import shlex import subprocess import sys @@ -21,6 +22,9 @@ def build_sd_image(src_dir: str, out_img: str, size_mb: int) -> int: if not os.path.isdir(src_dir): print(f"[error] source folder not found: {src_dir}") return 1 + if size_mb < 64: + print("[error] --size-mb must be at least 64: FAT32 needs 65525 clusters") + return 1 src_dir_abs = os.path.abspath(src_dir) out_img_abs = os.path.abspath(out_img) @@ -45,6 +49,13 @@ def build_sd_image(src_dir: str, out_img: str, size_mb: int) -> int: print(f"[*] formatting + populating via Docker (alpine)") fdisk_script = f"o\\nn\\np\\n1\\n2048\\n\\nt\\nc\\nw\\n" + # FatFs (and every FAT driver) decides FAT12/16/32 by cluster count, and + # FAT32 needs at least 65525 clusters: 4 KiB clusters only get there from + # ~260 MB up. Below that, format with 512-byte clusters, or the payload's + # f_mount rejects the volume (FR_NO_FILESYSTEM). + spc = 8 if size_mb >= 512 else 1 + # File names go into a shell command line: quote them. + q_fat, q_img = shlex.quote(fat_name), shlex.quote(img_name) docker_cmd = [ "docker", "run", "--rm", "-v", f"{work_dir}:/work", @@ -53,10 +64,12 @@ def build_sd_image(src_dir: str, out_img: str, size_mb: int) -> int: "alpine", "sh", "-c", "apk add --no-cache dosfstools mtools util-linux >/dev/null && " - f"mkfs.fat -F 32 -s 8 {fat_name} && " - f"mcopy -i {fat_name} -s /src/* :: && " - f"printf '{fdisk_script}' | fdisk {img_name} && " - f"dd if={fat_name} of={img_name} bs=1M seek=1 conv=notrunc status=none" + f"mkfs.fat -F 32 -s {spc} {q_fat} && " + # Every top-level entry, dotfiles included; an empty source is fine. + f"(cd /src && find . -mindepth 1 -maxdepth 1 " + f"-exec mcopy -i /work/{q_fat} -s {{}} :: \\;) && " + f"printf '{fdisk_script}' | fdisk {q_img} && " + f"dd if={q_fat} of={q_img} bs=1M seek=1 conv=notrunc status=none" ] try: subprocess.run(docker_cmd, check=True) diff --git a/platform.cpp b/platform.cpp new file mode 100644 index 0000000..7db8cac --- /dev/null +++ b/platform.cpp @@ -0,0 +1,81 @@ +#include "platform.h" + +#include +#include +#include + +#ifdef _WIN32 +#include +#else +#include +#endif + +// ---- Zero-filled memory, committed only where touched -------------------- +// +// The emulated DRAM window is 2 GiB. calloc gets it from the OS as demand- +// zero pages, so only what a payload touches becomes resident - but a soft +// reboot used to memset() the whole block back to zero, which touched every +// page and left the process 2 GiB resident from the first reboot on. These +// allocate the same demand-zero memory directly, and hand back fresh zero +// pages on reset, at the same address (the engines hold host pointers into +// it), without touching any. + +uint8_t *zeroed_alloc(size_t size) { +#ifdef _WIN32 + return (uint8_t *)VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, + PAGE_READWRITE); +#else + void *p = mmap(nullptr, size, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0); + return p == MAP_FAILED ? nullptr : (uint8_t *)p; +#endif +} + +void zeroed_reset(uint8_t *p, size_t size) { +#ifdef _WIN32 + // Decommitted pages come back zero-filled when committed again. + if (!VirtualFree(p, size, MEM_DECOMMIT) || + !VirtualAlloc(p, size, MEM_COMMIT, PAGE_READWRITE)) + memset(p, 0, size); +#else + // A fresh anonymous mapping over the old one: zero pages, same address. + if (mmap(p, size, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE | MAP_FIXED, -1, + 0) == MAP_FAILED) + memset(p, 0, size); +#endif +} + +void zeroed_free(uint8_t *p, size_t size) { + if (!p) + return; +#ifdef _WIN32 + (void)size; + VirtualFree(p, 0, MEM_RELEASE); +#else + munmap(p, size); +#endif +} + +// ---- Opening files by name ------------------------------------------------- + +FILE *platform_fopen(const char *path, const char *mode) { + FILE *f = fopen(path, mode); +#ifdef _WIN32 + // Command-line paths arrive in the ANSI code page, which fopen expects; + // SDL hands dropped files over as UTF-8, which it does not. Try the name + // as UTF-8 before giving up. + if (!f) { + int n = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, path, -1, + nullptr, 0); + int m = MultiByteToWideChar(CP_UTF8, 0, mode, -1, nullptr, 0); + if (n > 0 && m > 0) { + std::wstring wpath(n, L'\0'), wmode(m, L'\0'); + MultiByteToWideChar(CP_UTF8, 0, path, -1, &wpath[0], n); + MultiByteToWideChar(CP_UTF8, 0, mode, -1, &wmode[0], m); + f = _wfopen(wpath.c_str(), wmode.c_str()); + } + } +#endif + return f; +} diff --git a/platform.h b/platform.h index 7650b31..d80eb2e 100644 --- a/platform.h +++ b/platform.h @@ -1,7 +1,9 @@ #ifndef RCM_PLATFORM_H #define RCM_PLATFORM_H +#include #include +#include #include #include #include @@ -34,4 +36,14 @@ static inline int64_t file_size64(int fd) { #endif } +// Large zero-filled memory that only becomes resident where it is touched +// (platform.cpp). zeroed_reset() makes all of it zero again, at the same +// address, without touching it. +uint8_t *zeroed_alloc(size_t size); +void zeroed_reset(uint8_t *p, size_t size); +void zeroed_free(uint8_t *p, size_t size); + +// fopen() that also accepts a UTF-8 name on Windows (a dropped file). +FILE *platform_fopen(const char *path, const char *mode); + #endif // RCM_PLATFORM_H diff --git a/t210/bpmp.cpp b/t210/bpmp.cpp index 23242e3..f7e5d91 100644 --- a/t210/bpmp.cpp +++ b/t210/bpmp.cpp @@ -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 // 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. -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) || (addr >= DRAM_BASE && addr < DRAM_BASE + DRAM_WINDOW_SIZE); 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); if (!p) return false; - static const uint8_t zero[16] = {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; } - if (nop_slide(s, address)) { + if (nop_slide(uc, s, address)) { if (!clk.nop_slide_reported) { clk.nop_slide_reported = true; printf("\n[emu] NOP-slide detected at 0x%08llX (zeroed memory being " @@ -220,7 +228,11 @@ uc_err bpmp_run(uc_engine *uc, EmuState *state, uint64_t begin, uint64_t max_insns) { clk.limit = state->insn_count + (max_insns ? max_insns : 1); clk.pending = 0; - 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 // 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. @@ -244,3 +256,7 @@ uint32_t bpmp_timerus_read(EmuState *state) { void bpmp_clock_jumped() { clk.polling = false; } + +void bpmp_yield() { + clk.limit = 0; +} diff --git a/t210/bpmp.h b/t210/bpmp.h index 467568b..a15e0e9 100644 --- a/t210/bpmp.h +++ b/t210/bpmp.h @@ -45,4 +45,10 @@ uint32_t bpmp_timerus_read(EmuState *state); // halt): whatever poll loop was being paced is over. void bpmp_clock_jumped(); +// End the current batch at the next block boundary - a clean stop, unlike +// uc_emu_stop() from an MMIO callback, which abandons the block in flight +// with the PC back at its start. Used when CPU0 is released, so its first +// slice starts now rather than a whole batch later. +void bpmp_yield(); + #endif // T210_BPMP_H diff --git a/t210/ccplex.cpp b/t210/ccplex.cpp index ceb1101..8e566dd 100644 --- a/t210/ccplex.cpp +++ b/t210/ccplex.cpp @@ -1,7 +1,10 @@ #include "ccplex.h" +#include "bpmp.h" #include #include +#include +#include #include @@ -27,10 +30,14 @@ #define CLK_V_MSELECT 3 #define CAR_RST_CPUG_CMPLX_SET 0x450 #define CAR_RST_CPUG_CMPLX_CLR 0x454 -// The bits ccplex_boot_cpu0() clears for CPU0 - CPURESET0, DBGRESET0, -// CORERESET0 and bit 30 - and NONCPURESET, which it clears first. The core -// runs once all five are clear. -#define RST_CPU0_MASK ((1u << 0) | (1u << 16) | (1u << 24) | (1u << 30)) +// RST_CPUG_CMPLX (TRM 5.2.152, reset 0x2000feef). CPU0 runs once nCPUPORESET +// (CPURESET0, bit 0), nCORERESET (CORERESET0, bit 16), nL2RESET (bit 24) and +// the nonCPU region's reset (NONCPURESET, bit 29) are all released. +// ccplex_boot_cpu0() also clears PRESETDBG (bit 30), but that only resets +// the CoreSight debug logic, which a core runs without; the DBGRESET/ +// WDRESET/DERESET bits in 15:4 are reserved on this SoC. +#define RST_CPUG_CMPLX_RESET 0x2000FEEFu +#define RST_CPU0_MASK ((1u << 0) | (1u << 16) | (1u << 24)) #define RST_NONCPU (1u << 29) // SB block, SYSREG + 0x200. @@ -94,7 +101,7 @@ namespace { enum class Cpu0 { Off, Running, Hung }; 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 cclk_burst = 0; uint32_t pllx_base = 0; @@ -122,6 +129,15 @@ struct Model { Model m; EmuState *g_state = nullptr; + +// Pages CPU0 has executed code from, with the bytes it translated; see +// drop_stale_code(). +struct CodePage { + uint64_t base; + uint8_t bytes[4096]; +}; +std::vector> code_pages; +uint64_t last_code_page = ~0ULL; uc_hook h_block, h_unmapped, h_intr; bool held() { return (m.rst_cpug & (RST_CPU0_MASK | RST_NONCPU)) != 0; } @@ -162,8 +178,6 @@ const char *boot_blocked(EmuState *state) { return "CCLK runs from PLLX but PLLX is disabled"; if (!(m.clk_enb_v & (1u << CLK_V_MSELECT))) return "MSELECT clock disabled"; if (!pcie_mselect_up()) return "MSELECT still in reset"; - if (!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)) 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"; @@ -171,6 +185,8 @@ const char *boot_blocked(EmuState *state) { } void destroy_engine() { + code_pages.clear(); + last_code_page = ~0ULL; if (!m.uc) return; mmio_unmap_bus(m.uc); @@ -199,6 +215,43 @@ void stop_cpu0(const char *why) { // ---- CPU0 engine hooks --------------------------------------------------- +// ---- Code the BPMP rewrites under CPU0 ---------------------------------- +// +// Stores the BPMP makes into shared DRAM/IRAM go through its own engine, so +// this engine's translation cache never hears of them: a stub loaded for a +// new job at the address of the last one would run the old one's code. A +// full flush before every slice cures that but costs tens of milliseconds a +// time (it walks the page descriptors of the whole 44-bit space), so instead +// the pages CPU0 has executed from are remembered with a copy of their +// bytes, and before each slice any that changed have just their own +// translations dropped. +void note_code_page(uint64_t address) { + uint64_t base = address & ~0xFFFULL; + if (base == last_code_page) + return; + last_code_page = base; + for (auto &p : code_pages) + if (p->base == base) + return; + const uint8_t *src = host_ptr(base, 4096); + if (!src || code_pages.size() >= 256) + return; + auto p = std::make_unique(); + p->base = base; + memcpy(p->bytes, src, 4096); + code_pages.push_back(std::move(p)); +} + +void drop_stale_code() { + for (auto &p : code_pages) { + const uint8_t *now = host_ptr(p->base, 4096); + if (!now || memcmp(now, p->bytes, 4096) == 0) + continue; + uc_ctl_remove_cache(m.uc, p->base, p->base + 4096); + memcpy(p->bytes, now, 4096); + } +} + void commit_pending() { m.ns += m.pending * NS_PER_INSN; m.retired += m.pending; @@ -228,6 +281,7 @@ void hook_block(uc_engine *uc, uint64_t address, uint32_t size, void *) { uc_emu_stop(uc); return; } + note_code_page(address); // Every A64 instruction is four bytes. m.pending = size >= 4 ? size / 4 : 1; if (const uint8_t *p = host_ptr(address + size - 4, 4)) { @@ -288,8 +342,9 @@ bool start_cpu0(EmuState *state) { // IRAM, DRAM and TZRAM are the same host memory the BPMP engine maps, so // a stub the BPMP copies into DRAM and the mailbox both cores poll are one - // set of bytes. CPU0's engine is new on every release, so it cannot hold - // stale translations of code the BPMP has rewritten since the last boot. + // set of bytes. Stores from the other engine bypass this one's self- + // modifying-code tracking, so ccplex_run() drops its translations before + // every slice. err = uc_mem_map_ptr(uc, IRAM_BASE, IRAM_SIZE, UC_PROT_ALL, state->iram_ptr); if (err == UC_ERR_OK) err = uc_mem_map_ptr(uc, DRAM_BASE, DRAM_WINDOW_SIZE, UC_PROT_ALL, @@ -330,6 +385,10 @@ bool start_cpu0(EmuState *state) { m.bus_accesses = 0; m.cpu0 = Cpu0::Running; m.boots++; + // Released from a BPMP register write: end the BPMP's batch at the next + // block so CPU0's first slice starts now, not up to a batch (~10 ms) later. + if (g_bus_master == BUS_BPMP) + bpmp_yield(); printf("[ccplex] CPU0 released: AArch64 EL3, MMU off, entry 0x%08llX " "(boot #%u)\n", (unsigned long long)entry, m.boots); fflush(stdout); @@ -352,6 +411,14 @@ void try_release(EmuState *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 // ========================================================================== @@ -375,10 +442,10 @@ void ccplex_reset(EmuState *state) { void ccplex_car_write(EmuState *state, uint32_t offset, uint32_t val) { switch (offset) { - case CAR_CCLK_BURST_POLICY: m.cclk_burst = val; break; - case CAR_PLLX_BASE: m.pllx_base = val; break; - case CAR_CLK_OUT_ENB_V: m.clk_enb_v = val; break; - case CAR_CLK_ENB_V_SET: m.clk_enb_v |= val; break; + case CAR_CCLK_BURST_POLICY: m.cclk_burst = val; maybe_release(state); break; + case CAR_PLLX_BASE: m.pllx_base = val; maybe_release(state); break; + case CAR_CLK_OUT_ENB_V: m.clk_enb_v = val; maybe_release(state); break; + case CAR_CLK_ENB_V_SET: m.clk_enb_v |= val; maybe_release(state); break; case CAR_CLK_ENB_V_CLR: m.clk_enb_v &= ~val; if ((val & (1u << CLK_V_CPUG)) && m.cpu0 == Cpu0::Running) { @@ -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)state; switch (offset) { case SB_CSR: // 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 - // from here either way. + // non-secure writers, and the vector write below does not check it. m.sb_csr |= val; break; - case SB_AA64_RESET_LOW: m.sb_rst_lo = val; break; - case SB_AA64_RESET_HIGH: m.sb_rst_hi = val; break; + case SB_AA64_RESET_LOW: m.sb_rst_lo = val; maybe_release(state); break; + case SB_AA64_RESET_HIGH: m.sb_rst_hi = val & 0xFFF; maybe_release(state); break; default: break; } } void ccplex_partition_changed(EmuState *state, int part, bool on) { - (void)state; - if (on) + if (on) { + maybe_release(state); return; + } if (part == POWER_RAIL_CRAIL) stop_cpu0("CRAIL partition powergated"); if (part == POWER_RAIL_C0NC) stop_cpu0("C0NC partition powergated"); if (part == POWER_RAIL_CE0) stop_cpu0("CE0 partition powergated"); @@ -456,14 +522,20 @@ void ccplex_partition_changed(EmuState *state, int part, bool on) { void ccplex_rail_changed(EmuState *state) { if (m.cpu0 != Cpu0::Off && !cpu_rail_on(state)) stop_cpu0("CPU rail switched off"); + else + maybe_release(state); } +void ccplex_preconditions_changed(EmuState *state) { maybe_release(state); } + void ccplex_bus_tick(EmuState *state) { m.ns += NS_PER_BUS_ACCESS; m.bus_accesses++; state->emu_usec = m.ns / 1000; } +uint64_t ccplex_now_us() { return m.ns / 1000; } + bool ccplex_cpu0_running() { return m.cpu0 == Cpu0::Running && m.uc; } void ccplex_run(EmuState *state, uint64_t until_us) { @@ -474,8 +546,12 @@ void ccplex_run(EmuState *state, uint64_t until_us) { return; // While CPU0 runs, it is the bus master and "now" is its clock: every - // register model reads state->emu_usec, and must see CPU0's time, not the - // BPMP's. Both are put back afterwards. + // register model reads state->emu_usec, and must see CPU0's time - a + // model timing CPU0's own sequence (PERST# after Trefclkstable, say) has + // to measure it on the clock CPU0 waits on. Both are put back afterwards. + // CPU0 trails the BPMP by up to a slice, so a model both cores touch sees + // time step back at the switch; such models must not assume `now` only + // grows. uint64_t bpmp_usec = state->emu_usec; BusMaster prev = g_bus_master; g_bus_master = BUS_CPU0; @@ -483,7 +559,11 @@ void ccplex_run(EmuState *state, uint64_t until_us) { m.target_ns = target; 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(); uc_reg_read(m.uc, UC_ARM64_REG_PC, &m.pc); diff --git a/t210/ccplex.h b/t210/ccplex.h index 1959b61..5816458 100644 --- a/t210/ccplex.h +++ b/t210/ccplex.h @@ -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_rail_changed(EmuState *state); +// Something CPU0 needs in order to run changed (MSELECT reset released, ...): +// a core already out of reset but refused starts if nothing is missing now. +void ccplex_preconditions_changed(EmuState *state); + +// CPU0's own clock, in emulated microseconds: what TIMERUS reads from CPU0. +uint64_t ccplex_now_us(); + // Called by the MMIO front-end for every access CPU0 makes: charges the bus // latency to CPU0's clock before the access is dispatched. void ccplex_bus_tick(EmuState *state); diff --git a/t210/i2c3.cpp b/t210/i2c3.cpp index 7e5ecf1..05c0481 100644 --- a/t210/i2c3.cpp +++ b/t210/i2c3.cpp @@ -132,17 +132,15 @@ void push_controller_ready() { if (ev_stack.size() < 32) ev_stack.push_back(ev); } -// If SDL has flagged a pending touch event, pack it into the FTS4 stack. +// Move whatever SDL has queued into the FTS4 event stack, oldest first. void try_emit_pending_touch(EmuState *state) { - bool was_pending = state->tc_event_pending.exchange(false); - if (!was_pending) return; - uint8_t op = state->tc_event_op.load(); - uint16_t x = state->tc_x.load(); - uint16_t y = state->tc_y.load(); - // pressure: a small non-zero value keeps z below the 500-palm-reject threshold - // in touch.c (z = (pressure_lo|pressure_hi<<8) << 6 / (mod+0x40)). - uint16_t pressure = (op == FTS4_EV_MULTI_TOUCH_LEAVE) ? 0 : 0x10; - push_event(op, state->tc_finger_id, x, y, pressure); + EmuState::TouchEvent ev; + while (ev_stack.size() < 32 && state->touch_take(&ev)) { + // pressure: a small non-zero value keeps z below the 500-palm-reject + // threshold in touch.c (z = (pressure_lo|pressure_hi<<8) << 6 / (mod+0x40)). + uint16_t pressure = (ev.op == FTS4_EV_MULTI_TOUCH_LEAVE) ? 0 : 0x10; + push_event(ev.op, state->tc_finger_id, ev.x, ev.y, pressure); + } } // Pop oldest event into 8-byte buffer; on empty, return NO_EVENT. @@ -307,6 +305,24 @@ uint32_t pull_rx_word() { } // namespace +void i2c3_reset(EmuState *state) { + slave_addr = 0; + dir_read = false; + cmd_data[0] = cmd_data[1] = 0; + last_cnfg = 0; + pkt_state = PKT_HDR_W1; + pkt_size = pkt_recv = 0; + pkt_is_combined = false; + tx_buf.clear(); + rx_buf.clear(); + rx_pos = 0; + ev_stack.clear(); + EmuState::TouchEvent ev; + while (state->touch_take(&ev)) { + } + state->tc_pressed = false; +} + uint32_t i2c3_read(EmuState *state, uint64_t addr) { uint32_t offset = (uint32_t)(addr - I2C3_BASE); switch (offset) { diff --git a/t210/i2c3.h b/t210/i2c3.h index 4ae7aa1..8ab53dc 100644 --- a/t210/i2c3.h +++ b/t210/i2c3.h @@ -12,4 +12,8 @@ struct EmuState; uint32_t i2c3_read(EmuState *state, uint64_t addr); void i2c3_write(EmuState *state, uint64_t addr, uint32_t val); +// Soft reboot: controller and touch controller back to power-on, with no +// events left over from the previous run. +void i2c3_reset(EmuState *state); + #endif diff --git a/t210/memory_map.h b/t210/memory_map.h index e59f505..3d12bab 100644 --- a/t210/memory_map.h +++ b/t210/memory_map.h @@ -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 I2C3_BASE = 0x7000C500; // GEN3_I2C, used by STMFTS touchscreen at slave 0x49 constexpr uint64_t I2C5_BASE = 0x7000D000; -constexpr uint64_t I2C_SIZE = 0x1000; +constexpr uint64_t I2C_SIZE = 0x1000; // the MMIO page: I2C5, I2C6, SPI2B +constexpr uint64_t I2C_CTRL_SIZE = 0x100; // one controller's registers +constexpr uint64_t I2C4_BASE = 0x7000C700; +constexpr uint64_t I2C6_BASE = 0x7000D100; constexpr uint64_t I2C3_SIZE = 0x100; // PWM @@ -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 // entry RWX, so PCIe space is reachable and uncached. // -// Only the windows a payload actually touches are mapped: 16 KiB covering -// both root ports plus PADS and AFI, 128 KiB of configuration aperture (bus -// 0 and bus 1 are all that exist), and one 4 KiB page of downstream memory -// for the endpoint's BAR0 register window. Mapping the architectural sizes -// (256 MiB of config, 208 MiB of memory) would cost the host gigabytes for -// address ranges nothing ever reads. +// These are MMIO windows (callbacks, no backing memory), so they are mapped +// at their architectural sizes: the whole 256 MiB configuration aperture - +// extended registers sit at AXI[27:24] - and the non-prefetchable memory +// window to the end of PCIE_A2, wherever software places the endpoint's BARs. +// A smaller map left a CPU0 access to, say, config offset 0x100 or BAR0 + +// 0x2000 unmapped: nothing answered and the core wedged, where silicon +// returns data or all-ones. constexpr uint64_t PCIE_RP0_BASE = 0x01000000; // root port 0 registers constexpr uint64_t PCIE_RP1_BASE = 0x01001000; // root port 1 registers constexpr uint64_t PCIE_PADS_BASE = 0x01003000; @@ -216,9 +220,9 @@ constexpr uint64_t PCIE_AFI_BASE = 0x01003800; constexpr uint64_t PCIE_BLOCK_BASE = 0x01000000; constexpr uint64_t PCIE_BLOCK_SIZE = 0x4000; constexpr uint64_t PCIE_CS_BASE = 0x02000000; // type-1 extended config -constexpr uint64_t PCIE_CS_MODEL_SIZE = 0x20000; // buses 0 and 1 only +constexpr uint64_t PCIE_CS_MODEL_SIZE = 0x10000000; // all of it: 256 MiB constexpr uint64_t PCIE_MEM_BASE = 0x13000000; // non-prefetchable window -constexpr uint64_t PCIE_MEM_MODEL_SIZE = 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) constexpr uint64_t TSEC_BASE = 0x54500000; diff --git a/t210/mmio.cpp b/t210/mmio.cpp index d367904..8800743 100644 --- a/t210/mmio.cpp +++ b/t210/mmio.cpp @@ -45,10 +45,19 @@ static inline ssize_t pwrite(int fd, const void *buf, size_t n, long long off) { #define BIT(n) (1U << (n)) -static uint32_t pmc_scratch0 = 0; -static uint32_t pmc_scratch37 = 0; static RegCache mmio_regs; +// A payload asked for a reset. Stop the BPMP where it is instead of letting +// it run to the end of its batch: bdk's power_set_state() follows the reset +// write with bpmp_halt(), which must not get the chance to end the run. +static void request_reboot(EmuState *state, bool power_cycle) { + if (power_cycle) + state->reboot_cold = true; + state->reboot_requested = true; + if (g_bus_master == BUS_BPMP) + uc_emu_stop(state->uc); +} + BusMaster g_bus_master = BUS_BPMP; // Standard CRC32 (poly 0xEDB88320), matching hekate's crc32_calc(0, ...) which @@ -134,7 +143,7 @@ static const uint8_t *emmc_synth_gpt(size_t *out_len) { // hook caches every store), but a pad nobody has touched still has a reset // value, and probes read those to prove a pad is where the BootROM left it. // Only the pads a probe actually samples are listed; everything else keeps -// reading 0, which is the honest "not modelled" answer. +// reading 0, the honest "not modelled" answer (most pads reset to non-zero). struct PinmuxDefault { uint16_t off; uint32_t val; }; static const PinmuxDefault pinmux_defaults[] = { // PH5 / BT_HOST_WAKE: E_INPUT | PARKED | TRISTATE | PULL_DOWN. Measured @@ -146,6 +155,16 @@ static const PinmuxDefault pinmux_defaults[] = { // pad does not drive until software clears it. {0x044, 0x00000460}, {0x048, 0x00000470}, + // Pads the wireless probes sample before (or without) configuring them. + // TRM 9.15 reset values: E_INPUT | PARKED | TRISTATE | PULL_DOWN (0x74), + // UART2_RX pulled up instead (0x78). + {0x0F8, 0x00000078}, // UART2_RX + {0x118, 0x00000074}, // UART4_RX (UART-D, the BT transport) + {0x1B8, 0x00000074}, // WIFI_RST + {0x1C0, 0x00000074}, // AP_WAKE_BT + {0x1C4, 0x00000074}, // BT_RST + {0x1CC, 0x00000074}, // AP_WAKE_NFC + {0x250, 0x00000074}, // GPIO_PH6 }; static uint32_t pinmux_reset_default(uint64_t addr) { @@ -185,6 +204,8 @@ static const uint32_t uart_bases[EmuState::N_UARTS] = { // Per-port electrical state the plain register cache cannot express. struct UartPort { uint16_t divisor = 0; // latched DLL/DLM, i.e. the programmed baud + uint8_t ier = 0; // IER, which shares +0x04 with DLM + uint8_t fcr = 0; // FCR, write-only; IIR 7:6 reports its bit 0 uint8_t mcr = 0; // last MCR write; bit 4 = internal loopback uint8_t msr_delta = 0; // MSR bits 3:0: set on change, cleared on read bool cts = false; // peer drove its RTS_N low -> MSR bit 4 @@ -265,8 +286,10 @@ static bool bt_radio_alive(EmuState *state) { // could observe it rather than from a timer: emu_usec only moves while the // CPU runs, so "now" is always current at the point of a register access. static void bt_chip_tick(EmuState *state) { + // `now` can step back a little when CPU0 takes the bus (it trails the + // BPMP by up to a slice), so compare rather than subtract. if (bt_chip.phase == BT_PHASE_POR && - state->emu_usec - bt_chip.por_us >= BT_POR_US) + state->emu_usec >= bt_chip.por_us + BT_POR_US) bt_chip.phase = BT_PHASE_READY; } @@ -518,9 +541,16 @@ uint32_t gpio_read(EmuState *state, uint64_t addr) { bool abs_off = (csr & (1u << 24)) != 0; uint32_t inv_duty = (csr >> 16) & 0xFF; // inverted: 236 = ~0% bool spinning = ch_en && !abs_off && inv_duty < 236; - if (spinning && ((state->emu_usec / 2186ull) & 1ull)) - return (1u << 7); - return 0; + uint32_t v = (spinning && ((state->emu_usec / 2186ull) & 1ull)) ? (1u << 7) : 0; + // PS3 is the gamecard slot's card detect: active low, pulled up. No + // cartridge is emulated, so an undriven PS3 reads high ("slot empty") - + // it read 0, "cartridge seated", before. + uint32_t oe = mmio_regs.get(GPIO_BASE + 0x418); + if (!(oe & (1u << 3))) + v |= 1u << 3; + // Pins the payload drives itself read back what it drives. + v = (v & ~oe) | (mmio_regs.get(GPIO_BASE + 0x428) & oe & 0x7F); + return v; } // Port H IN. Resolved per pin (see gpio_h_in) instead of mirroring OUT, @@ -653,10 +683,14 @@ static uint16_t codec_reg_get(uint8_t reg) { // the values the fixed answers used to give. // // MAX77621 VOUT/VOUT_DVS: bit 7 = enable, bits 6:0 = 606.25 mV + N*6.25 mV. -static uint8_t max77621_regs[2][8] = { +static const uint8_t kMax77621Seed[2][8] = { {0x80 | 63, 0x80 | 63, 0, 0, 0, 0, 0, 0}, // CPU, 1.000 V {0x80 | 63, 0x80 | 63, 0, 0, 0, 0, 0, 0}, // GPU, 1.000 V }; +static uint8_t max77621_regs[2][8] = { + {0x80 | 63, 0x80 | 63, 0, 0, 0, 0, 0, 0}, + {0x80 | 63, 0x80 | 63, 0, 0, 0, 0, 0, 0}, +}; static uint8_t max77812_regs[256]; static bool max77812_ready = false; @@ -707,15 +741,21 @@ bool cpu_rail_on(EmuState *state) { // Deliberately absent, because they are absent on the board this models: // I2C_1 0x1A TC94B15WBG headphone amp - not fitted on Erista; hwtest // reports "not fitted on this board" and that is correct. -#define I2C_STATUS_NOACK (0xFu << 0) +// I2C_STATUS CMD1_STAT (3:0): 1 = SL1_NOACK_FOR_BYTE1, i.e. nobody answered +// the address byte (TRM 35.x). bdk tests the whole nibble. +#define I2C_STATUS_NOACK (1u << 0) static bool i2c_slave_present(EmuState *state, bool on_i2c5, uint8_t addr) { if (on_i2c5) { + bool mariko = state && state->pmic_otp.load() == 0x53; switch (addr) { - case 0x1B: // MAX77621 CPU DC-DC - case 0x33: // RTC / PMIC sub-block + case 0x1B: // MAX77621 CPU DC-DC (Erista) + case 0x1C: // MAX77621 GPU DC-DC (Erista) + return !mariko; + case 0x33: // MAX77812 CPU/GPU/DRAM buck (Mariko family) + return mariko; case MAX77620_I2C_ADDR: // 0x3C PMIC - case 0x68: // MAX77812 / GPU rail + case 0x68: // MAX77620 RTC sub-block return true; default: return false; @@ -762,11 +802,16 @@ static uint32_t i2c_cnfg_reg[2] = {0, 0}; // Rail-OK status: SD rails via STATSD (0x14, bit set = NOT ok), LDO rails via // each LDOx_CFG2 POK bit (BIT(3)). static bool max77620_regs_ready = false; +static uint8_t max77620_seed_otp = 0; static void max77620_regs_init(EmuState *state) { - if (max77620_regs_ready) + // Seeded for one console generation; switching it in the config window + // re-seeds on the next access instead of keeping the other one's rails. + uint8_t otp = state ? state->pmic_otp.load() : 0; + if (max77620_regs_ready && otp == max77620_seed_otp) return; max77620_regs_ready = true; + max77620_seed_otp = otp; // Two SD rails differ per SoC generation, measured on real consoles: // SD1 (DRAM) 1.125 V Erista (LPDDR4) vs 1.100 V Mariko (LPDDR4X) @@ -823,9 +868,11 @@ static void max77620_regs_init(EmuState *state) { for (int i = 0; i < 9; i++) { const LdoDef &l = ldos[i]; uint8_t code = (uint8_t)(((l.uv - 800000u) / l.step) & 0x3F); - max77620_regs[l.volt_reg] = (uint8_t)(code | (3u << 6)); // POWER_MODE_NORMAL - // CFG2 POK is what max77620_regulator_get_status() reads for an LDO. - max77620_regs[l.volt_reg + 1] = l.on ? (BIT(3) | BIT(2)) : 0x00; + // Power mode in CFG 7:6: NORMAL for a rail that is up, DISABLE for one + // that is down. CFG2 bit 3 (POK), which max77620_regulator_get_status() + // reads, is derived from it on every read (max77620_read). + max77620_regs[l.volt_reg] = (uint8_t)(code | ((l.on ? 3u : 0u) << 6)); + max77620_regs[l.volt_reg + 1] = BIT(2); } // SD CFG1 registers (0x1D..0x20): flag the rails as power-OK too. for (uint8_t r = 0x1D; r <= 0x20; r++) @@ -874,7 +921,8 @@ static void max77620_regs_init(EmuState *state) { // that watches TX_FIFO writes, captures the slave/register/direction, and // pre-fills an RX buffer when a read header arrives. struct PacketState { - int hdr_idx = 0; // word index since last PROT magic + int hdr_idx = 0; // 0 PROT, 1 size, 2 header, 3 payload + uint32_t tx_seen = 0; // payload bytes of this packet so far uint8_t dev_addr = 0; uint32_t payload_size = 0; // bytes bool is_read = false; @@ -1192,7 +1240,15 @@ uint32_t i2c_read(EmuState *state, uint64_t addr) { // payload has written since. Returning 0 here (the old behaviour) made // every rail decode as 0.600 V and made writes look like they had no // effect ("not settable"). - default: return max77620_regs[i2c_reg_addr]; + default: + // LDOn_CFG2 (0x24, 0x26 .. 0x34): POK (bit 3) follows the rail, i.e. + // the power mode in LDOn_CFG, so a rail the payload switches on + // reports good and one it switches off stops doing so. + if (i2c_reg_addr >= 0x24 && i2c_reg_addr <= 0x34 && !(i2c_reg_addr & 1)) { + bool up = (max77620_regs[i2c_reg_addr - 1] >> 6) != 0; + return (max77620_regs[i2c_reg_addr] & ~BIT(3)) | (up ? BIT(3) : 0); + } + return max77620_regs[i2c_reg_addr]; } } // MAX77621 CPU/GPU regulator (slave 0x1B/0x1C on I2C_5, Erista only). @@ -1227,7 +1283,7 @@ uint32_t i2c_read(EmuState *state, uint64_t addr) { // advance the seconds from the emulated clock so repeated reads move // forward (an RTC that never ticks is itself a fault a payload may flag). if (on_i2c5 && i2c_slave_addr == 0x68) { - if (i2c_reg_addr == 0x03) return 0x00; // CONTROL: binary mode, 24h + if (i2c_reg_addr == 0x03) return 0x03; // CONTROL: BIN_FORMAT | 24H if (i2c_reg_addr == 0x04 || i2c_reg_addr == 0x05) return 0x00; // UPDATE0/1: idle if (i2c_reg_addr >= 0x07 && i2c_reg_addr <= 0x0D) { // 2026-01-15 12:34:00 + emulated uptime, in binary (BCD_MODE off). @@ -1340,6 +1396,38 @@ static uint32_t i2c_device_reg_read(EmuState *state, bool on_i2c5, uint8_t slave return v; } +// One register byte written through a packet-mode transfer: the same +// effect on the modelled chips as a normal-mode [reg, value] write. +static void i2c_packet_reg_write(EmuState *state, bool on_i2c5, uint8_t dev, + uint8_t reg, uint8_t v) { + if (!on_i2c5) + return; + bool mariko = state->pmic_otp.load() == 0x53; + if (dev == MAX77620_I2C_ADDR) { + max77620_regs_init(state); + max77620_regs[reg] = v; + if (reg == 0x41 && (v & 0x02)) { // ONOFFCNFG1_PWR_OFF + printf("[emu] MAX77620 PWR_OFF received - exiting\n"); + fflush(stdout); + state->running = false; + } else if (reg == 0x41 && (v & 0x80)) { // ONOFFCNFG1_SFT_RST + printf("[emu] MAX77620 SFT_RST received - rebooting payload\n"); + fflush(stdout); + request_reboot(state, true); + } + if (reg == 0x3B || reg == 0x40) + ccplex_rail_changed(state); + } else if (!mariko && (dev == 0x1B || dev == 0x1C) && reg < 8 && + reg != 0x04 && reg != 0x05) { + max77621_regs[dev - 0x1B][reg] = v; + ccplex_rail_changed(state); + } else if (mariko && dev == 0x33 && reg != 0x14) { + max77812_regs_init(); + max77812_regs[reg] = v; + ccplex_rail_changed(state); + } +} + void i2c_write(EmuState *state, uint64_t addr, uint32_t val) { bool on_i2c5 = (addr >= I2C5_BASE); uint32_t base = on_i2c5 ? I2C5_BASE : I2C1_BASE; @@ -1421,48 +1509,52 @@ void i2c_write(EmuState *state, uint64_t addr, uint32_t val) { } else if (v & 0x80) { // ONOFFCNFG1_SFT_RST printf("[emu] MAX77620 SFT_RST received - rebooting payload\n"); fflush(stdout); - state->reboot_requested = true; + request_reboot(state, true); } } break; case 0x50: { // I2C_TX_FIFO (packet-mode dispatch) - // Each packet starts with the PROT magic word; subsequent words follow a - // fixed layout: [size-1, header, payload...]. The header carries dev_addr - // and a READ flag; for write phases the first payload byte is the slave's - // register address that the matching read phase will target. - if (val == I2C_PACKET_PROT_I2C) { - pkt.hdr_idx = 1; // word 0 (PROT) just consumed - return; - } - int idx = pkt.hdr_idx++; - if (idx == 1) { + // The word stream bdk's _i2c_send_packet / i2c_xfer_packet push: + // PROT_I2C, size-1, header (addr << 1 | READ/REP_START...), then the + // payload packed four bytes to a word, little-endian. + // A combined write+read sends its second packet straight after the + // first, with no FIFO flush, so a packet ends when its payload has been + // seen. The PROT marker is only looked for at a packet boundary: as a + // data word, 0x10 is just a register number or a length. + switch (pkt.hdr_idx) { + case 0: + if (val == I2C_PACKET_PROT_I2C) + pkt.hdr_idx = 1; + break; + case 1: pkt.payload_size = (val & 0xFFF) + 1; - } else if (idx == 2) { + pkt.hdr_idx = 2; + break; + case 2: pkt.dev_addr = (val >> 1) & 0x7F; pkt.is_read = (val & I2C_HEADER_READ) != 0; i2c_slave_addr = pkt.dev_addr; // mirror for any cross-path lookups + pkt.tx_seen = 0; if (pkt.is_read) { packet_populate_rx(state, on_i2c5, pkt); + pkt.hdr_idx = 0; + } else { + pkt.hdr_idx = 3; } - } else if (!pkt.is_read && idx == 3) { - // First (and for our slaves, only) payload byte = register address. - pkt.reg_addr = val & 0xFF; - } else if (!pkt.is_read && idx == 4) { - // Second payload byte = value being written. Watch for PMIC commands - // that mean "shut the SoC down" or "reset" so the emulator can react - // the same way real hardware would. - if (on_i2c5 && pkt.dev_addr == 0x3C && pkt.reg_addr == 0x41) { - uint8_t v = val & 0xFF; - if (v & 0x02) { // ONOFFCNFG1_PWR_OFF - printf("[emu] MAX77620 PWR_OFF received - exiting\n"); - fflush(stdout); - state->running = false; - } else if (v & 0x80) { // ONOFFCNFG1_SFT_RST - printf("[emu] MAX77620 SFT_RST received - rebooting payload\n"); - fflush(stdout); - state->reboot_requested = true; - } + break; + default: + for (int k = 0; k < 4 && pkt.tx_seen < pkt.payload_size; k++) { + uint8_t b = (uint8_t)(val >> (8 * k)); + if (pkt.tx_seen == 0) + pkt.reg_addr = b; // first payload byte: the register address + else + i2c_packet_reg_write(state, on_i2c5, pkt.dev_addr, + (uint8_t)(pkt.reg_addr + pkt.tx_seen - 1), b); + pkt.tx_seen++; } + if (pkt.tx_seen >= pkt.payload_size) + pkt.hdr_idx = 0; + break; } break; } @@ -1619,6 +1711,11 @@ uint32_t misc_read(EmuState *state, uint64_t addr) { // Erista 0x00022117 (major 1, minor 2). if (addr == APB_MISC_BASE + 0x804) return state->is_mariko.load() ? 0x00012127u : 0x00022117u; + // The rest of APB_MISC (pad control, GP_* configuration, PINMUX_GLOBAL): + // R/W registers that read back what was written. They read 0 before even + // though every write was cached, so a read-modify-write lost its bits. + if (addr >= APB_MISC_BASE && addr < PINMUX_BASE) + return mmio_regs.get(addr); // UART if (addr >= 0x70006000 && addr < 0x70006500) { @@ -1651,6 +1748,13 @@ uint32_t misc_read(EmuState *state, uint64_t addr) { // read, which is why the payload sees 0x4F once right after its // loopback self-test and 0x40 on every quiet read afterwards. uint32_t msr = 0x40 | (up.cts ? 0x10 : 0) | up.msr_delta; + // In internal loopback the modem inputs come from this port's own + // outputs instead (TRM 36.x): RTS -> CTS, DTR -> DSR, OUT1 -> RI, + // OUT2 -> DCD. + if (up.mcr & 0x10) + msr = up.msr_delta | ((up.mcr & 0x02) ? 0x10 : 0) | + ((up.mcr & 0x01) ? 0x20 : 0) | ((up.mcr & 0x04) ? 0x40 : 0) | + ((up.mcr & 0x08) ? 0x80 : 0); up.msr_delta = 0; return msr; } @@ -1666,6 +1770,19 @@ uint32_t misc_read(EmuState *state, uint64_t addr) { return up.divisor & 0xFF; // DLL if (offset == 0x04 && dlab) return (up.divisor >> 8) & 0xFF; // DLM + if (offset == 0x04) + return up.ier; + if (offset == 0x08) { + // IIR, read-only (FCR is the write-only register at the same offset): + // 7:6 set while the FIFOs are enabled, then the highest-priority + // pending interrupt - received data, then THR empty - or 1 for none. + uint32_t iir = (up.fcr & 0x01) ? 0xC0 : 0x00; + if ((up.ier & 0x01) && !state->uart_rx_fifo[port].empty()) + return iir | 0x04; + if (up.ier & 0x02) + return iir | 0x02; + return iir | 0x01; + } if (offset == 0x00) { // RBR: pop the next queued byte; empty FIFO returns 0 (the payload @@ -1808,11 +1925,13 @@ uint32_t misc_read(EmuState *state, uint64_t addr) { 0x376CD08C; // Full Tegra capabilities (64-bit, SDMA, ADMA2, etc.) else if (offset == 0x44) result = 0x10002F73; // CAP1 - else if (offset == 0x30) - result = ((base == SDMMC4_BASE ? state->sdmmc4_errintsts - : state->sdmmc_errintsts) - << 16) | - norintsts; + else if (offset == 0x30) { + // NORMAL_INT_STATUS bit 15, ERR_INTERRUPT, is the OR of every error + // bit (SDHCI 2.2.18) - what BDK's _sdmmc_check_mask_interrupt tests. + uint32_t err = base == SDMMC4_BASE ? state->sdmmc4_errintsts + : state->sdmmc_errintsts; + result = (err << 16) | norintsts | (err ? 0x8000u : 0u); + } else if (offset == 0x32) result = (base == SDMMC4_BASE) ? state->sdmmc4_errintsts : state->sdmmc_errintsts; @@ -1831,6 +1950,28 @@ uint32_t misc_read(EmuState *state, uint64_t addr) { return 0; } +// Where a single-buffer data phase (EXT_CSD, CMD6 status, ACMD13, SCR) lands. +// Tegra's SDMA takes its system address from 0x58 (bdk _sdmmc_dma_init +// writes it there, SD Host Controller v4 style), falling back to the +// standard 0x00 SDMA register. Under ADMA2 it is the first descriptor's +// buffer: 32-bit address in an 8-byte descriptor, 64-bit in a 12-byte one. +static uint64_t sdmmc_dma_target(uc_engine *uc, uint8_t hostctl, + uint64_t adma_addr, uint32_t sysad) { + uint32_t dmasel = hostctl & 0x18; + if (dmasel == 0x10 || dmasel == 0x18) { + uint8_t d[12] = {0}; + if (uc_mem_read(uc, adma_addr, d, dmasel == 0x18 ? 12 : 8) != UC_ERR_OK) + return 0; + uint64_t a = (uint64_t)d[4] | ((uint64_t)d[5] << 8) | + ((uint64_t)d[6] << 16) | ((uint64_t)d[7] << 24); + if (dmasel == 0x18) + a |= ((uint64_t)d[8] | ((uint64_t)d[9] << 8) | ((uint64_t)d[10] << 16) | + ((uint64_t)d[11] << 24)) << 32; + return a; + } + return adma_addr ? adma_addr : sysad; +} + void misc_write(uc_engine *uc, EmuState *state, uint64_t addr, int64_t value, int size) { uint32_t val = (uint32_t)value; @@ -1949,6 +2090,11 @@ void misc_write(uc_engine *uc, EmuState *state, uint64_t addr, int64_t value, switch (cmd) { case 0: + // GO_IDLE_STATE: the eMMC comes back in its user area (PARTITION_ + // ACCESS = 0). Leaving BOOT0 selected made the next init read the + // GPT - and write user data - into the boot partition's image. + if (base == SDMMC4_BASE) + state->emmc_partition = 0; break; case 8: rsp[0] = (base == SDMMC4_BASE) ? 0x00000900 : arg; @@ -1992,7 +2138,7 @@ void misc_write(uc_engine *uc, EmuState *state, uint64_t addr, int64_t value, // captures that write, so it IS the destination, not a descriptor // pointer. Fall back to sysad (SDHCI standard 0x00) if 0x58 wasn't // programmed. - dma_addr = adma_addr ? adma_addr : sysad; + dma_addr = sdmmc_dma_target(uc, hostctl, adma_addr, sysad); if (dma_addr) uc_mem_write(uc, dma_addr, ext_csd, 512); norintsts |= 0x0002; // TRANSFER_COMPLETE } @@ -2089,23 +2235,9 @@ void misc_write(uc_engine *uc, EmuState *state, uint64_t addr, int64_t value, if (is_acmd) { uint8_t ss[64] = {0}; ss[0] = 0x80; // 4-bit support (bit 511:510 = 10) - uint64_t dma_addr = 0; - if (trnmod & 0x0001) { - if ((hostctl & 0x18) == 0x10) { // ADMA2 - uint8_t desc[12]; - if (uc_mem_read(uc, adma_addr, desc, 12) == UC_ERR_OK) { - uint32_t low = *(uint32_t *)(desc + 4); - uint32_t high = *(uint32_t *)(desc + 8); - dma_addr = ((uint64_t)high << 32) | low; - } - } else { // SDMA - dma_addr = sysad; - } - if (dma_addr) - uc_mem_write(uc, dma_addr, ss, 64); - } else { - uc_mem_write(uc, sysad, ss, 64); - } + uint64_t dma_addr = sdmmc_dma_target(uc, hostctl, adma_addr, sysad); + if (dma_addr) + uc_mem_write(uc, dma_addr, ss, 64); norintsts |= 0x0002; } rsp[0] = r1_base | (4 << 9); // TRAN state @@ -2139,23 +2271,9 @@ void misc_write(uc_engine *uc, EmuState *state, uint64_t addr, int64_t value, status[13] = 0x02; // HS Support status[16] = 0x01; // Group 1 switched to HS - uint64_t dma_addr = 0; - if (trnmod & 0x0001) { // DMA Enabled - if ((hostctl & 0x18) == 0x10) { // ADMA2 - uint8_t desc[12]; - if (uc_mem_read(uc, adma_addr, desc, 12) == UC_ERR_OK) { - uint32_t low = *(uint32_t *)(desc + 4); - uint32_t high = *(uint32_t *)(desc + 8); - dma_addr = ((uint64_t)high << 32) | low; - } - } else { // SDMA - dma_addr = sysad; - } - if (dma_addr) - uc_mem_write(uc, dma_addr, status, 64); - } else { // PIO - uc_mem_write(uc, sysad, status, 64); - } + uint64_t dma_addr = sdmmc_dma_target(uc, hostctl, adma_addr, sysad); + if (dma_addr) + uc_mem_write(uc, dma_addr, status, 64); norintsts |= 0x0002; // Transfer Complete rsp[0] = r1_base | (4 << 9); } else if (base == SDMMC4_BASE) { @@ -2197,7 +2315,7 @@ void misc_write(uc_engine *uc, EmuState *state, uint64_t addr, int64_t value, // Tegra drives this small read over SDMA with the destination in // register 0x58 (captured here as adma_addr), NOT the SDHCI-standard // sysad (0x00), which Tegra leaves unused. Matches the EXT_CSD path. - uint64_t dma_addr = adma_addr ? adma_addr : sysad; + uint64_t dma_addr = sdmmc_dma_target(uc, hostctl, adma_addr, sysad); if (dma_addr) uc_mem_write(uc, dma_addr, scr, 8); norintsts |= 0x0002; @@ -2226,7 +2344,7 @@ void misc_write(uc_engine *uc, EmuState *state, uint64_t addr, int64_t value, fd = -2; // GPP (handled below) } - if (fd != -1) { + { // fd == -1: no image behind it - do_io serves it as blank uint64_t sector = arg; uint64_t file_off = sector * 512; uint16_t bcnt = @@ -2241,8 +2359,36 @@ void misc_write(uc_engine *uc, EmuState *state, uint64_t addr, int64_t value, } size_t xfer_len = bcnt * 512; + // A write that did not land, or a DMA address nothing backs, ends + // the command with a data error instead of a silent "complete". + bool io_err = false; + // Read `len` bytes at `off` of one image file into buf. Anything + // past its end reads as blank, as on a card larger than its dump. + auto file_read = [&](int f, uint64_t off, uint8_t *buf, size_t len) { + ssize_t res = pread(f, buf, len, (off_t)off); + if (res < 0) + res = 0; + if ((size_t)res < len) + TRACE("[sdmmc] short read at 0x%llX: %zd of %zu bytes\n", + (unsigned long long)off, res, len); + }; + auto file_write = [&](int f, uint64_t off, const uint8_t *buf, + size_t len) { + ssize_t res = pwrite(f, buf, len, (off_t)off); + if (res != (ssize_t)len) { + printf("[sdmmc] write of %zu bytes at 0x%llX failed (%zd)\n", len, + (unsigned long long)off, res); + io_err = true; + } + }; + auto do_io = [&](int current_fd, uint64_t current_off, uint64_t dma_addr, size_t len) { + std::vector io_buf(len, 0); + if (!is_read && uc_mem_read(uc, dma_addr, io_buf.data(), len) != UC_ERR_OK) { + io_err = true; + return; + } if (current_fd == -2) { // GPP Spanning // No rawnand image loaded: serve a synthesized valid GPT so the // [eMMC GPT] probe sees "EFI PART" with good CRCs instead of @@ -2251,92 +2397,100 @@ void misc_write(uc_engine *uc, EmuState *state, uint64_t addr, int64_t value, if (is_read) { size_t glen = 0; const uint8_t *gpt = emmc_synth_gpt(&glen); - std::vector io_buf(len, 0); for (size_t o = 0; o < len; o++) { uint64_t abs = current_off + o; if (abs < glen) io_buf[o] = gpt[abs]; } - uc_mem_write(uc, dma_addr, io_buf.data(), len); } - return; - } - // Hekate-style rawnand splitting can use 2GB or 4GB chunks. - // Stat the first part once and cache; assumes all but the last - // part are the same size (true for both Hekate's standard - // 4GB-FAT32-friendly splits and tools that use 2GB chunks). - static size_t part_size = 0; - if (!part_size && !state->emmc_gpp_fds.empty()) { - int64_t sz = file_size64(state->emmc_gpp_fds[0]); - if (sz > 0) - part_size = (size_t)sz; - else - part_size = 4ULL * 1024 * 1024 * 1024; - TRACE("[sdmmc] GPP part size detected: %zu bytes\n", part_size); - } - if (!part_size) return; // No GPP files — nothing to read. - int part_idx = (int)(current_off / part_size); - uint64_t part_off = current_off % part_size; - if (part_idx < (int)state->emmc_gpp_fds.size()) { - int real_fd = state->emmc_gpp_fds[part_idx]; - std::vector io_buf(len); - if (is_read) { - ssize_t res = pread(real_fd, io_buf.data(), len, part_off); - if (res != (ssize_t)len) - TRACE("[sdmmc] eMMC GPP READ ERROR: res=%zd, " - "expected=%zu, off=0x%llX\n", - res, len, (unsigned long long)part_off); - uc_mem_write(uc, dma_addr, io_buf.data(), len); - } else { - uc_mem_read(uc, dma_addr, io_buf.data(), len); - ssize_t res = pwrite(real_fd, io_buf.data(), len, part_off); - if (res != (ssize_t)len) - TRACE("[sdmmc] eMMC GPP WRITE ERROR: res=%zd, " - "expected=%zu, off=0x%llX\n", - res, len, (unsigned long long)part_off); + } else { + // Hekate-style rawnand splitting can use 2GB or 4GB chunks. + // Stat the first part once and cache; assumes all but the + // last part are the same size (true for both Hekate's + // standard 4GB-FAT32-friendly splits and tools that use 2GB + // chunks). + static uint64_t part_size = 0; + if (!part_size) { + int64_t sz = file_size64(state->emmc_gpp_fds[0]); + part_size = sz > 0 ? (uint64_t)sz : 4ULL * 1024 * 1024 * 1024; + TRACE("[sdmmc] GPP part size detected: %llu bytes\n", + (unsigned long long)part_size); + } + // A transfer can straddle two parts (a 2 GiB split falls in + // the middle of SYSTEM): go part by part. Past the last part + // the device is blank; writes there have nowhere to go. + size_t done = 0; + while (done < len) { + uint64_t off = current_off + done; + size_t idx = (size_t)(off / part_size); + uint64_t part_off = off % part_size; + size_t n = (size_t)std::min(len - done, part_size - part_off); + if (idx < state->emmc_gpp_fds.size()) { + int real_fd = state->emmc_gpp_fds[idx]; + if (is_read) + file_read(real_fd, part_off, io_buf.data() + done, n); + else + file_write(real_fd, part_off, io_buf.data() + done, n); + } else if (!is_read) { + printf("[sdmmc] eMMC write past the last rawnand part " + "(0x%llX) dropped\n", (unsigned long long)off); + io_err = true; + } + done += n; } } } else if (current_fd >= 0) { - std::vector io_buf(len); - if (is_read) { - ssize_t res = - pread(current_fd, io_buf.data(), len, current_off); - if (res != (ssize_t)len) - TRACE("[sdmmc] SD/BOOT READ ERROR: res=%zd, expected=%zu, " - "off=0x%llX\n", - res, len, (unsigned long long)current_off); - uc_mem_write(uc, dma_addr, io_buf.data(), len); - } else { - uc_mem_read(uc, dma_addr, io_buf.data(), len); - ssize_t res = - pwrite(current_fd, io_buf.data(), len, current_off); - if (res != (ssize_t)len) - TRACE("[sdmmc] SD/BOOT WRITE ERROR: res=%zd, expected=%zu, " - "off=0x%llX\n", - res, len, (unsigned long long)current_off); - } + if (is_read) + file_read(current_fd, current_off, io_buf.data(), len); + else + file_write(current_fd, current_off, io_buf.data(), len); } + // No image behind this partition (BOOT1, a BOOT0 not given): + // it reads as blank and swallows writes. + if (is_read && uc_mem_write(uc, dma_addr, io_buf.data(), len) != UC_ERR_OK) + io_err = true; }; if (trnmod & 0x0001) { // DMA Enabled (Bit 0 of TRNMOD) - if ((hostctl & 0x18) == 0x10) { // ADMA2 - // Parse ADMA2 descriptors + uint32_t dmasel = hostctl & 0x18; + if (dmasel == 0x10 || dmasel == 0x18) { + // ADMA2 (SD Host Controller spec 1.13): each descriptor is + // attr (bit 0 Valid, bit 1 End, 5:4 Act: 10b transfer, 11b + // link), a 16-bit length (0 = 64 KiB) and the address - 32 + // bits in an 8-byte descriptor, 64 in a 12-byte one. The walk + // is bounded: a table with no End bit must not run through all + // of DRAM. + bool d64 = dmasel == 0x18; uint64_t desc_addr = adma_addr; - uint8_t desc[12]; - while (true) { - if (uc_mem_read(uc, desc_addr, desc, 12) != UC_ERR_OK) + for (int n = 0; n < 4096; n++) { + uint8_t desc[12] = {0}; + if (uc_mem_read(uc, desc_addr, desc, d64 ? 12 : 8) != UC_ERR_OK) { + errintsts |= 1u << 9; // ADMA error break; - uint16_t attr = desc[0]; - uint16_t len = *(uint16_t *)(desc + 2); - uint32_t low = *(uint32_t *)(desc + 4); - uint32_t high = *(uint32_t *)(desc + 8); - uint64_t dma_addr = ((uint64_t)high << 32) | low; - if ((attr & 0x3) == 0x2) { // Action: Transfer - do_io(fd, file_off, dma_addr, len); - file_off += len; } - if (attr & 0x02) - break; // End bit is bit 1 - desc_addr += 12; + uint16_t attr = (uint16_t)(desc[0] | (desc[1] << 8)); + uint32_t dlen = (uint32_t)(desc[2] | (desc[3] << 8)); + if (!dlen) + dlen = 65536; + uint64_t addr = (uint64_t)desc[4] | ((uint64_t)desc[5] << 8) | + ((uint64_t)desc[6] << 16) | ((uint64_t)desc[7] << 24); + if (d64) + addr |= ((uint64_t)desc[8] | ((uint64_t)desc[9] << 8) | + ((uint64_t)desc[10] << 16) | ((uint64_t)desc[11] << 24)) << 32; + if (!(attr & 0x01)) { // not Valid: the engine stops, in error + errintsts |= 1u << 9; + break; + } + uint32_t act = (attr >> 4) & 3; + if (act == 2) { // transfer + do_io(fd, file_off, addr, dlen); + file_off += dlen; + } else if (act == 3) { // link to the next table + desc_addr = addr; + continue; + } + if (attr & 0x02) // End + break; + desc_addr += d64 ? 12 : 8; } } else { // SDMA do_io(fd, file_off, adma_addr, xfer_len); @@ -2344,7 +2498,13 @@ void misc_write(uc_engine *uc, EmuState *state, uint64_t addr, int64_t value, } else { // PIO do_io(fd, file_off, sysad, xfer_len); } + if (io_err) + errintsts |= 1u << 4; // data timeout } + // R1 for the read/write command itself: TRAN, READY_FOR_DATA, no + // error bits. bdk checks this cached response after every transfer; + // it used to hold whatever the previous command had answered. + rsp[0] = r1_base | (4 << 9) | (1u << 8); norintsts |= 0x0002; // Transfer Complete break; } @@ -2364,24 +2524,37 @@ void misc_write(uc_engine *uc, EmuState *state, uint64_t addr, int64_t value, // ==================== PMC ==================== +// APBDEV_RTC (TRM 11.x). SECONDS counts once per second and is writable; +// reading MILLI_SECONDS snapshots SECONDS into SHADOW_SECONDS, which is how +// bdk's get_tmr_ms() reads both halves of one instant. The RTC is always-on: +// it keeps counting across a SoC reset (rtc_base_us carries the time over). +static uint64_t rtc_base_us = 0; // RTC time at emu_usec == 0 +static int64_t rtc_sec_adjust = 0; // SECONDS writes, as an offset +static uint32_t rtc_shadow_seconds = 0; + +static uint32_t rtc_seconds(EmuState *state) { + return (uint32_t)((int64_t)((rtc_base_us + state->emu_usec) / 1000000) + + rtc_sec_adjust); +} + uint32_t rtc_read(EmuState *state, uint64_t addr) { uint32_t offset = (uint32_t)(addr - RTC_BASE); - uint64_t ms = state->emu_usec / 1000; - switch (offset) { + case 0x08: + return rtc_seconds(state); // APBDEV_RTC_SECONDS case 0x0C: - return (uint32_t)(ms / 1000); // APBDEV_RTC_SHADOW_SECONDS - case 0x10: - return (uint32_t)(ms % 1000); // APBDEV_RTC_MILLI_SECONDS + return rtc_shadow_seconds; // APBDEV_RTC_SHADOW_SECONDS + case 0x10: // APBDEV_RTC_MILLI_SECONDS + rtc_shadow_seconds = rtc_seconds(state); + return (uint32_t)(((rtc_base_us + state->emu_usec) / 1000) % 1000); default: - return 0; + return mmio_regs.get(addr); } } void rtc_write(EmuState *state, uint64_t addr, uint32_t val) { - (void)state; - (void)addr; - (void)val; + if ((uint32_t)(addr - RTC_BASE) == 0x08) + rtc_sec_adjust += (int64_t)val - (int64_t)rtc_seconds(state); } // ---- power partitions and I/O-pad deep power down -------------------------- @@ -2398,6 +2571,10 @@ void rtc_write(EmuState *state, uint64_t addr, uint32_t val) { // and a Mariko (hwtest's Wi-Fi probe reads PWRGATE_STATUS before touching it). static uint32_t pmc_pwrgate_status = 1u << 3; static uint32_t pmc_io_dpd_status[2] = {0, 0}; +// Everything else in the PMC is plain read/write storage: the scratch +// registers payloads leave notes in, the secure scratch the SE deposits its +// context key in, pad and timing configuration. +static uint32_t pmc_regs[PMC_SIZE / 4]; bool pmc_partition_on(int part) { return part >= 0 && part < 32 && ((pmc_pwrgate_status >> part) & 1); @@ -2416,10 +2593,6 @@ uint32_t pmc_read(EmuState *state, uint64_t addr) { return pmc_io_dpd_status[0]; // APBDEV_PMC_IO_DPD_STATUS case 0x1C4: return pmc_io_dpd_status[1]; // APBDEV_PMC_IO_DPD2_STATUS - case 0x50: - return pmc_scratch0; // APBDEV_PMC_SCRATCH0 - case 0x1A0: - return 0; // PMC_PWR_DET - all rails OK case 0x2BC: // APBDEV_PMC_GLB_AMAP_CFG: which CCPLEX apertures decode as MMIO or DRAM // (TRM 12.6.172). Measured 0x00020000 in RCM; bits 1..3 clear means the @@ -2427,14 +2600,23 @@ uint32_t pmc_read(EmuState *state, uint64_t addr) { // the root complex depend on. return 0x00020000; default: - return 0; + return offset < PMC_SIZE ? pmc_regs[offset / 4] : 0; } } +void pmc_secure_scratch_write(unsigned n, uint32_t value) { + static const uint16_t kOffset[8] = {0xB0, 0xB4, 0xB8, 0xBC, + 0xC0, 0xC4, 0x224, 0x228}; + if (n < 8) + pmc_regs[kOffset[n] / 4] = value; +} + // ==================== PMC ==================== void pmc_write(EmuState *state, uint64_t addr, uint32_t val) { uint32_t offset = (uint32_t)(addr - PMC_BASE); + if (offset < PMC_SIZE) + pmc_regs[offset / 4] = val; switch (offset) { case 0x00: // APBDEV_PMC_CNTRL — bit 4 = MAIN_RST. Hekate writes this from @@ -2443,7 +2625,7 @@ void pmc_write(EmuState *state, uint64_t addr, uint32_t val) { if (val & (1u << 4)) { printf("[emu] PMC MAIN_RST written - rebooting payload\n"); fflush(stdout); - state->reboot_requested = true; + request_reboot(state, false); } break; case 0x30: { @@ -2472,12 +2654,6 @@ void pmc_write(EmuState *state, uint64_t addr, uint32_t val) { pmc_io_dpd_status[bank] |= mask; // DPD ON: park them break; } - case 0x50: - pmc_scratch0 = val; - break; - case 0x120: - pmc_scratch37 = val; - break; } } @@ -2494,59 +2670,130 @@ static constexpr uint32_t HALT_MSEC = 1u << 24; static constexpr uint32_t HALT_USEC = 1u << 25; static constexpr uint32_t HALT_TIMED = HALT_SEC | HALT_MSEC | HALT_USEC; -// FLOW_CTLR_RAM_REPAIR (0x40): bit 0 = REQ, bit 1 = STS. -// ccplex_boot_cpu0() requests RAM repair for the fast cluster and then spins -// on STS with no timeout (bdk soc/ccplex.c). Reads used to fall through to 0, -// so anything that brings up the CCPLEX - e.g. a payload running its memory -// test on the A57s - hung there forever. Latch REQ and report the repair as -// complete straight away. +// FLOW_CTLR_RAM_REPAIR (0x40, TRM 17.2.9, reset 0x4 = BYPASS_EN). Software +// sets REQ (bit 0); hardware repairs every segment, sets STS (bit 1, read- +// only) and clears REQ again. ccplex_boot_cpu0() sets REQ and spins on STS +// with no timeout (bdk soc/ccplex.c), so the repair completes at once. static constexpr uint32_t RAM_REPAIR_REQ = 1u << 0; static constexpr uint32_t RAM_REPAIR_STS = 1u << 1; -static uint32_t flow_ram_repair = 0; +static constexpr uint32_t RAM_REPAIR_RESET = 1u << 2; // BYPASS_EN +static uint32_t flow_ram_repair = RAM_REPAIR_RESET; -bool flow_ram_repair_done() { return (flow_ram_repair & RAM_REPAIR_REQ) != 0; } +// ---- 1 MHz timers TMR0..TMR9 ---------------------------------------------- +// +// Only what a halted BPMP needs: bdk's timer_usleep() arms TMR8 and stops +// the core with FLOW_MODE_STOP_UNTIL_IRQ until it fires. PTV (TRM 8.7.1): +// bit 31 EN, bit 30 PER (periodic), 28:0 the count, in an n+1 scheme. +static const uint16_t kTmrPtv[10] = {0x88, 0x00, 0x08, 0x50, 0x58, + 0x60, 0x68, 0x70, 0x78, 0x80}; // TMR0..9 +static uint64_t tmr_armed_us[10]; +static constexpr uint32_t TMR_EN = 1u << 31, TMR_PER = 1u << 30; + +static void tmr_write(EmuState *state, uint64_t addr, uint32_t val) { + uint32_t off = (uint32_t)(addr - TMR_BASE); + for (int t = 0; t < 10; t++) + if (off == kTmrPtv[t] && (val & TMR_EN)) + tmr_armed_us[t] = state->emu_usec; +} + +// The first armed timer to fire: its expiry time. One-shot timers disarm, +// periodic ones re-arm from their expiry. +static bool tmr_fire_next(EmuState *state, uint64_t *when) { + int best = -1; + uint64_t best_at = 0; + for (int t = 0; t < 10; t++) { + uint32_t ptv = mmio_regs.get(TMR_BASE + kTmrPtv[t]); + if (!(ptv & TMR_EN)) + continue; + uint64_t at = tmr_armed_us[t] + (ptv & 0x1FFFFFFF) + 1; + if (best < 0 || at < best_at) { + best = t; + best_at = at; + } + } + if (best < 0) + return false; + uint64_t addr = TMR_BASE + kTmrPtv[best]; + uint32_t ptv = mmio_regs.get(addr); + if (ptv & TMR_PER) + tmr_armed_us[best] = best_at; + else + mmio_regs[addr] = ptv & ~TMR_EN; + *when = best_at > state->emu_usec ? best_at : state->emu_usec; + return true; +} static uint32_t flow_read(EmuState *state, uint64_t addr) { (void)state; uint32_t offset = (uint32_t)(addr - 0x60007000); if (offset == 0x40) - return flow_ram_repair | (flow_ram_repair & RAM_REPAIR_REQ ? RAM_REPAIR_STS : 0); + return flow_ram_repair; return mmio_regs.get(addr); } static void flow_write(EmuState *state, uint64_t addr, uint32_t val) { uint32_t offset = (uint32_t)(addr - 0x60007000); if (offset == 0x40) { - flow_ram_repair = val; + flow_ram_repair = (val & ~(RAM_REPAIR_REQ | RAM_REPAIR_STS)) | + (flow_ram_repair & RAM_REPAIR_STS); + if (val & RAM_REPAIR_REQ) + flow_ram_repair |= RAM_REPAIR_STS; return; } if (offset == 0x04) { - // Two very different things get written here and they must not be - // conflated: + // HALT_COP_EVENTS: MODE in 31:29 (TRM 17.2.2). + // 0 NONE, 1 RUN_AND_INT - no halt at all + // 2/3 WAITEVENT(_AND_INT) - stop until an event source fires + // 4/5 STOP_UNTIL_IRQ(_AND_INT), 6 STOP_UNTIL_EVENT_AND_IRQ + // Three different things arrive here: // // 1. bpmp_usleep() / bpmp_msleep() park the BPMP with a TIMER event // source (HALT_USEC / HALT_MSEC / HALT_SEC) plus a delay count, to // sleep with the core clock-gated. The timer event wakes the core - // and execution continues. This is a routine sleep and happens all - // over the BDK - treating it as terminal killed any payload that - // slept this way (e.g. a 200 ms bpmp_msleep = 0x410000C8). - // - // 2. bpmp_halt() writes WAITEVENT | JTAG with no timer source and is + // and execution continues. + // 2. timer_usleep() arms TMR8 and waits in STOP_UNTIL_IRQ for its + // interrupt, the only interrupt source modelled here. + // 3. bpmp_halt() writes WAITEVENT | JTAG with no timer source and is // followed by `while(true);`. That one really is "payload done" - // (power-off / reboot / fatal), so we exit cleanly. + // (power-off / reboot / fatal) - unless CPU0 is still running, as + // after fusee's or hekate's L4T handoff, which then carries on + // alone. + uint32_t mode = val >> 29; + if (mode <= 1) + return; + if (state->reboot_requested) { + // power_set_state() halts right after writing MAIN_RST or SFT_RST: + // the reset is on its way, so this is not the end of the run. + if (g_bus_master == BUS_BPMP) + uc_emu_stop(state->uc); + return; + } + uint64_t wake = 0; if (val & HALT_TIMED) { // Advance the emulated microsecond counter by the requested delay so // TIMERUS-based delta loops observe the time actually passing, then // let the CPU run on. uint32_t delay = val & 0xFF; - uint64_t us = (val & HALT_USEC) ? (uint64_t)delay - : (val & HALT_MSEC) ? (uint64_t)delay * 1000ULL - : (uint64_t)delay * 1000000ULL; - state->emu_usec += us; - state->bpmp_slept_us += us; // feeds the ACTMON BPMP-load model + wake = state->emu_usec + + ((val & HALT_USEC) ? (uint64_t)delay + : (val & HALT_MSEC) ? (uint64_t)delay * 1000ULL + : (uint64_t)delay * 1000000ULL); + } else if (mode >= 4 && !tmr_fire_next(state, &wake)) { + wake = 0; + } + if (wake) { + state->bpmp_slept_us += wake - state->emu_usec; // ACTMON BPMP load + state->emu_usec = wake; bpmp_clock_jumped(); return; } + if (ccplex_cpu0_running()) { + printf("[flow] BPMP halted for good (val=0x%08X); CPU0 runs on\n", val); + fflush(stdout); + state->bpmp_halted = true; + bpmp_yield(); + return; + } printf("[flow] BPMP HALT/WaitEvent (val=0x%08X), shutting down emulator\n", val); state->running = false; @@ -2573,8 +2820,10 @@ static void flow_write(EmuState *state, uint64_t addr, uint32_t val) { // is CLK_L bit 15, which the hardcoded _L value 0x9802D1B0 already carries, so // dropping the forced bit costs the storage model nothing and lets _U match // hardware exactly. -static uint32_t car_rst_u = 0x828EC5F8; -static uint32_t car_enb_u = 0x01F00200; +static constexpr uint32_t CAR_RST_U_RCM = 0x828EC5F8; +static constexpr uint32_t CAR_ENB_U_RCM = 0x01F00200; +static uint32_t car_rst_u = CAR_RST_U_RCM; +static uint32_t car_enb_u = CAR_ENB_U_RCM; uint32_t clk_rst_read(EmuState *state, uint64_t addr) { uint32_t offset = (uint32_t)(addr - CLK_RST_BASE); @@ -2602,9 +2851,16 @@ uint32_t clk_rst_read(EmuState *state, uint64_t addr) { // PLLU 0xC0 down enabled + locked // PLLD 0xD0 enabled + locked enabled + locked // PLLX/D2/DP/RE down on both + // PLLE_BASE (0xE8) and PLLREFE_BASE (0x4C4) are not in this list: bit 30 + // is PLLE's LOCK_OVERRIDE, bit 27 sits inside a divider field in both + // (PLDIV_CML / KCP, TRM 5.2), and they report lock in their _MISC + // registers - pcie_car_read() answers for those. Forcing bit 27 on here + // handed back, and invited a read-modify-write to store, a divider the + // payload never programmed. + if (offset == 0xE8 || offset == 0x4C4) + return mmio_regs.get(addr); switch (offset) { - case 0x80: case 0xB0: case 0xE0: case 0xE8: - case 0x4B8: case 0x4C4: { + case 0x80: case 0xB0: case 0xE0: case 0x4B8: { uint32_t w = mmio_regs.get(addr); if (w & (1u << 30)) return w | (1u << 27); // payload brought it up -> locked @@ -2634,7 +2890,7 @@ uint32_t clk_rst_read(EmuState *state, uint64_t addr) { { switch (offset) { case 0xA4: return 0x00000003; // PLLP_OUTA - case 0x68: return 0x00005C00; // PLLP_OUTB + case 0x68: return 0x00005C00; // PLLE_SS_CNTL (TRM reset value) // SCLK_BURST differs slightly by generation (measured). case 0x28: return mariko ? 0x20003333u : 0x20003330u; case 0x2C: return 0x80000000; // SUPER_SCLK_DIVIDER @@ -2695,8 +2951,11 @@ uint32_t clk_rst_read(EmuState *state, uint64_t addr) { if (offset == 0x5C) return 2343; // -> 38.4 MHz, BUSY clear (we answer instantly) + // OSC_CTRL: 31:28 OSC_FREQ, 5 = 38.4 MHz, the Switch's crystal (TRM + // 5.2.x, reset 0x500003f1; bdk hw_init() writes 0x50000071). This used to + // answer 4, which decodes as 19.2 MHz and contradicted OSC_FREQ_DET. if (offset == 0x50) - return (4 << 28); // OSC_CTRL, informational + return mmio_regs.get(addr, 0x500003F1); if (offset == 0x04) return 0; // RST_DEVICES_L (none in reset) @@ -2735,7 +2994,7 @@ void clk_rst_write(EmuState *state, uint64_t addr, uint32_t val) { } // The PCIe root complex depends on PLLE, PLLREFE and the PCIE/AFI/ // PCIEXCLK/UPHY/padctl reset+enable bits, so it shadows the same writes. - pcie_car_write(offset, val); + pcie_car_write(state, offset, val); // The CPU complex: CPU reset/clock enables, PLLX and CCLK. ccplex_car_write(state, offset, val); } @@ -3121,6 +3380,12 @@ static void audio_play_take(void) { // No ALLOW_ANY_CHANGE: SDL_QueueAudio does not convert, so a device opened // at a different rate or format would replay the take at the wrong pitch. // Better to fail and keep the WAV than to play something misleading. + // One device at a time: a new take replaces the one still playing + // instead of leaking a device per take. + if (audio_dev) { + SDL_CloseAudioDevice(audio_dev); + audio_dev = 0; + } audio_dev = SDL_OpenAudioDevice(nullptr, 0, &want, &have, 0); if (!audio_dev) { printf("[audio] no device (%s) - WAV only\n", SDL_GetError()); @@ -3247,10 +3512,12 @@ static void adma_write(EmuState *state, uint64_t addr, uint32_t val) { // FLOW_CTLR timed halt (bpmp_usleep / bpmp_msleep, tracked in bpmp_slept_us). // A payload that measures load while spinning therefore sees a high number, // and one that measures while sleeping sees a low one - which is exactly what -// an ACTMON test is checking for. +// an ACTMON test is checking for. The COP monitor is the exception: it counts +// the halted time instead, as the hardware does. static constexpr uint32_t ACTMON_OFF_IN_SYSREG = 0x800; static constexpr uint32_t ACTMON_FULL_COUNT = 1920000; // 100.0 % for one period static constexpr int ACTMON_NDEV = 7; +static constexpr int ACTMON_DEV_COP = 1; // device order: CPU, COP, AHB, ... struct ActmonDev { uint32_t ctrl = 0; @@ -3269,7 +3536,7 @@ static uint32_t actmon_glb_period = 0; // Recompute count/avg_count for `d` from the activity in the window that has // elapsed since the last sample. Windows shorter than 200 us reuse the last // value so back-to-back reads stay coherent. -static void actmon_sample(EmuState *state, ActmonDev &d) { +static void actmon_sample(EmuState *state, ActmonDev &d, bool counts_halt) { uint64_t now = state->emu_usec; uint64_t slept = state->bpmp_slept_us; if (!d.seeded) { @@ -3278,15 +3545,21 @@ static void actmon_sample(EmuState *state, ActmonDev &d) { d.seeded = true; return; } - uint64_t window = now - d.last_us; - if (window < 200) + // `now` can step back when CPU0 takes the bus (it trails the BPMP by up to + // a slice); an unsigned difference would wrap into a huge window. + if (now < d.last_us + 200) return; + uint64_t window = now - d.last_us; uint64_t win_slept = slept - d.last_slept; if (win_slept > window) win_slept = window; uint64_t active = window - win_slept; + // The BPMP (COP) monitor counts the cycles the BPMP-Lite spends halted, + // not running (TRM 41.x: "counts the clock cycles when BPMP-Lite is in + // halt state"); the others count activity. + uint64_t counted = counts_halt ? win_slept : active; - uint32_t c = (uint32_t)((active * ACTMON_FULL_COUNT) / window); + uint32_t c = (uint32_t)((counted * ACTMON_FULL_COUNT) / window); d.count = c; // avg_count trails count with a simple IIR (bdk asks for a 128-sample // average via K_VAL; an exponential decay is a fair stand-in). @@ -3317,10 +3590,10 @@ static uint32_t actmon_read(EmuState *state, uint32_t off) { case 0x0C: return d.init_avg; case 0x18: return d.count_weight; case 0x1C: - if (d.ctrl & (1u << 31)) actmon_sample(state, d); + if (d.ctrl & (1u << 31)) actmon_sample(state, d, dev == ACTMON_DEV_COP); return d.count; case 0x20: - if (d.ctrl & (1u << 31)) actmon_sample(state, d); + if (d.ctrl & (1u << 31)) actmon_sample(state, d, dev == ACTMON_DEV_COP); return d.avg_count; default: return d.regs[(f / 4) & 15]; } @@ -3345,7 +3618,7 @@ static void actmon_write(EmuState *state, uint32_t off, uint32_t val) { d.seeded = false; d.count = 0; d.avg_count = 0; - actmon_sample(state, d); + actmon_sample(state, d, dev == ACTMON_DEV_COP); } break; case 0x0C: d.init_avg = val; break; @@ -3491,15 +3764,31 @@ static void bpmp_cache_write(EmuState *state, uint64_t addr, uint32_t val) { // callbacks serve CPU0's engine, which is what lets the two cores share one // set of register models. +// I2C4 and I2C6: controllers with nothing modelled behind them. Every +// transaction completes at once with the address NACKed, so a bus scan finds +// an empty bus instead of a device at every address (a 0 STATUS reads as +// "ACK"). CNFG reads back without SEND, which the hardware clears when done. +static uint32_t i2c_empty_bus_read(uint64_t address) { + switch ((uint32_t)(address & 0xFF)) { + case 0x00: return mmio_regs.get(address) & ~(1u << 9); + case 0x1C: return I2C_STATUS_NOACK; + case 0x8C: return 0; // CONFIG_LOAD self-clears + default: return mmio_regs.get(address); + } +} + uint32_t mmio_bus_read(EmuState *state, uint64_t address, unsigned size) { (void)size; if (address >= TMR_BASE && address < TMR_BASE + TMR_SIZE) { // TIMERUS_CNTR_1US. The rest of the timer block reads 0. The BPMP's // reads go through the clock's poll pacing; CPU0 has its own clock. - if (address - TMR_BASE != 0x10) - return 0; + uint32_t off = (uint32_t)(address - TMR_BASE); + if (off == 0x14) // TIMERUS_USEC_CFG, reset 0x0000000C + return mmio_regs.get(address, 0x0000000C); + if (off != 0x10) + return mmio_regs.get(address); return g_bus_master == BUS_BPMP ? bpmp_timerus_read(state) - : (uint32_t)state->emu_usec; + : (uint32_t)ccplex_now_us(); } if (address >= GPIO_BASE && address < GPIO_BASE + GPIO_SIZE) return gpio_read(state, address); @@ -3540,8 +3829,11 @@ uint32_t mmio_bus_read(EmuState *state, uint64_t address, unsigned size) { return i2c3_read(state, address); if (address >= I2C1_BASE && address < I2C1_BASE + 0x100) return i2c_read(state, address); - if (address >= I2C5_BASE && address < I2C5_BASE + I2C_SIZE) + if (address >= I2C5_BASE && address < I2C5_BASE + I2C_CTRL_SIZE) return i2c_read(state, address); + if ((address >= I2C4_BASE && address < I2C4_BASE + I2C_CTRL_SIZE) || + (address >= I2C6_BASE && address < I2C6_BASE + I2C_CTRL_SIZE)) + return i2c_empty_bus_read(address); if (address >= DISPLAY_A_BASE && address < DISPLAY_A_BASE + DISPLAY_SIZE) return display_read(state, address); if (address >= PMC_BASE && address < PMC_BASE + PMC_SIZE) @@ -3578,7 +3870,10 @@ static void uart_write(EmuState *state, uint64_t address, uint32_t val) { up.divisor = (uint16_t)((up.divisor & 0xFF00) | (val & 0xFF)); } else if (offset == 0x04 && dlab) { up.divisor = (uint16_t)((up.divisor & 0x00FF) | ((val & 0xFF) << 8)); + } else if (offset == 0x04) { + up.ier = (uint8_t)val; } else if (offset == 0x08) { + up.fcr = (uint8_t)val; // FCR. RX_CLR is honoured only on the BT port, where the receive FIFO is // fed by an emulated device and dropping it is exactly what the hardware // does. On the console ports that FIFO models a human at a terminal, and @@ -3650,7 +3945,9 @@ void mmio_bus_write(EmuState *state, uint64_t address, unsigned size, uint32_t val = (uint32_t)value; mmio_regs[address] = val; // read-back cache for the simple registers - if (address >= GPIO_BASE && address < GPIO_BASE + GPIO_SIZE) { + if (address >= TMR_BASE && address < TMR_BASE + TMR_SIZE) { + tmr_write(state, address, val); + } else if (address >= GPIO_BASE && address < GPIO_BASE + GPIO_SIZE) { gpio_write(state, address, val); } else if ((address >= PCIE_BLOCK_BASE && address < PCIE_BLOCK_BASE + PCIE_BLOCK_SIZE) || @@ -3695,7 +3992,7 @@ void mmio_bus_write(EmuState *state, uint64_t address, unsigned size, i2c3_write(state, address, val); } else if (address >= I2C1_BASE && address < I2C1_BASE + 0x100) { i2c_write(state, address, val); - } else if (address >= I2C5_BASE && address < I2C5_BASE + I2C_SIZE) { + } else if (address >= I2C5_BASE && address < I2C5_BASE + I2C_CTRL_SIZE) { i2c_write(state, address, val); } else if (address >= DISPLAY_A_BASE && address < DISPLAY_A_BASE + DISPLAY_SIZE) { @@ -3923,12 +4220,110 @@ void mmio_init(uc_engine *uc, EmuState *state) { (void *)hook_unmapped, state, 1, 0); } -void mmio_soft_reset(EmuState *state) { - // A soft reboot is a SoC reset: the A57 cluster goes back to reset and the - // PCIe root complex to its power-on state. Both used to survive, so a - // payload re-run after a reboot found CPU0 already "booted" and the link - // already trained. +void mmio_soft_reset(EmuState *state, bool power_cycle) { + // A reboot is a SoC reset: every block on the SoC goes back to its power- + // on state. Only the always-on side survives - PMC SCRATCH0 and the reset + // status (TRM 12.x: "MAIN_RST resets everything but scratch 0 and reset + // status"), the RTC - and, unless the board was power-cycled, the PMIC and + // the regulators behind it, which are not on the SoC at all. + // + // This used to reset only the CCPLEX and PCIe models, so a payload run + // after a reboot found GPIOs, pinmux, UART modes, powered partitions, + // unlocked PLLs, SE keys and a half-read touch event where the previous run + // left them - and, after a PMIC reset, CPU rails still switched on. ccplex_reset(state); pcie_reset(state); - flow_ram_repair = 0; + se_engine_reset(); + i2c3_reset(state); + + mmio_regs.clear(); + for (auto &u : uart_ports) + u = UartPort(); + for (auto &fifo : state->uart_rx_fifo) + fifo.clear(); + bt_chip = BtChip(); + codec_regs.clear(); + + i2c_slave_addr = i2c_reg_addr = 0; + i2c_cmd_data1 = 0; + i2c_cnfg_reg[0] = i2c_cnfg_reg[1] = 0; + pkt_i2c1 = PacketState(); + pkt_i2c5 = PacketState(); + i2c2_slave = i2c2_reg = 0; + i2c2_cnfg = 0; + if (power_cycle) { + max77620_regs_ready = false; // re-seeded on next access + max77812_ready = false; + memcpy(max77621_regs, kMax77621Seed, sizeof(max77621_regs)); + } + + g_kfuse_keyaddr = 0; + pmc_pwrgate_status = 1u << 3; + pmc_io_dpd_status[0] = pmc_io_dpd_status[1] = 0; + uint32_t scratch0 = pmc_regs[0x50 / 4], rst_status = pmc_regs[0x1B4 / 4]; + memset(pmc_regs, 0, sizeof(pmc_regs)); + if (!power_cycle) { + pmc_regs[0x50 / 4] = scratch0; + pmc_regs[0x1B4 / 4] = rst_status; + } + if (power_cycle) { + rtc_base_us = 0; + rtc_sec_adjust = 0; + } else { + rtc_base_us += state->emu_usec; // the RTC keeps counting through it + } + rtc_shadow_seconds = 0; + + flow_ram_repair = RAM_REPAIR_RESET; + memset(tmr_armed_us, 0, sizeof(tmr_armed_us)); + car_rst_u = CAR_RST_U_RCM; + car_enb_u = CAR_ENB_U_RCM; + g_fuse_ctrl_addr = 0; + g_last_mrr_mrx = 5; + g_dsi_pending_dcs_cmd = 0; + memset(g_dsi_rx_fifo, 0, sizeof(g_dsi_rx_fifo)); + g_dsi_rx_count = g_dsi_rx_pos = 0; + vic_src_addr = vic_dst_addr = vic_config_addr = 0; + vic_config_size = vic_last_falcon_addr = 0; + for (auto &d : actmon_dev) + d = ActmonDev(); + actmon_glb_period = 0; + audio_pcm.clear(); + audio_pcm_full = false; + + // Storage controllers. The images stay open; the eMMC is back in its user + // area, as after CMD0. + state->sdmmc_arg = state->sdmmc_sysad = 0; + state->sdmmc_norintsts = state->sdmmc_errintsts = 0; + memset(state->sdmmc_rsp, 0, sizeof(state->sdmmc_rsp)); + state->sdmmc_hostctl = 0; + state->sdmmc_blksize = state->sdmmc_blkcnt = state->sdmmc_trnmod = 0; + state->sdmmc_adma_addr = 0; + state->sdmmc4_arg = state->sdmmc4_sysad = 0; + state->sdmmc4_norintsts = state->sdmmc4_errintsts = 0; + memset(state->sdmmc4_rsp, 0, sizeof(state->sdmmc4_rsp)); + state->sdmmc4_hostctl = 0; + state->sdmmc4_blksize = state->sdmmc4_blkcnt = state->sdmmc4_trnmod = 0; + state->sdmmc4_adma_addr = 0; + state->emmc_partition = 0; + state->last_cmd_was_55 = state->last_cmd4_was_55 = false; + + // Display controller back to its defaults (emu_state.h). + state->pre_addr = 0; + state->fb_width = state->pre_w = 720; + state->fb_height = state->pre_h = 1280; + state->fb_stride = state->pre_stride = 2880; + state->fb_swizzle = state->pre_sw = 0; + state->fb_rotation = state->pre_rot = 0; + state->pre_bh = 0; + state->fb_sw_gobs = 80; + state->fb_bh = 0; + state->dc_window_sel = 0x10; + state->winA_addr = 0; + state->winA_w = 720; + state->winA_h = 1280; + state->winA_stride = 2880; + state->winA_sw = state->winA_rot = state->winA_bh = 0; + + state->bpmp_halted = false; } diff --git a/t210/mmio.h b/t210/mmio.h index 10fef5e..8f87af8 100644 --- a/t210/mmio.h +++ b/t210/mmio.h @@ -44,13 +44,17 @@ void mmio_bus_write(EmuState *state, uint64_t addr, unsigned size, uint64_t value); // Reset the per-run peripheral state that a soft reboot must not carry over. -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`). bool pmc_partition_on(int part); -// FLOW_CTLR_RAM_REPAIR has been requested (the fast cluster's RAMs repaired). -bool flow_ram_repair_done(); +// APBDEV_PMC_SECURE_SCRATCH`n` (n = 0..7), written by hardware: the SE +// deposits its context-save key there. +void pmc_secure_scratch_write(unsigned n, uint32_t value); // True when the CCPLEX CPU rail is up: the MAX77621 on Erista (enabled, and // its EN pin driven by MAX77620 GPIO5), the MAX77812 M4 phase on Mariko. diff --git a/t210/pcie.cpp b/t210/pcie.cpp index dee918f..5200135 100644 --- a/t210/pcie.cpp +++ b/t210/pcie.cpp @@ -1,4 +1,5 @@ #include "pcie.h" +#include "ccplex.h" #include #include @@ -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 // bits 23:20 and root port 1 disabled (bit 2) until software clears it. static constexpr uint32_t MSELECT_CONFIG_RESET = 0x07FF4020; +static constexpr uint32_t MSELECT_CFG_ENABLE_PCIE_APERTURE = 1u << 5; static constexpr uint32_t AFI_PCIE_CONFIG_RESET = 0x00103025; // Broadcom identity (brcm_hw_ids.h, brcmfmac/pcie.c). @@ -227,9 +229,8 @@ bool radio_core_alive(EmuState *state) { // hardware this is the difference between a register read and a dead // console, so it is checked before every single access rather than folded // into the link-training preconditions. -// Everything this emulator executes is BPMP code - Unicorn runs the ARM7, -// there is no CCPLEX model - and the BPMP cannot reach PCIe on real silicon. -// Measured on an Erista and a Mariko: with clocks, resets, power and PLLE all +// The BPMP cannot reach PCIe on real silicon; only a CPU-complex master can +// (CPU0, t210/ccplex.cpp). Measured on an Erista and a Mariko: with clocks, resets, power and PLLE all // correct, the AFI window reads 0xFFFFFFFF and every offset of MSELECT reads // one constant. The TRM agrees (ch.19: BPMP-Lite is an AHB master, PCIe is // not an AHB slave; ch.16: MSELECT is CPU-complex hardware), and so does the @@ -272,6 +273,21 @@ void mselect_complain(uint64_t addr) { fflush(stdout); } +// MSELECT_CONFIG bit 5, ENABLE_PCIE_APERTURE (TRM 16.3.1, set at reset): +// with it clear MSELECT does not route the PCIe apertures at all. +static bool pcie_aperture_enabled(uint64_t addr) { + if (pcie.mselect[0] & MSELECT_CFG_ENABLE_PCIE_APERTURE) + return true; + static bool warned = false; + if (!warned) { + warned = true; + printf("[pcie] access to %08X with MSELECT_CONFIG.ENABLE_PCIE_APERTURE " + "clear: MSELECT does not route it\n", (unsigned)addr); + fflush(stdout); + } + return false; +} + const char *link_blocked(EmuState *state, int port) { if (!mselect_up()) return "MSELECT still in reset"; if (pcie.powergated) return "PCIE partition still gated"; @@ -394,7 +410,8 @@ void pcie_wl_reg_on(EmuState *state, bool level) { // ---- clock and reset controller ----------------------------------------- -void pcie_car_write(uint32_t offset, uint32_t val) { +void pcie_car_write(EmuState *state, uint32_t offset, uint32_t val) { + bool mselect_was_up = mselect_up(); switch (offset) { case CAR_RST_DEVICES_U: pcie.rst_u = val; break; case CAR_CLK_OUT_ENB_U: pcie.enb_u = val; break; @@ -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_DEV_V_SET: pcie.rst_v |= val; break; case CAR_RST_DEV_V_CLR: pcie.rst_v &= ~val; break; + case CAR_RST_DEVICES_W: pcie.rst_w = val; break; case CAR_RST_DEV_W_SET: pcie.rst_w |= val; break; case CAR_RST_DEV_W_CLR: pcie.rst_w &= ~val; break; + case CAR_RST_DEVICES_Y: pcie.rst_y = val; break; case CAR_PLLE_BASE: pcie.plle = (val & PLLE_BASE_ENABLE) != 0; break; case CAR_PLLREFE_BASE: pcie.pllrefe = (val & PLLREFE_BASE_ENABLE) != 0; break; default: break; } + // MSELECT out of reset is one of the things CPU0 waits on. + if (!mselect_was_up && mselect_up()) + ccplex_preconditions_changed(state); } // PLLE and PLLREFE do not follow the generic "ENABLE bit 30, LOCK bit 27 in @@ -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)state; + // Writes from the BPMP go nowhere either, as with the AFI window. + if (bpmp_pcie_denied(addr)) + return; uint32_t off = (uint32_t)(addr - MSELECT_BASE) & 0xFFC; // Held in reset, MSELECT latches nothing - which is exactly the state a // payload is in when it thinks it configured the fabric and did not. @@ -635,6 +660,8 @@ uint32_t pcie_read(EmuState *state, uint64_t addr) { mselect_complain(addr); return 0xFFFFFFFF; } + if (!pcie_aperture_enabled(addr)) + return 0xFFFFFFFF; // Root port register windows, 0x01000000 and 0x01001000. if (addr >= PCIE_RP0_BASE && addr < PCIE_RP0_BASE + 0x2000) { @@ -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) { uint32_t a = (uint32_t)(addr - PCIE_CS_BASE); uint32_t bus = (a >> 16) & 0xFF, dev = (a >> 11) & 0x1F; - uint32_t fn = (a >> 8) & 0x7, reg = a & 0xFC; + uint32_t fn = (a >> 8) & 0x7; + // Register number: {AXI[27:24], AXI[7:0]} (TRM 34.3.3). + uint32_t reg = ((a >> 16) & 0xF00) | (a & 0xFC); link_update(state, 1); if (bus != 1 || dev != 0 || fn != 0 || !ep_reachable(state)) return 0xFFFFFFFF; // unsupported request -> all ones + if (reg >= sizeof(pcie.ep)) + return 0; // no extended capabilities return pcie.ep[reg / 4]; } @@ -695,13 +726,24 @@ uint32_t pcie_read(EmuState *state, uint64_t addr) { return 0xFFFFFFFF; if (!(pcie.ep[0x04 / 4] & 0x2)) // MEM space disabled return 0xFFFFFFFF; - if ((pcie.ep[0x10 / 4] & ~0xFu) != PCIE_MEM_BASE) // BAR0 unassigned + // Decode against wherever software put the BARs: BAR0 is the 32 KiB + // register window (backplane window in its first 4 KiB, core + // registers above), BAR2 the 2 MiB TCM. Anything else is claimed by + // no function: all ones. + uint32_t a32 = (uint32_t)addr; + uint32_t bar0 = pcie.ep[0x10 / 4] & EP_BAR0_MASK; + uint32_t bar2 = pcie.ep[0x18 / 4] & EP_BAR2_MASK; + bool in_bar0 = bar0 && (a32 & EP_BAR0_MASK) == bar0; + bool in_bar2 = bar2 && (a32 & EP_BAR2_MASK) == bar2; + if (!in_bar0 && !in_bar2) return 0xFFFFFFFF; if (!radio_core_alive(state)) return 0xFFFFFFFF; // front-end answers, the die does not + if (in_bar2 || (a32 - bar0) >= 0x1000) + return 0; // modelled as quiet registers / RAM uint32_t win = pcie.ep[BRCM_BAR0_WINDOW / 4] & ~0xFFFu; - uint32_t bp = win + ((uint32_t)(addr - PCIE_MEM_BASE) & 0xFFF); + uint32_t bp = win + ((a32 - bar0) & 0xFFF); if (bp == BRCM_SI_ENUM_BASE) return BRCM_4356_CHIPID; return 0; @@ -718,10 +760,15 @@ void pcie_write(EmuState *state, uint64_t addr, uint32_t val) { mselect_complain(addr); return; } + if (!pcie_aperture_enabled(addr)) + return; if (addr >= PCIE_RP0_BASE && addr < PCIE_RP0_BASE + 0x2000) { int port = (addr >= PCIE_RP1_BASE) ? 1 : 0; - pcie.rp[port].reg[(uint32_t)(addr & 0xFFC) / 4] = val; + uint32_t off = (uint32_t)(addr & 0xFFC); + if (off == RP_VEND_XP) + val &= ~RP_VEND_XP_DL_UP; // read-only: the link state + pcie.rp[port].reg[off / 4] = val; return; } @@ -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) { uint32_t a = (uint32_t)(addr - PCIE_CS_BASE); uint32_t bus = (a >> 16) & 0xFF, dev = (a >> 11) & 0x1F; - uint32_t fn = (a >> 8) & 0x7, reg = a & 0xFC; - if (bus != 1 || dev != 0 || fn != 0 || !ep_reachable(state)) + uint32_t fn = (a >> 8) & 0x7; + uint32_t reg = ((a >> 16) & 0xF00) | (a & 0xFC); + if (bus != 1 || dev != 0 || fn != 0 || !ep_reachable(state) || + reg >= sizeof(pcie.ep)) return; switch (reg) { case 0x04: // command: only the low half is RW diff --git a/t210/pcie.h b/t210/pcie.h index 6e1365b..249bb83 100644 --- a/t210/pcie.h +++ b/t210/pcie.h @@ -15,17 +15,20 @@ struct EmuState; * (0x02000000), the endpoint's BAR0 backplane window, and the UPHY PLL P0 * calibration/lock state machine in the XUSB pad controller. * - * The link only trains when the payload has satisfied every precondition - * real silicon and the CYW4356 datasheet impose -- power partition, clocks, - * resets, PLLE, UPHY, lane mux, IDDQ, and the refclk/PERST#/POR timing of - * Table 62. A payload that skips one gets a link that stays down and a - * `[pcie]` line on stdout naming what it missed. + * The link only trains once the payload has satisfied the preconditions + * this model checks -- power partition, AFI clock, resets, PLLE, UPHY, lane + * mux, IDDQ, and the refclk/PERST#/POR timing of Table 62. A payload that + * skips one gets a link that stays down and a `[pcie]` line on stdout naming + * what it missed. Not every step of the TRM's bring-up (34.3) is checked: + * the PCIe clock enable, PRSNT_MAP, PEX_BIAS_PWRD, the PEX_L1_RST_N pinmux + * and the AUX_MUX_LP0 clamps are not, so a sequence that leaves one out can + * train here and not on silicon. */ void pcie_reset(EmuState *state); -// 0x01000000..0x01003FFF (root ports, PADS, AFI), 0x02000000 config -// aperture, and the 0x13000000 BAR0 memory window. +// 0x01000000..0x01003FFF (root ports, PADS, AFI), the 0x02000000 config +// aperture and the 0x13000000 non-prefetchable memory window. uint32_t pcie_read(EmuState *state, uint64_t addr); void pcie_write(EmuState *state, uint64_t addr, uint32_t val); @@ -40,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 // PCIE/AFI/PCIEXCLK/UPHY reset+enable bits, all of which live in CAR. // pcie_car_read returns true when it wants to override the CAR model's answer. -void pcie_car_write(uint32_t offset, uint32_t val); +void pcie_car_write(EmuState *state, uint32_t offset, uint32_t val); bool pcie_car_read(uint32_t offset, uint32_t *out); // MSELECT clocked out of reset (RST_DEV_V bit 3 clear). The CCPLEX needs it diff --git a/t210/se_engine.cpp b/t210/se_engine.cpp index fa71b49..00e5163 100644 --- a/t210/se_engine.cpp +++ b/t210/se_engine.cpp @@ -1,12 +1,14 @@ #include "se_engine.h" #include "../emu_state.h" #include "memory_map.h" +#include "mmio.h" #include #include #include #include +#include // ============================================================================= // Tegra X1 Security Engine (SE) emulation @@ -41,25 +43,20 @@ static const uint32_t K[64] = { #define ROR32(x, n) (((x) >> (n)) | ((x) << (32 - (n)))) -static void compute(const uint8_t *msg, uint32_t len, uint8_t out[32]) { - uint32_t H[8] = { - 0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a, - 0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19, - }; - // Total padded length: msg + 0x80 + zeros + 8-byte length, multiple of 64 - uint64_t bitlen = (uint64_t)len * 8; - uint32_t padded_len = ((len + 1 + 8 + 63) / 64) * 64; - uint8_t *buf = (uint8_t*)std::calloc(1, padded_len); - std::memcpy(buf, msg, len); - buf[len] = 0x80; - for (int i = 0; i < 8; i++) buf[padded_len - 1 - i] = (uint8_t)(bitlen >> (i * 8)); - for (uint32_t off = 0; off < padded_len; off += 64) { +static const uint32_t H0[8] = { + 0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a, + 0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19, +}; + +// Compress `nblocks` 64-byte blocks into the running state H. +static void blocks(uint32_t H[8], const uint8_t *p, size_t nblocks) { + for (size_t blk = 0; blk < nblocks; blk++, p += 64) { uint32_t W[64]; for (int i = 0; i < 16; i++) { - W[i] = ((uint32_t)buf[off + i*4 + 0] << 24) | - ((uint32_t)buf[off + i*4 + 1] << 16) | - ((uint32_t)buf[off + i*4 + 2] << 8) | - ((uint32_t)buf[off + i*4 + 3]); + W[i] = ((uint32_t)p[i*4 + 0] << 24) | + ((uint32_t)p[i*4 + 1] << 16) | + ((uint32_t)p[i*4 + 2] << 8) | + ((uint32_t)p[i*4 + 3]); } for (int i = 16; i < 64; i++) { uint32_t s0 = ROR32(W[i-15],7) ^ ROR32(W[i-15],18) ^ (W[i-15] >> 3); @@ -79,13 +76,23 @@ static void compute(const uint8_t *msg, uint32_t len, uint8_t out[32]) { H[0]+=a; H[1]+=b; H[2]+=c; H[3]+=d; H[4]+=e; H[5]+=f; H[6]+=g; H[7]+=h; } - std::free(buf); - for (int i = 0; i < 8; i++) { - out[i*4 + 0] = (uint8_t)(H[i] >> 24); - out[i*4 + 1] = (uint8_t)(H[i] >> 16); - out[i*4 + 2] = (uint8_t)(H[i] >> 8); - out[i*4 + 3] = (uint8_t)(H[i]); - } +} + +// Hash the last `len` bytes of a message whose total length is `total_bits`, +// padding as FIPS 180-4 requires. Whole blocks go straight through; only the +// tail is copied. +static void final(uint32_t H[8], const uint8_t *msg, size_t len, + uint64_t total_bits) { + size_t whole = len / 64; + blocks(H, msg, whole); + uint8_t tail[128] = {0}; + size_t rest = len - whole * 64; + std::memcpy(tail, msg + whole * 64, rest); + tail[rest] = 0x80; + size_t tail_len = (rest + 1 + 8 <= 64) ? 64 : 128; + for (int i = 0; i < 8; i++) + tail[tail_len - 1 - i] = (uint8_t)(total_bits >> (i * 8)); + blocks(H, tail, tail_len / 64); } #undef ROR32 @@ -249,8 +256,33 @@ constexpr uint32_t SE_RNG_CONFIG_REG = 0x340; constexpr uint32_t SE_HASH_RESULT_REG = 0x030; // 16 dwords constexpr uint32_t SE_STATUS_REG = 0x800; constexpr uint32_t SE_ERR_STATUS_REG = 0x804; +constexpr uint32_t SE_CONTEXT_SAVE_CONFIG_REG = 0x070; +constexpr uint32_t SE_SHA_CONFIG_REG = 0x200; +constexpr uint32_t SE_SHA_MSG_LENGTH_REG = 0x204; // 4 dwords, in bits +constexpr uint32_t SE_SHA_MSG_LEFT_REG = 0x214; // 4 dwords, in bits constexpr uint32_t SE_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_AES_DEC = 1; @@ -312,106 +344,141 @@ static uint32_t reg_err_status = 0; static uint32_t reg_rng_config = 0; static uint32_t spare_regs[256] = {0}; // catch-all for less critical regs +// Secure random key for context save, and the CBC chain the saved blocks +// are encrypted under. See ctx_save(). +static uint8_t srk[16] = {0}; +static uint8_t ctx_chain[16] = {0}; + // LL descriptor: { num, addr, size }. Hekate often uses num=0 (single descriptor). struct LLDesc { uint32_t num, addr, size; }; static bool read_ll(uc_engine *uc, uint32_t ll_addr, LLDesc *out) { if (!ll_addr) return false; if (uc_mem_read(uc, ll_addr, out, sizeof(LLDesc)) != UC_ERR_OK) return false; + out->size &= LL_SIZE_MASK; return true; } -// Encrypt/decrypt a buffer in-place using the keyslot's key (assumes 128-bit). +// The operation touched memory it cannot reach: finish with an error, which +// bdk's _se_op_wait() reports instead of handing back a buffer of zeros. +static void op_fail(const char *what, uint32_t addr) { + std::printf("[se] %s: cannot access 0x%08X - operation failed\n", what, addr); + reg_int_status |= SE_INT_OP_DONE | SE_INT_ERR_STAT; +} + +static inline void xor16(uint8_t *d, const uint8_t *s) { + for (int j = 0; j < 16; ++j) d[j] ^= s[j]; +} + +// SE_CRYPTO_LINEAR_CTR holds the counter as the driver wrote it, bytes in +// memory order; it counts as one big-endian 128-bit number. +static void ctr_add(uint32_t n) { + uint8_t *p = (uint8_t *)linear_ctr; + for (int j = 15; j >= 0 && n; --j) { + uint32_t v = p[j] + (n & 0xFF); + p[j] = (uint8_t)v; + n = (n >> 8) + (v >> 8); + } +} + +// One AES operation over `blocks` 16-byte blocks, chained the way the SE +// datapath chains them. The configurations bdk's sec/se.c uses: +// +// ECB INPUT_MEMORY XOR_BYPASS out = AES(in) +// CBC enc INPUT_MEMORY XOR_TOP VCTRAM_AESOUT out = AES(in ^ v); v = out +// CBC dec INPUT_MEMORY XOR_BOTTOM VCTRAM_PREVMEM out = AES(in) ^ v; v = in +// OFB INPUT_AESOUT XOR_BOTTOM v = AES(v); out = v ^ in +// CTR INPUT_LNR_CTR XOR_BOTTOM out = AES(ctr) ^ in; ctr += n +// +// v, the vector RAM, starts from the slot's original or updated IV (IV_SEL). +// When the mode chains, the final v is left in the slot's UPDATED_IV: that is +// how bdk continues a chain into a trailing partial block, and how its CMAC +// feeds the last block after the others. With HASH enabled (CMAC) the last +// AES output goes to SE_HASH_RESULT. static void run_aes_blocks(uint32_t slot, bool encrypt, const uint8_t *in, uint8_t *out, size_t blocks, uint32_t xor_pos, uint32_t input_sel, uint32_t vctram_sel, uint32_t iv_sel, - bool ctr_mode, bool hash_mode) { + uint32_t ctr_step, bool hash_mode) { uint8_t rk[176]; aes::key_expand(ks_table[slot].key, rk); - // Pick which IV to use for chaining. Hekate typically uses ORIGINAL_IV for - // CBC starts and switches to UPDATED_IV mid-CMAC; we honour that. - uint8_t chain[16]; - if (iv_sel == IV_UPDATED) std::memcpy(chain, ks_table[slot].iv_upd, 16); - else std::memcpy(chain, ks_table[slot].iv_orig, 16); - - uint8_t prev_in[16] = {0}; - uint8_t hash_state[16] = {0}; // accumulator for HASH=1 (CMAC) — XOR top, encrypt - if (hash_mode) std::memcpy(hash_state, chain, 16); + uint8_t v[16]; + std::memcpy(v, iv_sel == IV_UPDATED ? ks_table[slot].iv_upd + : ks_table[slot].iv_orig, 16); + uint8_t aes_out[16] = {0}; for (size_t i = 0; i < blocks; ++i) { - uint8_t in_block[16]; - uint8_t out_block[16]; + const uint8_t *mem = in + i * 16; + uint8_t a[16]; + if (input_sel == INPUT_LNR_CTR) std::memcpy(a, linear_ctr, 16); + else if (input_sel == INPUT_AESOUT) std::memcpy(a, v, 16); + else std::memcpy(a, mem, 16); - if (input_sel == INPUT_LNR_CTR) { - // CTR mode input is the linear counter (big-endian 128-bit), per-block. - // Our linear_ctr[] is stored as 4 dwords little-endian; assemble. - uint8_t ctr_be[16]; - for (int j = 0; j < 4; ++j) { - uint32_t w = linear_ctr[j]; - ctr_be[j*4 + 0] = (w >> 0) & 0xFF; - ctr_be[j*4 + 1] = (w >> 8) & 0xFF; - ctr_be[j*4 + 2] = (w >> 16) & 0xFF; - ctr_be[j*4 + 3] = (w >> 24) & 0xFF; - } - std::memcpy(in_block, ctr_be, 16); - } else if (input_sel == INPUT_AESOUT) { - // Re-feeding previous AES output (used in some chained constructions). - std::memcpy(in_block, prev_in, 16); - } else { - std::memcpy(in_block, in + i*16, 16); - } + if (xor_pos == XOR_TOP) xor16(a, v); + if (encrypt) aes::encrypt_block(a, aes_out, rk); + else aes::decrypt_block(a, aes_out, rk); - // VCTRAM source: the value XORed at XOR_TOP / XOR_BOTTOM. - uint8_t vctram[16]; - if (vctram_sel == VCTRAM_AESOUT) std::memcpy(vctram, prev_in, 16); - else if (vctram_sel == VCTRAM_PREVMEM) std::memcpy(vctram, (i==0)? chain : (in + (i-1)*16), 16); - else std::memcpy(vctram, chain, 16); + uint8_t *o = out + i * 16; + std::memcpy(o, aes_out, 16); + // After the core: CBC decrypt XORs the vector; OFB and CTR XOR the data. + if (xor_pos == XOR_BOTTOM) xor16(o, input_sel == INPUT_MEMORY ? v : mem); - if (xor_pos == XOR_TOP) { - for (int j = 0; j < 16; ++j) in_block[j] ^= vctram[j]; - } + if (input_sel == INPUT_AESOUT || vctram_sel == VCTRAM_AESOUT) + std::memcpy(v, aes_out, 16); + else if (vctram_sel == VCTRAM_PREVMEM) + std::memcpy(v, mem, 16); - if (encrypt) aes::encrypt_block(in_block, out_block, rk); - else aes::decrypt_block(in_block, out_block, rk); - - if (xor_pos == XOR_BOTTOM) { - // Output XOR with chain (CTR keystream XOR plaintext, etc.) - const uint8_t *xb = (input_sel == INPUT_LNR_CTR) - ? (in + i*16) // CTR: XOR with plaintext from memory - : vctram; - for (int j = 0; j < 16; ++j) out_block[j] ^= xb[j]; - } - - if (out) std::memcpy(out + i*16, out_block, 16); - - // Advance chain for next block. - if (xor_pos == XOR_BOTTOM && input_sel != INPUT_LNR_CTR) { - // CBC encrypt: chain = ciphertext = out_block - std::memcpy(chain, out_block, 16); - } else if (xor_pos == XOR_TOP) { - // CBC decrypt: chain = ciphertext (the input block we read) - std::memcpy(chain, in + i*16, 16); - } - std::memcpy(prev_in, out_block, 16); - - 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 (input_sel == INPUT_LNR_CTR) ctr_add(ctr_step); } - if (hash_mode) { - // For HASH paths the final cipher block is exposed via SE_HASH_RESULT_REG. - std::memcpy(hash_result, prev_in, 16); + if (hash_mode) std::memcpy(hash_result, aes_out, 16); + bool chained = input_sel == INPUT_AESOUT || vctram_sel == VCTRAM_AESOUT || + vctram_sel == VCTRAM_PREVMEM; + if (chained && blocks) std::memcpy(ks_table[slot].iv_upd, v, 16); +} + +// SHA-256, one-shot or in parts (bdk _se_sha_hash_256). SHA_INIT_HASH starts +// from the standard initial state, SHA_CONTINUE from the state the previous +// part left in SE_HASH_RESULT - which is where the hardware keeps it, too. +// SE_SHA_MSG_LEFT says whether this is the last part: bdk passes one byte +// more than it feeds for any part but the last, so the engine pads the part +// only when LEFT equals the data it has, using the total from +// SE_SHA_MSG_LENGTH. HASH_RESULT holds the state as 8 dwords, most +// significant byte first; the driver byte-swaps them into the digest. +static void sha_op(EmuState *state) { + LLDesc in_ll{}; + if (!read_ll(state->uc, reg_in_ll_addr, &in_ll) || !in_ll.size) { + reg_int_status |= SE_INT_OP_DONE; + return; } - // Save updated IV (chain) for next call's IV_UPDATED. - std::memcpy(ks_table[slot].iv_upd, chain, 16); + std::vector buf(in_ll.size); + if (uc_mem_read(state->uc, in_ll.addr, buf.data(), in_ll.size) != UC_ERR_OK) { + op_fail("SHA-256 input", in_ll.addr); + return; + } + auto reg64 = [](uint32_t off) { + return (uint64_t)spare_regs[off / 4] | ((uint64_t)spare_regs[off / 4 + 1] << 32); + }; + uint64_t total_bits = reg64(SE_SHA_MSG_LENGTH_REG); + uint64_t left_bits = reg64(SE_SHA_MSG_LEFT_REG); + bool init = (spare_regs[SE_SHA_CONFIG_REG / 4] & 1) == SHA_INIT_HASH; + + uint32_t H[8]; + if (init) std::memcpy(H, sha256::H0, sizeof(H)); + else std::memcpy(H, hash_result, sizeof(H)); + + bool last = left_bits <= (uint64_t)in_ll.size * 8; + if (last) + sha256::final(H, buf.data(), in_ll.size, total_bits); + else + sha256::blocks(H, buf.data(), in_ll.size / 64); + std::memcpy(hash_result, H, sizeof(H)); + + std::printf("[se] SHA-256 %s%s over %u bytes @0x%X -> %08X...\n", + init ? "" : "continued ", last ? "final" : "part", + in_ll.size, in_ll.addr, H[0]); + reg_int_status |= SE_INT_OP_DONE; } static void op_start(EmuState *state) { @@ -423,37 +490,21 @@ static void op_start(EmuState *state) { bool dec = (dec_alg == ALG_AES_DEC) && (enc_alg == ALG_NOP); bool enc = (enc_alg == ALG_AES_ENC) && (dec_alg == ALG_NOP); - // ---- SHA-256 path ---- - // ALG_SHA=3, MODE_SHA256=5, DST=DST_HASHREG. Driver flow: writes - // SE_SHA_MSG_LENGTH/LEFT, sets up IN_LL pointing at src/src_size, then - // OP_START. Output 32 bytes go into HASH_RESULT_REG as 8 big-endian dwords - // (driver byte_swap_32's each on read). We currently only model the - // oneshot case (SHA_INIT_HASH); save_process_header uses oneshot. - if (enc_alg == 3 /*ALG_SHA*/ && dst_kind == DST_HASHREG && enc_mode == 5 /*MODE_SHA256*/) { - LLDesc in_ll{}; - bool got_in = read_ll(state->uc, reg_in_ll_addr, &in_ll); - if (!got_in || !in_ll.size) { - reg_int_status |= SE_INT_OP_DONE; - return; - } - std::vector buf(in_ll.size, 0); - uc_mem_read(state->uc, in_ll.addr, buf.data(), in_ll.size); - uint8_t digest[32]; - sha256::compute(buf.data(), in_ll.size, digest); - // Pack into HASH_RESULT_REG as 8 big-endian dwords (driver byteswaps). - for (int i = 0; i < 8; i++) { - hash_result[i] = ((uint32_t)digest[i*4 + 0] << 24) | - ((uint32_t)digest[i*4 + 1] << 16) | - ((uint32_t)digest[i*4 + 2] << 8) | - ((uint32_t)digest[i*4 + 3]); - } - std::printf("[se] SHA-256 over %u bytes @0x%X -> %02X%02X%02X%02X...\n", - in_ll.size, in_ll.addr, digest[0], digest[1], digest[2], digest[3]); + if (enc_alg == ALG_SHA && dst_kind == DST_HASHREG && enc_mode == MODE_SHA256) { + sha_op(state); + return; + } + + // RNG into the secure random key: the start of a context save. The key is + // fixed rather than random so runs stay reproducible. + if (enc_alg == ALG_RNG && dst_kind == DST_SRK) { + for (int i = 0; i < 16; ++i) srk[i] = (uint8_t)(0xA5 ^ (i * 0x1D)); + std::memset(ctx_chain, 0, sizeof(ctx_chain)); reg_int_status |= SE_INT_OP_DONE; return; } - if (dst_kind == 4 /* DST_RSAREG */) { + if (dst_kind == DST_RSAREG) { // RSA not implemented — leave output zero. reg_int_status |= SE_INT_OP_DONE; return; @@ -470,46 +521,51 @@ static void op_start(EmuState *state) { uint32_t iv_sel = (reg_crypto_config >> 7) & 0x1; uint32_t core_sel = (reg_crypto_config >> 8) & 0x1; bool hash_en = (reg_crypto_config >> 0) & 0x1; - uint32_t ctr_cnt = (reg_crypto_config >> 11) & 0x1; + uint32_t ctr_step = (reg_crypto_config >> 11) & 0xFF; uint32_t key_index = (reg_crypto_config >> 24) & 0xF; bool encrypt = (core_sel == CORE_ENCRYPT); - uint32_t blocks = reg_block_count + 1; + // SE_CRYPTO_LAST_BLOCK is the index of the last block. Bounded by what one + // linked-list entry can describe, so a wild value cannot overflow the + // buffer size below. + uint32_t blocks = (reg_block_count % MAX_AES_BLOCKS) + 1; uint32_t total_bytes = blocks * 16; - // Read input via IN_LL. - std::vector in_buf, out_buf; - in_buf.resize(total_bytes, 0); - out_buf.resize(total_bytes, 0); + std::vector in_buf(total_bytes, 0), out_buf(total_bytes, 0); LLDesc in_ll{}, out_ll{}; bool got_in = read_ll(state->uc, reg_in_ll_addr, &in_ll); bool got_out = read_ll(state->uc, reg_out_ll_addr, &out_ll); - (void)got_out; - if (got_in && in_ll.size && input_sel == INPUT_MEMORY) { + // Memory input is data for every mode: the block itself for ECB/CBC, what + // the keystream is XORed with for OFB/CTR. + if (got_in && in_ll.size) { uint32_t copy = (in_ll.size < total_bytes) ? in_ll.size : total_bytes; - uc_mem_read(state->uc, in_ll.addr, in_buf.data(), copy); + if (uc_mem_read(state->uc, in_ll.addr, in_buf.data(), copy) != UC_ERR_OK) { + op_fail("AES input", in_ll.addr); + return; + } } run_aes_blocks(key_index, encrypt, in_buf.data(), out_buf.data(), blocks, - xor_pos, input_sel, vctram_sel, iv_sel, - (input_sel == INPUT_LNR_CTR) || ctr_cnt, hash_en); + xor_pos, input_sel, vctram_sel, iv_sel, ctr_step, hash_en); if (dst_kind == DST_MEMORY) { if (got_out && out_ll.size) { uint32_t copy = (out_ll.size < total_bytes) ? out_ll.size : total_bytes; - uc_mem_write(state->uc, out_ll.addr, out_buf.data(), copy); + if (uc_mem_write(state->uc, out_ll.addr, out_buf.data(), copy) != UC_ERR_OK) { + op_fail("AES output", out_ll.addr); + return; + } } } else if (dst_kind == DST_KEYTABLE) { - // Unwrap-key path: store the (single-block) result in the destination slot. + // Unwrap-key path: the (single-block) result lands in the destination + // slot's selected word quad. uint32_t dst_slot = (reg_keytable_dst >> 8) & 0xF; - uint32_t word_quad = reg_keytable_dst & 0x3; - uint8_t *target = (word_quad == 1) - ? ks_table[dst_slot].key + 16 - : ks_table[dst_slot].key + 0; - std::memcpy(target, out_buf.data(), 16); + Keyslot &k = ks_table[dst_slot]; + uint8_t *target[4] = {k.key, k.key + 16, k.iv_orig, k.iv_upd}; + std::memcpy(target[reg_keytable_dst & 0x3], out_buf.data(), 16); } // DST_HASHREG: hash_result is already populated by run_aes_blocks. @@ -522,6 +578,40 @@ static void op_start(EmuState *state) { got_in ? in_ll.addr : 0, got_out ? out_ll.addr : 0); } +// SE_OP_CTX_SAVE, as bdk's se_aes_ctx_get_keys() drives it to read keyslots +// back: an RNG op seeds the secure random key (SRK); each save of an AES +// keytable quad writes that quad to memory encrypted under the SRK, CBC- +// chained from one save to the next; saving the SRK source deposits the key +// in PMC SECURE_SCRATCH4..7. The driver then loads the SRK into a slot and +// CBC-decrypts everything it saved in one pass with that slot's original IV, +// which it never sets - zero from reset - so the chain starts from zero. +static void ctx_save(EmuState *state) { + uint32_t cfg = spare_regs[SE_CONTEXT_SAVE_CONFIG_REG / 4]; + uint32_t src = cfg >> 29; + if ((reg_config >> 2 & 0x7) == DST_MEMORY && src == CTX_SRC_AES_KEYTABLE) { + const Keyslot &k = ks_table[(cfg >> 8) & 0xF]; + const uint8_t *quad[4] = {k.key, k.key + 16, k.iv_orig, k.iv_upd}; + uint8_t blk[16], rk[176]; + std::memcpy(blk, quad[cfg & 0x3], 16); + xor16(blk, ctx_chain); + aes::key_expand(srk, rk); + aes::encrypt_block(blk, ctx_chain, rk); + LLDesc out_ll{}; + if (read_ll(state->uc, reg_out_ll_addr, &out_ll) && out_ll.size >= 16 && + uc_mem_write(state->uc, out_ll.addr, ctx_chain, 16) != UC_ERR_OK) { + op_fail("context save output", out_ll.addr); + return; + } + } else if (src == CTX_SRC_SRK && reg_config != 0) { + for (int i = 0; i < 4; ++i) { + uint32_t w; + std::memcpy(&w, srk + i * 4, 4); + pmc_secure_scratch_write(4 + i, w); + } + } + reg_int_status |= SE_INT_OP_DONE; +} + // Keytable address layout: bits 4..7 = slot, bits 2..3 = quad, bits 0..1 = pkt static void keytable_write(uint32_t addr, uint32_t val) { uint32_t slot = (addr >> 4) & 0xF; @@ -541,14 +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 // doesn't faithfully model some part of the chain; the override is a // pragmatic shortcut that lets the BIS XTS layer succeed regardless. + // Two writes are never BIS keys and are left alone: clearing a slot (all + // zeros), and loading the context-save SRK (bdk puts it in slot 3). if (quad == 0 && pkt == 3 && slot < 6) { - if (bis_override_present[slot]) { + static const uint8_t zero[16] = {0}; + bool clear = std::memcmp(ks_table[slot].key, zero, 16) == 0; + bool is_srk = std::memcmp(ks_table[slot].key, srk, 16) == 0; + if (bis_override_present[slot] && !clear && !is_srk) { std::memcpy(ks_table[slot].key, bis_override_keys[slot], 16); std::printf("[se] slot %u BIS key overridden from prod.keys:", slot); for (int i = 0; i < 16; ++i) std::printf(" %02X", ks_table[slot].key[i]); std::printf("\n"); - } else { - std::printf("[se] slot %u key loaded (derived):", slot); + } else if (!clear) { + std::printf("[se] slot %u key loaded:", slot); for (int i = 0; i < 16; ++i) std::printf(" %02X", ks_table[slot].key[i]); std::printf("\n"); } @@ -574,8 +669,6 @@ static uint32_t keytable_read(uint32_t addr) { } // namespace -#include - uint32_t se_engine_read(EmuState *state, uint64_t addr) { uint32_t off = (uint32_t)(addr - SE_BASE); 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) { case SE_OPERATION_REG: reg_op = val; - // SE_OP_START runs the configured AES op; other op codes (RESTART_*, - // CTX_SAVE, ABORT) just need OP_DONE so the driver's _se_wait() exits. - if ((val & 0x7) == 1 /*SE_OP_START*/) { + // SE_OP_START runs the configured op and CTX_SAVE saves context; + // the others (RESTART_*) just need OP_DONE so _se_op_wait() exits. + if ((val & 0x7) == SE_OP_START) { op_start(state); + } else if ((val & 0x7) == SE_OP_CTX_SAVE) { + ctx_save(state); } else if ((val & 0x7) != 0 /*not ABORT*/) { reg_int_status |= SE_INT_OP_DONE; } @@ -647,9 +742,27 @@ void se_engine_write(EmuState *state, uint64_t addr, uint32_t val) { (void)state; } +// Keys a prod.keys file pre-loaded, which a soft reboot puts back. +static Keyslot ks_preload[16]; + void se_engine_set_aes128_key(uint32_t slot, const uint8_t key[16]) { if (slot >= 16) return; std::memcpy(ks_table[slot].key, key, 16); + std::memcpy(ks_preload[slot].key, key, 16); +} + +void se_engine_reset() { + std::memcpy(ks_table, ks_preload, sizeof(ks_table)); + reg_config = reg_crypto_config = 0; + reg_in_ll_addr = reg_out_ll_addr = 0; + reg_block_count = reg_keytable_addr = reg_keytable_dst = 0; + reg_op = reg_int_status = reg_int_enable = 0; + reg_err_status = reg_rng_config = 0; + std::memset(linear_ctr, 0, sizeof(linear_ctr)); + std::memset(hash_result, 0, sizeof(hash_result)); + std::memset(spare_regs, 0, sizeof(spare_regs)); + std::memset(srk, 0, sizeof(srk)); + std::memset(ctx_chain, 0, sizeof(ctx_chain)); } // ---- prod.keys parser ------------------------------------------------------- diff --git a/t210/se_engine.h b/t210/se_engine.h index 0dacafe..9aa54ee 100644 --- a/t210/se_engine.h +++ b/t210/se_engine.h @@ -10,17 +10,18 @@ struct EmuState; // operations against an emulated 16-slot keytable. // // Currently implemented: -// * AES-128 ECB encrypt/decrypt (single + multi-block, DMA via LL descriptors) -// * AES-128 CBC encrypt/decrypt -// * AES-128 CTR mode +// * AES-128 ECB, CBC, OFB and CTR, single and multi-block, with the IV +// chained through UPDATED_IV the way bdk's partial-block path expects +// * AES-CMAC (HASH_ENABLE into SE_HASH_RESULT) // * AES "unwrap" (decrypt and store result in destination keyslot) +// * SHA-256, one-shot and in parts (SHA_INIT_HASH / SHA_CONTINUE) +// * Context save of AES keyslots under a secure random key, as bdk's +// se_aes_ctx_get_keys() reads keys back // * Keyslot programming (CRYPTO_KEYTABLE_ADDR/DATA) // * Pre-population of keyslots from a Switch prod.keys file // -// Not implemented (returns zero / no-op): -// * AES-CMAC (HASH+VCTRAM_AESOUT path) -// * SHA / RNG / RSA -// Each unimplemented op still completes (sets OP_DONE) so the boot doesn't hang. +// Not implemented: RNG output, RSA, AES-192/256 key sizes. Those operations +// still complete (set OP_DONE) so a payload does not hang on them. uint32_t se_engine_read (EmuState *state, uint64_t addr); void se_engine_write(EmuState *state, uint64_t addr, uint32_t val); @@ -31,6 +32,10 @@ void se_engine_write(EmuState *state, uint64_t addr, uint32_t val); // AES, so this is enough. void se_engine_set_aes128_key(uint32_t slot, const uint8_t key[16]); +// Soft reboot: registers back to reset, keyslots back to what prod.keys +// pre-loaded. +void se_engine_reset(); + // Parse a switch-style "prod.keys" file (lines of `name = hex_value`) and // pre-populate the well-known bootrom-derived keyslots (KS_TSEC=12, // KS_SECURE_BOOT=14, KS_TSEC_ROOT=13) so Lockpick / Hekate's derivation diff --git a/tests/ccplex/run.sh b/tests/ccplex/run.sh index 809160d..64d8848 100755 --- a/tests/ccplex/run.sh +++ b/tests/ccplex/run.sh @@ -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 'CPU0 stopped (held in reset)' 'RST_CPUG_CMPLX_SET stops the core' expect 'MAX77620 PWR_OFF received' 'the payload ran to its power-off' +if [ "$status" -eq 0 ]; then + echo " ok the emulator exited cleanly" +else + echo " FAIL the emulator exited with status $status (124 = timed out)" + fail=1 +fi # TIMERUS as CPU0 saw it must have moved across its busy loop. dt=$(sed -n 's/.*dt=\([0-9A-F]*\).*/\1/p' "$LOG" | head -1) diff --git a/tests/hwtest/run.sh b/tests/hwtest/run.sh index 72bc66e..e30fc9d 100755 --- a/tests/hwtest/run.sh +++ b/tests/hwtest/run.sh @@ -7,7 +7,9 @@ # soon as the dump's last line appears (with a hard timeout behind it). EMU=${1:-./rcm_emu} BIN=${2:-build-hwtest/hwtest-rcm/build/hwtest.bin} -shift 2 2>/dev/null +# Anything after the two positional arguments goes to the emulator. (A bare +# `shift 2` with fewer than two arguments makes dash exit on the spot.) +[ $# -ge 2 ] && shift 2 || set -- LOG=${LOG:-tests/hwtest/out.log} LIMIT=${LIMIT:-300}