From f19a52b779cf21a11ac33ae1ec669c53b48aa4a1 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 15:55:48 +0000 Subject: [PATCH 01/21] Run CCPLEX CPU0 so hwtest's PCIe probe completes, and speed up the core hwtest-rcm's Wi-Fi probe hands PCIe to an AArch64 stub on CPU0, because PCIe and MSELECT answer a CPU-complex master only. The emulator had no CCPLEX, so the stub never reported; and the sweep never got that far anyway, because it hung in the fan test. CPU0 (t210/ccplex.cpp) - A second Unicorn engine, AArch64, Cortex-A57, sharing IRAM, DRAM, TZRAM and every peripheral model with the BPMP. It starts when RST_CPUG_CMPLX_CLR releases CPU0 with every precondition of bdk's ccplex_boot_cpu0() met: CPU rail (MAX77621 + MAX77620 GPIO5 on Erista, MAX77812 EN_M4 on Mariko), CRAIL/C0NC/CE0, CPUG clock, PLLX, MSELECT, RAM repair, an AArch64 vector in SB_AA64_RESET_LOW/HIGH. A release that misses one is refused and the reason printed. - Entered at EL3, MMU off, like silicon. Unicorn builds its ARM64 core at EL1 and neither a PSTATE write (stale hflags) nor an exception (never delivered) moves it, so a one-instruction ERET trampoline does. - Its own clock (1 ns/instruction, 250 ns/bus access), run in 250 us lockstep slices behind the BPMP; WFE/WFI park it to the slice end. - PCIe is master-aware: the BPMP still reads all ones, CPU0 is served. MSELECT, AFI_PCIE_CONFIG, LNKSTA, the endpoint class/BAR, the PCIE partition, PEX_L1 pinmux and PMC_GLB_AMAP_CFG take their measured values. hwtest now runs its whole sweep and reports "WLAN core enumerated on the PCIe bus" / "Wireless : pass", matching the healthy-console capture in its README. Performance - No per-instruction hooks. Three UC_HOOK_CODE callbacks (one registered twice, one doing a uc_mem_read per instruction) are replaced by a block hook that counts each block's instructions once (cached), credited when it has run - the same totals, so the clock is unchanged. - Peripherals are uc_mmio_map() windows instead of memory hooks, which had forced every guest load/store onto Unicorn's slow path; the register cache is a paged array instead of a std::map. - The display reads the framebuffer straight from host DRAM, reuses its buffers, skips unchanged frames, and no renderer uses PRESENTVSYNC (a vsync'd present could stall the emulated CPU for a whole frame). Reaching hwtest's fan test: 2.7 s -> 0.8 s; whole sweep ~3 s. Reliability - TIMERUS poll pacing: bdk's fan_get_speed() waits for TIMERUS to EQUAL a deadline (int - u32 is unsigned, so `> 0` is `!= 0`), and the dilated clock stepped past it, so the loop spun until TIMERUS wrapped. Polls at most 200 instructions apart now advance the clock by at most 1 us. - MAX77621/MAX77812 are register files: bdk's hw_init() disabling the Erista CPU/GPU bucks used to be ignored and read back as enabled. - Mariko reads FUSE_RESERVED_ODM28_B01 bit 0 set, so bdk addresses the retail MAX77812 at 0x33 instead of the NAK'd 0x31. - Windows: disk images are opened O_BINARY (MinGW defaults to text mode, corrupting sectors) and rawnand chunks are sized with _fstati64. - Soft reboot resets CPU0 and the PCIe root complex; the payload is loaded once, size-checked; an empty/unreadable payload is rejected; the NOP-slide check no longer trips on a counter that never reset; the M/C windows fall back to a software renderer. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb --- display/config_window.cpp | 8 +- display/console_window.cpp | 8 +- display/sdl_display.cpp | 82 ++- main.cpp | 142 +++-- platform.h | 37 ++ t210/bpmp.cpp | 246 ++++++++ t210/bpmp.h | 48 ++ t210/ccplex.cpp | 509 ++++++++++++++++ t210/ccplex.h | 57 ++ t210/memory_map.h | 11 +- t210/mmio.cpp | 1171 ++++++++++++++++++------------------ t210/mmio.h | 39 ++ t210/pcie.cpp | 40 +- t210/pcie.h | 4 + t210/regcache.h | 86 +++ 15 files changed, 1816 insertions(+), 672 deletions(-) create mode 100644 platform.h create mode 100644 t210/bpmp.cpp create mode 100644 t210/bpmp.h create mode 100644 t210/ccplex.cpp create mode 100644 t210/ccplex.h create mode 100644 t210/regcache.h diff --git a/display/config_window.cpp b/display/config_window.cpp index ec0753c..e1ef3ec 100644 --- a/display/config_window.cpp +++ b/display/config_window.cpp @@ -944,7 +944,13 @@ bool config_window_init() { fprintf(stderr, "[config_window] SDL_CreateWindow failed: %s\n", SDL_GetError()); return false; } - g_renderer = SDL_CreateRenderer(g_window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); + // No PRESENTVSYNC: this window renders on the emulation thread, and + // vsync would stall the emulated CPU for up to a frame per present. + g_renderer = SDL_CreateRenderer(g_window, -1, SDL_RENDERER_ACCELERATED); + // Same fallback as the main window: no GPU renderer (a headless run, a + // VM without GL) should not cost the window altogether. + if (!g_renderer) + g_renderer = SDL_CreateRenderer(g_window, -1, SDL_RENDERER_SOFTWARE); if (!g_renderer) { fprintf(stderr, "[config_window] SDL_CreateRenderer failed: %s\n", SDL_GetError()); SDL_DestroyWindow(g_window); diff --git a/display/console_window.cpp b/display/console_window.cpp index 10623c0..1413c4d 100644 --- a/display/console_window.cpp +++ b/display/console_window.cpp @@ -165,7 +165,13 @@ bool console_window_init() fprintf(stderr, "[console_window] SDL_CreateWindow failed: %s\n", SDL_GetError()); return false; } - g_renderer = SDL_CreateRenderer(g_window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); + // No PRESENTVSYNC: this window renders on the emulation thread, and + // vsync would stall the emulated CPU for up to a frame per present. + g_renderer = SDL_CreateRenderer(g_window, -1, SDL_RENDERER_ACCELERATED); + // Same fallback as the main window: no GPU renderer (a headless run, a + // VM without GL) should not cost the window altogether. + if (!g_renderer) + g_renderer = SDL_CreateRenderer(g_window, -1, SDL_RENDERER_SOFTWARE); if (!g_renderer) { fprintf(stderr, "[console_window] SDL_CreateRenderer failed: %s\n", SDL_GetError()); SDL_DestroyWindow(g_window); diff --git a/display/sdl_display.cpp b/display/sdl_display.cpp index 25e9852..c91590f 100644 --- a/display/sdl_display.cpp +++ b/display/sdl_display.cpp @@ -30,6 +30,8 @@ static bool event_targets_window(const SDL_Event &ev, Uint32 wid) { static SDL_Window *window = nullptr; static SDL_Renderer *renderer = nullptr; static SDL_Texture *texture = nullptr; +// The last converted frame (ARGB8888, out_w x out_h), reused across updates. +static std::vector g_frame; static int g_swizzle_override = -1; // -1 = Auto, 0 = Pitch Linear, 2 = Block Linear @@ -41,8 +43,10 @@ bool sdl_display_init() { SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE); if (!window) return false; - renderer = SDL_CreateRenderer( - window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); + // No PRESENTVSYNC. The CPU runs on this same thread and the main loop + // already paces redraws to ~60 Hz by wall clock; with vsync on, each + // SDL_RenderPresent could block the emulated CPU for up to a whole frame. + renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); if (!renderer) renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_SOFTWARE); if (!renderer) @@ -230,10 +234,61 @@ void sdl_display_update(EmuState *state, uc_engine *uc) { if (fb_size > 32 * 1024 * 1024) fb_size = 32 * 1024 * 1024; - std::vector buf(fb_size); - if (uc_mem_read(uc, eff_addr, buf.data(), fb_size) == UC_ERR_OK) { - std::vector proc(out_w * out_h, - 0xFF000000); // Initialize opaque black + // The surface is read straight out of the host memory backing emulated + // DRAM when it lives there (it always does for hekate/Nyx), instead of a + // uc_mem_read into a fresh 3.5 MB vector - and the converted frame reuses + // one buffer too. The old code allocated and zero-filled two such vectors + // on every frame, 60 times a second, which showed up in profiles as page- + // fault and munmap churn on the emulation thread. + static std::vector fallback; + const uint8_t *src = nullptr; + if (state->dram_low_ptr && eff_addr >= DRAM_BASE && + eff_addr + fb_size <= DRAM_BASE + DRAM_WINDOW_SIZE) { + src = state->dram_low_ptr + (eff_addr - DRAM_BASE); + } else { + fallback.resize(fb_size); + if (uc_mem_read(uc, eff_addr, fallback.data(), fb_size) == UC_ERR_OK) + src = fallback.data(); + } + + // Skip the de-swizzle and the texture upload when neither the surface + // bytes nor the way they are laid out has changed since the last frame - + // the common case for a payload sitting on a menu or waiting on hardware. + struct Layout { + uint64_t addr = 0; + uint32_t w = 0, h = 0, stride = 0, sw = 0, bh = 0, gobs = 0, out_w = 0, + out_h = 0; + int rot = 0; + bool operator==(const Layout &o) const { + return addr == o.addr && w == o.w && h == o.h && stride == o.stride && + sw == o.sw && bh == o.bh && gobs == o.gobs && out_w == o.out_w && + out_h == o.out_h && rot == o.rot; + } + }; + static Layout last_layout; + static std::vector last_src; + Layout layout; + layout.addr = eff_addr; + layout.w = width; + layout.h = height; + layout.stride = eff_stride; + layout.sw = sw; + layout.bh = bh; + layout.gobs = sw_gobs; + layout.out_w = out_w; + layout.out_h = out_h; + layout.rot = rot; + bool unchanged = src && layout == last_layout && last_src.size() == fb_size && + memcmp(last_src.data(), src, fb_size) == 0; + static bool snapshot_pending = true; + + if (src && !unchanged) { + last_layout = layout; + last_src.assign(src, src + fb_size); + snapshot_pending = true; + const uint8_t *buf_data = src; + std::vector &proc = g_frame; + proc.assign((size_t)out_w * out_h, 0xFF000000); // opaque black for (uint32_t sy = 0; sy < height; sy++) { for (uint32_t sx = 0; sx < width; sx++) { @@ -269,7 +324,7 @@ void sdl_display_update(EmuState *state, uc_engine *uc) { uint32_t byte_off = gob_idx * 512 + gob_off; // Read 16-bit pixel and expand to 32-bit ARGB if (byte_off + 2 <= fb_size) { - uint16_t u16 = *(uint16_t *)&buf[byte_off]; + uint16_t u16 = *(const uint16_t *)&buf_data[byte_off]; uint32_t p = (((u16 >> 11) & 0x1F) << 19) | (((u16 >> 5) & 0x3F) << 10) | ((u16 & 0x1F) << 3) | 0xFF000000; @@ -290,7 +345,7 @@ void sdl_display_update(EmuState *state, uc_engine *uc) { } if (off < fb_size / 4) { - uint32_t p = ((uint32_t *)buf.data())[off]; + uint32_t p = ((const uint32_t *)buf_data)[off]; uint32_t dx = sx, dy = sy; switch (rot) { @@ -317,12 +372,17 @@ void sdl_display_update(EmuState *state, uc_engine *uc) { } } SDL_UpdateTexture(texture, nullptr, proc.data(), out_w * 4); + } - // Snapshot for PNG conversion — save periodically (~1s) so the last - // written file always reflects the most recent frame content. + if (src) { + // Snapshot for PNG conversion — at most once a second (~60 frames), and + // only when the frame has changed since the last one written, so an idle + // payload no longer rewrites a 3.5 MB file every second. static int snap_counter = 0; - if (++snap_counter >= 60) { // ~1 second at 60 FPS + const std::vector &proc = g_frame; + if (++snap_counter >= 60 && snapshot_pending && !proc.empty()) { snap_counter = 0; + snapshot_pending = false; FILE *f = fopen("last_fb.rgba", "wb"); if (f) { fwrite(proc.data(), 1, proc.size() * 4, f); diff --git a/main.cpp b/main.cpp index 240ab7d..d56121e 100644 --- a/main.cpp +++ b/main.cpp @@ -22,9 +22,11 @@ #include #include "emu_state.h" -#include +#include "platform.h" #include "payload_picker.h" #include "trace.h" +#include "t210/bpmp.h" +#include "t210/ccplex.h" #include "t210/memory_map.h" #include "t210/mmio.h" #include "display/sdl_display.h" @@ -41,9 +43,15 @@ static uint8_t *load_payload(const char *path, size_t *out_size) { return nullptr; } - fseek(f, 0, SEEK_END); - size_t size = ftell(f); - fseek(f, 0, SEEK_SET); + long len = -1; + if (fseek(f, 0, SEEK_END) == 0) + len = ftell(f); + if (len <= 0 || fseek(f, 0, SEEK_SET) != 0) { + fclose(f); + fprintf(stderr, "[error] Payload is empty or unreadable: %s\n", path); + return nullptr; + } + size_t size = (size_t)len; uint8_t *buf = (uint8_t *)malloc(size); if (!buf) { @@ -83,42 +91,6 @@ static uint8_t *load_payload(const char *path, size_t *out_size) { // ==================== Emulation Setup ==================== -// Global for instruction tracing -static uint32_t pc_trace[2000]; -static size_t pc_trace_idx = 0; -static uint32_t last_valid_block = 0; -static uc_hook trace_h, block_h; - -static void trace_callback(uc_engine *uc, uint64_t address, uint32_t size, void *user_data) { - static uint32_t last_pc = 0; - if (address == last_pc) return; - last_pc = (uint32_t)address; - - pc_trace[pc_trace_idx] = (uint32_t)address; - pc_trace_idx = (pc_trace_idx + 1) % 2000; - - // NOP-slide detection - if (address >= 0x40030000 && address < 0x41000000) { - uint16_t insn = 0; - if (uc_mem_read(uc, address, &insn, 2) == UC_ERR_OK && insn == 0) { - static int nop_count = 0; - if (++nop_count > 10) { - printf("\n[emu] NOP-slide detected at 0x%08llX! Last valid block: 0x%08X\n", - (unsigned long long)address, last_valid_block); - uc_emu_stop(uc); - } - } else { - // nop_count = 0; // would need a persistent counter - } - } -} - -static void block_callback(uc_engine *uc, uint64_t address, uint32_t size, void *user_data) { - if (address >= 0x40000000 && address < 0x40030000) { - last_valid_block = (uint32_t)address; - } -} - static uc_engine *setup_emulation(EmuState *state, uint8_t *payload, size_t payload_size) { uc_engine *uc; uc_err err; @@ -131,9 +103,12 @@ static uc_engine *setup_emulation(EmuState *state, uint8_t *payload, size_t payl } state->uc = uc; - // Setup hooks - uc_hook_add(uc, &trace_h, UC_HOOK_CODE, (void*)trace_callback, nullptr, 1, 0); - uc_hook_add(uc, &block_h, UC_HOOK_BLOCK, (void*)block_callback, nullptr, 1, 0); + // No UC_HOOK_CODE anywhere: a per-instruction callback keeps Unicorn off + // its fast path for every block it covers. This used to register three + // of them (one of them twice) - an instruction-trace ring buffer nothing + // read, a NOP-slide check that did a uc_mem_read per instruction, and + // the clock. The clock and the NOP-slide check now run once per block + // (t210/bpmp.cpp). // Enable VFP/NEON uint32_t cpacr = 0x00F00000; @@ -152,8 +127,6 @@ static uc_engine *setup_emulation(EmuState *state, uint8_t *payload, size_t payl (unsigned long long)(IRAM_BASE + IRAM_SIZE), (unsigned)(IRAM_SIZE / 1024)); - uc_mem_write(uc, IPL_LOAD_ADDR, payload, payload_size); - // Pre-set Hekate's "watchdog fired" magic at IRAM 0x4003FF18 (cookie "WDT") // so its early boot does `goto skip_lp0_minerva_config`, skipping both // libsys_lp0.bso and the Minerva DRAM-training path. The matching @@ -167,9 +140,6 @@ static uc_engine *setup_emulation(EmuState *state, uint8_t *payload, size_t payl uc_mem_write(uc, 0x4003FF18, &wdt_magic, sizeof(wdt_magic)); } - // Setup instruction tracing - uc_hook_add(uc, &trace_h, UC_HOOK_CODE, (void*)trace_callback, nullptr, 1, 0); - // ---- Map DRAM as one contiguous region ---- // 0x80000000 .. 0x100000000, i.e. the whole 32-bit-addressable DRAM window // the BPMP can reach. This used to be two islands (256 MB at 0x80000000 @@ -229,14 +199,10 @@ static uc_engine *setup_emulation(EmuState *state, uint8_t *payload, size_t payl // ---- Nyx Storage (16MB @ 0xED000000) ---- // Already mapped as part of 2GB DRAM chunk - // ---- Map Peripherals (PWM, SDMMC, etc.) ---- - // Map individual pages to allow MMIO hooks - // The mappings previously declared manually were moved here: - // Some are mapped earlier in setup_emulation properly using FB_BASE e.g. - uc_mem_map(uc, 0x7000A000, 0x1000, UC_PROT_ALL); // PWM - uc_mem_map(uc, 0x700B0000, 0x1000, UC_PROT_ALL); // SDMMC1 - uc_mem_map(uc, 0x7000E000, 0x1000, UC_PROT_ALL); // RTC/PMC - uc_mem_map(uc, 0x6000C000, 0x2000, UC_PROT_ALL); // SYSREG/APB_SEMAPH + // Peripherals are all mapped by mmio_init() below as MMIO windows. PWM, + // SDMMC1, RTC/PMC and SYSREG used to be mapped here first as plain RAM, + // which only worked because MMIO was a pair of address-range hooks over + // whatever happened to be mapped. // BootROM (iROM) at 0x100000, 96 KB. We don't have the real BootROM // contents, but mapping the region as zero-filled lets Hekate's "Bootrom @@ -267,9 +233,10 @@ static uc_engine *setup_emulation(EmuState *state, uint8_t *payload, size_t payl printf("[emu] Initial PC=0x%08X SP=0x%08X\n", pc, sp); - // ---- Setup MMIO hooks ---- + // ---- Peripherals and the deterministic clock ---- mmio_init(uc, state); - printf("[emu] MMIO hooks registered\n"); + bpmp_attach(uc, state); + printf("[emu] MMIO windows mapped\n"); return uc; } @@ -420,12 +387,12 @@ int main(int argc, char *argv[]) { } if (sd_path) { - state.sd_fd = open(sd_path, O_RDWR); + state.sd_fd = open(sd_path, O_RDWR | O_BINARY); if (state.sd_fd < 0) perror("[emu] Failed to open SD image"); else printf("[emu] SD image opened: %s\n", sd_path); } if (boot0_path) { - state.emmc_boot0_fd = open(boot0_path, O_RDWR); + state.emmc_boot0_fd = open(boot0_path, O_RDWR | O_BINARY); if (state.emmc_boot0_fd < 0) perror("[emu] Failed to open BOOT0 image"); else printf("[emu] BOOT0 image opened: %s\n", boot0_path); } @@ -433,7 +400,7 @@ int main(int argc, char *argv[]) { for (int i = 0; i < 16; i++) { char path[512]; snprintf(path, sizeof(path), "%s.%02d", rawnand_prefix, i); - int fd = open(path, O_RDWR); + int fd = open(path, O_RDWR | O_BINARY); if (fd >= 0) { state.emmc_gpp_fds.push_back(fd); // printf("[emu] rawnand part %02d opened: %s\n", i, path); @@ -480,6 +447,11 @@ int main(int argc, char *argv[]) { const uint64_t BATCH_INSTRUCTIONS = 100000; // Instructions per batch const int DISPLAY_UPDATE_MS = 16; // ~60 FPS + // While CPU0 is running the two cores advance in lockstep slices of this + // many BPMP instructions (250 us of emulated time). The BPMP polls CPU0's + // mailbox every 500 us, so neither side ever waits on a stale view of the + // other for longer than one of its own poll intervals. + const uint64_t CPU0_QUANTUM_INSTRUCTIONS = 2500; auto last_display_update = std::chrono::steady_clock::now(); @@ -492,9 +464,16 @@ 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); + // 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); + bpmp_clock_reset(); // One contiguous block now; dram_ptr is a view into it. memset(state.dram_low_ptr, 0, DRAM_WINDOW_SIZE); - uc_mem_write(uc, IPL_LOAD_ADDR, state.payload_ptr, state.payload_len); + 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)); uint32_t reset_pc = IPL_LOAD_ADDR; @@ -506,6 +485,7 @@ int main(int argc, char *argv[]) { 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"); @@ -644,17 +624,34 @@ int main(int argc, char *argv[]) { state.touch_x, state.touch_y); } - // Run a batch of ARM instructions - uint32_t start_addr = pc; - if (cpsr & (1 << 5)) start_addr |= 1; + // Run a batch of ARM instructions. With CPU0 up, the batch is cut + // into lockstep slices: the BPMP runs a quantum, then CPU0 runs up + // to the same emulated time. Scripted input and the display are + // still serviced once per full batch, as before. + uint64_t batch_end = state.insn_count + BATCH_INSTRUCTIONS; + while (state.running && !state.paused && + state.insn_count < batch_end) { + uint64_t budget = batch_end - state.insn_count; + if (ccplex_cpu0_running() && budget > CPU0_QUANTUM_INSTRUCTIONS) + budget = CPU0_QUANTUM_INSTRUCTIONS; - uc_err err = uc_emu_start(uc, start_addr, 0, 0, BATCH_INSTRUCTIONS); - if (err != UC_ERR_OK) { - uint32_t error_pc; - uc_reg_read(uc, UC_ARM_REG_PC, &error_pc); - fprintf(stderr, "\n[emu] FATAL: Emulation error at PC=0x%08X: %s\n", error_pc, uc_strerror(err)); - state.running = false; - break; + uc_reg_read(uc, UC_ARM_REG_PC, &pc); + uc_reg_read(uc, UC_ARM_REG_CPSR, &cpsr); + uint32_t start_addr = pc; + if (cpsr & (1 << 5)) start_addr |= 1; + + uc_err err = bpmp_run(uc, &state, start_addr, budget); + if (err != UC_ERR_OK) { + uint32_t error_pc; + uc_reg_read(uc, UC_ARM_REG_PC, &error_pc); + fprintf(stderr, "\n[emu] FATAL: Emulation error at PC=0x%08X: %s\n", error_pc, uc_strerror(err)); + state.running = false; + break; + } + // CPU0 catches up to the BPMP's clock. + ccplex_run(&state, state.emu_usec); + if (state.reboot_requested.load()) + break; } } else { std::this_thread::sleep_for(std::chrono::milliseconds(10)); @@ -689,6 +686,7 @@ int main(int argc, char *argv[]) { console_window_shutdown(); config_window_shutdown(); sdl_display_shutdown(); + ccplex_reset(&state); // closes CPU0's engine, if one is up uc_close(uc); free(state.iram_ptr); diff --git a/platform.h b/platform.h new file mode 100644 index 0000000..7650b31 --- /dev/null +++ b/platform.h @@ -0,0 +1,37 @@ +#ifndef RCM_PLATFORM_H +#define RCM_PLATFORM_H + +#include +#include +#include +#include + +// Small portability helpers for the disk-image code, which is the one place +// the emulator does raw POSIX file I/O. + +// MinGW's open() defaults to TEXT mode: _read() turns every CR LF into LF +// and stops at the first 0x1A byte. On an SD card or eMMC image that is +// silent sector corruption, so every image fd must be opened O_BINARY. +// POSIX has no such flag (and no such mode), so it is a no-op there. +#ifndef O_BINARY +#define O_BINARY 0 +#endif + +// Size of an open file, in 64 bits. MinGW's plain struct stat carries a +// 32-bit st_size, which cannot describe the 4 GiB chunks Hekate splits a +// rawnand dump into; _fstati64 can. +static inline int64_t file_size64(int fd) { +#ifdef _WIN32 + struct _stati64 st; + if (_fstati64(fd, &st) != 0) + return -1; + return (int64_t)st.st_size; +#else + struct stat st; + if (fstat(fd, &st) != 0) + return -1; + return (int64_t)st.st_size; +#endif +} + +#endif // RCM_PLATFORM_H diff --git a/t210/bpmp.cpp b/t210/bpmp.cpp new file mode 100644 index 0000000..23242e3 --- /dev/null +++ b/t210/bpmp.cpp @@ -0,0 +1,246 @@ +#include "bpmp.h" + +#include +#include + +#include "../emu_state.h" +#include "memory_map.h" + +namespace { + +// ---- TIMERUS pacing -------------------------------------------------------- +// +// Real silicon retires a few hundred BPMP instructions per microsecond; this +// clock credits ten. That dilation is what makes busy-waits cheap to emulate, +// and it is harmless for the usual `while (now - start < us)` wait. It is not +// harmless for a wait that needs to SEE a particular counter value. bdk's own +// fan_get_speed() is one: +// +// int timer = get_tmr_us() + 2000000; +// while ((timer - get_tmr_us()) > 0) // int - u32: unsigned, so "!= 0" +// +// GCC compiles that to `cmp; bne`: the loop ends only on the exact deadline. +// Its body is ~30 instructions - a tenth of a microsecond on hardware, three +// microseconds here - so the emulated counter stepped past the deadline and +// the loop spun until TIMERUS wrapped, about 72 emulated minutes later. That +// is where a hwtest sweep used to stall, in the fan spin-up test. +// +// So polls are paced the way hardware paces them: while TIMERUS reads come +// at most POLL_WINDOW instructions apart - under a microsecond at real speed - +// the clock advances by at most 1 us from one read to the next. Time stays +// monotonic for every observer (only increments are capped), a wait still +// ends at the emulated time it asked for, and a loop that polls less often +// than that runs on the plain instruction clock. +constexpr uint64_t POLL_WINDOW = 200; + +struct Clock { + uint64_t limit = 0; // insn_count at which the current batch ends + uint32_t pending = 0; // instructions of the block now executing + // TIMERUS pacing (see above). + bool polling = false; + uint64_t poll_insn = 0; // insn_count at the last TIMERUS read + uint64_t poll_usec = 0; // value it returned + // Diagnostics. + uint64_t loop_addr = 0; + uint64_t loop_insns = 0; + bool stall_logged = false; + bool nop_slide_reported = false; +}; + +Clock clk; +uc_hook h_block; + +// Credit `n` retired instructions. emu_usec ticks once per ten, exactly as +// the per-instruction counter used to tick it, and anything a FLOW_CTLR +// timed halt added to emu_usec directly is preserved. +inline void commit(EmuState *s, uint32_t n) { + uint64_t before = s->insn_count; + s->insn_count += n; + uint64_t delta = s->insn_count / 10 - before / 10; + if (clk.polling && delta) { + if (s->insn_count - clk.poll_insn <= POLL_WINDOW) { + uint64_t cap = clk.poll_usec + 1; + uint64_t room = cap > s->emu_usec ? cap - s->emu_usec : 0; + if (delta > room) + delta = room; + } else { + clk.polling = false; + } + } + s->emu_usec += delta; +} + +inline const uint8_t *code_ptr(const EmuState *s, uint64_t a, uint32_t len) { + if (a >= IRAM_BASE && a + len <= IRAM_BASE + IRAM_SIZE) + return s->iram_ptr + (a - IRAM_BASE); + if (a >= DRAM_BASE && a + len <= DRAM_BASE + DRAM_WINDOW_SIZE) + return s->dram_low_ptr + (a - DRAM_BASE); + return nullptr; +} + +// Instructions in a translated block, counted the way Unicorn's per- +// instruction hook saw them. ARM: all four bytes. Thumb: a halfword whose top +// five bits are 0b11101, 0b11110 or 0b11111 opens a 32-bit instruction - on +// this core (Unicorn's Cortex-A15) that includes the Thumb-1 BL/BLX prefix +// and suffix pair, which decodes as one instruction. +uint32_t decode_insns(uc_engine *uc, const EmuState *s, uint64_t addr, + uint32_t size) { + uint32_t cpsr = 0; + uc_reg_read(uc, UC_ARM_REG_CPSR, &cpsr); + if (!(cpsr & (1u << 5))) + return size >= 4 ? size / 4 : 1; + + static uint8_t scratch[8192]; + const uint8_t *p = code_ptr(s, addr, size); + if (!p) { + // Code outside IRAM/DRAM (the zero-filled iROM, low scratch): rare. + uint32_t n = size < sizeof(scratch) ? size : (uint32_t)sizeof(scratch); + if (uc_mem_read(uc, addr, scratch, n) != UC_ERR_OK) + return size >= 2 ? size / 2 : 1; + p = scratch; + size = n; + } + uint32_t n = 0; + for (uint32_t i = 0; i + 1 < size; n++) { + uint16_t hw = (uint16_t)(p[i] | (p[i + 1] << 8)); + i += ((hw & 0xF800) >= 0xE800) ? 4 : 2; + } + return n ? n : 1; +} + +// Decoding a hot block on every execution was most of this hook's cost, so +// counts are cached per block. A block is identified by address and size, +// and fingerprinted by its first and last words: code rewritten in place +// (a relocation, a chainloaded payload) almost always changes one of those, +// and when it does not, the translator's own retranslation still gives the +// same instruction boundaries unless the 16/32-bit mix inside changed too. +struct CountCacheEntry { + uint32_t addr; + uint32_t head; + uint32_t tail; + uint16_t size; + uint16_t count; +}; +constexpr size_t kCountCacheSize = 1u << 16; +CountCacheEntry count_cache[kCountCacheSize]; + +inline uint32_t load32(const uint8_t *p) { + uint32_t v; + memcpy(&v, p, 4); + return v; +} + +uint32_t count_insns(uc_engine *uc, const EmuState *s, uint64_t addr, + uint32_t size) { + const uint8_t *p = (size >= 4 && size < 0x10000) ? code_ptr(s, addr, size) + : nullptr; + if (!p) + return decode_insns(uc, s, addr, size); + uint32_t head = load32(p), tail = load32(p + size - 4); + CountCacheEntry &e = count_cache[(addr >> 1) & (kCountCacheSize - 1)]; + if (e.addr == (uint32_t)addr && e.size == size && e.head == head && + e.tail == tail && e.count) + return e.count; + uint32_t n = decode_insns(uc, s, addr, size); + e.addr = (uint32_t)addr; + e.size = (uint16_t)size; + e.head = head; + e.tail = tail; + e.count = (uint16_t)n; + return n; +} + +// A payload that jumps into zeroed memory executes `movs r0, r0` (Thumb +// 0x0000) or `andeq r0, r0, r0` (ARM) until it hits something. No compiler +// emits sixteen zero bytes at the start of a block, so that is the signal. +bool nop_slide(const EmuState *s, uint64_t addr) { + bool in_range = (addr >= 0x40030000 && addr < IRAM_BASE + IRAM_SIZE) || + (addr >= DRAM_BASE && addr < DRAM_BASE + DRAM_WINDOW_SIZE); + if (!in_range) + return false; + const uint8_t *p = code_ptr(s, addr, 16); + if (!p) + return false; + static const uint8_t zero[16] = {0}; + return memcmp(p, zero, sizeof(zero)) == 0; +} + +// Once per translated block, before it runs. Credits the previous block, +// which has now fully executed. When the batch budget is spent it stops the +// engine here, and Unicorn does not run this block at all - PC stays on its +// first instruction and the next batch starts there - so it is not counted. +void hook_block(uc_engine *uc, uint64_t address, uint32_t size, void *ud) { + EmuState *s = (EmuState *)ud; + commit(s, clk.pending); + clk.pending = 0; + if (s->insn_count >= clk.limit) { + uc_emu_stop(uc); + return; + } + + if (nop_slide(s, address)) { + if (!clk.nop_slide_reported) { + clk.nop_slide_reported = true; + printf("\n[emu] NOP-slide detected at 0x%08llX (zeroed memory being " + "executed) - emulation paused\n", (unsigned long long)address); + fflush(stdout); + } + s->paused = true; + uc_emu_stop(uc); + return; + } + + clk.pending = count_insns(uc, s, address, size); + + // A single-instruction self-loop (`b .`) spinning for a long time is a + // payload that has given up; say so once when it finally leaves it. + if (size <= 4 && address == clk.loop_addr) { + clk.loop_insns += clk.pending; + } else { + if (clk.loop_insns > 100000 && !clk.stall_logged) { + printf("[trace] STALL at PC=0x%08llX (looped %llu times)\n", + (unsigned long long)clk.loop_addr, + (unsigned long long)clk.loop_insns); + clk.stall_logged = true; + } else if (clk.loop_insns == 0) { + clk.stall_logged = false; + } + clk.loop_addr = address; + clk.loop_insns = 0; + } +} + +} // namespace + +void bpmp_attach(uc_engine *uc, EmuState *state) { + uc_hook_add(uc, &h_block, UC_HOOK_BLOCK, (void *)hook_block, state, 1, 0); +} + +uc_err bpmp_run(uc_engine *uc, EmuState *state, uint64_t begin, + uint64_t max_insns) { + clk.limit = state->insn_count + (max_insns ? max_insns : 1); + clk.pending = 0; + uc_err err = uc_emu_start(uc, begin, 0, 0, 0); + // If something other than the budget ended the run (an MMIO handler + // calling uc_emu_stop, a fault), the block in flight has still run to its + // end - Unicorn only checks for a stop between blocks - so credit it. + commit(state, clk.pending); + clk.pending = 0; + return err; +} + +void bpmp_clock_reset() { + clk = Clock(); + memset(count_cache, 0, sizeof(count_cache)); +} + +uint32_t bpmp_timerus_read(EmuState *state) { + clk.polling = true; + clk.poll_insn = state->insn_count; + clk.poll_usec = state->emu_usec; + return (uint32_t)state->emu_usec; +} + +void bpmp_clock_jumped() { + clk.polling = false; +} diff --git a/t210/bpmp.h b/t210/bpmp.h new file mode 100644 index 0000000..467568b --- /dev/null +++ b/t210/bpmp.h @@ -0,0 +1,48 @@ +#ifndef T210_BPMP_H +#define T210_BPMP_H + +#include +#include + +struct EmuState; + +/* + * BPMP execution and its deterministic clock. + * + * Emulated time is derived from retired instructions, never from the host: + * emu_usec = skipped_us + insn_count / 10, where skipped_us is whatever a + * FLOW_CTLR timed halt jumped over. That makes a run reproducible - the same + * payload sees the same TIMERUS value at the same instruction every time - + * which scripted input (--input-script, --auto-te-script) depends on. + * + * The instruction count used to come from a UC_HOOK_CODE callback on every + * single instruction, which kept Unicorn from running any translated block + * at native speed. It now comes from a block hook: the block's instructions + * are counted once, from its bytes, and credited when the block has run. The + * totals are exactly what per-instruction counting gave. What changed is + * resolution inside a block: an MMIO read there sees the time at the start + * of its block, not at its own instruction - a fraction of a microsecond at + * 10 instructions per microsecond. + */ + +// Install the clock's block hook on the BPMP engine. +void bpmp_attach(uc_engine *uc, EmuState *state); + +// Run from `begin` (bit 0 = Thumb) until at least `max_insns` more +// instructions have retired, or something stops the engine. Batches end on +// a block boundary. +uc_err bpmp_run(uc_engine *uc, EmuState *state, uint64_t begin, + uint64_t max_insns); + +// Forget any half-accounted block (soft reboot). +void bpmp_clock_reset(); + +// TIMERUS_CNTR_1US as the BPMP reads it. See the pacing note in bpmp.cpp: +// polls issued close together never see the counter skip a value. +uint32_t bpmp_timerus_read(EmuState *state); + +// Time jumped forward outside instruction accounting (a FLOW_CTLR timed +// halt): whatever poll loop was being paced is over. +void bpmp_clock_jumped(); + +#endif // T210_BPMP_H diff --git a/t210/ccplex.cpp b/t210/ccplex.cpp new file mode 100644 index 0000000..ceb1101 --- /dev/null +++ b/t210/ccplex.cpp @@ -0,0 +1,509 @@ +#include "ccplex.h" + +#include +#include + +#include + +#include "../emu_state.h" +#include "memory_map.h" +#include "mmio.h" +#include "pcie.h" + +// ========================================================================== +// Registers (bdk soc/clock.h, soc/t210.h, soc/pmc.h; Tegra X1 TRM ch.5/16) +// ========================================================================== + +#define CAR_CCLK_BURST_POLICY 0x020 +#define CCLK_RUN_SRC(v) (((v) >> 4) & 0xF) +#define CCLK_SRC_PLLX_OUT0_LJ 8 +#define CCLK_SRC_PLLX_OUT0 14 +#define CAR_PLLX_BASE 0x0E0 +#define PLL_BASE_ENABLE (1u << 30) +#define CAR_CLK_OUT_ENB_V 0x360 +#define CAR_CLK_ENB_V_SET 0x440 +#define CAR_CLK_ENB_V_CLR 0x444 +#define CLK_V_CPUG 0 +#define CLK_V_MSELECT 3 +#define CAR_RST_CPUG_CMPLX_SET 0x450 +#define CAR_RST_CPUG_CMPLX_CLR 0x454 +// 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)) +#define RST_NONCPU (1u << 29) + +// SB block, SYSREG + 0x200. +#define SB_CSR 0x00 +#define SB_AA64_RESET_LOW 0x30 +#define SB_AA64_RESET_HIGH 0x34 +#define SB_AA64_RST_AARCH64_MODE_EN (1u << 0) + +// PMC partitions carrying CPU0. +#define POWER_RAIL_CRAIL 0 +#define POWER_RAIL_CE0 14 +#define POWER_RAIL_C0NC 15 + +// ========================================================================== +// Timing +// ========================================================================== +// +// PLLX runs the A57s at ~1 GHz. Retiring one instruction per nanosecond is +// the right order of magnitude, and it is ten times the rate the BPMP clock +// model uses, which is the other thing that has to hold: CPU0 is the fast +// core. +// +// A bus access is not free. From the A57, a register read goes out through +// MSELECT and the APC bridge onto a 100-odd MHz APB, and costs a few hundred +// nanoseconds. Charging it keeps a udelay() loop - which is nothing but +// TIMERUS reads - at a realistic few million accesses per emulated second +// instead of a billion instructions of busy-wait. +static constexpr uint64_t NS_PER_INSN = 1; +static constexpr uint64_t NS_PER_BUS_ACCESS = 250; + +// ========================================================================== +// Reset entry +// ========================================================================== +// +// A real A57 comes out of reset at EL3 in AArch64 and fetches from the +// SB_AA64_RESET vector. Unicorn creates its ARM64 core at EL1 instead (a +// backward-compatibility choice in its cpu init), and it cannot be moved: +// writing PSTATE updates the mode bits but not the translator's cached +// hflags, so the first `msr scr_el3` still decodes as EL1 and is UNDEFINED. +// Nor can an exception carry it up, because Unicorn never delivers guest +// exceptions - SMC and friends end the run. +// +// ERET can. Its helper takes the current EL from PSTATE - which the register +// write did update - reads SPSR_EL3/ELR, and rebuilds hflags for the target +// EL. So the core starts on a one-instruction trampoline in a page only CPU0 +// can see, with PSTATE, SPSR_EL3 = EL3h/DAIF masked and ELR = the vector. +// The translator fetches the new PC's address from ELR at the EL it thinks +// it is at (EL1), so ELR_EL1 carries it too. One ERET later the core is at +// EL3h with interrupts masked and the MMU off: architectural reset state. +// +// The page sits at 1 TiB: inside the A57's 44-bit physical space, far +// outside the Tegra's, so it can never alias anything a payload can reach. +static constexpr uint64_t RESET_TRAMPOLINE = 0x10000000000ULL; +static constexpr uint32_t A64_ERET = 0xD69F03E0; +static constexpr uint32_t A64_WFE = 0xD503205F; +static constexpr uint32_t A64_WFI = 0xD503207F; +static constexpr uint64_t PSTATE_EL3H_DAIF = 0x3CD; + +namespace { + +enum class Cpu0 { Off, Running, Hung }; + +struct Model { + uint32_t rst_cpug = 0xFFFFFFFFu; // everything held at power-on + uint32_t clk_enb_v = 0; + uint32_t cclk_burst = 0; + uint32_t pllx_base = 0; + uint32_t sb_csr = 0; + uint32_t sb_rst_lo = 0; + uint32_t sb_rst_hi = 0; + + Cpu0 cpu0 = Cpu0::Off; + uc_engine *uc = nullptr; + uint64_t pc = 0; + uint64_t ns = 0; // CPU0's clock, emulated nanoseconds + uint64_t target_ns = 0; // end of the slice being run + uint64_t pending = 0; // instructions in the block now executing + bool wfe_next = false; // the block now executing ends in WFE/WFI + bool in_run = false; + bool kill_pending = false; + bool reset_pending = false; + const char *kill_reason = nullptr; + + uint64_t retired = 0; + uint64_t bus_accesses = 0; + uint32_t boots = 0; + const char *last_refusal = nullptr; +}; + +Model m; +EmuState *g_state = nullptr; +uc_hook h_block, h_unmapped, h_intr; + +bool held() { return (m.rst_cpug & (RST_CPU0_MASK | RST_NONCPU)) != 0; } + +uint64_t entry_vector() { + return ((uint64_t)m.sb_rst_hi << 32) | (m.sb_rst_lo & ~1u); +} + +bool entry_mapped(uint64_t a) { + return (a >= DRAM_BASE && a + 4 <= DRAM_BASE + DRAM_WINDOW_SIZE) || + (a >= IRAM_BASE && a + 4 <= IRAM_BASE + IRAM_SIZE); +} + +const uint8_t *host_ptr(uint64_t a, uint32_t len) { + // Valid for the identity map CPU0 runs with before (MMU off) and after + // (the stub's 1 GiB identity blocks) enabling the MMU. + if (a >= DRAM_BASE && a + len <= DRAM_BASE + DRAM_WINDOW_SIZE) + return g_state->dram_low_ptr + (a - DRAM_BASE); + if (a >= IRAM_BASE && a + len <= IRAM_BASE + IRAM_SIZE) + return g_state->iram_ptr + (a - IRAM_BASE); + return nullptr; +} + +// Everything the core needs to actually execute once released. Returns the +// first thing missing, or nullptr. +const char *boot_blocked(EmuState *state) { + if (!cpu_rail_on(state)) + return state->pmic_otp.load() == 0x53 + ? "CPU rail off (MAX77812 EN_CTRL.EN_M4 clear)" + : "CPU rail off (MAX77621 VOUT_EN / MAX77620 GPIO5 EN pin)"; + if (!pmc_partition_on(POWER_RAIL_CRAIL)) return "CRAIL partition powergated"; + if (!pmc_partition_on(POWER_RAIL_C0NC)) return "C0NC partition powergated"; + if (!pmc_partition_on(POWER_RAIL_CE0)) return "CE0 partition powergated"; + if (!(m.clk_enb_v & (1u << CLK_V_CPUG))) return "CPUG clock disabled (CLK_ENB_V bit 0)"; + uint32_t src = CCLK_RUN_SRC(m.cclk_burst); + if ((src == CCLK_SRC_PLLX_OUT0_LJ || src == CCLK_SRC_PLLX_OUT0) && + !(m.pllx_base & PLL_BASE_ENABLE)) + return "CCLK runs from PLLX but PLLX is disabled"; + if (!(m.clk_enb_v & (1u << CLK_V_MSELECT))) return "MSELECT clock disabled"; + if (!pcie_mselect_up()) return "MSELECT still in reset"; + if (!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"; + return nullptr; +} + +void destroy_engine() { + if (!m.uc) + return; + mmio_unmap_bus(m.uc); + uc_close(m.uc); + m.uc = nullptr; +} + +void stop_cpu0(const char *why) { + if (m.cpu0 == Cpu0::Off) + return; + if (m.in_run) { + // The core is the one executing: it just wrote the register that stops + // it. Finish the current access, then tear down once the run returns. + m.kill_pending = true; + m.kill_reason = why; + uc_emu_stop(m.uc); + return; + } + printf("[ccplex] CPU0 stopped (%s) after %llu instructions, %llu bus " + "accesses\n", why, (unsigned long long)m.retired, + (unsigned long long)m.bus_accesses); + fflush(stdout); + destroy_engine(); + m.cpu0 = Cpu0::Off; +} + +// ---- CPU0 engine hooks --------------------------------------------------- + +void commit_pending() { + m.ns += m.pending * NS_PER_INSN; + m.retired += m.pending; + m.pending = 0; +} + +// Once per translated block, before it runs. Accounts the previous block +// (which has now fully executed), ends the slice when CPU0's clock reaches +// its target, and parks the core after a WFE/WFI. Stopping here means the +// block is NOT executed - Unicorn leaves PC on its first instruction - so +// the next slice picks it up again. +void hook_block(uc_engine *uc, uint64_t address, uint32_t size, void *) { + commit_pending(); + if (m.wfe_next) { + // The block that just ran ended in WFE/WFI: the core sleeps until + // something wakes it. Nothing in this model sends it an event, so it + // sleeps to the end of the slice and resumes - a spurious wake-up, which + // the architecture allows, and which a `for(;;) wfe;` park loop turns + // straight back into sleep. Without this that loop would spin through + // hundreds of millions of instructions per emulated second. + m.wfe_next = false; + if (m.ns < m.target_ns) + m.ns = m.target_ns; + } + g_state->emu_usec = m.ns / 1000; + if (m.ns >= m.target_ns || m.kill_pending) { + uc_emu_stop(uc); + return; + } + // Every A64 instruction is four bytes. + m.pending = size >= 4 ? size / 4 : 1; + if (const uint8_t *p = host_ptr(address + size - 4, 4)) { + uint32_t last; + memcpy(&last, p, 4); + m.wfe_next = (last == A64_WFE || last == A64_WFI); + } +} + +bool hook_unmapped(uc_engine *uc, uc_mem_type type, uint64_t address, int size, + int64_t value, void *) { + (void)size; + (void)value; + uint64_t pc = 0; + uc_reg_read(uc, UC_ARM64_REG_PC, &pc); + const char *kind = type == UC_MEM_FETCH_UNMAPPED ? "fetch" + : type == UC_MEM_WRITE_UNMAPPED ? "write" + : "read"; + // Nothing decodes this address, so on silicon the transaction never + // completes and the core waits on it for ever. Return false: the run ends + // and the core is marked wedged, which is what the BPMP's watchdog on the + // mailbox heartbeat is there to notice. + printf("[ccplex] CPU0 %s of unmapped 0x%llX at PC=0x%llX: nothing answers, " + "CPU0 wedged\n", kind, (unsigned long long)address, + (unsigned long long)pc); + fflush(stdout); + return false; +} + +void hook_intr(uc_engine *uc, uint32_t intno, void *) { + // Unicorn does not deliver guest exceptions (see the reset-entry note), + // so a fault cannot reach the stub's own vectors. Say what happened and + // stop the core rather than resume past the faulting instruction. + uint64_t pc = 0; + uc_reg_read(uc, UC_ARM64_REG_PC, &pc); + static const char *names[] = {"?", "UDEF", "SWI", "PREFETCH_ABORT", + "DATA_ABORT", "IRQ", "FIQ", "BKPT", "EXIT", + "KERNEL_TRAP", "HVC", "HYP_TRAP", "SMC"}; + printf("[ccplex] CPU0 took exception %u (%s) near PC=0x%llX; exception " + "entry is not modelled, CPU0 halted\n", intno, + intno < sizeof(names) / sizeof(names[0]) ? names[intno] : "?", + (unsigned long long)pc); + fflush(stdout); + m.kill_pending = false; + m.cpu0 = Cpu0::Hung; + uc_emu_stop(uc); +} + +bool start_cpu0(EmuState *state) { + uint64_t entry = entry_vector(); + uc_engine *uc = nullptr; + uc_err err = uc_open(UC_ARCH_ARM64, UC_MODE_ARM, &uc); + if (err != UC_ERR_OK) { + printf("[ccplex] cannot create the CPU0 engine: %s\n", uc_strerror(err)); + return false; + } + uc_ctl_set_cpu_model(uc, UC_CPU_ARM64_A57); + + // IRAM, DRAM and TZRAM are the same host memory the BPMP engine maps, so + // a stub the BPMP copies into DRAM and the mailbox both cores poll are one + // set of bytes. CPU0's engine is new on every release, so it cannot hold + // stale translations of code the BPMP has rewritten since the last boot. + err = uc_mem_map_ptr(uc, IRAM_BASE, IRAM_SIZE, UC_PROT_ALL, state->iram_ptr); + if (err == UC_ERR_OK) + err = uc_mem_map_ptr(uc, DRAM_BASE, DRAM_WINDOW_SIZE, UC_PROT_ALL, + state->dram_low_ptr); + if (err == UC_ERR_OK) + err = uc_mem_map(uc, RESET_TRAMPOLINE, 0x1000, UC_PROT_READ | UC_PROT_EXEC); + if (err != UC_ERR_OK) { + printf("[ccplex] cannot map CPU0 memory: %s\n", uc_strerror(err)); + uc_close(uc); + return false; + } + mmio_map_bus(uc, state); + uc_mem_write(uc, RESET_TRAMPOLINE, &A64_ERET, sizeof(A64_ERET)); + + uint64_t v = PSTATE_EL3H_DAIF; + uc_reg_write(uc, UC_ARM64_REG_PSTATE, &v); + uc_arm64_cp_reg spsr_el3 = {4, 0, 3, 6, 0, PSTATE_EL3H_DAIF}; // crn crm op0 op1 op2 + uc_arm64_cp_reg elr_el3 = {4, 0, 3, 6, 1, entry}; + uc_arm64_cp_reg scr_el3 = {1, 1, 3, 6, 0, 0}; // reset: secure, nothing routed + uc_reg_write(uc, UC_ARM64_REG_CP_REG, &spsr_el3); + uc_reg_write(uc, UC_ARM64_REG_CP_REG, &elr_el3); + uc_reg_write(uc, UC_ARM64_REG_CP_REG, &scr_el3); + v = entry; + uc_reg_write(uc, UC_ARM64_REG_ELR_EL1, &v); + + uc_hook_add(uc, &h_block, UC_HOOK_BLOCK, (void *)hook_block, nullptr, 1, 0); + uc_hook_add(uc, &h_unmapped, UC_HOOK_MEM_UNMAPPED, (void *)hook_unmapped, + nullptr, 1, 0); + uc_hook_add(uc, &h_intr, UC_HOOK_INTR, (void *)hook_intr, nullptr, 1, 0); + + m.uc = uc; + m.pc = RESET_TRAMPOLINE; + m.ns = state->emu_usec * 1000; // released at the BPMP's current time + m.pending = 0; + m.wfe_next = false; + m.kill_pending = false; + m.retired = 0; + m.bus_accesses = 0; + m.cpu0 = Cpu0::Running; + m.boots++; + printf("[ccplex] CPU0 released: AArch64 EL3, MMU off, entry 0x%08llX " + "(boot #%u)\n", (unsigned long long)entry, m.boots); + fflush(stdout); + return true; +} + +void try_release(EmuState *state) { + const char *why = boot_blocked(state); + if (why) { + // On silicon the core would never run and nothing would say why. Name + // it, once per distinct reason, so a payload that got the sequence wrong + // learns what it got wrong. + if (why != m.last_refusal) + printf("[ccplex] CPU0 released from reset but cannot run: %s\n", why); + m.last_refusal = why; + fflush(stdout); + return; + } + m.last_refusal = nullptr; + start_cpu0(state); +} + +} // namespace + +// ========================================================================== + +void ccplex_reset(EmuState *state) { + g_state = state; + if (m.in_run) { + // A reset from inside CPU0's own slice: defer the teardown to the end + // of the run. + m.kill_pending = true; + m.reset_pending = true; + m.kill_reason = "SoC reset"; + uc_emu_stop(m.uc); + return; + } + destroy_engine(); + uint32_t boots = m.boots; + m = Model(); + m.boots = boots; +} + +void ccplex_car_write(EmuState *state, uint32_t offset, uint32_t val) { + switch (offset) { + case CAR_CCLK_BURST_POLICY: m.cclk_burst = val; 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_CLK_ENB_V_CLR: + m.clk_enb_v &= ~val; + if ((val & (1u << CLK_V_CPUG)) && m.cpu0 == Cpu0::Running) { + // Clock stopped under a running core: it freezes where it is. Treat + // it as wedged until the next reset, which is how bdk always follows + // this write anyway. + printf("[ccplex] CPUG clock gated under a running CPU0 - core frozen\n"); + m.cpu0 = Cpu0::Hung; + } + break; + case CAR_RST_CPUG_CMPLX_SET: + m.rst_cpug |= val; + if (val & (RST_CPU0_MASK | RST_NONCPU)) + stop_cpu0("held in reset"); + break; + case CAR_RST_CPUG_CMPLX_CLR: { + bool was_held = held(); + m.rst_cpug &= ~val; + if (was_held && !held() && m.cpu0 == Cpu0::Off) + try_release(state); + break; + } + default: + break; + } +} + +bool ccplex_car_read(uint32_t offset, uint32_t *out) { + switch (offset) { + case CAR_CLK_OUT_ENB_V: + *out = m.clk_enb_v; + return true; + case CAR_RST_CPUG_CMPLX_SET: + case CAR_RST_CPUG_CMPLX_CLR: + *out = m.rst_cpug; + return true; + default: + return false; + } +} + +uint32_t ccplex_sb_read(uint32_t offset) { + switch (offset) { + case SB_CSR: return m.sb_csr; + case SB_AA64_RESET_LOW: return m.sb_rst_lo; + case SB_AA64_RESET_HIGH: return m.sb_rst_hi; + default: return 0; + } +} + +void ccplex_sb_write(EmuState *state, uint32_t offset, uint32_t val) { + (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. + 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; + default: break; + } +} + +void ccplex_partition_changed(EmuState *state, int part, bool on) { + (void)state; + if (on) + return; + if (part == POWER_RAIL_CRAIL) stop_cpu0("CRAIL partition powergated"); + if (part == POWER_RAIL_C0NC) stop_cpu0("C0NC partition powergated"); + if (part == POWER_RAIL_CE0) stop_cpu0("CE0 partition powergated"); +} + +void ccplex_rail_changed(EmuState *state) { + if (m.cpu0 != Cpu0::Off && !cpu_rail_on(state)) + stop_cpu0("CPU rail switched off"); +} + +void ccplex_bus_tick(EmuState *state) { + m.ns += NS_PER_BUS_ACCESS; + m.bus_accesses++; + state->emu_usec = m.ns / 1000; +} + +bool ccplex_cpu0_running() { return m.cpu0 == Cpu0::Running && m.uc; } + +void ccplex_run(EmuState *state, uint64_t until_us) { + if (!ccplex_cpu0_running()) + return; + uint64_t target = until_us * 1000; + if (m.ns >= target) + return; + + // 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. + uint64_t bpmp_usec = state->emu_usec; + BusMaster prev = g_bus_master; + g_bus_master = BUS_CPU0; + state->emu_usec = m.ns / 1000; + m.target_ns = target; + m.in_run = true; + + uc_err err = uc_emu_start(m.uc, m.pc, 0, 0, 0); + + commit_pending(); + uc_reg_read(m.uc, UC_ARM64_REG_PC, &m.pc); + m.in_run = false; + g_bus_master = prev; + state->emu_usec = bpmp_usec; + + if (m.kill_pending) { + m.kill_pending = false; + const char *why = m.kill_reason ? m.kill_reason : "stopped"; + m.cpu0 = Cpu0::Running; // so stop_cpu0 does the teardown + stop_cpu0(why); + if (m.reset_pending) + ccplex_reset(state); + return; + } + if (err != UC_ERR_OK && m.cpu0 == Cpu0::Running) { + printf("[ccplex] CPU0 wedged at PC=0x%llX: %s\n", + (unsigned long long)m.pc, uc_strerror(err)); + fflush(stdout); + m.cpu0 = Cpu0::Hung; + } +} diff --git a/t210/ccplex.h b/t210/ccplex.h new file mode 100644 index 0000000..1959b61 --- /dev/null +++ b/t210/ccplex.h @@ -0,0 +1,57 @@ +#ifndef T210_CCPLEX_H +#define T210_CCPLEX_H + +#include + +struct EmuState; + +/* + * CCPLEX CPU0 - the first Cortex-A57 of the Tegra X1's main CPU cluster. + * + * An RCM payload runs on the BPMP, but it can boot CPU0 itself with bdk's + * ccplex_boot_cpu0(): rail on, PLLX, CCLK, the CRAIL/C0NC/CE0 partitions, + * RAM repair, the AArch64 reset vector in SB_AA64_RESET_LOW/HIGH, then + * RST_CPUG_CMPLX_CLR. hwtest does exactly that for its PCIe probe, because + * PCIe answers a CPU-complex master only. + * + * This model watches those registers and, when the core is released with + * every precondition met, runs it: a second Unicorn engine in AArch64 mode, + * entered at EL3 with the MMU off at the programmed vector, sharing IRAM, + * DRAM, TZRAM and every peripheral model with the BPMP. A release that is + * missing something does not start the core, and says which precondition + * was missing - on silicon the core would simply never run. + * + * Time: CPU0 keeps its own clock, advanced by the instructions it retires + * and by the latency of each bus access it makes, and the main loop runs it + * in short slices up to the BPMP's current time. WFE/WFI park it until the + * end of the slice. Everything is a pure function of the instruction stream, + * so runs stay deterministic. + */ + +// Power-on state: CPU0 in reset, no vector, clocks off. +void ccplex_reset(EmuState *state); + +// CAR (clock and reset controller) forwarding. +void ccplex_car_write(EmuState *state, uint32_t offset, uint32_t val); +bool ccplex_car_read(uint32_t offset, uint32_t *out); + +// SB block (SYSREG + 0x200): SB_CSR and the AArch64 reset vector. +uint32_t ccplex_sb_read(uint32_t offset); +void ccplex_sb_write(EmuState *state, uint32_t offset, uint32_t val); + +// A PMC power partition toggled / the CPU rail regulator changed. Losing any +// of them under a running core stops it. +void ccplex_partition_changed(EmuState *state, int part, bool on); +void ccplex_rail_changed(EmuState *state); + +// Called by the MMIO front-end for every access CPU0 makes: charges the bus +// latency to CPU0's clock before the access is dispatched. +void ccplex_bus_tick(EmuState *state); + +// True while CPU0 is out of reset and executing (not parked on a hung bus). +bool ccplex_cpu0_running(); + +// Run CPU0 until its clock reaches `until_us` - the BPMP's current time. +void ccplex_run(EmuState *state, uint64_t until_us); + +#endif // T210_CCPLEX_H diff --git a/t210/memory_map.h b/t210/memory_map.h index 90774d6..e59f505 100644 --- a/t210/memory_map.h +++ b/t210/memory_map.h @@ -147,10 +147,19 @@ constexpr uint64_t HOST1X_SIZE = 0x40000; constexpr uint64_t BPMP_CACHE_BASE = 0x50040000; constexpr uint64_t BPMP_CACHE_SIZE = 0x1000; -// System Registers (SYSREG) +// System Registers (SYSREG). SB (secure boot) sits at +0x200 and holds the +// CCPLEX's AArch64 reset vector (SB_AA64_RESET_LOW/HIGH, +0x230/+0x234). constexpr uint64_t SYSREG_BASE = 0x6000C000; constexpr uint64_t SYSREG_SIZE = 0x1000; +// Flow controller: BPMP/CPU halt events, cluster control, RAM repair. +constexpr uint64_t FLOW_CTLR_BASE = 0x60007000; +constexpr uint64_t FLOW_CTLR_SIZE = 0x1000; + +// Exception vectors, incl. EVP_CPU_RESET_VECTOR (+0x100) for AArch32 boot. +constexpr uint64_t EXCP_VEC_BASE = 0x6000F000; +constexpr uint64_t EXCP_VEC_SIZE = 0x1000; + // I2S (Audio) constexpr uint64_t I2S_BASE = 0x702D1000; constexpr uint64_t I2S_SIZE = 0x1000; diff --git a/t210/mmio.cpp b/t210/mmio.cpp index be5d5c3..d367904 100644 --- a/t210/mmio.cpp +++ b/t210/mmio.cpp @@ -1,9 +1,13 @@ #include "mmio.h" #include "trace.h" #include "../emu_state.h" +#include "../platform.h" #include "i2c3.h" #include "memory_map.h" +#include "bpmp.h" +#include "ccplex.h" #include "pcie.h" +#include "regcache.h" #include "se_engine.h" #include "tegra_bl.h" @@ -14,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -42,7 +47,9 @@ static inline ssize_t pwrite(int fd, const void *buf, size_t n, long long off) { static uint32_t pmc_scratch0 = 0; static uint32_t pmc_scratch37 = 0; -static std::map mmio_regs; +static RegCache mmio_regs; + +BusMaster g_bus_master = BUS_BPMP; // Standard CRC32 (poly 0xEDB88320), matching hekate's crc32_calc(0, ...) which // the payload uses to validate the GPT. Init/final via ~ like the reference. @@ -133,6 +140,12 @@ static const PinmuxDefault pinmux_defaults[] = { // PH5 / BT_HOST_WAKE: E_INPUT | PARKED | TRISTATE | PULL_DOWN. Measured // as 0x0074 at payload entry on all four reference consoles. {0x1C8, 0x00000074}, + // PEX_L1_RST_N / PEX_L1_CLKREQ_N: the root-port-1 reset and clock-request + // pads. TRM reset values, and what hwtest's Wi-Fi probe reads on a real + // console before it unparks them: PE1 function, PARKED (bit 5) set, so the + // pad does not drive until software clears it. + {0x044, 0x00000460}, + {0x048, 0x00000470}, }; static uint32_t pinmux_reset_default(uint64_t addr) { @@ -402,7 +415,7 @@ static const uint16_t gpio_h_pinmux[8] = { 0x000, 0x1B8, 0x000, 0x1C0, 0x1C4, 0x1C8, 0x000, 0x1CC}; static uint32_t gpio_reg(uint64_t addr) { - return mmio_regs.count(addr) ? mmio_regs[addr] : 0; + return mmio_regs.get(addr); } // Level of a port-H pin the Tegra is NOT driving: the pad simply follows @@ -483,8 +496,7 @@ uint32_t gpio_read(EmuState *state, uint64_t addr) { // never moved" - so the input register has to reflect what the output // register is driving, or that check reports a dead pin on a healthy // console. Mirror OUT (port Z is 0x624) into IN for that pin. - uint32_t out = mmio_regs.count(GPIO_BASE + 0x624) - ? mmio_regs[GPIO_BASE + 0x624] : 0; + uint32_t out = mmio_regs.get(GPIO_BASE + 0x624); val |= out & (1u << 4); return val; } @@ -501,8 +513,7 @@ uint32_t gpio_read(EmuState *state, uint64_t addr) { // Only toggle while the PWM channel is actually driving the fan, so a // payload that checks "duty 0 -> should read 0 RPM" still sees that. if (offset == 0x438) { - uint32_t csr = mmio_regs.count(PWM_BASE + PWM_CSR_1_OFF) - ? mmio_regs[PWM_BASE + PWM_CSR_1_OFF] : 0; + uint32_t csr = mmio_regs.get(PWM_BASE + PWM_CSR_1_OFF); bool ch_en = (csr & (1u << 31)) != 0; bool abs_off = (csr & (1u << 24)) != 0; uint32_t inv_duty = (csr >> 16) & 0xFF; // inverted: 236 = ~0% @@ -541,14 +552,14 @@ uint32_t gpio_read(EmuState *state, uint64_t addr) { if (offset < 0x800) { if (bank_off < 0x30) { // CNF / OE / OUT: hand back the cached write. - uint32_t v = mmio_regs.count(addr) ? mmio_regs[addr] : 0; + uint32_t v = mmio_regs.get(addr); TRACE("[gpio] R: offset 0x%X (CNF/OE/OUT cache) = 0x%08X\n", offset, v); return v; } if (bank_off < 0x40) { // IN: mirror of the matching OUT one slot earlier. uint64_t out_addr = addr - 0x10; - uint32_t v = mmio_regs.count(out_addr) ? mmio_regs[out_addr] : 0; + uint32_t v = mmio_regs.get(out_addr); TRACE("[gpio] R: offset 0x%X (IN, mirror of OUT @ 0x%X) = 0x%08X\n", offset, (uint32_t)(offset - 0x10), v); return v; @@ -556,7 +567,7 @@ uint32_t gpio_read(EmuState *state, uint64_t addr) { // MSK_CNF 0x80 / MSK_OE 0x90 / MSK_OUT 0xA0: aliases that read back the // plain register they write through, 0x80 lower. if (bank_off >= 0x80 && bank_off < 0xB0) { - uint32_t v = mmio_regs.count(addr - 0x80) ? mmio_regs[addr - 0x80] : 0; + uint32_t v = mmio_regs.get(addr - 0x80); TRACE("[gpio] R: offset 0x%X (masked alias of 0x%X) = 0x%08X\n", offset, (uint32_t)(offset - 0x80), v); return v; @@ -582,7 +593,7 @@ void gpio_write(EmuState *state, uint64_t addr, uint32_t val) { if (offset < 0x800 && bank_off >= 0x80 && bank_off < 0xB0) { uint64_t plain = addr - 0x80; uint32_t mask = (val >> 8) & 0xFF; - uint32_t cur = mmio_regs.count(plain) ? mmio_regs[plain] : 0; + uint32_t cur = mmio_regs.get(plain); mmio_regs[plain] = (cur & ~mask) | (val & mask); TRACE("[gpio] W: offset 0x%X masked -> 0x%X = 0x%08X\n", offset, (uint32_t)(offset - 0x80), mmio_regs[plain]); @@ -631,6 +642,63 @@ static uint16_t codec_reg_get(uint8_t reg) { return it == codec_regs.end() ? 0 : it->second; } +// ---- CCPLEX CPU rail regulators on I2C_5 ---- +// +// Erista: two MAX77621 bucks, CPU at 0x1B and GPU at 0x1C. Mariko: one +// MAX77812 at 0x33 (PHASE211) whose M4 phase is the CPU rail. These used to +// be fixed read-only answers, which was fine while nothing but an identity +// read ever reached them - but bdk's ccplex_boot_cpu0() turns the CPU rail on +// through them with read-modify-writes, and whether that rail is up decides +// whether CPU0 can run at all. So they are register files now, seeded with +// 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] = { + {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 max77812_regs[256]; +static bool max77812_ready = false; + +static void max77812_regs_init() { + if (max77812_ready) + return; + max77812_ready = true; + auto vout = [](uint32_t mv) -> uint8_t { + return (uint8_t)(((mv - 250u) / 5u) & 0xFF); + }; + memset(max77812_regs, 0, sizeof(max77812_regs)); + max77812_regs[0x14] = 0x05; // VERSION: QS silicon (ES2 = 0x04) + max77812_regs[0x05] = 0x00; // TOPSYS_STAT: no thermal / OV / UV fault + max77812_regs[0x22] = 0x00; // BUCK_STAT: no per-rail fault latch + // EN_CTRL: in RCM the CPU/GPU rails are still dormant (HOS brings them up), + // so all phases start disabled - that is the true cold state. + max77812_regs[0x06] = 0x00; + // Measured on a real Mariko while dormant in RCM. + max77812_regs[0x23] = vout(650); // M1 GPU + max77812_regs[0x25] = vout(600); // M3 DRAM (VDD2) + max77812_regs[0x26] = vout(600); // M4 CPU +} + +static void max77620_regs_init(EmuState *state); +static uint8_t max77620_regs[256]; + +bool cpu_rail_on(EmuState *state) { + if (state->pmic_otp.load() == 0x53) { + max77812_regs_init(); + return (max77812_regs[0x06] >> 6) & 1; // EN_CTRL.EN_M4 (CPU) + } + // The MAX77621's EN pin is MAX77620 GPIO5 (bdk _ccplex_enable_power_t210 + // configures it push-pull, output high, before touching the buck), and the + // buck's own output enable is VOUT bit 7. Both have to be on. + max77620_regs_init(state); + uint8_t gpio5 = max77620_regs[0x3B]; + bool en_pin = !(max77620_regs[0x40] & (1u << 5)) && // plain GPIO, not AME + !(gpio5 & (1u << 1)) && // DIR = output + (gpio5 & (1u << 3)); // output high + return en_pin && (max77621_regs[0][0] & 0x80); +} + // Which slaves actually answer, per bus. This is the emulator's answer to // "is that chip fitted?", so it must list exactly what is modelled below and // nothing else - a bus scan is a real diagnostic and an emulator that ACKs @@ -660,8 +728,7 @@ static bool i2c_slave_present(EmuState *state, bool on_i2c5, uint8_t addr) { case 0x6B: // BQ24193 charger return true; case 0x1C: // ALC5639 codec - only once LDO1_EN is up - return (mmio_regs.count(GPIO_BASE + 0x624) - ? mmio_regs[GPIO_BASE + 0x624] : 0) & (1u << 4); + return (mmio_regs.get(GPIO_BASE + 0x624)) & (1u << 4); default: (void)state; return false; @@ -694,7 +761,6 @@ static uint32_t i2c_cnfg_reg[2] = {0, 0}; // 50 mV (rest), base 800 mV; bits 7:6 = power mode (3 = normal). // Rail-OK status: SD rails via STATSD (0x14, bit set = NOT ok), LDO rails via // each LDOx_CFG2 POK bit (BIT(3)). -static uint8_t max77620_regs[256]; static bool max77620_regs_ready = false; static void max77620_regs_init(EmuState *state) { @@ -1030,8 +1096,7 @@ uint32_t i2c_read(EmuState *state, uint64_t addr) { // payload enables it. Gating on PZ4 keeps that behaviour observable // instead of handing out an identity the hardware would not have given. if (!on_i2c5 && i2c_slave_addr == 0x1C) { - uint32_t pz4_out = mmio_regs.count(GPIO_BASE + 0x624) - ? mmio_regs[GPIO_BASE + 0x624] : 0; + uint32_t pz4_out = mmio_regs.get(GPIO_BASE + 0x624); if (!(pz4_out & (1u << 4))) return 0; // LDO1 still off: the part is silent auto be16 = [](uint16_t v) -> uint16_t { @@ -1137,10 +1202,10 @@ uint32_t i2c_read(EmuState *state, uint64_t addr) { // payload sees both the MAX77621 and the MAX77812 present at once. if (state->pmic_otp.load() == 0x53) return 0; if (i2c_reg_addr == 0x04) return state->cpu_pmic_version.load(); - // VOUT (0x00) / VOUT_DVS (0x01): bit 7 = enable, bits 6:0 = 606.25 mV + - // N * 6.25 mV. Report the rails enabled at a sane 1.0 V idle point. - if (i2c_reg_addr == 0x00 || i2c_reg_addr == 0x01) - return 0x80 | (uint8_t)((1000000u - 606250u) / 6250u); + // VOUT (0x00) / VOUT_DVS (0x01) / CONTROL1/2 read back what was last + // written; see max77621_regs. + if (i2c_reg_addr < 8) + return max77621_regs[i2c_slave_addr - 0x1B][i2c_reg_addr]; return 0; } // MAX77812 multi-phase buck (Mariko / Lite / OLED), I2C_5 @ 0x33 for the @@ -1149,22 +1214,8 @@ uint32_t i2c_read(EmuState *state, uint64_t addr) { // M4 = CPU; vout_mv = 250 + N * 5. if (on_i2c5 && i2c_slave_addr == 0x33) { if (state->pmic_otp.load() != 0x53) return 0; // Mariko-family only - auto vout = [](uint32_t mv) -> uint8_t { - return (uint8_t)(((mv - 250u) / 5u) & 0xFF); - }; - switch (i2c_reg_addr) { - case 0x14: return 0x05; // VERSION: QS silicon (ES2 = 0x04) - case 0x05: return 0x00; // TOPSYS_STAT: no thermal / OV / UV fault - case 0x22: return 0x00; // BUCK_STAT: no per-rail fault latch - // EN_CTRL: in RCM the CPU/GPU rails are still dormant (HOS brings them - // up), so report all phases disabled - that is the true cold state. - case 0x06: return 0x00; - // Measured on a real Mariko while dormant in RCM. - case 0x23: return vout(650); // M1 GPU - case 0x25: return vout(600); // M3 DRAM (VDD2) - case 0x26: return vout(600); // M4 CPU - default: return 0; - } + max77812_regs_init(); + return max77812_regs[i2c_reg_addr]; } // MAX77620 RTC (slave 0x68 on I2C_5). Separate slave address from the PMIC // core. Registers 0x07..0x0D hold SEC/MIN/HOUR/WEEKDAY/MONTH/YEAR/DAY. @@ -1311,6 +1362,26 @@ void i2c_write(EmuState *state, uint64_t addr, uint32_t val) { max77620_regs_init(state); max77620_regs[i2c_cmd_data1 & 0xFF] = (uint8_t)((i2c_cmd_data1 >> 8) & 0xFF); } + // CPU/GPU rail bucks. Same wire format; only the chip this SoC + // generation is fitted with takes the write (the other one NAKs). + if ((val & (1u << 9)) && is_write && size >= 2 && on_i2c5) { + uint8_t reg = (uint8_t)(i2c_cmd_data1 & 0xFF); + uint8_t v = (uint8_t)((i2c_cmd_data1 >> 8) & 0xFF); + bool mariko = state->pmic_otp.load() == 0x53; + if (!mariko && (i2c_slave_addr == 0x1B || i2c_slave_addr == 0x1C) && + reg < 8 && reg != 0x04 && reg != 0x05) { // CHIPID is RO + max77621_regs[i2c_slave_addr - 0x1B][reg] = v; + ccplex_rail_changed(state); + } else if (mariko && i2c_slave_addr == 0x33 && reg != 0x14) { + max77812_regs_init(); + max77812_regs[reg] = v; + ccplex_rail_changed(state); + } + } + if ((val & (1u << 9)) && is_write && size >= 2 && on_i2c5 && + i2c_slave_addr == MAX77620_I2C_ADDR && + ((i2c_cmd_data1 & 0xFF) == 0x3B || (i2c_cmd_data1 & 0xFF) == 0x40)) + ccplex_rail_changed(state); // GPIO5 / AME_GPIO: the MAX77621 EN pin // ALC5639 codec: a 16-bit register write arrives as three bytes packed // into CMD_DATA1 - [reg, value MSB, value LSB] - because the part is // big-endian on the wire while bdk packs the buffer little-endian. @@ -1533,7 +1604,7 @@ uint32_t misc_read(EmuState *state, uint64_t addr) { // (the old behavior) silently dropped the muxed function bits, which // broke any probe that read back PINMUX_AUX_* to confirm a pin's mode. if (addr >= PINMUX_BASE && addr < PINMUX_BASE + PINMUX_SIZE) { - return mmio_regs.count(addr) ? mmio_regs[addr] : pinmux_reset_default(addr); + return mmio_regs.get(addr, pinmux_reset_default(addr)); } // APB_MISC_GP_HIDREV - hardware revision. // Bits 11:8 = chip ID (0x21 for both T210 / T210B01), @@ -1554,7 +1625,7 @@ uint32_t misc_read(EmuState *state, uint64_t addr) { uint32_t offset = 0; int port = uart_port_of(addr, &offset); if (port < 0) // the gaps between the five register blocks - return mmio_regs.count(addr) ? mmio_regs[addr] : 0; + return mmio_regs.get(addr); UartPort &up = uart_ports[port]; // Anything on UART-D can observe the radio, so settle its state machine // (POR completion, RTS_N) before answering. @@ -1589,7 +1660,7 @@ uint32_t misc_read(EmuState *state, uint64_t addr) { // divisor no longer POPS a byte off the receive FIFO. That silently ate // host bytes, which is corruption waiting to happen on a sideload. uint32_t base = uart_bases[port]; - bool dlab = (mmio_regs.count(base + 0x0C) ? mmio_regs[base + 0x0C] : 0) & 0x80; + bool dlab = (mmio_regs.get(base + 0x0C)) & 0x80; if (offset == 0x00 && dlab) return up.divisor & 0xFF; // DLL @@ -1611,7 +1682,7 @@ uint32_t misc_read(EmuState *state, uint64_t addr) { // latches, and a payload that reports its own UART config - baud divisor, // word length, DLAB state - got zeros before this, so it decoded as // "0 baud, word=5". - return mmio_regs.count(addr) ? mmio_regs[addr] : 0; + return mmio_regs.get(addr); } // DSI if (addr >= DSI_BASE && addr < DSI_BASE + DSI_SIZE) { @@ -1635,7 +1706,7 @@ uint32_t misc_read(EmuState *state, uint64_t addr) { // already; return whatever was last written so the payload can read // back its own duty cycle / enable bit. if (addr >= PWM_BASE && addr < PWM_BASE + 0x1000) { - return mmio_regs.count(addr) ? mmio_regs[addr] : 0; + return mmio_regs.get(addr); } // TSEC (Tegra Security Co-processor) — base 0x54500000 per Hekate bdk/soc/t210.h. // The TSEC microcontroller's firmware blob runs HDCP-based key derivation that @@ -2195,9 +2266,9 @@ void misc_write(uc_engine *uc, EmuState *state, uint64_t addr, int64_t value, // 4GB-FAT32-friendly splits and tools that use 2GB chunks). static size_t part_size = 0; if (!part_size && !state->emmc_gpp_fds.empty()) { - struct stat st; - if (fstat(state->emmc_gpp_fds[0], &st) == 0 && st.st_size > 0) - part_size = (size_t)st.st_size; + 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); @@ -2323,9 +2394,15 @@ void rtc_write(EmuState *state, uint64_t addr, uint32_t val) { // IO_DPD_REQ/STATUS park pad groups in deep power down. Both reset to 0 (no // pad parked), and writes carry a 2-bit command in bits 31:30: 1 = DPD OFF // (wake the named pads), 2 = DPD ON (park them). -static uint32_t pmc_pwrgate_status = 0; +// Bit 3 (PCIE) is already ungated at RCM entry - measured on both an Erista +// 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}; +bool pmc_partition_on(int part) { + return part >= 0 && part < 32 && ((pmc_pwrgate_status >> part) & 1); +} + uint32_t pmc_read(EmuState *state, uint64_t addr) { (void)state; uint32_t offset = (uint32_t)(addr - PMC_BASE); @@ -2343,6 +2420,12 @@ uint32_t pmc_read(EmuState *state, uint64_t addr) { 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 + // three PCIe apertures are MMIO for the CPU, which CPU0's accesses to + // the root complex depend on. + return 0x00020000; default: return 0; } @@ -2370,8 +2453,12 @@ void pmc_write(EmuState *state, uint64_t addr, uint32_t val) { if (val & (1u << 8)) { uint32_t part = val & 0x1F; pmc_pwrgate_status ^= (1u << part); + bool on = (pmc_pwrgate_status >> part) & 1; if (part == 3) // POWER_RAIL_PCIE - pcie_set_powergate((pmc_pwrgate_status & (1u << 3)) != 0); + pcie_set_powergate(on); + // CRAIL / CE0 / C0NC carry CPU0: gating one under a running core + // takes the core down with it. + ccplex_partition_changed(state, (int)part, on); } break; } @@ -2417,12 +2504,14 @@ 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; +bool flow_ram_repair_done() { return (flow_ram_repair & RAM_REPAIR_REQ) != 0; } + 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 mmio_regs.count(addr) ? mmio_regs[addr] : 0; + return mmio_regs.get(addr); } static void flow_write(EmuState *state, uint64_t addr, uint32_t val) { @@ -2455,6 +2544,7 @@ static void flow_write(EmuState *state, uint64_t addr, uint32_t val) { : (uint64_t)delay * 1000000ULL; state->emu_usec += us; state->bpmp_slept_us += us; // feeds the ACTMON BPMP-load model + bpmp_clock_jumped(); return; } printf("[flow] BPMP HALT/WaitEvent (val=0x%08X), shutting down emulator\n", @@ -2515,20 +2605,20 @@ uint32_t clk_rst_read(EmuState *state, uint64_t addr) { switch (offset) { case 0x80: case 0xB0: case 0xE0: case 0xE8: case 0x4B8: case 0x4C4: { - uint32_t w = mmio_regs.count(addr) ? mmio_regs[addr] : 0; + uint32_t w = mmio_regs.get(addr); if (w & (1u << 30)) return w | (1u << 27); // payload brought it up -> locked return w; // measured: down on both } case 0x90: { // PLLM - uint32_t w = mmio_regs.count(addr) ? mmio_regs[addr] : 0; + uint32_t w = mmio_regs.get(addr); if (w & (1u << 30)) return w | (1u << 27); // Erista leaves PLLM enabled but unlocked at this point; Mariko has it off. return mariko ? 0u : (1u << 30); } case 0xC0: { // PLLU - uint32_t w = mmio_regs.count(addr) ? mmio_regs[addr] : 0; + uint32_t w = mmio_regs.get(addr); if (w & (1u << 30)) return w | (1u << 27); return mariko ? 0u : ((1u << 30) | (1u << 27)); @@ -2561,7 +2651,7 @@ uint32_t clk_rst_read(EmuState *state, uint64_t addr) { // CLK_SOURCE_UARTD. clock_uart_use_src_div() programs PLLP_OUT0 with // CLK_SRC_DIV(2) here (0x00000002) and sets UART_SRC_CLK_DIV_EN for the // 1M/3M rates; the payload reads it back to confirm the port's source. - case 0x1C0: return mmio_regs.count(addr) ? mmio_regs[addr] : 0; + case 0x1C0: return mmio_regs.get(addr); } } @@ -2578,8 +2668,7 @@ uint32_t clk_rst_read(EmuState *state, uint64_t addr) { // "not running" answer (CCLK_G really is idle - the A57s are off - and // PLLP_OBS is not routed). if (offset == 0x64) { - uint32_t cntl = mmio_regs.count(CLK_RST_BASE + 0x60) - ? mmio_regs[CLK_RST_BASE + 0x60] : 0; + uint32_t cntl = mmio_regs.get(CLK_RST_BASE + 0x60); uint32_t src = (cntl >> 14) & 0x1FF; // PTO_SRC_SEL uint32_t khz = 0; switch (src) { @@ -2611,10 +2700,17 @@ uint32_t clk_rst_read(EmuState *state, uint64_t addr) { if (offset == 0x04) return 0; // RST_DEVICES_L (none in reset) + // CPU complex clock/reset state (CLK_OUT_ENB_V, RST_CPUG_CMPLX, ...). + { + uint32_t v = 0; + if (ccplex_car_read(offset, &v)) + return v; + } + // PLLE and PLLREFE report lock in their _MISC registers, not in _BASE bit // 27 like the PLLs handled above, so the PCIe model answers for them. { - uint32_t v = mmio_regs.count(addr) ? mmio_regs[addr] : 0; + uint32_t v = mmio_regs.get(addr); if (pcie_car_read(offset, &v)) return v; } @@ -2640,6 +2736,8 @@ 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); + // The CPU complex: CPU reset/clock enables, PLLX and CCLK. + ccplex_car_write(state, offset, val); } // ==================== Fuse ==================== @@ -2666,7 +2764,16 @@ uint32_t fuse_read(EmuState *state, uint64_t addr) { return 0; } if (offset >= EmuState::FUSE_WORDS * 4) return 0; - return state->fuse_at(offset).load(); + uint32_t v = state->fuse_at(offset).load(); + // FUSE_RESERVED_ODM28_B01 bit 0 tells bdk which MAX77812 is fitted: clear + // means the PHASE31 part at I2C_5 0x31, set the PHASE211 retail part at + // 0x33 (bdk power/max7762x.c _max77812_get_address). This model only + // answers at 0x33, so a Mariko must read the bit set; left clear, every + // bdk regulator call went to a NAKing 0x31 and the CPU rail could never + // be enabled - which is exactly what booting CPU0 needs. + if (offset == 0x240 && state->is_mariko.load()) + v |= 1u; + return v; } void fuse_write(EmuState *state, uint64_t addr, uint32_t val) { @@ -2921,7 +3028,7 @@ static uint32_t i2s_read(EmuState *state, uint64_t addr) { (void)state; // Read back what the payload programmed. mmio_regs is populated by the // write hook before dispatch, so this needs no state of its own. - return mmio_regs.count(addr) ? mmio_regs[addr] : 0; + return mmio_regs.get(addr); } static void i2s_write(EmuState *state, uint64_t addr, uint32_t val) { @@ -2949,7 +3056,7 @@ static uint32_t admaif_read(EmuState *state, uint64_t addr) { case 0x744: // TX ACIF FIFO_FULL - never full, so PIO never spins return 0; default: - return mmio_regs.count(addr) ? mmio_regs[addr] : 0; + return mmio_regs.get(addr); } } @@ -3110,7 +3217,7 @@ static uint32_t adma_read(EmuState *state, uint64_t addr) { uint32_t offset = (uint32_t)(addr - ADMA_BASE); if (offset == 0xC04) // global soft reset - completed return 0; - return mmio_regs.count(addr) ? mmio_regs[addr] : 0; + return mmio_regs.get(addr); } static void adma_write(EmuState *state, uint64_t addr, uint32_t val) { @@ -3253,6 +3360,9 @@ static uint32_t sysreg_read(EmuState *state, uint64_t addr) { uint32_t offset = (uint32_t)(addr - SYSREG_BASE); if (offset >= ACTMON_OFF_IN_SYSREG) return actmon_read(state, offset - ACTMON_OFF_IN_SYSREG); + // SB (secure boot) block at +0x200: CSR and the CCPLEX reset vector. + if (offset >= 0x200 && offset < 0x300) + return ccplex_sb_read(offset - 0x200); return 0; } @@ -3262,6 +3372,10 @@ static void sysreg_write(EmuState *state, uint64_t addr, uint32_t val) { actmon_write(state, offset - ACTMON_OFF_IN_SYSREG, val); return; } + if (offset >= 0x200 && offset < 0x300) { + ccplex_sb_write(state, offset - 0x200, val); + return; + } TRACE("[sysreg] W: 0x%08X = 0x%08X\n", offset, val); } @@ -3360,560 +3474,461 @@ static void bpmp_cache_write(EmuState *state, uint64_t addr, uint32_t val) { (void)val; } -static void hook_mmio_read(uc_engine *uc, uc_mem_type type, uint64_t address, - int size, int64_t value, void *user_data) { - EmuState *state = (EmuState *)user_data; - uint32_t result = 0; +// ==================== Bus dispatch ==================== +// +// One dispatch serves every master. It used to live inside a pair of Unicorn +// UC_HOOK_MEM_READ / UC_HOOK_MEM_WRITE callbacks over plain RAM pages, with +// the read result smuggled back by uc_mem_write()-ing it into the page before +// the load completed. That had two costs well beyond the handlers themselves: +// +// - Unicorn routes EVERY guest load and store through its slow path while +// any memory hook exists, so IRAM and DRAM traffic paid for MMIO's hooks; +// - each read did a uc_mem_write, i.e. a linear walk of Unicorn's mapped +// region list, which is dozens of entries long here. +// +// The windows are now uc_mmio_map() regions: loads and stores to RAM run on +// the translator's fast path, and an MMIO access is one callback. The same +// callbacks serve CPU0's engine, which is what lets the two cores share one +// set of register models. +uint32_t mmio_bus_read(EmuState *state, uint64_t address, unsigned size) { + (void)size; if (address >= TMR_BASE && address < TMR_BASE + TMR_SIZE) { - uint32_t offset = (uint32_t)(address - TMR_BASE); - if (offset == 0x10) - result = (uint32_t)state->emu_usec; // TIMERUS_CNTR_1US - else - result = 0; - } else { - uint32_t pc; - uc_reg_read(uc, UC_ARM_REG_PC, &pc); - - if (mmio_regs.count(address)) { - result = mmio_regs[address]; - } - - if (address >= GPIO_BASE && address < GPIO_BASE + GPIO_SIZE) { - result = gpio_read(state, address); - } else if ((address >= PCIE_BLOCK_BASE && - address < PCIE_BLOCK_BASE + PCIE_BLOCK_SIZE) || - (address >= PCIE_CS_BASE && - address < PCIE_CS_BASE + PCIE_CS_MODEL_SIZE) || - (address >= PCIE_MEM_BASE && - address < PCIE_MEM_BASE + PCIE_MEM_MODEL_SIZE)) { - result = pcie_read(state, address); - } else if (address >= XUSB_PADCTL_BASE && - address < XUSB_PADCTL_BASE + XUSB_PADCTL_SIZE) { - result = padctl_read(state, address); - } else if (address >= MSELECT_BASE && - address < MSELECT_BASE + MSELECT_SIZE) { - result = mselect_read(state, address); - } else if (address >= VIC_BASE && address < VIC_BASE + VIC_SIZE) { - result = vic_read(state, address); - } else if (address >= SYSREG_BASE && address < SYSREG_BASE + SYSREG_SIZE) { - result = sysreg_read(state, address); - } else if (address >= BPMP_CACHE_BASE && - address < BPMP_CACHE_BASE + BPMP_CACHE_SIZE) { - result = bpmp_cache_read(state, address); - } else if (address >= SOC_THERM_BASE && - address < SOC_THERM_BASE + SOC_THERM_SIZE) { - result = soc_therm_read(state, address); - } else if (address >= 0x60007000 && address < 0x60007000 + 0x1000) { - result = flow_read(state, address); - } else if (address >= I2S_BASE && address < I2S_BASE + I2S_SIZE) { - result = i2s_read(state, address); - } else if (address >= ADMAIF_BASE && address < ADMAIF_BASE + ADMAIF_SIZE) { - result = admaif_read(state, address); - } else if (address >= ADMA_BASE && address < ADMA_BASE + ADMA_SIZE) { - result = adma_read(state, address); - } else if (address >= RTC_BASE && address < RTC_BASE + RTC_SIZE) { - result = rtc_read(state, address); - } else if (address >= I2C2_BASE && address < I2C2_BASE + I2C2_SIZE) { - // I²C2 / BH1730 ambient light sensor (slave 0x29). - result = i2c2_read(state, address); - } else if (address >= I2C3_BASE && address < I2C3_BASE + I2C3_SIZE) { - // I²C3 / STMFTS touchscreen (slave 0x49). Must be tested before the I²C1 - // branch, which would otherwise swallow the I²C3 page. - result = i2c3_read(state, address); - } else if (address >= I2C1_BASE && address < I2C1_BASE + 0x100) { - result = i2c_read(state, address); - } else if (address >= I2C5_BASE && address < I2C5_BASE + I2C_SIZE) { - result = i2c_read(state, address); - } else if (address >= DISPLAY_A_BASE && - address < DISPLAY_A_BASE + DISPLAY_SIZE) { - result = display_read(state, address); - } else if (address >= PMC_BASE && address < PMC_BASE + PMC_SIZE) { - result = pmc_read(state, address); - } else if (address >= CLK_RST_BASE && - address < CLK_RST_BASE + CLK_RST_SIZE) { - result = clk_rst_read(state, address); - } else if (address >= FUSE_BASE && address < FUSE_BASE + FUSE_SIZE) { - result = fuse_read(state, address); - } else if ((address >= EMC_BASE && address < EMC_BASE + EMC_SIZE) || - (address >= EMC0_BASE && address < EMC0_BASE + EMC_SIZE) || - (address >= EMC1_BASE && address < EMC1_BASE + EMC_SIZE)) { - result = emc_read(state, address); - } else if (address >= SE_BASE && address < SE_BASE + SE_SIZE) { - result = se_read(state, address); - } else { - result = misc_read(state, address); - } - // TRACE("[mmio] R: 0x%08llX = 0x%08X (PC=0x%08X)\n", (unsigned long - // long)address, result, pc); + // 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; + return g_bus_master == BUS_BPMP ? bpmp_timerus_read(state) + : (uint32_t)state->emu_usec; } - - uc_mem_write(uc, address, &result, size); + if (address >= GPIO_BASE && address < GPIO_BASE + GPIO_SIZE) + return gpio_read(state, address); + if ((address >= PCIE_BLOCK_BASE && + address < PCIE_BLOCK_BASE + PCIE_BLOCK_SIZE) || + (address >= PCIE_CS_BASE && address < PCIE_CS_BASE + PCIE_CS_MODEL_SIZE) || + (address >= PCIE_MEM_BASE && address < PCIE_MEM_BASE + PCIE_MEM_MODEL_SIZE)) + return pcie_read(state, address); + if (address >= XUSB_PADCTL_BASE && + address < XUSB_PADCTL_BASE + XUSB_PADCTL_SIZE) + return padctl_read(state, address); + if (address >= MSELECT_BASE && address < MSELECT_BASE + MSELECT_SIZE) + return mselect_read(state, address); + if (address >= VIC_BASE && address < VIC_BASE + VIC_SIZE) + return vic_read(state, address); + if (address >= SYSREG_BASE && address < SYSREG_BASE + SYSREG_SIZE) + return sysreg_read(state, address); + if (address >= BPMP_CACHE_BASE && address < BPMP_CACHE_BASE + BPMP_CACHE_SIZE) + return bpmp_cache_read(state, address); + if (address >= SOC_THERM_BASE && address < SOC_THERM_BASE + SOC_THERM_SIZE) + return soc_therm_read(state, address); + if (address >= FLOW_CTLR_BASE && address < FLOW_CTLR_BASE + FLOW_CTLR_SIZE) + return flow_read(state, address); + if (address >= I2S_BASE && address < I2S_BASE + I2S_SIZE) + return i2s_read(state, address); + if (address >= ADMAIF_BASE && address < ADMAIF_BASE + ADMAIF_SIZE) + return admaif_read(state, address); + if (address >= ADMA_BASE && address < ADMA_BASE + ADMA_SIZE) + return adma_read(state, address); + if (address >= RTC_BASE && address < RTC_BASE + RTC_SIZE) + return rtc_read(state, address); + // I²C2 / BH1730 ambient light sensor (slave 0x29). + if (address >= I2C2_BASE && address < I2C2_BASE + I2C2_SIZE) + return i2c2_read(state, address); + // I²C3 / STMFTS touchscreen (slave 0x49). Must be tested before the I²C1 + // branch, which would otherwise swallow the I²C3 page. + if (address >= I2C3_BASE && address < I2C3_BASE + I2C3_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) + return i2c_read(state, 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) + return pmc_read(state, address); + if (address >= CLK_RST_BASE && address < CLK_RST_BASE + CLK_RST_SIZE) + return clk_rst_read(state, address); + if (address >= FUSE_BASE && address < FUSE_BASE + FUSE_SIZE) + return fuse_read(state, address); + if ((address >= EMC_BASE && address < EMC_BASE + EMC_SIZE) || + (address >= EMC0_BASE && address < EMC0_BASE + EMC_SIZE) || + (address >= EMC1_BASE && address < EMC1_BASE + EMC_SIZE)) + return emc_read(state, address); + if (address >= SE_BASE && address < SE_BASE + SE_SIZE) + return se_read(state, address); + return misc_read(state, address); } -static void hook_mmio_write(uc_engine *uc, uc_mem_type type, uint64_t address, - int size, int64_t value, void *user_data) { - EmuState *state = (EmuState *)user_data; +// THR writes on any of the five UARTs. +static void uart_write(EmuState *state, uint64_t address, uint32_t val) { + uint32_t offset = 0; + int port = uart_port_of(address, &offset); + if (port < 0) + return; + // Note offset 0 is the divisor latch LSB - not the transmit register - + // whenever DLAB is set, so writing the baud divisor must not be mistaken + // for a character to print. Every register (including this one) was + // already cached by the caller; the divisor is additionally kept in + // UartPort because a later THR write overwrites that cache entry. + UartPort &up = uart_ports[port]; + uint32_t ubase = uart_bases[port]; + bool dlab = mmio_regs.get(ubase + 0x0C) & 0x80; + + if (offset == 0x00 && dlab) { + 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 == 0x08) { + // 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 + // bdk's uart_init() issues an unconditional RX_CLR - which would silently + // eat scripted keystrokes. + if (port == UART_D && (val & 0x02)) + state->uart_rx_fifo[port].clear(); + } else if (offset == 0x10) { + uint8_t old_mcr = up.mcr; + up.mcr = (uint8_t)val; + // Entering or leaving 16550 internal loopback swings all four modem + // inputs at once - MCR[3:0] are tied onto MSR[7:4] while it is on - so + // every delta bit latches. That is what makes the payload's first MSR + // read after its loopback self-test 0x4F, not 0x40. + if ((old_mcr ^ up.mcr) & 0x10) + up.msr_delta |= 0x0F; + } + + if (offset != 0 || dlab) + return; + + uint8_t b = (uint8_t)val; + if (up.mcr & 0x10) { + // Internal loopback: the byte is tied straight back to this port's own + // receiver inside the controller and never reaches a pad. It must NOT be + // handed to whatever is on the far end, or the BT chip's H4 parser + // desyncs on the A5 5A 00 FF test pattern - and it must not reach the TX + // log either, since it is not something the payload actually transmitted. + state->uart_rx_fifo[port].push_back(b); + return; + } + + // UART-D is the Bluetooth radio's H4 transport. + if (port == UART_D) + bt_chip_rx(state, b); + + // Append every byte to the per-port TX log — the console window renders + // this as scrolling text. Trim from the front if it grows past 64 KB so + // ImGui rendering stays responsive. + std::string &log = state->uart_tx_log[port]; + if (b == '\n' || (b >= 0x20 && b < 0x7F)) + log.push_back((char)b); + if (log.size() > 64 * 1024) + log.erase(0, log.size() - 48 * 1024); + + // Mirror to host stdout in line-buffered form so existing `grep '[uart]'` + // workflows still work. + static char uart_line[EmuState::N_UARTS][512]; + static size_t uart_len[EmuState::N_UARTS] = {0}; + auto flush_uart_line = [&](int p) { + if (uart_len[p] > 0) { + uart_line[p][uart_len[p]] = 0; + printf("[uart%c] %s\n", 'A' + (char)p, uart_line[p]); + fflush(stdout); + uart_len[p] = 0; + } + }; + if (b == '\n' || b == '\r') { + flush_uart_line(port); + } else if (b >= 0x20 && b < 0x7F) { + if (uart_len[port] + 1 >= sizeof(uart_line[port])) + flush_uart_line(port); + uart_line[port][uart_len[port]++] = (char)b; + } +} + +void mmio_bus_write(EmuState *state, uint64_t address, unsigned size, + uint64_t value) { uint32_t val = (uint32_t)value; - uint32_t pc; - uc_reg_read(uc, UC_ARM_REG_PC, &pc); - // TRACE("[mmio] W: 0x%08llX = 0x%08X (PC=0x%08X)\n", (unsigned long - // long)address, val, pc); fflush(stdout); + mmio_regs[address] = val; // read-back cache for the simple registers - if (address >= IRAM_BASE && address < IRAM_BASE + 0x40000) { - // Log IRAM writes if debugging + 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) || + (address >= PCIE_CS_BASE && + address < PCIE_CS_BASE + PCIE_CS_MODEL_SIZE) || + (address >= PCIE_MEM_BASE && + address < PCIE_MEM_BASE + PCIE_MEM_MODEL_SIZE)) { + pcie_write(state, address, val); + } else if (address >= XUSB_PADCTL_BASE && + address < XUSB_PADCTL_BASE + XUSB_PADCTL_SIZE) { + padctl_write(state, address, val); + } else if (address >= MSELECT_BASE && address < MSELECT_BASE + MSELECT_SIZE) { + mselect_write(state, address, val); + } else if ((address >= SDMMC1_BASE && address < SDMMC1_BASE + 0x200) || + (address >= SDMMC4_BASE && address < SDMMC4_BASE + 0x200)) { + // DMA targets IRAM/DRAM, which every engine maps from the same host + // memory, so the BPMP engine can move the data for either master. + misc_write(state->uc, state, address, (int64_t)value, (int)size); + } else if (address >= 0x70006000 && address < 0x70006500) { + uart_write(state, address, val); + } else if (address >= VIC_BASE && address < VIC_BASE + VIC_SIZE) { + vic_write(state, address, val); + } else if (address >= SYSREG_BASE && address < SYSREG_BASE + SYSREG_SIZE) { + sysreg_write(state, address, val); + } else if (address >= BPMP_CACHE_BASE && + address < BPMP_CACHE_BASE + BPMP_CACHE_SIZE) { + bpmp_cache_write(state, address, val); + } else if (address >= SOC_THERM_BASE && + address < SOC_THERM_BASE + SOC_THERM_SIZE) { + soc_therm_write(state, address, val); + } else if (address >= I2S_BASE && address < I2S_BASE + I2S_SIZE) { + i2s_write(state, address, val); + } else if (address >= ADMAIF_BASE && address < ADMAIF_BASE + ADMAIF_SIZE) { + admaif_write(state, address, val); + } else if (address >= ADMA_BASE && address < ADMA_BASE + ADMA_SIZE) { + adma_write(state, address, val); + } else if (address >= RTC_BASE && address < RTC_BASE + RTC_SIZE) { + rtc_write(state, address, val); + } else if (address >= I2C2_BASE && address < I2C2_BASE + I2C2_SIZE) { + i2c2_write(state, address, val); + } else if (address >= I2C3_BASE && address < I2C3_BASE + I2C3_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) { + i2c_write(state, address, val); + } else if (address >= DISPLAY_A_BASE && + address < DISPLAY_A_BASE + DISPLAY_SIZE) { + display_write(state, address, val); + } else if (address >= DSI_BASE && address < DSI_BASE + DSI_SIZE) { + dsi_write(state, address, val); + } else if (address >= PMC_BASE && address < PMC_BASE + PMC_SIZE) { + pmc_write(state, address, val); + } else if (address >= FLOW_CTLR_BASE && + address < FLOW_CTLR_BASE + FLOW_CTLR_SIZE) { + flow_write(state, address, val); + } else if (address >= CLK_RST_BASE && address < CLK_RST_BASE + CLK_RST_SIZE) { + clk_rst_write(state, address, val); + } else if (address >= FUSE_BASE && address < FUSE_BASE + FUSE_SIZE) { + fuse_write(state, address, val); + } else if ((address >= EMC_BASE && address < EMC_BASE + EMC_SIZE) || + (address >= EMC0_BASE && address < EMC0_BASE + EMC_SIZE) || + (address >= EMC1_BASE && address < EMC1_BASE + EMC_SIZE)) { + emc_write(state, address, val); + } else if (address >= SE_BASE && address < SE_BASE + SE_SIZE) { + se_write(state, address, val); } else { - mmio_regs[address] = val; // Persistent storage - - 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) || - (address >= PCIE_CS_BASE && - address < PCIE_CS_BASE + PCIE_CS_MODEL_SIZE) || - (address >= PCIE_MEM_BASE && - address < PCIE_MEM_BASE + PCIE_MEM_MODEL_SIZE)) { - pcie_write(state, address, val); - } else if (address >= XUSB_PADCTL_BASE && - address < XUSB_PADCTL_BASE + XUSB_PADCTL_SIZE) { - padctl_write(state, address, val); - } else if (address >= MSELECT_BASE && - address < MSELECT_BASE + MSELECT_SIZE) { - mselect_write(state, address, val); - } else if (address >= SDMMC1_BASE && address < SDMMC1_BASE + 0x200) { - misc_write(uc, state, address, value, size); - } else if (address >= SDMMC4_BASE && address < SDMMC4_BASE + 0x200) { - misc_write(uc, state, address, value, size); - } else if (address >= 0x70006000 && address < 0x70006500) { - uint32_t offset = 0; - int port = uart_port_of(address, &offset); - // Note offset 0 is the divisor latch LSB - not the transmit register - - // whenever DLAB is set, so writing the baud divisor must not be - // mistaken for a character to print. Every register (including this - // one) was already cached above; the divisor is additionally kept in - // UartPort because a later THR write overwrites that cache entry. - if (port >= 0) { - UartPort &up = uart_ports[port]; - uint32_t ubase = uart_bases[port]; - bool dlab = (mmio_regs.count(ubase + 0x0C) ? mmio_regs[ubase + 0x0C] : 0) & 0x80; - - if (offset == 0x00 && dlab) { - 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 == 0x08) { - // 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 bdk's uart_init() issues an unconditional - // RX_CLR - which would silently eat scripted keystrokes. - if (port == UART_D && (val & 0x02)) - state->uart_rx_fifo[port].clear(); - } else if (offset == 0x10) { - uint8_t old_mcr = up.mcr; - up.mcr = (uint8_t)val; - // Entering or leaving 16550 internal loopback swings all four modem - // inputs at once - MCR[3:0] are tied onto MSR[7:4] while it is on - - // so every delta bit latches. That is what makes the payload's - // first MSR read after its loopback self-test 0x4F, not 0x40. - if ((old_mcr ^ up.mcr) & 0x10) - up.msr_delta |= 0x0F; - } - - if (offset == 0 && !dlab) { - uint8_t b = (uint8_t)val; - - if (up.mcr & 0x10) { - // Internal loopback: the byte is tied straight back to this - // port's own receiver inside the controller and never reaches a - // pad. It must NOT be handed to whatever is on the far end, or - // the BT chip's H4 parser desyncs on the A5 5A 00 FF test - // pattern - and it must not reach the TX log either, since it is - // not something the payload actually transmitted. - state->uart_rx_fifo[port].push_back(b); - } else { - // UART-D is the Bluetooth radio's H4 transport. - if (port == UART_D) - bt_chip_rx(state, b); - - // Append every byte to the per-port TX log — the console window - // renders this as scrolling text. Trim from the front if it grows - // past 64 KB so ImGui rendering stays responsive. - std::string &log = state->uart_tx_log[port]; - if (b == '\n' || (b >= 0x20 && b < 0x7F)) - log.push_back((char)b); - if (log.size() > 64 * 1024) - log.erase(0, log.size() - 48 * 1024); - - // Mirror to host stdout in line-buffered form so existing - // `grep '[uart]'` workflows still work. - static char uart_line[EmuState::N_UARTS][512]; - static size_t uart_len[EmuState::N_UARTS] = {0}; - auto flush_uart_line = [&](int p) { - if (uart_len[p] > 0) { - uart_line[p][uart_len[p]] = 0; - printf("[uart%c] %s\n", 'A' + (char)p, uart_line[p]); - fflush(stdout); - uart_len[p] = 0; - } - }; - if (b == '\n' || b == '\r') { - flush_uart_line(port); - } else if (b >= 0x20 && b < 0x7F) { - if (uart_len[port] + 1 >= sizeof(uart_line[port])) flush_uart_line(port); - uart_line[port][uart_len[port]++] = (char)b; - } - } - } - } - } else if (address >= VIC_BASE && address < VIC_BASE + VIC_SIZE) { - vic_write(state, address, val); - } else if (address >= SYSREG_BASE && address < SYSREG_BASE + SYSREG_SIZE) { - sysreg_write(state, address, val); - } else if (address >= BPMP_CACHE_BASE && - address < BPMP_CACHE_BASE + BPMP_CACHE_SIZE) { - bpmp_cache_write(state, address, val); - } else if (address >= SOC_THERM_BASE && - address < SOC_THERM_BASE + SOC_THERM_SIZE) { - soc_therm_write(state, address, val); - } else if (address >= I2S_BASE && address < I2S_BASE + I2S_SIZE) { - i2s_write(state, address, val); - } else if (address >= ADMAIF_BASE && address < ADMAIF_BASE + ADMAIF_SIZE) { - admaif_write(state, address, val); - } else if (address >= ADMA_BASE && address < ADMA_BASE + ADMA_SIZE) { - adma_write(state, address, val); - } else if (address >= RTC_BASE && address < RTC_BASE + RTC_SIZE) { - rtc_write(state, address, val); - } else if (address >= I2C2_BASE && address < I2C2_BASE + I2C2_SIZE) { - i2c2_write(state, address, val); - } else if (address >= I2C3_BASE && address < I2C3_BASE + I2C3_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) { - i2c_write(state, address, val); - } else if (address >= DISPLAY_A_BASE && - address < DISPLAY_A_BASE + DISPLAY_SIZE) { - display_write(state, address, val); - } else if (address >= DSI_BASE && address < DSI_BASE + DSI_SIZE) { - dsi_write(state, address, val); - } else if (address >= PMC_BASE && address < PMC_BASE + PMC_SIZE) { - pmc_write(state, address, val); - } else if (address >= 0x60007000 && address < 0x60007000 + 0x1000) { - flow_write(state, address, val); - } else if (address >= CLK_RST_BASE && - address < CLK_RST_BASE + CLK_RST_SIZE) { - clk_rst_write(state, address, val); - } else if (address >= FUSE_BASE && address < FUSE_BASE + FUSE_SIZE) { - fuse_write(state, address, val); - } else if ((address >= EMC_BASE && address < EMC_BASE + EMC_SIZE) || - (address >= EMC0_BASE && address < EMC0_BASE + EMC_SIZE) || - (address >= EMC1_BASE && address < EMC1_BASE + EMC_SIZE)) { - emc_write(state, address, val); - } else if (address >= SE_BASE && address < SE_BASE + SE_SIZE) { - se_write(state, address, val); - } else { - // Log other MMIO writes but don't duplicate SDMMC/I2C/etc. - if (!((address >= SDMMC1_BASE && address < SDMMC1_BASE + 0x1000) || - (address >= SDMMC4_BASE && address < SDMMC4_BASE + 0x1000) || - (address >= I2C1_BASE && address < I2C1_BASE + 0x1000) || - (address >= I2C5_BASE && address < I2C5_BASE + 0x1000) || - (address >= SE_BASE && address < SE_BASE + SE_SIZE) || - (address >= RTC_BASE && address < RTC_BASE + RTC_SIZE))) { - TRACE("[mmio] W: 0x%08llX = 0x%08X (PC=0x%08X)\n", - (unsigned long long)address, val, pc); - fflush(stdout); - } - misc_write(uc, state, address, val, size); + // The TRACE is the only output here. Its fflush used to sit outside the + // macro, so every write to an unmodelled register forced a write(2) of + // whatever stdout had buffered even with tracing off. + if (emu_trace_enabled && + !((address >= SDMMC1_BASE && address < SDMMC1_BASE + 0x1000) || + (address >= SDMMC4_BASE && address < SDMMC4_BASE + 0x1000) || + (address >= I2C1_BASE && address < I2C1_BASE + 0x1000) || + (address >= I2C5_BASE && address < I2C5_BASE + 0x1000))) { + printf("[mmio] W: 0x%08llX = 0x%08X (%s)\n", (unsigned long long)address, + val, g_bus_master == BUS_CPU0 ? "CPU0" : "BPMP"); + fflush(stdout); } + misc_write(state->uc, state, address, (int64_t)val, (int)size); } } -static bool hook_unmapped(uc_engine *uc, uc_mem_type type, uint64_t address, - int size, int64_t value, void *user_data) { - uint32_t pc; +// ==================== Unicorn MMIO windows ==================== + +namespace { + +// One per uc_mmio_map() call. Unicorn hands the callbacks an offset relative +// to the start of the mapping, so each window remembers its base. +struct MmioWindow { + EmuState *state; + uint64_t base; + uc_engine *uc; +}; +std::vector> g_windows; + +uint64_t mmio_cb_read(uc_engine *uc, uint64_t offset, unsigned size, + void *user_data) { + (void)uc; + const MmioWindow *w = (const MmioWindow *)user_data; + uint64_t addr = w->base + offset; + if (g_bus_master == BUS_CPU0) + ccplex_bus_tick(w->state); + if (size == 8) { + // A 64-bit load from CPU0 reaches these 32-bit register files as two + // consecutive word accesses, low word first. + uint64_t lo = mmio_bus_read(w->state, addr, 4); + uint64_t hi = mmio_bus_read(w->state, addr + 4, 4); + return lo | (hi << 32); + } + uint32_t v = mmio_bus_read(w->state, addr, size); + if (size < 4) + v &= (1u << (size * 8)) - 1; + return v; +} + +void mmio_cb_write(uc_engine *uc, uint64_t offset, unsigned size, + uint64_t value, void *user_data) { + (void)uc; + const MmioWindow *w = (const MmioWindow *)user_data; + uint64_t addr = w->base + offset; + if (g_bus_master == BUS_CPU0) + ccplex_bus_tick(w->state); + if (size == 8) { + mmio_bus_write(w->state, addr, 4, value & 0xFFFFFFFFu); + mmio_bus_write(w->state, addr + 4, 4, value >> 32); + return; + } + mmio_bus_write(w->state, addr, size, value); +} + +uc_err map_window(uc_engine *uc, EmuState *state, uint64_t base, + uint64_t size) { + g_windows.push_back(std::make_unique(MmioWindow{state, base, uc})); + MmioWindow *w = g_windows.back().get(); + return uc_mmio_map(uc, base, size, mmio_cb_read, w, mmio_cb_write, w); +} + +// Every peripheral window a payload is known to touch. Overlaps and +// duplicates are fine: the list is flattened to 4 KiB pages below. +const struct { + uint64_t base; + uint64_t size; +} kRegions[] = { + {CLK_RST_BASE, CLK_RST_SIZE}, + {TMR_BASE, TMR_SIZE}, + {GPIO_BASE, GPIO_SIZE}, + {PINMUX_BASE, PINMUX_SIZE}, + {UART_A_BASE, UART_SIZE}, + {I2C1_BASE, I2C_SIZE}, + {I2C5_BASE, I2C_SIZE}, + {PWM_BASE, PWM_SIZE}, + {RTC_BASE, RTC_SIZE}, + {PMC_BASE, PMC_SIZE}, + {FUSE_BASE, FUSE_SIZE}, + {FLOW_CTLR_BASE, FLOW_CTLR_SIZE}, + {EXCP_VEC_BASE, EXCP_VEC_SIZE}, + {EMC_BASE, EMC_SIZE}, + {EMC0_BASE, EMC_SIZE}, + {EMC1_BASE, EMC_SIZE}, + {MC_BASE, MC_SIZE}, + {DISPLAY_A_BASE, DISPLAY_SIZE}, + {DSI_BASE, DSI_SIZE}, + {I2C2_BASE, I2C2_SIZE}, + {SOC_THERM_BASE, SOC_THERM_SIZE}, + {MIPI_CAL_BASE, MIPI_CAL_SIZE}, + {SOR_BASE, SOR_SIZE}, + {SDMMC1_BASE, SDMMC_SIZE}, + {SDMMC4_BASE, SDMMC_SIZE}, + {APB_MISC_BASE, APB_MISC_SIZE}, + {HOST1X_BASE, HOST1X_SIZE}, + {VIC_BASE, VIC_SIZE}, + {SYSREG_BASE, SYSREG_SIZE}, + {I2S_BASE, I2S_SIZE}, + {ADMAIF_BASE, ADMAIF_SIZE}, + {ADMA_BASE, ADMA_SIZE}, + {SE_BASE, SE_SIZE}, + {TSEC_BASE, TSEC_SIZE}, + {SYSCTR0_BASE, SYSCTR0_SIZE}, + {BPMP_CACHE_BASE, BPMP_CACHE_SIZE}, + {XUSB_PADCTL_BASE, XUSB_PADCTL_SIZE}, + {MSELECT_BASE, MSELECT_SIZE}, + // PCIe. T210 puts the root complex at the BOTTOM of the address map, + // below every other peripheral. + {PCIE_BLOCK_BASE, PCIE_BLOCK_SIZE}, + {PCIE_CS_BASE, PCIE_CS_MODEL_SIZE}, + {PCIE_MEM_BASE, PCIE_MEM_MODEL_SIZE}, +}; + +// TZRAM is SRAM, not registers, and every master sees the same 64 KiB. It +// used to be an MMIO window whose "contents" were the register cache, which +// only held whole words at the exact address last written. +uint8_t *g_tzram = nullptr; + +bool in_mmio_band(uint64_t a) { return a >= 0x50000000 && a < 0x80000000; } + +// Unmapped BPMP access. Addresses in the peripheral band get an MMIO page of +// their own, so the generic register cache and misc handlers see them like +// any other register; anything else becomes plain RAM, as before. +bool hook_unmapped(uc_engine *uc, uc_mem_type type, uint64_t address, int size, + int64_t value, void *user_data) { + EmuState *state = (EmuState *)user_data; + uint32_t pc = 0; uc_reg_read(uc, UC_ARM_REG_PC, &pc); - if (type == UC_MEM_READ_UNMAPPED) { - TRACE("[mmio] UNMAPPED R: 0x%08lX (PC=0x%08X)\n", (unsigned long)address, - pc); + if (type == UC_MEM_READ_UNMAPPED || type == UC_MEM_FETCH_UNMAPPED) { + TRACE("[mmio] UNMAPPED R: 0x%08lX (PC=0x%08X)\n", (unsigned long)address, pc); } else { TRACE("[mmio] UNMAPPED W: 0x%08lX = 0x%08llX (PC=0x%08X)\n", - (unsigned long)address, (unsigned long long)value, pc); + (unsigned long)address, (unsigned long long)value, pc); } uint64_t page = address & ~0xFFFULL; - uc_mem_map(uc, page, 0x1000, UC_PROT_ALL); - if (type == UC_MEM_WRITE_UNMAPPED) { + if (in_mmio_band(page) && type != UC_MEM_FETCH_UNMAPPED) + return map_window(uc, state, page, 0x1000) == UC_ERR_OK; + if (uc_mem_map(uc, page, 0x1000, UC_PROT_ALL) != UC_ERR_OK) + return false; + if (type == UC_MEM_WRITE_UNMAPPED) uc_mem_write(uc, address, &value, size); - } return true; } -void hook_code(uc_engine *uc, uint64_t address, uint32_t size, - void *user_data) { - EmuState *state = (EmuState *)user_data; - static uint32_t last_pc = 0; - static int loop_count = 0; - static int logged_stall = 0; +} // namespace - // Deterministic timer: 10 instructions per microsecond (approx 10MHz - // speed-up) - state->insn_count++; - if ((state->insn_count % 10) == 0) { - state->emu_usec++; +void mmio_map_bus(uc_engine *uc, EmuState *state) { + // Flatten to pages, then map each run of contiguous pages as one window. + std::vector pages; + for (const auto &r : kRegions) { + uint64_t first = r.base & ~0xFFFULL; + uint64_t end = (r.base + r.size + 0xFFF) & ~0xFFFULL; + for (uint64_t p = first; p < end; p += 0x1000) + pages.push_back(p); + } + std::sort(pages.begin(), pages.end()); + pages.erase(std::unique(pages.begin(), pages.end()), pages.end()); + for (size_t i = 0; i < pages.size();) { + size_t j = i + 1; + while (j < pages.size() && pages[j] == pages[j - 1] + 0x1000) + j++; + uint64_t base = pages[i], len = pages[j - 1] + 0x1000 - base; + uc_err err = map_window(uc, state, base, len); + if (err != UC_ERR_OK) + fprintf(stderr, "[mmio] cannot map 0x%08llX+0x%llX: %s\n", + (unsigned long long)base, (unsigned long long)len, + uc_strerror(err)); + i = j; } - // Framebuffer-change-aware automation - static uint32_t last_fb_sum = 0; - static int fb_changes = 0; - static int auto_stage = -1; // Disabled for manual debugging - static uint64_t stage_start = 0; - static uint64_t last_change_insn = 0; + if (!g_tzram) + g_tzram = (uint8_t *)calloc(1, TZRAM_SIZE); + if (g_tzram) + uc_mem_map_ptr(uc, TZRAM_BASE, TZRAM_SIZE, UC_PROT_ALL, g_tzram); +} - // Ignore changes for the first 2s (20M insns) to avoid boot transients - if (auto_stage == 0 && state->insn_count > 20000000) { - auto_stage = 1; - printf("[emu] Initial boot period over. Waiting for screen change...\n"); - } - - if (auto_stage >= 1 && (state->insn_count % 1000000) == 0) { - uint64_t current_fb = state->fb_addr ? state->fb_addr : 0xF5A00000; - uint32_t pixels[2048]; - uint32_t sum = 0; - - // Sample Top rows for maximum sensitivity - if (uc_mem_read(uc, current_fb, pixels, sizeof(pixels)) == UC_ERR_OK) { - for (int i = 0; i < 2048; i++) - sum += (pixels[i] & 0xFFFFFF); - - if (sum != last_fb_sum && sum != 0) { - // Ensure there's a gap between 'changes' to let screens settle - if (state->insn_count > last_change_insn + 5000000) { // 0.5s gap - fb_changes++; - last_fb_sum = sum; - last_change_insn = state->insn_count; - printf("[emu] FB Change #%d detected (sum=0x%08X). PC=0x%08llX\n", - fb_changes, sum, (unsigned long long)address); - fflush(stdout); - - if (auto_stage == 1) { // Error Screen or Menu - auto_stage = 2; - stage_start = state->insn_count; - } else if (auto_stage == 3) { // Subsequent menu transition - auto_stage = 4; - stage_start = state->insn_count; - } - } - } - } - } - - // State Machine for Inputs (AutoRCM Verification Path) - if (auto_stage == 2) { // Skip SD fail / Error screen - uint64_t press = stage_start + 5000000; - if (state->insn_count == press) { - printf("[emu] POWER (Skip Screen)\n"); - state->btn_power = true; - } - if (state->insn_count == press + 1000000) { - state->btn_power = false; - auto_stage = 3; - } - } else if (auto_stage == 4) { // Main Menu reached Change #2 - uint64_t base = stage_start + 10000000; - - // 1. Move to "Tools..." (1 tap down from Launch) - if (state->insn_count == base) { - printf("[emu] VOL_DOWN (Select Tools)\n"); - state->btn_vol_down = true; - } - if (state->insn_count == base + 1000000) { - state->btn_vol_down = false; - } - - // 2. Enter Tools - if (state->insn_count == base + 5000000) { - printf("[emu] POWER (Enter Tools)\n"); - state->btn_power = true; - } - if (state->insn_count == base + 6000000) { - state->btn_power = false; - } - - // 3. Move to "AutoRCM" in Tools menu (2 taps down to skip Back and - // Separator) - if (state->insn_count == base + 10000000) { - printf("[emu] VOL_DOWN (Select AutoRCM 1)\n"); - state->btn_vol_down = true; - } - if (state->insn_count == base + 11000000) { - state->btn_vol_down = false; - } - if (state->insn_count == base + 15000000) { - printf("[emu] VOL_DOWN (Select AutoRCM 2)\n"); - state->btn_vol_down = true; - } - if (state->insn_count == base + 16000000) { - state->btn_vol_down = false; - } - - // 4. Enter AutoRCM - if (state->insn_count == base + 20000000) { - printf("[emu] POWER (Enter AutoRCM)\n"); - state->btn_power = true; - } - if (state->insn_count == base + 21000000) { - state->btn_power = false; - } - - // 5. Toggle AutoRCM (Enable) / Clear potential red error - if (state->insn_count == base + 30000000) { - printf("[emu] POWER (Toggle/Skip Error 1)\n"); - state->btn_power = true; - } - if (state->insn_count == base + 31000000) { - state->btn_power = false; - } - if (state->insn_count == base + 35000000) { - printf("[emu] POWER (Toggle/Skip Error 2)\n"); - state->btn_power = true; - } - if (state->insn_count == base + 36000000) { - state->btn_power = false; - } - - // 6. Go back to Main Menu (Using VOL_UP (Back) repeatedly) - if (state->insn_count == base + 50000000) { - printf("[emu] VOL_UP (Back to Tools)\n"); - state->btn_vol_up = true; - } - if (state->insn_count == base + 51000000) { - state->btn_vol_up = false; - } - - if (state->insn_count == base + 60000000) { - printf("[emu] VOL_UP (Back to Main Menu)\n"); - state->btn_vol_up = true; - } - if (state->insn_count == base + 61000000) { - state->btn_vol_up = false; - } - - // 7. Navigate to Power Off from Main Menu - // Power Off is near the bottom. Let's do 10 taps of VOL_DOWN. - uint64_t nav_base = base + 80000000; - for (int i = 0; i < 10; i++) { - uint64_t tap = nav_base + (i * 4000000); - if (state->insn_count == tap) { - printf("[emu] VOL_DOWN (Nav to Off %d)\n", i + 1); - state->btn_vol_down = true; - } - if (state->insn_count == tap + 1000000) { - state->btn_vol_down = false; - } - } - - // 8. Power Off - uint64_t pwr_off = nav_base + 50000000; - if (state->insn_count == pwr_off + 1000000) { - state->btn_power = false; - auto_stage = 5; - } - } - - if (address == last_pc) { - loop_count++; - } else { - if (loop_count > 100000 && !logged_stall) { - printf("[trace] STALL at PC=0x%08llX (looped %d times)\n", - (unsigned long long)last_pc, loop_count); - logged_stall = 1; - } else if (loop_count == 0) { - logged_stall = 0; - } - last_pc = (uint32_t)address; - loop_count = 0; - } +void mmio_unmap_bus(uc_engine *uc) { + g_windows.erase(std::remove_if(g_windows.begin(), g_windows.end(), + [uc](const std::unique_ptr &w) { + return w->uc == uc; + }), + g_windows.end()); } void mmio_init(uc_engine *uc, EmuState *state) { - static uc_hook h_read, h_write, h_unmapped, h_code; - - const struct { - uint64_t base; - uint64_t size; - } regions[] = { - {CLK_RST_BASE, CLK_RST_SIZE}, - {TMR_BASE, TMR_SIZE}, - {GPIO_BASE, GPIO_SIZE}, - {PINMUX_BASE, PINMUX_SIZE}, - {UART_A_BASE, UART_SIZE}, - {I2C1_BASE, I2C_SIZE}, - {I2C5_BASE, I2C_SIZE}, - {RTC_BASE, RTC_SIZE}, - {PMC_BASE, PMC_SIZE}, - {FUSE_BASE, FUSE_SIZE}, - {0x60007000, 0x1000}, // FLOW_CTLR - {EMC_BASE, EMC_SIZE}, - {EMC0_BASE, EMC_SIZE}, - {EMC1_BASE, EMC_SIZE}, - {MC_BASE, MC_SIZE}, - {DISPLAY_A_BASE, DISPLAY_SIZE}, - {DSI_BASE, DSI_SIZE}, - {I2C2_BASE, I2C2_SIZE}, - {SOC_THERM_BASE, SOC_THERM_SIZE}, - {MIPI_CAL_BASE, MIPI_CAL_SIZE}, - {SOR_BASE, SOR_SIZE}, - {SDMMC1_BASE, SDMMC_SIZE}, - {SDMMC4_BASE, SDMMC_SIZE}, - {APB_MISC_BASE, APB_MISC_SIZE}, - {HOST1X_BASE, HOST1X_SIZE}, - {VIC_BASE, VIC_SIZE}, - {SYSREG_BASE, SYSREG_SIZE}, - {I2S_BASE, I2S_SIZE}, - {ADMAIF_BASE, ADMAIF_SIZE}, - {ADMA_BASE, ADMA_SIZE}, - {SE_BASE, SE_SIZE}, - {TSEC_BASE, TSEC_SIZE}, - {SYSCTR0_BASE, SYSCTR0_SIZE}, - {BPMP_CACHE_BASE, BPMP_CACHE_SIZE}, // BPMP_CACHE - {TZRAM_BASE, TZRAM_SIZE}, // TZRAM - {XUSB_PADCTL_BASE, XUSB_PADCTL_SIZE}, - {MSELECT_BASE, MSELECT_SIZE}, - // PCIe. These are the only mapped regions below 0x50000000, so they - // also need their own hooks (see below) - the main MMIO hook pair - // covers 0x50000000..0x7FFFFFFF and would never see them. - {PCIE_BLOCK_BASE, PCIE_BLOCK_SIZE}, - {PCIE_CS_BASE, PCIE_CS_MODEL_SIZE}, - {PCIE_MEM_BASE, PCIE_MEM_MODEL_SIZE}, - }; - - for (const auto &r : regions) { - uint64_t map_base = r.base & ~0xFFFULL; - uint64_t map_end = (r.base + r.size + 0xFFF) & ~0xFFFULL; - uint64_t map_size = map_end - map_base; - uc_mem_map(uc, map_base, map_size, UC_PROT_ALL); - } - - uc_hook_add(uc, &h_read, UC_HOOK_MEM_READ, (void *)hook_mmio_read, state, - 0x50000000, 0x7FFFFFFF); - uc_hook_add(uc, &h_write, UC_HOOK_MEM_WRITE, (void *)hook_mmio_write, state, - 0x50000000, 0x7FFFFFFF); - - // T210 puts the PCIe root complex at the BOTTOM of the address map, below - // every other peripheral, so it needs a second hook pair. The range is a - // filter, not a mapping - only the three small regions mapped above ever - // resolve inside it. - static uc_hook h_pcie_read, h_pcie_write; - uc_hook_add(uc, &h_pcie_read, UC_HOOK_MEM_READ, (void *)hook_mmio_read, - state, PCIE_BLOCK_BASE, PCIE_MEM_BASE + PCIE_MEM_MODEL_SIZE - 1); - uc_hook_add(uc, &h_pcie_write, UC_HOOK_MEM_WRITE, (void *)hook_mmio_write, - state, PCIE_BLOCK_BASE, PCIE_MEM_BASE + PCIE_MEM_MODEL_SIZE - 1); + static uc_hook h_unmapped; + mmio_map_bus(uc, state); pcie_reset(state); + ccplex_reset(state); uc_hook_add(uc, &h_unmapped, UC_HOOK_MEM_READ_UNMAPPED | UC_HOOK_MEM_WRITE_UNMAPPED, (void *)hook_unmapped, state, 1, 0); +} - uc_hook_add(uc, &h_code, UC_HOOK_CODE, (void *)hook_code, 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. + ccplex_reset(state); + pcie_reset(state); + flow_ram_repair = 0; } diff --git a/t210/mmio.h b/t210/mmio.h index 942b028..10fef5e 100644 --- a/t210/mmio.h +++ b/t210/mmio.h @@ -14,9 +14,48 @@ // Forward declarations for peripheral modules. struct EmuState; +// Which processor issued the access being dispatched. Two masters share one +// register model: the BPMP (the ARM7 every RCM payload runs on) and CPU0 of +// the CCPLEX (Cortex-A57), which a payload can boot through bdk's +// ccplex_boot_cpu0(). They do not see the same bus - PCIe and MSELECT answer +// a CPU-complex master only (Tegra X1 TRM ch.16/ch.19) - so the few models +// that care consult this. Both cores run on the emulator's one thread, one +// slice at a time, so a global is exact: whoever is running is the master. +enum BusMaster : uint8_t { + BUS_BPMP = 0, + BUS_CPU0 = 1, +}; +extern BusMaster g_bus_master; + // Initialize all MMIO hooks on the Unicorn engine. void mmio_init(uc_engine *uc, EmuState *state); +// Map the same peripheral windows into another engine (CPU0's), backed by the +// same register models. Everything in the 0x50000000..0x7FFFFFFF band plus +// the PCIe apertures low in the map. +void mmio_map_bus(uc_engine *uc, EmuState *state); +// Forget the windows mapped into `uc`, before that engine is closed. +void mmio_unmap_bus(uc_engine *uc); + +// The shared dispatch both engines' MMIO callbacks funnel into. `size` is the +// access width in bytes (1, 2 or 4). +uint32_t mmio_bus_read(EmuState *state, uint64_t addr, unsigned size); +void mmio_bus_write(EmuState *state, uint64_t addr, unsigned size, + uint64_t value); + +// Reset the per-run peripheral state that a soft reboot must not carry over. +void mmio_soft_reset(EmuState *state); + +// 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(); + +// True when the CCPLEX CPU rail is up: the MAX77621 on Erista (enabled, and +// its EN pin driven by MAX77620 GPIO5), the MAX77812 M4 phase on Mariko. +bool cpu_rail_on(EmuState *state); + // Individual peripheral handlers. uint32_t timer_read(EmuState *state, uint64_t addr); void timer_write(EmuState *state, uint64_t addr, uint32_t val); diff --git a/t210/pcie.cpp b/t210/pcie.cpp index e64c1ea..dee918f 100644 --- a/t210/pcie.cpp +++ b/t210/pcie.cpp @@ -5,6 +5,7 @@ #include "../emu_state.h" #include "memory_map.h" +#include "mmio.h" // ========================================================================== // Register map (tegra210.dtsi pcie@1003000, U-Boot drivers/pci/pci_tegra.c) @@ -108,6 +109,14 @@ static constexpr uint64_t T_VDD_TO_POR_US = 57000; // WL_REG_ON -> POR done static constexpr uint64_t T_REFCLK_STABLE_US = 10000; // refclk -> PERST# high +// Reset values, as a CPU-complex master reads them on real silicon. +// MSELECT_CONFIG_0 is the TRM's documented reset value (16.3.1): the PCIe +// aperture (bit 5) is already enabled. AFI_PCIE_CONFIG is what hwtest's CPU0 +// stub reads straight after the BPMP has cycled the AFI reset - xbar X4_X1 in +// bits 23:20 and root port 1 disabled (bit 2) until software clears it. +static constexpr uint32_t MSELECT_CONFIG_RESET = 0x07FF4020; +static constexpr uint32_t AFI_PCIE_CONFIG_RESET = 0x00103025; + // Broadcom identity (brcm_hw_ids.h, brcmfmac/pcie.c). static constexpr uint32_t BRCM_4356_CFG0 = 0x43EC14E4; static constexpr uint32_t BRCM_BAR0_WINDOW = 0x80; @@ -158,7 +167,8 @@ struct PcieModel { bool mgmt_warned = false; bool plle = false; bool pllrefe = false; - bool powergated = true; + // The PCIE partition is already up at RCM entry (see pmc_pwrgate_status). + bool powergated = false; // XUSB pad controller. uint32_t padctl[0x1000 / 4] = {}; @@ -177,9 +187,11 @@ PcieModel pcie; // BAR sizing masks: a write of all-ones reads back ~(size-1) with the type // bits preserved, which is how any enumerator discovers how big a BAR is. -// BAR0 is 32 KiB of registers, BAR2 the 2 MiB TCM; both are 64-bit -// prefetchable, which is why brcmfmac calls them resource 0 and resource 2. -constexpr uint32_t EP_BAR_TYPE = 0x0000000C; // 64-bit, prefetchable +// BAR0 is 32 KiB of registers, BAR2 the 2 MiB TCM; both are 64-bit memory +// BARs, which is why brcmfmac calls them resource 0 and resource 2. They are +// NOT prefetchable: a real CYW4356 in ROM phase reads BAR0 = 0x00000004 +// (hwtest's healthy-console capture), i.e. type 64-bit, prefetch clear. +constexpr uint32_t EP_BAR_TYPE = 0x00000004; // 64-bit, non-prefetchable constexpr uint32_t EP_BAR0_MASK = ~(0x8000u - 1); constexpr uint32_t EP_BAR2_MASK = ~(0x200000u - 1); @@ -187,7 +199,7 @@ void ep_init() { memset(pcie.ep, 0, sizeof(pcie.ep)); pcie.ep[0x00 / 4] = BRCM_4356_CFG0; // 14E4:43EC pcie.ep[0x04 / 4] = 0x00100000; // status: capability list - pcie.ep[0x08 / 4] = 0x02800000; // network controller, other + pcie.ep[0x08 / 4] = 0x02800003; // network controller, rev 03 pcie.ep[0x0C / 4] = 0x00000000; // header type 0 pcie.ep[0x10 / 4] = EP_BAR_TYPE; // BAR0 lo: 32 KiB registers pcie.ep[0x18 / 4] = EP_BAR_TYPE; // BAR2 lo: 2 MiB TCM @@ -227,6 +239,9 @@ bool radio_core_alive(EmuState *state) { // which is how a probe that cannot work on hardware passed here for days. // Refusing them is the single most valuable thing this file does. static bool bpmp_pcie_denied(uint64_t addr) { + // CPU0 (t210/ccplex.cpp) is a CPU-complex master and reaches all of it. + if (g_bus_master == BUS_CPU0) + return false; static bool warned = false; if (!warned) { warned = true; @@ -249,7 +264,8 @@ void mselect_complain(uint64_t addr) { pcie.mselect_warned = true; printf("[pcie] *** access to %08X with MSELECT still in reset ***\n", (unsigned)addr); - printf("[pcie] *** on real silicon this STALLS THE BPMP for good: no ***\n"); + printf("[pcie] *** on real silicon this STALLS THE %s for good: no ***\n", + g_bus_master == BUS_CPU0 ? "CPU0" : "BPMP"); printf("[pcie] *** abort, no timeout, no reboot path. Clear ***\n"); printf("[pcie] *** RST_DEV_V bit %d first (bdk ccplex.c:121). ***\n", CLK_V_MSELECT); @@ -345,9 +361,13 @@ bool ep_reachable(EmuState *state) { void pcie_reset(EmuState *state) { pcie = PcieModel(); ep_init(); + pcie.mselect[0] = MSELECT_CONFIG_RESET; + pcie.afi[AFI_PCIE_CONFIG / 4] = AFI_PCIE_CONFIG_RESET; (void)state; } +bool pcie_mselect_up() { return mselect_up(); } + void pcie_set_powergate(bool ungated) { if (pcie.powergated == !ungated) return; @@ -469,7 +489,8 @@ uint32_t padctl_read(EmuState *state, uint64_t addr) { pcie.padctl_warned = true; printf("[pcie] *** read of XUSB_PADCTL %08X with the block still ***\n", (unsigned)addr); - printf("[pcie] *** in reset. On real silicon this STALLS THE ***\n"); + printf("[pcie] *** in reset. On real silicon this STALLS THE %s ***\n", + g_bus_master == BUS_CPU0 ? "CPU0" : "BPMP"); printf("[pcie] *** BPMP for good. Clear RST_DEV_W bit %d first. ***\n", CLK_W_XUSB_PADCTL); fflush(stdout); @@ -637,8 +658,11 @@ uint32_t pcie_read(EmuState *state, uint64_t addr) { // speeds"), so speed = 1 and width = 1. if (!rp.link) return rp.reg[off / 4] & 0xFFFF; + // LNKSTA 0x3011 on hardware: gen1, x1, Slot Clock + // Configuration (bit 28 - the endpoint runs off the refclk the + // root port drives) and Data Link Layer Link Active. return (rp.reg[off / 4] & 0xFFFF) | RP_LINK_DL_ACTIVE | - (1u << 16) | (1u << 20); + (1u << 28) | (1u << 16) | (1u << 20); default: return rp.reg[off / 4]; } diff --git a/t210/pcie.h b/t210/pcie.h index 7a2df34..6e1365b 100644 --- a/t210/pcie.h +++ b/t210/pcie.h @@ -43,6 +43,10 @@ void padctl_write(EmuState *state, uint64_t addr, uint32_t val); void pcie_car_write(uint32_t offset, uint32_t val); bool pcie_car_read(uint32_t offset, uint32_t *out); +// MSELECT clocked out of reset (RST_DEV_V bit 3 clear). The CCPLEX needs it +// as much as PCIe does: it is the CPU cluster's path to every slave. +bool pcie_mselect_up(); + // The PCIE power partition, toggled through PMC_PWRGATE_TOGGLE. void pcie_set_powergate(bool ungated); diff --git a/t210/regcache.h b/t210/regcache.h new file mode 100644 index 0000000..e40a197 --- /dev/null +++ b/t210/regcache.h @@ -0,0 +1,86 @@ +#ifndef T210_REGCACHE_H +#define T210_REGCACHE_H + +#include +#include +#include +#include + +// Last-written value of every MMIO address, for the registers whose model is +// "read back what the payload wrote" (PINMUX, PWM, UART LCR, CLK_SOURCE_*...). +// +// This sits on the hottest path in the emulator - every MMIO write stores +// into it and a good share of reads consult it - and it used to be a +// std::map: a red-black tree walk plus, for a new key, a +// heap allocation per access. Profiling a hwtest sweep put the tree lookups +// on par with the peripheral models themselves. +// +// Registers cluster into a few dozen 4 KiB pages, so this keeps one flat page +// per touched page with a presence bitmap, and caches the last page looked +// up. The interface is the subset of std::map the call sites use (count() and +// operator[]), so they did not have to change. Keys stay byte-granular: a +// byte store at 0x70006001 is its own entry, exactly as it was in the map. +class RegCache { + struct Page { + uint32_t val[4096]; + uint64_t present[4096 / 64]; + }; + + std::unordered_map> pages_; + mutable uint64_t last_key_ = ~0ULL; + mutable Page *last_ = nullptr; + + Page *find(uint64_t key) const { + if (key == last_key_) + return last_; + auto it = pages_.find(key); + if (it == pages_.end()) + return nullptr; + last_key_ = key; + last_ = it->second.get(); + return last_; + } + +public: + size_t count(uint64_t addr) const { + const Page *p = find(addr >> 12); + if (!p) + return 0; + uint32_t o = (uint32_t)(addr & 0xFFF); + return (p->present[o >> 6] >> (o & 63)) & 1; + } + + uint32_t &operator[](uint64_t addr) { + uint64_t key = addr >> 12; + Page *p = find(key); + if (!p) { + auto page = std::make_unique(); + memset(page.get(), 0, sizeof(Page)); + p = page.get(); + pages_.emplace(key, std::move(page)); + last_key_ = key; + last_ = p; + } + uint32_t o = (uint32_t)(addr & 0xFFF); + p->present[o >> 6] |= 1ULL << (o & 63); + return p->val[o]; + } + + // Value if ever written, else `dflt`. One lookup instead of the + // count()-then-operator[] pair. + uint32_t get(uint64_t addr, uint32_t dflt = 0) const { + const Page *p = find(addr >> 12); + if (!p) + return dflt; + uint32_t o = (uint32_t)(addr & 0xFFF); + return ((p->present[o >> 6] >> (o & 63)) & 1) ? p->val[o] : dflt; + } + + void clear() { + pages_.clear(); + last_key_ = ~0ULL; + last_ = nullptr; + } +}; + +#endif // T210_REGCACHE_H From 11ad2e4d9f22cb6eb0cbfde18bbed461768a62b2 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 15:56:00 +0000 Subject: [PATCH 02/21] Test the CCPLEX model and the hwtest sweep in CI, and document both - tests/ccplex: a self-contained BPMP payload (ARM, arm-none-eabi-gcc; the AArch64 side is pre-assembled words) that drives CPU0 through bdk's ccplex_boot_cpu0() register sequence. It checks that an unpowered release is refused with its reason, that a powered one runs at EL3 from the SB vector and writes the mailbox, that CPU0 sees TIMERUS move, that WFE parks the core, and that RST_CPUG_CMPLX_SET stops it. `make test`. - tests/hwtest: build hwtest-rcm from a pinned commit with distro toolchains (an empty base_rules stands in for devkitARM, the CPU0 stub builds with gcc-aarch64-linux-gnu) and run its whole sweep headless, checking the CPU0-driven Wi-Fi probe enumerates the CYW4356. - CI runs both in the Linux job and keeps their logs on failure. - Makefile: `test` target; the clean rule's line continuation was a literal "\n" that only worked by accident. - README/DESIGN: CCPLEX CPU0, the uc_mmio_map bus, the block-level clock and TIMERUS poll pacing, the new bug-history entries. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb --- .github/workflows/build.yml | 28 +++++- .gitignore | 2 + DESIGN.md | 166 +++++++++++++++++++++++++++++++++--- Makefile | 23 ++++- README.md | 68 ++++++++++++--- tests/ccplex/link.ld | 10 +++ tests/ccplex/payload.c | 165 +++++++++++++++++++++++++++++++++++ tests/ccplex/run.sh | 50 +++++++++++ tests/hwtest/build.sh | 31 +++++++ tests/hwtest/run.sh | 49 +++++++++++ 10 files changed, 566 insertions(+), 26 deletions(-) create mode 100644 tests/ccplex/link.ld create mode 100644 tests/ccplex/payload.c create mode 100755 tests/ccplex/run.sh create mode 100755 tests/hwtest/build.sh create mode 100755 tests/hwtest/run.sh diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 044bc74..09fcb32 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -27,7 +27,8 @@ jobs: run: | sudo apt-get update -qq sudo apt-get install -y --no-install-recommends \ - build-essential pkg-config libunicorn-dev libsdl2-dev + build-essential pkg-config libunicorn-dev libsdl2-dev \ + gcc-arm-none-eabi libnewlib-arm-none-eabi gcc-aarch64-linux-gnu - name: Build run: make -j"$(nproc)" @@ -44,6 +45,31 @@ jobs: grep -q "RCM Payload Emulator" out.txt \ || { echo "banner missing - binary did not start"; exit 1; } + - name: CCPLEX regression test + # A small self-contained payload boots CPU0 through bdk's + # ccplex_boot_cpu0() register sequence: an unpowered release must be + # refused, a powered one must run an AArch64 blob at EL3, and WFE must + # park the core. + run: make test + + - name: hwtest end to end + # hwtest-rcm's whole hardware sweep, including the Wi-Fi probe that + # hands PCIe to an AArch64 stub on CPU0. Built from a pinned commit + # with distro toolchains; the run must enumerate the CYW4356. + run: | + tests/hwtest/build.sh build-hwtest + tests/hwtest/run.sh ./rcm_emu build-hwtest/hwtest-rcm/build/hwtest.bin + + - name: Keep test logs + if: failure() + uses: actions/upload-artifact@v4 + with: + name: test-logs + path: | + tests/ccplex/out.log + tests/hwtest/out.log + if-no-files-found: ignore + - name: Upload artifact uses: actions/upload-artifact@v4 with: diff --git a/.gitignore b/.gitignore index 3d8cec6..0c77899 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ rcm_emu rcm_emu.exe *.o *.d +*.elf # Runtime captures last_fb.rgba @@ -26,5 +27,6 @@ last_audio*.wav __pycache__/ *.pyc backup/ +build-hwtest/ imgui.ini rcm_emu.ini diff --git a/DESIGN.md b/DESIGN.md index e2232f7..e194859 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -10,12 +10,15 @@ them. Read [README.md](README.md) first for usage. flowchart TB main["main.cpp
arg parsing, payload load, CLI
emulation loop, auto-script state"] - main -->|uc_emu_start| uc["Unicorn Engine
ARM32, T210
IRAM / DRAM / MMIO"] + main -->|bpmp_run| uc["Unicorn Engine
ARM32 BPMP
IRAM / DRAM / MMIO"] + main -->|ccplex_run| a57["t210/ccplex
2nd Unicorn engine, AArch64
CCPLEX CPU0 (Cortex-A57)"] + a57 -->|MMIO callbacks| mmio + a57 -.->|shares| uc main -->|sdl_display_*| sdl["display/sdl_display
block-linear de-swizzle
rotate, blit"] main -->|config_window_*| cfg["display/config_window
2nd SDL window + ImGui
live hardware tweaks"] main -->|console_window_*| con["display/console_window
3rd SDL window + ImGui
per-port UART TX log + RX inject"] - uc -->|MMIO trap| mmio["t210/mmio.cpp
central read/write dispatch
by address range"] + uc -->|MMIO callbacks| mmio["t210/mmio.cpp
mmio_bus_read / mmio_bus_write
shared by both masters"] mmio --> sdmmc["sdmmc
SDMMC1 / SDMMC4
CMD0..18, EXT_CSD, ADMA2"] mmio --> se["se_engine
AES-128, SHA-256
BIS keyslot override"] @@ -23,6 +26,7 @@ flowchart TB mmio --> i2c1["I2C_1 slaves (inline)
MAX17050, TMP451,
BQ24193, BM92T36"] mmio --> i2c5["I2C_5 slaves (inline)
MAX77620, MAX77621"] mmio --> stubs["inline stubs
GPIO, PMC, TSEC, KFUSE,
PWM, DC, CLK, TMR, FUSE, UART"] + mmio --> pcie["pcie
AFI, root ports, CYW4356
(CPU-complex master only)"] cfg -.->|writes atomics| state["EmuState
(emu_state.h)"] con -.->|RX inject / TX log| state @@ -35,6 +39,11 @@ touchscreen atomics, framebuffer parameters from the display controller, file descriptors for SD and eMMC images, and a deterministic `emu_usec` counter used for auto-script timing. +Two processors can execute: the BPMP, which every RCM payload runs on, and - +once a payload boots it - CPU0 of the CCPLEX. Each is its own Unicorn engine; +both map the same host memory for IRAM, DRAM and TZRAM, and both reach the +same peripheral models through one dispatch (see [CCPLEX CPU0](#ccplex-cpu0)). + ## Boot flow (Hekate as the example) 1. The payload is loaded into IRAM (Internal RAM) at `0x40010000` via @@ -65,10 +74,27 @@ Mapped explicitly in `setup_emulation()`: | `0x80000000 – 0x90000000` | 256 MB | DRAM low | | `0xC0000000 – 0xFFFFFFFF` | 1 GB | DRAM high (covers FB at 0xF5A00000) | | `0x00000000 – 0x01000000` | 16 MB | low scratch (some null derefs) | -| Various MMIO pages | 4 KB ea | trapped via UC hooks | +| `0x7C010000 – 0x7C020000` | 64 KB | TZRAM (shared with CPU0) | +| Peripheral windows | 4 KB ea | `uc_mmio_map` callbacks | -MMIO (Memory-Mapped I/O) ranges are added as plain mapped pages with read and -write hooks. The actual register modelling lives in `t210/mmio.cpp`. +MMIO (Memory-Mapped I/O) windows are `uc_mmio_map()` regions: Unicorn calls +`mmio_cb_read` / `mmio_cb_write`, which forward to `mmio_bus_read` / +`mmio_bus_write` in `t210/mmio.cpp`, where the register models live. The list +of windows is `kRegions` in the same file; it is flattened to 4 KiB pages and +mapped as contiguous runs, once per engine. + +They used to be plain RAM pages with `UC_HOOK_MEM_READ` / `UC_HOOK_MEM_WRITE` +hooks, a read's result written into the page with `uc_mem_write` before the +load completed. Unicorn sends every guest load and store through its slow path +while any memory hook exists, so ordinary IRAM/DRAM traffic paid for MMIO's +hooks, and each MMIO read cost a walk of Unicorn's region list on top. An +unmapped access in the peripheral band now gets an MMIO page of its own on the +fly (`hook_unmapped`), so the generic register cache still sees it. + +The "read back what was written" behaviour of simple registers (PINMUX, PWM, +UART LCR, CLK_SOURCE_* ...) comes from `mmio_regs`, a `RegCache` +(`t210/regcache.h`): flat 4 KiB pages with a presence bitmap and a last-page +cache, replacing a `std::map` that was a measurable share of all MMIO time. ## Subsystems @@ -252,8 +278,12 @@ Hekate and Nyx draw into a block-linear surface. One block-height row covers 5. Blits to an SDL_Texture at the host window current size. The de-swizzle is the hottest path. It is inlined and operates on `u32` -units. A blit cache keys on `(addr, w, h, stride, sw, rot, bh)` so identical -frames don't re-touch the surface. +units. The surface is read straight from the host memory behind emulated DRAM, +and a frame whose bytes and layout `(addr, w, h, stride, sw, bh, rot)` match +the previous one skips the de-swizzle and the texture upload entirely. No +renderer uses `PRESENTVSYNC`: the CPU runs on the same thread, the loop +already paces redraws to ~60 Hz, and a vsync'd present could stall the +emulated CPU for a whole frame. ### UART @@ -326,9 +356,9 @@ needed. The 64 KB TX log trim happens in-place during the write hook. - **TSEC.** `DMATRFCMD_IDLE` is reported set, and the keygen status word is hardcoded to `0xB0B0B0B0` (the success magic from AMS, the Atmosphère keygen). No firmware is actually executed. -- **Timer and RTC.** Backed by `EmuState::emu_usec`, incremented per CPU - batch by a fixed amount so timing is deterministic across runs. The - auto-script feature relies on this. +- **Timer and RTC.** Backed by `EmuState::emu_usec`, derived from retired + instructions (see [Determinism](#determinism-and-the-auto-script-flag)), so + timing is identical across runs. The auto-script feature relies on this. - **Probe-magic constants.** Several reads return fixed values, not because they are tweakable but because the chip-detection code expects exact cookies: `MAX17050.DevName=0x00AC`, `BQ24193.VendorPart=0x2F`, the BM92T36 @@ -338,10 +368,34 @@ needed. The 64 KB TX log trim happens in-place during the write hook. ## Determinism and the auto-script flag -`emu_usec` advances by a constant per Unicorn batch, never by host wall-clock. +`emu_usec` is derived from retired BPMP instructions, never from host +wall-clock: `emu_usec = skipped_us + insn_count / 10`, where `skipped_us` is +whatever a FLOW_CTLR timed halt (`bpmp_usleep` / `bpmp_msleep`) jumped over. That makes the entire run reproducible: a payload at PC X always sees timer value Y, regardless of how busy the host machine is. +The count comes from a `UC_HOOK_BLOCK` callback in `t210/bpmp.cpp`, not from +a callback on every instruction (which kept Unicorn off its fast path for all +code). Each translated block's instructions are counted once from its bytes +(Thumb: a halfword with top bits `0b11101`/`0b11110`/`0b11111` opens a 32-bit +instruction, which includes the Thumb-1 BL pair), cached per block, and +credited when the block has run. Totals match per-instruction counting +exactly; inside a block an MMIO read sees the time at the block's start. A +batch ends by stopping the engine from the block hook, which Unicorn honours +*before* running that block, so no instruction is ever counted twice or lost. + +**TIMERUS poll pacing.** Ten instructions per microsecond is a deliberate +dilation - real silicon retires a few hundred - and it is what makes busy-waits +cheap. It is harmless for `while (now - start < us)`, but not for a wait that +must *see* a value. bdk's `fan_get_speed()` is one: `int timer = get_tmr_us() + +2000000; while ((timer - get_tmr_us()) > 0)` is unsigned arithmetic, i.e. +`!= 0`, and compiles to `cmp; bne`. Its ~30-instruction body is 0.1 us on +hardware and 3 us here, so the counter stepped past the deadline and the loop +spun until TIMERUS wrapped. So while TIMERUS reads come at most 200 +instructions apart (under a microsecond at real speed), the clock advances at +most 1 us between them. Only increments are capped, so time stays monotonic for +every observer and a wait still ends at the emulated time it asked for. + The `--auto-pin-recovery` and `--auto-te-script` flags exploit this. A real interactive run was captured by logging every keyboard up and down event with the matching `emu_usec`, then the same schedule was re-applied verbatim in @@ -363,6 +417,67 @@ Because `emu_usec` is deterministic, the same timestamps land at the same UI states across runs. Adding a new automated flow is "press the buttons once with `[input]` logging on, copy the timestamps". +## CCPLEX CPU0 + +`t210/ccplex.cpp` models CPU0 of the main CPU cluster, enough for a payload to +hand work to it the way bdk's `ccplex_boot_cpu0()` does. hwtest-rcm's Wi-Fi +probe is the driving case: PCIe answers a CPU-complex master only (TRM ch.16 / +ch.19: MSELECT is CCPLEX hardware, the BPMP-Lite is an AHB master), so it +copies an AArch64 stub to DRAM, boots CPU0 at it, and supervises through a +mailbox while the stub trains the link and enumerates the CYW4356. + +**Release.** The model shadows the registers the boot sequence writes and +starts the core when `RST_CPUG_CMPLX_CLR` clears the last of CPU0's reset bits +(CPURESET0, DBGRESET0, CORERESET0, bit 30, NONCPURESET) - but only if the core +could actually run: + +| Precondition | Where it comes from | +| --- | --- | +| CPU rail up | Erista: MAX77621 @ I2C5 0x1B VOUT_EN and its EN pin, MAX77620 GPIO5 driven high. Mariko: MAX77812 EN_CTRL.EN_M4 | +| CRAIL, C0NC, CE0 ungated | PMC PWRGATE_STATUS bits 0, 15, 14 | +| CPUG clock on, PLLX up if CCLK uses it | CLK_ENB_V bit 0, CCLK_BURST_POLICY, PLLX_BASE | +| MSELECT clocked and out of reset | CLK_ENB_V bit 3, RST_DEV_V bit 3 | +| RAM repair requested | FLOW_CTLR_RAM_REPAIR | +| An AArch64 vector in IRAM/DRAM | SB_AA64_RESET_LOW bit 0 + address, SB_AA64_RESET_HIGH | + +A release that misses one prints `[ccplex] CPU0 released from reset but +cannot run: ` and the core stays dark, which is what silicon does, +minus the explanation. Asserting a reset bit, gating a partition or dropping +the rail stops a running core. + +**Entry at EL3.** A real A57 leaves reset at EL3, AArch64, MMU off. Unicorn +builds its ARM64 core at EL1 and cannot be moved: a PSTATE write does not +rebuild the translator's cached `hflags`, and Unicorn never delivers guest +exceptions, so no SMC can carry it up either. ERET can: its helper takes the +current EL from PSTATE and rebuilds `hflags` for the target. So each boot +creates a fresh engine (no stale translations of a rewritten stub), writes +PSTATE = SPSR_EL3 = EL3h with DAIF masked and ELR_EL3 = ELR_EL1 = the vector, +and starts it on a one-instruction `eret` trampoline in a page at 1 TiB that +only CPU0 maps. + +**Bus.** CPU0's engine maps IRAM, DRAM and TZRAM from the same host memory +as the BPMP's and the same MMIO windows. `g_bus_master` says who is issuing an +access; the PCIe model refuses the BPMP (`0xFFFFFFFF`, and one warning +explaining why) and serves CPU0. MSELECT reads its TRM reset value +`0x07FF4020`, AFI_PCIE_CONFIG `0x00103025`, and LNKSTA `0x3011` once the link +is up - the values hwtest's healthy-console capture shows. An access CPU0 +makes to an address nothing decodes wedges it, as on silicon; the BPMP's +watchdog on the mailbox heartbeat is what reports it. + +**Time.** CPU0 keeps its own clock: 1 ns per retired instruction (PLLX runs +the A57 at ~1 GHz) plus 250 ns per bus access (MSELECT, the APC bridge, APB). +While it runs, the main loop cuts the BPMP's batch into 250 us slices and runs +CPU0 up to the BPMP's time after each - lockstep at a finer grain than the +500 us the BPMP polls the mailbox at. During a CPU0 slice `emu_usec` is CPU0's +clock, so every register model timestamps with the right core's time. WFE / +WFI park the core to the end of the slice: the stub's final `for(;;) wfe;` +would otherwise spin through a billion instructions per emulated second. + +`make test` runs `tests/ccplex/`, a self-contained payload that checks the +refusal, the EL3 entry, the mailbox, WFE parking and the reset. +`tests/hwtest/` builds hwtest-rcm with distro toolchains and runs its whole +sweep; CI runs both. + ## Bug history These are baked into the current source. Listed here so future maintainers @@ -398,13 +513,38 @@ don't repeat the diagnosis: `APBDEV_PMC_CNTRL.MAIN_RST`, then exit or flip `state->reboot_requested`. +- **A hwtest sweep never finished.** It stalled in the fan spin-up test: + bdk's `fan_get_speed()` waits for TIMERUS to *equal* a deadline, and the + dilated clock stepped past it. Fix: TIMERUS poll pacing (see + [Determinism](#determinism-and-the-auto-script-flag)). +- **Per-instruction hooks.** Three `UC_HOOK_CODE` callbacks (one registered + twice), one doing a `uc_mem_read` per instruction for a NOP-slide check + whose counter never reset, plus memory hooks forcing every load and store + onto Unicorn's slow path, and a display path that re-converted and + re-allocated every frame. Reaching hwtest's fan test took 2.7 s; it takes + 0.8 s now, and the whole sweep about 3 s. Fix: block-level clock, + `uc_mmio_map` windows, a change-detecting display path. +- **MAX77621 writes were dropped**, so after bdk's `hw_init()` disabled the + Erista CPU/GPU bucks a payload still read them as on. Fix: register files + for MAX77621 and MAX77812. +- **Mariko's MAX77812 was unreachable through bdk.** bdk picks its address + from `FUSE_RESERVED_ODM28_B01` bit 0; left clear it talked to the NAK'd + PHASE31 address 0x31. Fix: a Mariko reads the bit set (retail PHASE211, + 0x33). +- **Windows image I/O ran in text mode.** MinGW's `open()` defaults to it, + so `_read()` rewrote CR LF and stopped at 0x1A inside SD/eMMC sectors, and + its 32-bit `st_size` could not size a 4 GiB rawnand chunk. Fix: `O_BINARY` + and `_fstati64` (`platform.h`). + See `git log` for the commit-by-commit diagnosis trail if you want more detail on any of them. ## Adding a new peripheral -1. Decide on an MMIO range and add a new `else if` branch in `mmio_read` or - `mmio_write` (or a dedicated module like `i2c3.cpp`). +1. Decide on an MMIO range, make sure it is covered by `kRegions`, and add a + branch in `mmio_bus_read` / `mmio_bus_write` (or a dedicated module like + `i2c3.cpp`). Both processors reach it; check `g_bus_master` if the real + block answers only one of them. 2. If the device participates in the boot fence (status registers polled by the BDK), make sure the read returns the "ready" or "done" state. Silent `0` returns are the most common cause of hangs. diff --git a/Makefile b/Makefile index 8a705d0..df8126e 100644 --- a/Makefile +++ b/Makefile @@ -59,7 +59,7 @@ WIN_CXXFLAGS = -Wall -g -O2 -std=c++17 -MMD -MP -I. -I$(IMGUI_DIR) WIN_LIBS = -lmingw32 -lSDL2main -lSDL2 -lunicorn -lpthread -lwinmm -limm32 -lole32 -loleaut32 -lversion -lsetupapi -lcfgmgr32 -lcomdlg32 -lgdi32 -lrpcrt4 -lws2_32 -luuid -lshell32 -ladvapi32 -luser32 WIN_LDFLAGS = -static -static-libgcc -static-libstdc++ -.PHONY: all clean windows +.PHONY: all clean windows test all: $(OUTPUT) @@ -84,5 +84,24 @@ $(OUTPUT): $(OBJS) # (or after `make clean`) since the files don't exist yet. -include $(OBJS:.o=.d) +# ---- Regression tests -------------------------------------------------------- +# +# `make test` boots the emulator headless on small self-contained payloads and +# checks what they report. Needs arm-none-eabi-gcc for the BPMP side (the +# AArch64 side of the CCPLEX test is pre-assembled words in the source). +TEST_CC = arm-none-eabi-gcc +TEST_OBJCOPY = arm-none-eabi-objcopy +TEST_CFLAGS = -marm -march=armv4t -O2 -ffreestanding -nostdlib -fno-builtin \ + -Wall -Wextra + +tests/ccplex/payload.bin: tests/ccplex/payload.c tests/ccplex/link.ld + $(TEST_CC) $(TEST_CFLAGS) -T tests/ccplex/link.ld -o tests/ccplex/payload.elf $< + $(TEST_OBJCOPY) -O binary tests/ccplex/payload.elf $@ + +test: $(OUTPUT) tests/ccplex/payload.bin + sh tests/ccplex/run.sh ./$(OUTPUT) tests/ccplex/payload.bin + clean: - rm -f $(OUTPUT) $(OBJS) $(OBJS:.o=.d) \n $(WIN_OUT) $(WIN_OBJS) $(WIN_OBJS:.o=.d) + rm -f $(OUTPUT) $(OBJS) $(OBJS:.o=.d) \ + tests/ccplex/payload.elf tests/ccplex/payload.bin tests/ccplex/out.log \ + $(WIN_OUT) $(WIN_OBJS) $(WIN_OBJS:.o=.d) diff --git a/README.md b/README.md index af61f8c..44e2b42 100644 --- a/README.md +++ b/README.md @@ -7,9 +7,10 @@ precompiled `.bin` (Hekate, Lockpick_RCM, TegraExplorer, custom payloads) and executes its ARM32 code on an emulated Tegra X1 (T210) environment, with a windowed framebuffer and keyboard input mapped to the Switch hardware buttons. -It is **not** a console emulator. Only the BPMP (Boot and Power Management -Processor) bootloader stage is modelled. You will not boot Horizon, run NSPs, -or load games. The intended use is payload development and scripted +It is **not** a console emulator. The BPMP (Boot and Power Management +Processor) bootloader stage is what is modelled, plus CPU0 of the main CPU +cluster for payloads that boot it to run bare-metal AArch64 code. You will not +boot Horizon, run NSPs, or load games. The intended use is payload development and scripted verification, plus security research where iterating on real hardware would be slow or destructive. @@ -21,6 +22,10 @@ slow or destructive. bypasses the parts of the chain that aren't fully modelled. - Run **TegraExplorer**, including `.te` script execution from an emulated SD card. +- Run **hwtest-rcm**'s complete hardware sweep in a few seconds, including its + Wi-Fi probe, which boots **CPU0** (Cortex-A57, AArch64) to bring up PCIe and + enumerate the CYW4356 - PCIe answers a CPU-complex master only. See + [CCPLEX CPU0](#ccplex-cpu0). - Replay deterministic button sequences via `--auto-pin-recovery` or `--auto-te-script`, so a payload flow can be exercised from a CI run or a one-shot script. @@ -141,6 +146,45 @@ Audio goes to WASAPI on Windows and ALSA/PulseAudio on Linux; SDL picks the backend, so nothing in the emulator cares which. `RCM_EMU_NO_AUDIO=1` skips playback entirely, which is what CI uses since a runner has no sound device. +## CCPLEX CPU0 + +A payload can boot the first Cortex-A57 exactly as bdk's `ccplex_boot_cpu0()` +does - CPU rail, PLLX, CCLK, the CRAIL/C0NC/CE0 partitions, RAM repair, the +AArch64 vector in `SB_AA64_RESET_LOW/HIGH`, then `RST_CPUG_CMPLX_CLR` - and the +emulator runs it: AArch64, entered at EL3 with the MMU off at the vector, +sharing IRAM, DRAM and every peripheral with the BPMP, in lockstep with it on +the emulated clock. Output is prefixed `[ccplex]`: + +``` +[ccplex] CPU0 released: AArch64 EL3, MMU off, entry 0xA0000000 (boot #1) +[pcie] root port 1: link UP, gen1 x1 (healthy WLAN) +[uartB] CPU0 : ran to completion (hb=613) +[uartB] AFI (CPU) : cfg=00103025 witness=A5A50000 -> APERTURE LIVE +[uartB] RP1 link : UP, DL active (LNKSTA=3011 gen1 x1) +[uartB] EP config : 14E4:43EC Broadcom BCM/CYW4356 WLAN +[uartB] Result : WLAN core enumerated on the PCIe bus +[ccplex] CPU0 stopped (held in reset) after 19402985 instructions, 4846717 bus accesses +``` + +A release with something missing does not run the core - silicon would not - +and says what was missing, e.g. `[ccplex] CPU0 released from reset but cannot +run: CPU rail off (MAX77621 VOUT_EN / MAX77620 GPIO5 EN pin)`. PCIe and +MSELECT answer CPU0 only; the BPMP reads all ones from them, as measured on +real consoles. Details in [DESIGN.md](DESIGN.md#ccplex-cpu0). + +## Tests + +```bash +make test # CCPLEX regression payload (needs arm-none-eabi-gcc) +tests/hwtest/build.sh build-hwtest # build hwtest-rcm (+ gcc-aarch64-linux-gnu) +tests/hwtest/run.sh ./rcm_emu build-hwtest/hwtest-rcm/build/hwtest.bin +``` + +The first boots CPU0 from a small self-contained payload and checks the +refusal of an unpowered release, the EL3 entry, the mailbox, WFE parking and +the reset. The second runs hwtest-rcm's whole hardware sweep headless and +checks that the CPU0-driven Wi-Fi probe enumerates the endpoint. CI runs both. + ## Live hardware tweaks Press `M` in the main window to open a second window that exposes the values @@ -232,7 +276,7 @@ needed. | `--prod-keys` | `prod.keys` | Override BIS keys from a Lockpick-style key file. | | `--oem` | `erista` \| `mariko` | Switch SoC generation. Drives `APB_MISC_GP_HIDREV` so Hekate's `h_cfg.t210b01` matches and pkg1 identification skips the right OEM header. Default `erista`. | | `--bt-radio` | `healthy` \| `faulty` \| `absent` | Broadcom CYW4356 behaviour on UART-D. `healthy` powers up on the `BT_REG_ON` edge, holds `BT_HOST_WAKE` high, asserts `RTS_N` and answers HCI; `faulty` reproduces the 2110-1118 console (module fitted, never leaves POR); `absent` additionally leaves `BT_UART_RXD` in a break condition. Overrides `[bluetooth] radio` in the ini. Default `healthy`. | -| `--wifi-radio` | `healthy` \| `faulty` \| `absent` | The WLAN half of the same CYW4356: a PCI Express endpoint on root port 1. `healthy` trains the link, enumerates as `14E4:43EC` and answers a ChipCommon ChipID read with `0x4356`; `faulty` still trains and enumerates but reads all ones on the backplane (live PCIe front-end, dead radio die); `absent` never leaves detect. The model also enforces the datasheet's power-up ordering, so a payload that releases PERST# too early gets a link that stays down and a `[pcie]` line naming the reason. Overrides `[wifi] radio` in the ini. Default `healthy`. | +| `--wifi-radio` | `healthy` \| `faulty` \| `absent` | The WLAN half of the same CYW4356: a PCI Express endpoint on root port 1, reachable only from CPU0 (the BPMP reads all ones, as on silicon). `healthy` trains the link, enumerates as `14E4:43EC` and answers a ChipCommon ChipID read with `0x4356`; `faulty` still trains and enumerates but reads all ones on the backplane (live PCIe front-end, dead radio die); `absent` never leaves detect. The model also enforces the datasheet's power-up ordering, so a payload that releases PERST# too early gets a link that stays down and a `[pcie]` line naming the reason. Overrides `[wifi] radio` in the ini. Default `healthy`. | | `--auto-pin-recovery` | (none) | Drive the Lockpick PIN-recovery menu without user input. | | `--auto-te-script` | (none) | Drive `recover_pin.te` in TegraExplorer without input. | @@ -244,9 +288,11 @@ flowchart LR root --> top["main.cpp
emu_state.h
Makefile
Dockerfile
README.md / DESIGN.md"] root --> t210["t210/
(SoC peripheral models)"] root --> display["display/"] + root --> tests["tests/
ccplex/, hwtest/"] - t210 --> mmio["mmio.{h,cpp}
memory_map.h
tegra_bl.h"] - t210 --> sdmmc["sdmmc.{h,cpp}
SDMMC1 / SDMMC4"] + t210 --> mmio["mmio.{h,cpp}
memory_map.h
regcache.h, tegra_bl.h"] + t210 --> cpus["bpmp.{h,cpp} BPMP clock
ccplex.{h,cpp} CPU0 (A57)"] + t210 --> pcie["pcie.{h,cpp}
root complex + CYW4356"] t210 --> se["se_engine.{h,cpp}
AES-128, SHA-256"] t210 --> i2c["i2c3.{h,cpp}
STMFTS / FTS4 touch"] @@ -257,8 +303,10 @@ For implementation details, see [DESIGN.md](DESIGN.md). ## Limitations -- **BPMP only.** Horizon and Atmosphère need A57 core emulation. This only - models the ARM7 bootloader environment. +- **BPMP plus one A57.** CPU0 runs bare-metal AArch64 handed to it by a + payload; there is no GIC, no generic timer, no secondary cores and no guest + exception delivery (a fault halts CPU0 and says so). Horizon and Atmosphère + are out of reach. - **Subset of MMIO (Memory-Mapped I/O).** Peripherals are modelled to the depth required by the payloads above. New payloads may exercise registers that fall through to the default catch-all and need handlers added. @@ -267,8 +315,8 @@ For implementation details, see [DESIGN.md](DESIGN.md). `--prod-keys` is a pragmatic shortcut: when Lockpick writes a derived BIS (Boot Image Storage) key into a keyslot, the value from the user-supplied key file is substituted. RSA, RNG, and chunked SHA are stubs. -- **Single-threaded.** The CPU runs in batches on the main thread between SDL - event polls. Tight host CPU loops will starve the display refresh. +- **Single-threaded.** Both cores run in batches on the main thread between + SDL event polls. That is also what keeps them deterministic. ## Acknowledgements diff --git a/tests/ccplex/link.ld b/tests/ccplex/link.ld new file mode 100644 index 0000000..bdc1203 --- /dev/null +++ b/tests/ccplex/link.ld @@ -0,0 +1,10 @@ +/* Loaded and entered at 0x40010000, like any RCM payload. */ +ENTRY(_start) +SECTIONS { + . = 0x40010000; + .text : { KEEP(*(.text.start)) *(.text*) } + .rodata : { *(.rodata*) } + .data : { *(.data*) } + .bss : { *(.bss*) *(COMMON) } + /DISCARD/ : { *(.comment) *(.note*) *(.ARM.attributes) *(.ARM.exidx*) } +} diff --git a/tests/ccplex/payload.c b/tests/ccplex/payload.c new file mode 100644 index 0000000..9afbddb --- /dev/null +++ b/tests/ccplex/payload.c @@ -0,0 +1,165 @@ +/* + * CCPLEX regression payload. + * + * A freestanding BPMP payload (ARM mode, loaded at 0x40010000 like any RCM + * payload) that drives the emulator's CPU0 model through the same register + * sequence as bdk's ccplex_boot_cpu0(), and reports what happened on UART-B. + * tests/ccplex/run.sh checks the emulator's log for the expected lines. + * + * 1. Release CPU0 from reset with nothing powered. The core must NOT run, + * and the emulator must say which precondition is missing. + * 2. Do the real bring-up - CPU rail (MAX77620 GPIO5 + MAX77621 VOUT on + * I2C5), CRAIL/C0NC/CE0 partitions, CPUG + MSELECT clocks, MSELECT out + * of reset, PLLX, RAM repair, SB_AA64_RESET_LOW - then release it. An + * AArch64 blob copied to DRAM records CurrentEL and a TIMERUS delta in + * a mailbox, writes a magic word last, and parks in WFE. + * 3. Put CPU0 back into reset and power the console off. + * + * Built by `make test` with arm-none-eabi-gcc; no other toolchain needed, as + * the AArch64 side is a handful of pre-assembled words. + */ + +typedef unsigned int u32; + +#define REG(a) (*(volatile u32 *)(a)) + +#define TIMERUS 0x60005010u +#define CAR 0x60006000u +#define FLOW 0x60007000u +#define SB 0x6000C200u +#define UARTB_THR 0x70006040u +#define PMC 0x7000E400u +#define I2C5 0x7000D000u + +#define CPU_ENTRY 0xA0000000u +#define MBOX 0xA0030000u +#define PCIE_MAGIC 0x50434945u + +/* AArch64, entered at EL3 with the MMU off: + * mov w1, #0xa0030000 ; mailbox + * mrs x8, currentel + * str w8, [x1, #4] ; [1] = CurrentEL + * mov w4, #0x5010 + * movk w4, #0x6000, lsl #16 ; TIMERUS + * ldr w5, [x4] + * mov w6, #2000 + * 1:subs w6, w6, #1 + * b.ne 1b + * ldr w7, [x4] + * sub w7, w7, w5 + * str w7, [x1, #8] ; [2] = TIMERUS delta across the loop + * mov w2, #0x4945 + * movk w2, #0x5043, lsl #16 + * str w2, [x1] ; [0] = 'PCIE', written last + * 2:wfe + * b 2b + */ +static const u32 cpu0_blob[] = { + 0x52b40061, 0xd5384248, 0xb9000428, 0x528a0204, 0x72ac0004, 0xb9400085, + 0x5280fa06, 0x710004c6, 0x54ffffe1, 0xb9400087, 0x4b0500e7, 0xb9000827, + 0x528928a2, 0x72aa0862, 0xb9000022, 0xd503205f, 0x17ffffff, +}; + +static void putc_(char c) { REG(UARTB_THR) = (u32)(unsigned char)c; } + +static void puts_(const char *s) { + while (*s) + putc_(*s++); +} + +static void puthex(u32 v) { + for (int i = 28; i >= 0; i -= 4) + putc_("0123456789ABCDEF"[(v >> i) & 0xF]); +} + +static void udelay(u32 us) { + u32 start = REG(TIMERUS); + while (REG(TIMERUS) - start < us) + ; +} + +/* bdk-style normal-mode I2C write: [reg, val] in CMD_DATA1, 2 bytes, GO. */ +static void i2c5_write(u32 dev, u32 reg, u32 val) { + REG(I2C5 + 0x04) = dev << 1; /* CMD_ADDR0 */ + REG(I2C5 + 0x0C) = reg | (val << 8); /* CMD_DATA1 */ + REG(I2C5 + 0x00) = (1u << 1) | (1u << 9); /* CNFG: 2 bytes, write, GO */ +} + +static void pwrgate_on(u32 part) { + if (!(REG(PMC + 0x38) & (1u << part))) /* PWRGATE_STATUS */ + REG(PMC + 0x30) = part | (1u << 8); /* PWRGATE_TOGGLE */ +} + +#define RST_CPU0 ((1u << 30) | (1u << 24) | (1u << 16) | (1u << 0)) +#define RST_NONCPU (1u << 29) + +static void release_cpu0(void) { + REG(SB + 0x30) = CPU_ENTRY | 1u; /* SB_AA64_RESET_LOW */ + REG(SB + 0x34) = 0; /* SB_AA64_RESET_HIGH */ + REG(CAR + 0x454) = RST_NONCPU; /* RST_CPUG_CMPLX_CLR */ + REG(CAR + 0x454) = RST_CPU0; +} + +static void hold_cpu0(void) { + REG(CAR + 0x450) = RST_CPU0; /* RST_CPUG_CMPLX_SET */ + REG(CAR + 0x450) = RST_NONCPU; +} + +__attribute__((section(".text.start"), noreturn)) +void _start(void) { + volatile u32 *mb = (volatile u32 *)MBOX; + + puts_("ccplex test: start\n"); + for (u32 i = 0; i < sizeof(cpu0_blob) / sizeof(cpu0_blob[0]); i++) + ((volatile u32 *)CPU_ENTRY)[i] = cpu0_blob[i]; + for (u32 i = 0; i < 4; i++) + mb[i] = 0; + + /* 1. Nothing powered: the release must be refused. */ + release_cpu0(); + udelay(2000); + puts_(mb[0] == PCIE_MAGIC ? "unpowered: CPU0 RAN (wrong)\n" + : "unpowered: CPU0 stayed dark\n"); + hold_cpu0(); + + /* 2. The real bring-up, in ccplex_boot_cpu0() order. */ + i2c5_write(0x3C, 0x40, 0x1C); /* MAX77620 AME_GPIO: GPIO5 plain */ + i2c5_write(0x3C, 0x3B, 0x09); /* GPIO5: push-pull, out high */ + i2c5_write(0x1B, 0x00, 0x80 | 55); /* MAX77621 VOUT: on, 0.950 V */ + REG(CAR + 0x0E0) = (1u << 30) | (2u << 20) | (156u << 8) | 2u; /* PLLX */ + REG(CAR + 0x3B4) = 4u << 1; /* CLK_SOURCE_MSELECT */ + REG(CAR + 0x440) = 1u << 3; /* CLK_ENB_V_SET: MSELECT */ + REG(CAR + 0x020) = 0x20008888; /* CCLK_BURST: PLLX_OUT0_LJ */ + REG(CAR + 0x024) = 1u << 31; /* SUPER_CCLK_DIVIDER */ + REG(CAR + 0x440) = 1u << 0; /* CLK_ENB_V_SET: CPUG */ + pwrgate_on(0); /* CRAIL */ + pwrgate_on(15); /* C0NC */ + pwrgate_on(14); /* CE0 */ + REG(FLOW + 0x40) = 1; /* RAM_REPAIR_REQ */ + while (!(REG(FLOW + 0x40) & 2)) + ; + REG(CAR + 0x434) = 1u << 3; /* RST_DEV_V_CLR: MSELECT */ + release_cpu0(); + + u32 start = REG(TIMERUS); + while (mb[0] != PCIE_MAGIC && REG(TIMERUS) - start < 100000) + udelay(100); + puts_("powered: magic="); + puthex(mb[0]); + puts_(" el="); + puthex(mb[1]); + puts_(" dt="); + puthex(mb[2]); + putc_('\n'); + + /* Let CPU0 sit in its WFE park for a while: it must cost next to + * nothing, which the retired-instruction count at reset shows. */ + udelay(50000); + + /* 3. Back into reset, then power off. */ + hold_cpu0(); + puts_("ccplex test: done\n"); + i2c5_write(0x3C, 0x41, 0x02); /* MAX77620 ONOFFCNFG1: PWR_OFF */ + for (;;) + ; +} diff --git a/tests/ccplex/run.sh b/tests/ccplex/run.sh new file mode 100755 index 0000000..809160d --- /dev/null +++ b/tests/ccplex/run.sh @@ -0,0 +1,50 @@ +#!/bin/sh +# CCPLEX regression test: boot CPU0 from a BPMP payload and check what the +# emulator and the payload report. Usage: tests/ccplex/run.sh [rcm_emu] [payload] +EMU=${1:-./rcm_emu} +PAYLOAD=${2:-tests/ccplex/payload.bin} +LOG=${LOG:-tests/ccplex/out.log} + +SDL_VIDEODRIVER=dummy RCM_EMU_NO_AUDIO=1 timeout 120 "$EMU" "$PAYLOAD" \ + > "$LOG" 2>&1 +status=$? + +fail=0 +expect() { + if grep -q -- "$1" "$LOG"; then + echo " ok $2" + else + echo " FAIL $2 (missing: $1)" + fail=1 + fi +} + +echo "ccplex test (emulator exit $status):" +expect 'cannot run: CPU rail off' 'an unpowered release is refused, with the reason' +expect 'unpowered: CPU0 stayed dark' 'and the core really did not execute' +expect 'CPU0 released: AArch64 EL3, MMU off, entry 0xA0000000' 'a powered release boots CPU0 at the SB vector' +expect 'powered: magic=50434945' 'CPU0 ran the blob and wrote the mailbox' +expect 'el=0000000C' 'CPU0 came up at EL3' +expect 'CPU0 stopped (held in reset)' 'RST_CPUG_CMPLX_SET stops the core' +expect 'MAX77620 PWR_OFF received' 'the payload ran to its power-off' + +# TIMERUS as CPU0 saw it must have moved across its busy loop. +dt=$(sed -n 's/.*dt=\([0-9A-F]*\).*/\1/p' "$LOG" | head -1) +if [ -n "$dt" ] && [ "$dt" != "00000000" ]; then + echo " ok CPU0 sees time advance (TIMERUS delta 0x$dt)" +else + echo " FAIL CPU0's TIMERUS delta is zero or missing" + fail=1 +fi + +# Parked in WFE for ~50 ms, the core must retire next to nothing: the park +# loop sleeps to the end of each slice instead of spinning. +retired=$(sed -n 's/.*CPU0 stopped (held in reset) after \([0-9]*\) instructions.*/\1/p' "$LOG" | head -1) +if [ -n "$retired" ] && [ "$retired" -lt 100000 ]; then + echo " ok WFE parks the core ($retired instructions retired in total)" +else + echo " FAIL WFE did not park the core (retired: ${retired:-?})" + fail=1 +fi + +[ $fail -eq 0 ] && echo "ccplex test: PASS" || { echo "ccplex test: FAIL - see $LOG"; exit 1; } diff --git a/tests/hwtest/build.sh b/tests/hwtest/build.sh new file mode 100755 index 0000000..4446907 --- /dev/null +++ b/tests/hwtest/build.sh @@ -0,0 +1,31 @@ +#!/bin/sh +# Build hwtest-rcm (https://github.com/Creased/hwtest-rcm) with distro +# toolchains, CPU0 stub included. Usage: tests/hwtest/build.sh +# Produces /hwtest-rcm/build/hwtest.bin. +# +# hwtest's Makefile only needs $(DEVKITARM)/base_rules to exist - it names +# arm-none-eabi-gcc itself - so an empty file stands in for devkitARM, and +# Debian/Ubuntu's gcc-aarch64-linux-gnu builds the AArch64 stub, which is +# what hwtest's own CI does too. +# +# Pinned so a change on the hwtest side cannot turn this emulator's CI red +# without a commit here; bump HWTEST_REF deliberately. +set -e +WORK=${1:-build-hwtest} +HWTEST_REF=${HWTEST_REF:-3738e9a47e1833605fc5a30eeca0ea95caa3b936} + +mkdir -p "$WORK" +cd "$WORK" +if [ ! -d hwtest-rcm/.git ]; then + git init -q hwtest-rcm + git -C hwtest-rcm remote add origin https://github.com/Creased/hwtest-rcm.git +fi +git -C hwtest-rcm fetch -q --depth 1 origin "$HWTEST_REF" +git -C hwtest-rcm checkout -q FETCH_HEAD +git -C hwtest-rcm submodule update -q --init --depth 1 third_party/hekate + +mkdir -p devkitARM +: > devkitARM/base_rules +make -C hwtest-rcm -j"$(nproc)" DEVKITARM="$PWD/devkitARM" \ + A64_CC=aarch64-linux-gnu-gcc A64_OC=aarch64-linux-gnu-objcopy REQUIRE_A64=1 +ls -l hwtest-rcm/build/hwtest.bin diff --git a/tests/hwtest/run.sh b/tests/hwtest/run.sh new file mode 100755 index 0000000..72bc66e --- /dev/null +++ b/tests/hwtest/run.sh @@ -0,0 +1,49 @@ +#!/bin/sh +# End-to-end: run hwtest's whole hardware sweep in the emulator, headless, +# and check the CPU0-driven PCIe probe enumerated the Wi-Fi endpoint. +# Usage: tests/hwtest/run.sh [extra emulator args...] +# +# hwtest sits in its pager once the sweep is dumped, so the run is ended as +# soon as the dump's last line appears (with a hard timeout behind it). +EMU=${1:-./rcm_emu} +BIN=${2:-build-hwtest/hwtest-rcm/build/hwtest.bin} +shift 2 2>/dev/null +LOG=${LOG:-tests/hwtest/out.log} +LIMIT=${LIMIT:-300} + +# POWER at 3 s picks "Hardware test" on hwtest's launcher. +SDL_VIDEODRIVER=dummy RCM_EMU_NO_AUDIO=1 "$EMU" "$BIN" --input-script "3000 P" "$@" \ + > "$LOG" 2>&1 & +pid=$! +t=0 +until grep -q 'end of dump' "$LOG" 2>/dev/null || ! kill -0 $pid 2>/dev/null; do + sleep 1 + t=$((t + 1)) + if [ $t -ge "$LIMIT" ]; then + echo "hwtest: no end of dump after ${LIMIT}s" + break + fi +done +kill $pid 2>/dev/null +wait $pid 2>/dev/null +echo "hwtest: sweep took ~${t}s of wall time" + +fail=0 +expect() { + if grep -q -- "$1" "$LOG"; then + echo " ok $2" + else + echo " FAIL $2 (missing: $1)" + fail=1 + fi +} +expect 'end of dump' 'the whole sweep ran to its end' +expect '\[ccplex\] CPU0 released: AArch64 EL3' 'hwtest booted CPU0' +expect 'CPU0 : ran to completion' 'the CPU0 stub ran to completion' +expect 'AFI (CPU) : cfg=00103025 witness=A5A50000 -> APERTURE LIVE' 'the PCIe aperture decodes for CPU0' +expect 'RP1 link : UP, DL active (LNKSTA=3011' 'root port 1 trained' +expect 'EP config : 14E4:43EC' 'the CYW4356 endpoint enumerated' +expect 'CPU0 : powergated' 'the cluster was powergated again' +expect 'Wireless : pass' 'the Wireless verdict passed' + +[ $fail -eq 0 ] && echo "hwtest: PASS" || { echo "hwtest: FAIL - see $LOG"; exit 1; } From 6753c5f3db6e1927879c568b07798d0ae67f9d32 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 17:45:02 +0000 Subject: [PATCH 03/21] Fix defects found in a code sweep and a TRM cross-check Security Engine: CTR ignored its input and returned the raw keystream; CBC encrypt skipped the IV on the first block and saved the wrong chaining value, so every CMAC over more than one block was wrong; OFB was broken. The datapath now follows INPUT_SEL/XOR_POS/VCTRAM_SEL the way bdk drives it, and matches OpenSSL for ECB, CBC, OFB, CTR and CMAC. SHA-256 works in parts (SHA_CONTINUE), SE_OP_CTX_SAVE reads keys back as se_aes_ctx_get_keys() expects, unwrap honours the word quad, guest block counts and LL sizes are bounded, and unreachable buffers end the op with an error. Soft reboot now resets the whole SoC (GPIO/pinmux cache, UARTs, I2C, PMC, CAR, flow controller, SE, touch, SDMMC, display, ACTMON, ...) while keeping what hardware keeps (PMC SCRATCH0, the RTC, and the PMIC unless the reboot is a power cycle). DRAM gets fresh zero pages instead of a memset that made all 2 GB resident; stale BPMP translations are dropped; CPSR returns to SVC; scripts restart. Execution: a branch to address 0 no longer hangs the emulator (until=0 made PC 0 an exit); bdk's reset-then-bpmp_halt() reboots instead of exiting; an untimed halt with CPU0 running parks the BPMP and lets CPU0 continue; CPU0 starts in the same batch it is released in; CPU0 drops translations of pages the BPMP rewrote; shared models no longer see time run backwards. TRM cross-check: RST_CPUG_CMPLX resets to 0x2000feef and CPU0 runs on CPURESET0/CORERESET0/L2RESET/NONCPURESET (bit names corrected); RAM repair clears REQ and sets STS, and is no longer a run condition; refused releases are re-evaluated; MSELECT ENABLE_PCIE_APERTURE gates PCIe; RST_DEVICES_W/Y direct writes land; DL_UP is read-only; the whole config aperture and memory window decode; OSC_CTRL reports 38.4 MHz; PLLE/PLLREFE no longer get bit 27 forced into a divider; PMC is a R/W register file; RTC SECONDS counts; FLOW halt modes follow 17.2.2 and STOP_UNTIL_IRQ wakes on the armed TMR; UART IIR/IER/ loopback MSR; I2C NOACK code and empty I2C4/I2C6 buses; pinmux reset values; the COP ACTMON counts halt time. Peripherals: MAX77620 LDO power-good follows the rail (hwtest's gamecard probe no longer fails), the Erista GPU MAX77621 answers at 0x1C, regulators ACK per generation, RTC CONTROL is binary/24h, PS3 card detect reads "slot empty", packet-mode I2C parses 4 bytes per word, rawnand I/O splits at part boundaries, eMMC returns to its user area on CMD0, ADMA2 descriptors decode per spec, SD CMD6/ACMD13 data reaches the programmed buffer, ERR_INTERRUPT is reported, R1 follows block commands. Frontend and tooling: touch events queue instead of overwriting each other, map through rotation overrides and bdk's edge offset, and use finger ID 0; a scripted press is always seen before its release; zeroed fuses persist in the ini; dropped UTF-8 paths open on Windows; bad --input-script is an error; test scripts check exit status and missing arguments; make_sd.py quotes names and picks a FAT32-valid cluster size; the Dockerfile marks the mount safe for git. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb --- DESIGN.md | 113 +++-- Dockerfile | 39 +- display/config_window.cpp | 7 +- display/sdl_display.cpp | 81 ++-- emu_state.h | 45 +- input_script.cpp | 13 + input_script.h | 4 + main.cpp | 157 +++++-- make_sd.py | 21 +- platform.cpp | 81 ++++ platform.h | 12 + t210/bpmp.cpp | 24 +- t210/bpmp.h | 6 + t210/ccplex.cpp | 126 +++++- t210/ccplex.h | 7 + t210/i2c3.cpp | 36 +- t210/i2c3.h | 4 + t210/memory_map.h | 22 +- t210/mmio.cpp | 861 +++++++++++++++++++++++++++----------- t210/mmio.h | 10 +- t210/pcie.cpp | 69 ++- t210/pcie.h | 19 +- t210/se_engine.cpp | 417 +++++++++++------- t210/se_engine.h | 19 +- tests/ccplex/run.sh | 6 + tests/hwtest/run.sh | 4 +- 26 files changed, 1615 insertions(+), 588 deletions(-) create mode 100644 platform.cpp 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} From 39bfad6a0b3b153c990017fc2a01d94ecc43b3a0 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 18:37:38 +0000 Subject: [PATCH 04/21] Model the SDMMC host registers, eMMC HS200 tuning and HS400 The SDHCI power, clock, reset and HOST_CONTROL2 registers and Tegra's vendor block all read 0, whatever was written. bdk picks the eMMC bus mode from them: POWER_CONTROL reading "off" made it fall back to HS52, so the eMMC ran at 51 MHz while its EXT_CSD claimed HS400. - Keep a register file per controller for 0x28-0x3F and 0x100-0x1FF, with the TRM reset values. INTERNAL_CLK_STABLE follows INT_CLK_EN, the SW_RESET bits self-clear (RESET_ALL resets the standard registers, RESET_CMD/RESET_DATA clear their line's status), and the pad auto-calibration and DLL calibration complete at once. - Model the tuning circuit (TRM 32.9.2.14). EXECUTE_TUNING starts it, each CMD19/CMD21 tries one tap against a fixed data eye, and after NUM_TUNING_ITERATIONS commands the final tap is set per MUL_M/DIV_N. The tuning block's BUFFER_READ_READY waits for the card clock to be re-enabled, which is the order bdk waits in. - Keep EXT_CSD as one array per power cycle. CMD6 SWITCH updates its writable bytes, CMD8 reads them back, and CMD0 resets the card fields. BOOT0/BOOT1 and RPMB are 4 MiB, as on a Switch. hwtest now tunes the eMMC in 128 iterations and reports a 199.68 MHz HS400 card clock. The hwtest check asserts both. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb --- DESIGN.md | 35 +++- t210/mmio.cpp | 441 +++++++++++++++++++++++++++++++++++++------- tests/hwtest/run.sh | 2 + 3 files changed, 410 insertions(+), 68 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 38f5fa7..237bee8 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -20,7 +20,7 @@ flowchart TB uc -->|MMIO callbacks| mmio["t210/mmio.cpp
mmio_bus_read / mmio_bus_write
shared by both masters"] - mmio --> sdmmc["sdmmc
SDMMC1 / SDMMC4
CMD0..18, EXT_CSD, ADMA2"] + mmio --> sdmmc["sdmmc
SDMMC1 / SDMMC4
CMD0..21, EXT_CSD, ADMA2
HS200 tuning, HS400"] mmio --> se["se_engine
AES-128, SHA-256
BIS keyslot override"] mmio --> i2c["i2c3
STMFTS / FTS4 touch"] mmio --> i2c1["I2C_1 slaves (inline)
MAX17050, TMP451,
BQ24193, BM92T36"] @@ -106,7 +106,7 @@ of the spec is modelled for the Hekate, Lockpick and TE init paths: - CMD0 GO_IDLE, CMD1 SEND_OP_COND, CMD2 ALL_SEND_CID, CMD3 SEND_RELATIVE_ADDR, CMD6 SWITCH, CMD7 SELECT_CARD, CMD8 SEND_EXT_CSD (eMMC) or SEND_IF_COND (SD), CMD9 SEND_CSD, CMD13 SEND_STATUS, CMD16 SET_BLOCKLEN, CMD17 and CMD18 - READ_(MULTI_)BLOCK, CMD55 APP_CMD. + READ_(MULTI_)BLOCK, CMD19 / CMD21 SEND_TUNING_BLOCK, CMD55 APP_CMD. - ADMA2 (Advanced DMA 2) with 64-bit descriptors, multi-block reads chunked into the host file IO via `pread`-style calls. - `--rawnand` opens the matching `rawnand.bin.NN` chunks and `fstat`s the first @@ -127,6 +127,37 @@ of the spec is modelled for the Hekate, Lockpick and TE init paths: sec_cnt) and writes it via the configured ADMA2 descriptor before raising the IRQ. +#### Host controller registers and HS400 + +Each controller keeps its SDHCI registers (0x28-0x3F: power, clock, software +reset, HOST_CONTROL2) and Tegra's vendor block (0x100-0x1FF) in a register +file with the TRM's reset values, plus the side effects bdk waits on: + +- CLOCK_CONTROL reports INTERNAL_CLK_STABLE once INT_CLK_EN is set. + SOFTWARE_RESET's bits self-clear. RESET_ALL puts the standard registers + back to reset and leaves the vendor block alone. +- AUTO_CAL_CONFIG.START and DLLCAL_CFG.CALIBRATE self-clear, and the status + registers report the calibration done. +- Setting HOST_CONTROL2.EXEC_TUNING starts tuning. Each CMD19/CMD21 tries one + tap: with TAP_VAL_UPDATED_BY_HW the taps step from TUNING_CNTRL0.START_TAP + by TUNING_CNTRL1's step size, otherwise the tap in VENDOR_CLOCK_CNTRL is + used. A tap passes when it falls in the modelled data eye, taps 26..82. + After NUM_TUNING_ITERATIONS commands EXEC_TUNING clears and TUNED_CLK is + set. The pass map lands in TUNING_STATUS0, and the chosen tap, first + + (last - first) x (MUL_M + 1) / 2^DIV_N (TRM 32.9.2.14), lands in + VENDOR_CLOCK_CNTRL. The tuning block's BUFFER_READ_READY is held until the + card clock is re-enabled, the order in which bdk's tuning loop waits. +- EXT_CSD is one 512-byte array that lives for a power cycle. CMD6 SWITCH + (write byte, set bits or clear bits) changes the bytes eMMC 5.1 makes + writable (BUS_WIDTH, HS_TIMING, PARTITION_CONFIG and a few more). CMD8 + returns the array and CMD0 puts the card-reset fields back. CARD_TYPE + advertises HS400 at 1.8 V, so bdk goes 8-bit, then HS200 (tuned), then + HS400, and reports a 199.68 MHz card clock. BOOT0, BOOT1 and RPMB are + 4 MiB each, as on a Switch. + +The SD card stays at High Speed (48 MHz). UHS-I needs ACMD41 to answer with +S18A and a CMD11 voltage switch, which the SD model does not do. + ### Security Engine (`t210/se_engine.cpp`) Models the SE (Security Engine) register block at `0x70012000`. Supports: diff --git a/t210/mmio.cpp b/t210/mmio.cpp index 8800743..1ca7eae 100644 --- a/t210/mmio.cpp +++ b/t210/mmio.cpp @@ -1690,6 +1690,355 @@ void dsi_write(EmuState *state, uint64_t addr, uint32_t val); // and the write path share one cursor. static uint32_t g_kfuse_keyaddr = 0; +// ---- SD host controller registers beyond the command model --------------- +// +// A byte-exact shadow of each controller's 512-byte register block, for what +// the command/data model below does not own: POWER_CONTROL, CLOCK_CONTROL, +// SW_RESET, the interrupt enables, HOST_CONTROL2 and the Tegra vendor block +// at 0x100..0x1FF (TRM 32.9.2). These all read 0 before, whatever was +// written - and bdk decides the eMMC bus mode from them: POWER_CONTROL +// reading "off" made _mmc_storage_enable_highspeed fall back to HS52, so the +// eMMC ran at 51 MHz while claiming HS400. HS200 then needs the tuning +// handshake, HS400 the tuned tap and a DLL calibration; all three are here. +struct SdhciRegs { + uint8_t b[0x200]; + // Hardware tuning (TRM 32.9.2.14): iteration count since EXECUTE_TUNING + // was set, the 256-bit per-iteration pass map, the best window found. + uint32_t tune_i; + uint32_t tune_map[8]; + uint8_t win_first, win_last; + // A tuning block sent with the card clock stopped, delivered when it runs. + bool tune_pending; +}; +static SdhciRegs sdhci_regs[2]; // [0] SDMMC1, [1] SDMMC4 + +// Trimmer taps at which the emulated eMMC's tuning block samples cleanly. +// At 200 MHz a unit interval is ~70 taps; a healthy part passes over most +// of one eye. Deterministic, so every run tunes to the same tap. +static constexpr uint32_t kTunePassFirst = 26, kTunePassLast = 82; + +static SdhciRegs &sdhci_of(uint32_t base) { + return sdhci_regs[base == SDMMC4_BASE ? 1 : 0]; +} +static uint32_t sdhci_get32(const SdhciRegs &r, uint32_t off) { + return (uint32_t)r.b[off] | ((uint32_t)r.b[off + 1] << 8) | + ((uint32_t)r.b[off + 2] << 16) | ((uint32_t)r.b[off + 3] << 24); +} +static void sdhci_put32(SdhciRegs &r, uint32_t off, uint32_t v) { + for (int i = 0; i < 4; i++) + r.b[off + i] = (uint8_t)(v >> (8 * i)); +} + +// Power-on state: the standard registers clear, the vendor block at its +// TRM reset values (the SDMMC2/4 set, which carries the DLL registers). +static void sdhci_reset_regs(SdhciRegs &r) { + memset(&r, 0, sizeof(r)); + static const struct { uint16_t off; uint32_t val; } kReset[] = { + {0x100, 0x0000D02D}, {0x104, 0x38600002}, {0x10C, 0x00000007}, + {0x11C, 0x00000C80}, {0x120, 0xFFFF0098}, {0x1AC, 0x00000015}, + {0x1B0, 0x16083504}, {0x1B4, 0x60000000}, {0x1B8, 0x20208780}, + {0x1BC, 0x10000000}, {0x1C0, 0x74020090}, {0x1C4, 0x00000023}, + {0x1D0, 0x0000000F}, {0x1D4, 0x00201000}, {0x1D8, 0x00100804}, + {0x1DC, 0x00000800}, {0x1E0, 0x88000001}, {0x1E4, 0x00010000}, + {0x1F8, 0x00000032}, + }; + for (const auto &e : kReset) + sdhci_put32(r, e.off, e.val); +} + +static bool sdhci_shadowed(uint32_t off) { + return (off >= 0x28 && off < 0x40) || (off >= 0x100 && off < 0x200); +} + +static uint8_t sdhci_byte(EmuState *s, uint32_t base, uint32_t off) { + if (off >= 0x200) + return 0; + SdhciRegs &r = sdhci_of(base); + bool e = base == SDMMC4_BASE; + uint32_t nor = e ? s->sdmmc4_norintsts : s->sdmmc_norintsts; + uint32_t err = e ? s->sdmmc4_errintsts : s->sdmmc_errintsts; + switch (off) { + case 0x28: + return e ? s->sdmmc4_hostctl : s->sdmmc_hostctl; + case 0x2C: { + // CLOCK_CONTROL: the internal clock is stable as soon as it is enabled. + uint8_t c = r.b[0x2C] & ~0x02; + return (c & 0x01) ? (uint8_t)(c | 0x02) : c; + } + case 0x2F: + return 0; // SW_RESET: completes at once + case 0x30: case 0x31: + // 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. + return (uint8_t)((nor | (err ? 0x8000u : 0u)) >> (8 * (off - 0x30))); + case 0x32: case 0x33: + return (uint8_t)(err >> (8 * (off - 0x32))); + case 0x3C: case 0x3D: + return 0; // AUTO_CMD_ERROR_STATUS + case 0x1B3: + return r.b[off] & 0x7F; // DLLCAL_CFG.CALIBRATE self-clears + case 0x1BF: + return r.b[off] & 0x7F; // DLLCAL_CFG_STA.ACTIVE: calibration done + case 0x1C8: case 0x1C9: case 0x1CA: case 0x1CB: { + // VENDOR_TUNING_STATUS0: the pass map word TUNING_WORD_SEL selects. + uint32_t w = r.tune_map[r.b[0x1C0] & 7]; + return (uint8_t)(w >> (8 * (off - 0x1C8))); + } + case 0x1CC: case 0x1CE: return r.win_first; // start, after / before fine + case 0x1CD: case 0x1CF: return r.win_last; // end, after / before fine + case 0x1E7: + return r.b[off] & 0x7F; // AUTO_CAL_CONFIG.START self-clears + case 0x1EC: + return 0x01; // AUTO_CAL_STATUS: done, pull-up code 1 + case 0x1ED: case 0x1EE: case 0x1EF: + return 0; // ...ACTIVE (bit 31) clear + default: + return r.b[off]; + } +} + +static uint32_t sdhci_read(EmuState *s, uint32_t base, uint32_t off) { + uint32_t v = 0; + for (int i = 3; i >= 0; i--) + v = (v << 8) | sdhci_byte(s, base, off + (uint32_t)i); + return v; +} + +// SW_RESET (0x2F). RESET_ALL puts the standard registers back to power-on +// and leaves the vendor block's trims alone; RESET_CMD / RESET_DATA clear +// the status their line owns (SDHCI 2.2.12). +static void sdhci_sw_reset(EmuState *s, uint32_t base, uint8_t v) { + bool e = base == SDMMC4_BASE; + uint32_t &nor = e ? s->sdmmc4_norintsts : s->sdmmc_norintsts; + uint32_t &err = e ? s->sdmmc4_errintsts : s->sdmmc_errintsts; + if (v & 0x01) { + SdhciRegs &r = sdhci_of(base); + uint8_t vendor[0x100]; + memcpy(vendor, r.b + 0x100, sizeof(vendor)); // vendor block survives + sdhci_reset_regs(r); + memcpy(r.b + 0x100, vendor, sizeof(vendor)); + nor = err = 0; + (e ? s->sdmmc4_hostctl : s->sdmmc_hostctl) = 0; + return; + } + if (v & 0x02) { // CMD line: command complete, CMD errors + nor &= ~0x0001u; + err &= ~0x000Fu; + } + if (v & 0x04) { // DAT line: transfer/DMA/buffer, DAT errors + nor &= ~0x003Eu; + err &= ~0x0270u; + } +} + +// A tuning block arriving: BUFFER_READ_READY. +static void sdhci_deliver_tuning_block(EmuState *s, uint32_t base) { + (base == SDMMC4_BASE ? s->sdmmc4_norintsts : s->sdmmc_norintsts) |= 0x0020; +} + +static void sdhci_write(EmuState *s, uint32_t base, uint32_t offset, + uint64_t value, int size) { + SdhciRegs &r = sdhci_of(base); + for (int i = 0; i < size; i++) { + uint32_t off = offset + (uint32_t)i; + if (off >= 0x200) + break; + uint8_t v = (uint8_t)(value >> (8 * i)); + switch (off) { + case 0x28: // HOST_CONTROL: command model + case 0x30: case 0x31: case 0x32: case 0x33: // W1C status: command model + case 0x3C: case 0x3D: // read-only + case 0x1BC: case 0x1BD: case 0x1BE: case 0x1BF: + case 0x1C8: case 0x1C9: case 0x1CA: case 0x1CB: + case 0x1CC: case 0x1CD: case 0x1CE: case 0x1CF: + case 0x1EC: case 0x1ED: case 0x1EE: case 0x1EF: + break; + case 0x2C: { + bool was_on = r.b[0x2C] & 0x04; + r.b[0x2C] = v; + // Tegra sends a tuning command with SD_CLK stopped, resets CMD/DAT, + // then restarts the clock: the block comes in now. + if (!was_on && (v & 0x04) && r.tune_pending) { + r.tune_pending = false; + sdhci_deliver_tuning_block(s, base); + } + break; + } + case 0x2F: + sdhci_sw_reset(s, base, v); + break; + case 0x3E: { + // HOST_CONTROL2 low byte. EXECUTE_TUNING (bit 6) belongs to the + // hardware once set: writing 1 starts tuning - clearing the sampling + // clock select and the pass map - and only the tuning circuit clears + // it again. SAMPLING_CLOCK_SELECT (bit 7) takes what is written. + uint8_t cur = r.b[0x3E]; + uint8_t nv = (uint8_t)((v & ~0x40) | (cur & 0x40)); + if ((v & 0x40) && !(cur & 0x40)) { + nv = (uint8_t)((nv | 0x40) & ~0x80); + r.tune_i = 0; + memset(r.tune_map, 0, sizeof(r.tune_map)); + r.win_first = r.win_last = 0; + } + r.b[0x3E] = nv; + break; + } + default: + r.b[off] = v; + break; + } + } +} + +// SEND_TUNING_BLOCK (CMD19 SD, CMD21 eMMC HS200) with the Tegra tuning +// circuit (TRM 32.9.2.14). With EXECUTE_TUNING set each block is one +// iteration at the next trimmer tap - START_TAP_VAL plus 2^STEP_SIZE per +// iteration when TAP_VAL_UPDATED_BY_HW is set, the programmed tap +// otherwise - and SAMPLING_CLOCK_SELECT reports whether it sampled +// cleanly. After NUM_TUNING_ITERATIONS blocks the circuit clears +// EXECUTE_TUNING; in hardware-tap mode it then sets the final tap +// first_pass + (last_pass - first_pass) * (MUL_M + 1) / 2^DIV_N and +// leaves SAMPLING_CLOCK_SELECT set if any tap passed. +static void sdhci_tuning_command(EmuState *s, uint32_t base) { + SdhciRegs &r = sdhci_of(base); + if (r.b[0x3E] & 0x40) { + static const uint16_t kTries[8] = {40, 64, 128, 192, 256, 256, 256, 256}; + uint32_t tun0 = sdhci_get32(r, 0x1C0), tun1 = sdhci_get32(r, 0x1C4); + bool hw_tap = tun0 & (1u << 17); + uint32_t tries = kTries[(tun0 >> 13) & 7]; + bool sdr50 = (r.b[0x3E] & 0x07) == 2; + uint32_t step = 1u << (sdr50 ? (tun1 & 7) : ((tun1 >> 4) & 7)); + uint32_t clk = sdhci_get32(r, 0x100); + uint32_t i = r.tune_i; + uint32_t tap = hw_tap ? ((((tun0 >> 18) & 0xFF) + i * step) & 0xFF) + : ((clk >> 16) & 0xFF); + bool pass = tap >= kTunePassFirst && tap <= kTunePassLast; + if (i < 256 && pass) + r.tune_map[i / 32] |= 1u << (i % 32); + if (hw_tap) + sdhci_put32(r, 0x100, (clk & ~0x00FF0000u) | (tap << 16)); + r.b[0x3E] = (uint8_t)((r.b[0x3E] & ~0x80) | (pass ? 0x80 : 0)); + r.tune_i = i + 1; + if (r.tune_i >= tries) { + r.b[0x3E] &= ~0x40; // tuning complete + if (hw_tap) { + int first = -1, last = -1; + uint32_t start = (tun0 >> 18) & 0xFF; + for (uint32_t k = 0; k < tries && k < 256; k++) { + if (!(r.tune_map[k / 32] & (1u << (k % 32)))) + continue; + uint32_t t = (start + k * step) & 0xFF; + if (first < 0) + first = (int)t; + last = (int)t; + } + if (first >= 0) { + uint32_t m = (tun0 >> 6) & 0x7F, n = (tun0 >> 3) & 7; + uint32_t fin = (uint32_t)first + + (((uint32_t)(last - first) * (m + 1)) >> n); + if (fin > (uint32_t)last) + fin = (uint32_t)last; + clk = sdhci_get32(r, 0x100); + sdhci_put32(r, 0x100, (clk & ~0x00FF0000u) | ((fin & 0xFF) << 16)); + r.win_first = (uint8_t)first; + r.win_last = (uint8_t)last; + r.b[0x3E] |= 0x80; + printf("[sdmmc] SDMMC%c tuned: %u iterations, pass window taps " + "%d..%d, tap %u\n", base == SDMMC4_BASE ? '4' : '1', + tries, first, last, fin & 0xFF); + } else { + r.b[0x3E] &= ~0x80; + printf("[sdmmc] SDMMC%c tuning failed: no tap passed\n", + base == SDMMC4_BASE ? '4' : '1'); + } + fflush(stdout); + } + } + } + if (r.b[0x2C] & 0x04) + sdhci_deliver_tuning_block(s, base); + else + r.tune_pending = true; +} + +// ---- The eMMC's EXT_CSD ----------------------------------------------------- +// +// The properties segment is fixed; the fields CMD6 SWITCH writes (bus +// width, HS_TIMING, partition access, ...) keep what was written until the +// card is reset, so a CMD8 after the bus-mode switches reads them back. +static uint8_t g_ext_csd[512]; +static bool g_ext_csd_ready = false; + +static uint8_t *emmc_ext_csd() { + if (g_ext_csd_ready) + return g_ext_csd; + g_ext_csd_ready = true; + uint8_t *x = g_ext_csd; + memset(x, 0, 512); + x[192] = 7; // EXT_CSD_REV: eMMC v5.0 + x[196] = 0x57; // CARD_TYPE: HS400_1.8V | HS200_1.8V | DDR_1.8V | HS_52 | HS_26 + // 32GB worth of sectors (BDK only uses sec_cnt for sanity, not for read + // addressing). + uint32_t sec_cnt = 64 * 1024 * 1024; + x[212] = sec_cnt & 0xFF; + x[213] = (sec_cnt >> 8) & 0xFF; + x[214] = (sec_cnt >> 16) & 0xFF; + x[215] = (sec_cnt >> 24) & 0xFF; + // BOOT0/BOOT1 and RPMB are 4 MiB each on the Switch's eMMC: 32 x 128 KiB. + x[226] = 32; // BOOT_SIZE_MULT + x[168] = 32; // RPMB_SIZE_MULT + // Capability/health bytes a diagnostic payload reports on. Values + // measured from the eMMC in a real Mariko; left at 0 these read as + // "feature not supported", which looks like a reduced-firmware + // replacement part. + x[503] = 0x01; // HPI_FEATURES: supported, CMD13 variant + x[231] = 0x55; // SEC_FEATURE_SUPPORT: secure erase/trim/sanitize + x[232] = 0x02; // TRIM_MULT + x[229] = 0x11; // SEC_TRIM_MULT (measured) + x[162] = 0x01; // RST_N_FUNCTION: permanently enabled + x[267] = 0x01; // PRE_EOL_INFO: normal + x[268] = 0x01; // DEVICE_LIFE_TIME_EST_TYP_A: 0-10% + x[269] = 0x01; // DEVICE_LIFE_TIME_EST_TYP_B: 0-10% + return x; +} + +// CMD0 / power-on: back to 1-bit legacy timing, in the user area. +static void emmc_ext_csd_card_reset() { + uint8_t *x = emmc_ext_csd(); + x[183] = 0; // BUS_WIDTH + x[185] = 0; // HS_TIMING + x[179] &= ~0x07; // PARTITION_ACCESS +} + +// CMD6 SWITCH, access modes 1 = set bits, 2 = clear bits, 3 = write byte, +// to the fields a host may change. +static void emmc_ext_csd_switch(uint32_t arg) { + uint32_t access = (arg >> 24) & 3, index = (arg >> 16) & 0xFF; + uint8_t value = (uint8_t)(arg >> 8); + switch (index) { + case 33: // CACHE_CTRL + case 34: // POWER_OFF_NOTIFICATION + case 161: // HPI_MGMT + case 163: // BKOPS_EN + case 175: // ERASE_GROUP_DEF + case 177: // BOOT_BUS_CONDITIONS + case 179: // PARTITION_CONFIG + case 183: // BUS_WIDTH + case 185: // HS_TIMING + case 187: // POWER_CLASS + break; + default: + return; + } + uint8_t *x = emmc_ext_csd(); + if (access == 1) + x[index] |= value; + else if (access == 2) + x[index] &= (uint8_t)~value; + else if (access == 3) + x[index] = value; +} + uint32_t misc_read(EmuState *state, uint64_t addr) { // PINMUX (APB_MISC pad config range) — every write lands in the global // mmio_regs map at line 1726, so we just hand it back. Returning 0 here @@ -1878,8 +2227,6 @@ uint32_t misc_read(EmuState *state, uint64_t addr) { uint32_t *rsp = (base == SDMMC4_BASE) ? state->sdmmc4_rsp : state->sdmmc_rsp; - uint32_t &norintsts = (base == SDMMC4_BASE) ? state->sdmmc4_norintsts - : state->sdmmc_norintsts; uint16_t blksize = (base == SDMMC4_BASE) ? state->sdmmc4_blksize : state->sdmmc_blksize; uint16_t blkcnt = @@ -1888,7 +2235,9 @@ uint32_t misc_read(EmuState *state, uint64_t addr) { (base == SDMMC4_BASE) ? state->sdmmc4_trnmod : state->sdmmc_trnmod; uint32_t result = 0; - if (offset == 0x00) + if (sdhci_shadowed(offset)) + result = sdhci_read(state, base, offset); + else if (offset == 0x00) result = (base == SDMMC4_BASE) ? state->sdmmc4_sysad : state->sdmmc_sysad; else if (offset == 0x04) result = (blkcnt << 16) | blksize; @@ -1909,36 +2258,13 @@ uint32_t misc_read(EmuState *state, uint64_t addr) { else result = 0x01F70000; // CARD_PRESENT | CD_STABLE | CD_LVL | DAT_LINE_LEVEL } - else if (offset == 0x28) { - // HOSTCTL. sdmmc_get_bus_width() reads this register directly to decide - // 1 / 4 / 8-bit (SDHCI_CTRL_4BITBUS = BIT(1), SDHCI_CTRL_8BITBUS = - // BIT(5)). It had no read handler at all, so every payload saw a 1-bit - // bus even after a successful 4-bit SD / 8-bit eMMC negotiation - and an - // eMMC HS400-vs-bus-width cross-check would call that a fault. - result = (base == SDMMC4_BASE) ? state->sdmmc4_hostctl - : state->sdmmc_hostctl; - } - else if (offset == 0x2C) - result = 0x0003; // SDHCI_CLOCK_INT_EN | SDHCI_CLOCK_INT_STABLE else if (offset == 0x40) result = 0x376CD08C; // Full Tegra capabilities (64-bit, SDMA, ADMA2, etc.) else if (offset == 0x44) result = 0x10002F73; // CAP1 - 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; else if (offset >= 0x10 && offset <= 0x1C) result = rsp[(offset - 0x10) / 4]; - else if (offset == 0x1EC) - result = 0x00000001; // AUTOCAL_STS else if (offset == 0xFE) result = 0x0303; // SDHCI Version 4.0 @@ -2010,20 +2336,14 @@ void misc_write(uc_engine *uc, EmuState *state, uint64_t addr, int64_t value, uint64_t &adma_addr = (base == SDMMC4_BASE) ? state->sdmmc4_adma_addr : state->sdmmc_adma_addr; + if (sdhci_shadowed(offset)) + sdhci_write(state, base, offset, value, size); if (offset == 0x00) sysad = val; if (offset == 0x28) // 0x3E, not 0x1E: the old mask dropped SDHCI_CTRL_8BITBUS (BIT(5)), so // an eMMC 8-bit bus could never be represented. hostctl = val & 0x3E; - if (offset == 0x2F) { - // Software Reset. Clear immediately to signify completion. - mmio_regs[base + 0x2C] &= ~(val << 24); - } - if (offset == 0x2C && size == 4) { - // If reset bits were set in 4-byte write, clear them for subsequent reads - mmio_regs[base + 0x2C] &= ~0x07000000; - } if (offset == 0x04) { if (size == 4) { blksize = val & 0x0FFF; @@ -2093,8 +2413,15 @@ void misc_write(uc_engine *uc, EmuState *state, uint64_t addr, int64_t value, // 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) + if (base == SDMMC4_BASE) { state->emmc_partition = 0; + emmc_ext_csd_card_reset(); + } + break; + case 19: // SD SEND_TUNING_BLOCK + case 21: // eMMC SEND_TUNING_BLOCK_HS200 + sdhci_tuning_command(state, base); + rsp[0] = r1_base | (4 << 9) | (1u << 8); break; case 8: rsp[0] = (base == SDMMC4_BASE) ? 0x00000900 : arg; @@ -2103,33 +2430,7 @@ void misc_write(uc_engine *uc, EmuState *state, uint64_t addr, int64_t value, // bails with storage->initialized = 0 — which silently breaks all // later sdmmc_storage_read calls (returns 0 without issuing CMD18). if (base == SDMMC4_BASE) { - uint8_t ext_csd[512] = {0}; - // Set a few fields BDK actually parses (most others can be 0): - // EXT_CSD_REV = 192 (offset 192) - // EXT_CSD_CARD_TYPE = 196 (HS-52 + HS200 + HS400 supported) - // EXT_CSD_SEC_CNT = 212..215 (sector count, little-endian u32) - ext_csd[192] = 7; // eMMC v5.0 - ext_csd[196] = 0x57; // HS400_1.8V | HS200_1.8V | HS_52 | HS_DDR - // 32GB worth of sectors (0x3A380000 = 977MB; for the user's actual - // dump size we'd want the real value, but BDK only uses sec_cnt for - // sanity, not for read addressing). - uint32_t sec_cnt = 64 * 1024 * 1024; // 32GB / 512B = 64M sectors - ext_csd[212] = sec_cnt & 0xFF; - ext_csd[213] = (sec_cnt >> 8) & 0xFF; - ext_csd[214] = (sec_cnt >> 16) & 0xFF; - ext_csd[215] = (sec_cnt >> 24) & 0xFF; - // Capability/health bytes a diagnostic payload reports on. Values - // measured from the eMMC in a real Mariko; left at 0 these read as - // "feature not supported", which looks like a reduced-firmware - // replacement part. - ext_csd[503] = 0x01; // HPI_FEATURES: supported, CMD13 variant - ext_csd[231] = 0x55; // SEC_FEATURE_SUPPORT: secure erase/trim/sanitize - ext_csd[232] = 0x02; // TRIM_MULT - ext_csd[229] = 0x11; // SEC_TRIM_MULT (measured) - ext_csd[162] = 0x01; // RST_N_FUNCTION: permanently enabled - ext_csd[267] = 0x01; // PRE_EOL_INFO: normal - ext_csd[268] = 0x01; // DEVICE_LIFE_TIME_EST_TYP_A: 0-10% - ext_csd[269] = 0x01; // DEVICE_LIFE_TIME_EST_TYP_B: 0-10% + const uint8_t *ext_csd = emmc_ext_csd(); uint64_t dma_addr = 0; // Tegra's SDMMC uses register 0x58 as the SDMA system-address @@ -2278,10 +2579,9 @@ void misc_write(uc_engine *uc, EmuState *state, uint64_t addr, int64_t value, rsp[0] = r1_base | (4 << 9); } else if (base == SDMMC4_BASE) { // CMD6: SWITCH (eMMC) - uint8_t index = (arg >> 16) & 0xFF; - uint8_t val = (arg >> 8) & 0xFF; - if (index == 179) { // PARTITION_CONFIG - state->emmc_partition = val & 0x7; + emmc_ext_csd_switch(arg); + if (((arg >> 16) & 0xFF) == 179) { // PARTITION_CONFIG + state->emmc_partition = emmc_ext_csd()[179] & 0x7; TRACE("[sdmmc] eMMC Partition Switch: %u\n", state->emmc_partition); } @@ -4214,6 +4514,8 @@ void mmio_init(uc_engine *uc, EmuState *state) { mmio_map_bus(uc, state); pcie_reset(state); ccplex_reset(state); + sdhci_reset_regs(sdhci_regs[0]); + sdhci_reset_regs(sdhci_regs[1]); uc_hook_add(uc, &h_unmapped, UC_HOOK_MEM_READ_UNMAPPED | UC_HOOK_MEM_WRITE_UNMAPPED, @@ -4307,6 +4609,12 @@ void mmio_soft_reset(EmuState *state, bool power_cycle) { state->sdmmc4_adma_addr = 0; state->emmc_partition = 0; state->last_cmd_was_55 = state->last_cmd4_was_55 = false; + sdhci_reset_regs(sdhci_regs[0]); + sdhci_reset_regs(sdhci_regs[1]); + if (power_cycle) + g_ext_csd_ready = false; + else + emmc_ext_csd_card_reset(); // Display controller back to its defaults (emu_state.h). state->pre_addr = 0; @@ -4325,5 +4633,6 @@ void mmio_soft_reset(EmuState *state, bool power_cycle) { state->winA_stride = 2880; state->winA_sw = state->winA_rot = state->winA_bh = 0; + state->bpmp_halted = false; } diff --git a/tests/hwtest/run.sh b/tests/hwtest/run.sh index e30fc9d..fb202a7 100755 --- a/tests/hwtest/run.sh +++ b/tests/hwtest/run.sh @@ -47,5 +47,7 @@ expect 'RP1 link : UP, DL active (LNKSTA=3011' 'root port 1 trained' expect 'EP config : 14E4:43EC' 'the CYW4356 endpoint enumerated' expect 'CPU0 : powergated' 'the cluster was powergated again' expect 'Wireless : pass' 'the Wireless verdict passed' +expect '\[sdmmc\] SDMMC4 tuned: 128 iterations' 'the eMMC passed HS200 tuning' +expect 'card_clock : 199.68 MHz' 'the eMMC runs at HS400 speed' [ $fail -eq 0 ] && echo "hwtest: PASS" || { echo "hwtest: FAIL - see $LOG"; exit 1; } From e32052ffd57f40773c84e20981500b142d3f7fad Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 18:40:26 +0000 Subject: [PATCH 05/21] Model the DC windows and VIC compose, and scan out what they describe The display model took each window's line stride from PRESCALED_SIZE rather than LINE_STRIDE, and kept one set of window parameters for all four windows, so window D's 656-pixel log window leaked into window A. Its block-linear decoder also had two GOB address bits swapped. The mock VIC only memcpy'd, so Nyx's rotated frame never existed. The renderer papered over all of this with per-address heuristics: a "known menu stride" of 2624, forced block-linear decoding of the IPL carveout, and a hard-coded 1280x720 geometry for Nyx's framebuffer. - DC: a register file per window (A-D), reached through the indirect pages per DISPLAY_WINDOW_HEADER or the A/B/C direct ranges. Writes land in the assembly copy, and WIN_x_ACT_REQ promotes it to the active copy the scan-out reads. Other DC registers read back what was written. STATE_CONTROL reads 0, and INT_STATUS reports frame end and vblank, which bdk polls before DSI commands. - VIC: on COMPOSE_START, read bdk's vic_config_t from guest memory and draw the enabled pitch slots into the target, with scaling, clipping and the output flip/transpose. Nyx's 270-degree rotation now happens. - Scan-out: fetch each enabled window per SURFACE_KIND (pitch, tiled or block linear, per TRM 20.1.2 Figure 47), LINE_STRIDE and COLOR_DEPTH, turn it per WIN_OPTIONS (H/V direction, SCAN_COLUMN), scale it from PRESCALED_SIZE to SIZE, place it at POSITION, and stack and blend the windows by depth and BLEND_*. When the surface on show was turned on its way to the panel, by the DC or by VIC, the view undoes the turn, so Nyx still shows landscape. All the heuristics are gone. hwtest's frame and Nyx's home screen are pixel-identical to before. Nyx's error console (window D over window A) now shows; before, it was invisible. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb --- DESIGN.md | 96 ++++-- README.md | 2 +- display/sdl_display.cpp | 704 ++++++++++++++++++++++------------------ emu_state.h | 67 +++- main.cpp | 2 - t210/mmio.cpp | 467 +++++++++++++++----------- 6 files changed, 795 insertions(+), 543 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 237bee8..37074ed 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -14,7 +14,7 @@ flowchart TB main -->|ccplex_run| a57["t210/ccplex
2nd Unicorn engine, AArch64
CCPLEX CPU0 (Cortex-A57)"] a57 -->|MMIO callbacks| mmio a57 -.->|shares| uc - main -->|sdl_display_*| sdl["display/sdl_display
block-linear de-swizzle
rotate, blit"] + main -->|sdl_display_*| sdl["display/sdl_display
DC window scan-out
blend, turn, blit"] main -->|config_window_*| cfg["display/config_window
2nd SDL window + ImGui
live hardware tweaks"] main -->|console_window_*| con["display/console_window
3rd SDL window + ImGui
per-port UART TX log + RX inject"] @@ -25,7 +25,8 @@ flowchart TB mmio --> i2c["i2c3
STMFTS / FTS4 touch"] mmio --> i2c1["I2C_1 slaves (inline)
MAX17050, TMP451,
BQ24193, BM92T36"] mmio --> i2c5["I2C_5 slaves (inline)
MAX77620, MAX77621"] - mmio --> stubs["inline stubs
GPIO, PMC, TSEC, KFUSE,
PWM, DC, CLK, TMR, FUSE, UART"] + mmio --> dc["DC + VIC (inline)
window registers A-D
VIC compose, flip/transpose"] + mmio --> stubs["inline stubs
GPIO, PMC, TSEC, KFUSE,
PWM, CLK, TMR, FUSE, UART"] mmio --> pcie["pcie
AFI, root ports, CYW4356
(CPU-complex master only)"] cfg -.->|writes atomics| state["EmuState
(emu_state.h)"] @@ -58,11 +59,13 @@ same peripheral models through one dispatch (see [CCPLEX CPU0](#ccplex-cpu0)). 2. PC is set to `0x40010000`, SP to `IPL_STACK_ADDR`. CPSR enters ARM mode. 3. The IPL (Initial Program Loader) initialises clocks, fuses and the display, then continues straight into the boot menu without loading LP0 or Minerva. -4. Hekate self-relocates into DRAM (`0xC0000000+`) and continues. The display - pipeline resamples its DRAM-side framebuffer parameters. -5. Nyx (the LVGL graphics stack) initialises and draws into a separate FB. The - DC (Display Controller) `WINDOW_HEADER` register tracks the currently - primary surface. The display code follows that pointer. +4. Hekate self-relocates into DRAM (`0xC0000000+`) and continues. It points + DC (Display Controller) window A at its portrait framebuffer and draws its + boot logo and menus there, sideways, for the landscape-mounted panel. +5. Nyx (the LVGL GUI) draws landscape into a second framebuffer and has VIC + turn every frame into the portrait surface that window A scans out. The + display follows the DC's windows, whatever they point at (see Display + pipeline). ## Memory map @@ -326,25 +329,61 @@ do not auto-creep into the build. ### Display pipeline (`display/sdl_display.cpp`) -Hekate and Nyx draw into a block-linear surface. One block-height row covers -16 GOBs (Group Of Bytes, NVIDIA's 64 by 8 pixel tile). The display thread: +The display controller is modelled as the registers of its four windows, +A-D (TRM 24.10-24.11), in `t210/mmio.cpp`. Payloads reach a window through +the indirect window pages (0x700-0x83F), which write every window +`DC_CMD_DISPLAY_WINDOW_HEADER` selects, or through a window's direct range +(A 0xB80, B 0xD80, C 0xF80). Writes land in the window's assembly copy, and +`WIN_x_ACT_REQ` in `DC_CMD_STATE_CONTROL` copies that into the active copy, +so a half-programmed window never shows. Reads return what was written. +`STATE_CONTROL` reads 0 (every request has completed), and `INT_STATUS` +reports a frame end and a vblank, which bdk polls before DSI commands. -1. Reads DC `WINDOW_HEADER` to follow the active surface (Window A, B, C or - D). -2. Looks up the FB pointer, stride and GOB block height latched from - `DC_WIN_x_SURFACE_KIND`. -3. De-swizzles into a linear RGBA buffer using a per-pixel address calc. -4. Optionally rotates 0, 90, 180 or 270 degrees to match the panel orientation - detected from window dimensions, with an `R` or `Shift+R` manual override. -5. Blits to an SDL_Texture at the host window current size. +Each display tick builds the picture the panel would receive, 720x1280 and +portrait, the way the DC builds it: -The de-swizzle is the hottest path. It is inlined and operates on `u32` -units. The surface is read straight from the host memory behind emulated DRAM, -and a frame whose bytes and layout `(addr, w, h, stride, sw, bh, rot)` match -the previous one skips the de-swizzle and the texture upload entirely. No -renderer uses `PRESENTVSYNC`: the CPU runs on the same thread, the loop -already paces redraws to ~60 Hz, and a vsync'd present could stall the -emulated CPU for a whole frame. +1. Every enabled window's surface is fetched at `START_ADDR`. The layout + comes from `SURFACE_KIND`: pitch, 16x16 tiled, or block linear with + 2^`BLOCK_HEIGHT` GOBs (Groups of Bytes, 64x8-byte tiles) per block. The + line pitch is `LINE_STRIDE`, and pixels are decoded per `COLOR_DEPTH`. + Block-linear byte order follows TRM 20.1.2 and Figure 47. +2. `WIN_OPTIONS` turns the surface: H_DIRECTION and V_DIRECTION mirror it, + and SCAN_COLUMN walks its columns (90/270 degrees, TRM Table 122). The + result is scaled from `PRESCALED_SIZE` to `SIZE`, nearest-neighbour, and + placed at `POSITION`. +3. The windows are stacked by layer depth (A under D when equal) and blended + per `BLEND_LAYER_CONTROL` and `BLEND_MATCH_SELECT`. Hekate's log console + (window D, K1 = 200) shows through as it does on the console. + +The panel picture is then turned for the host window. When the surface on +show was turned on its way to the panel, by the DC (SCAN_COLUMN) or by a +VIC compose (Nyx), the turn is undone. A GUI drawn landscape is then shown +landscape. A surface drawn straight into portrait (hekate's logo and TUI, +hwtest) is shown as the panel receives it. `Ctrl+R` / `Ctrl+Shift+R` +override the turn, and `S` forces pitch or block-linear decoding for +diagnosis. Until +the payload first activates a window, the emulator's own framebuffer at +`FB_BASE` stands in as window A. + +A frame whose surfaces' bytes and layout match the previous frame skips the +rebuild and the texture upload. Surfaces are read straight from the host +memory behind emulated DRAM. No renderer uses `PRESENTVSYNC`: the CPU runs +on the same thread, the loop already paces redraws to ~60 Hz, and a vsync'd +present could stall the emulated CPU for a whole frame. + +### VIC (`t210/mmio.cpp`) + +bdk drives VIC through the Falcon private-register window. The model keeps +the config struct's address (`VIC_SC_PRAMBASE`), the slots' source surfaces +(`VIC_SC_SFC0_BASE_LUMA(n)`) and the target (`VIC_BL_TARGET_BASADR`). On +`VIC_FC_COMPOSE` it reads bdk's `vic_config_t` from guest memory and draws +every enabled pitch slot into the target, scaling the source rect onto the +dest rect, clipped to the target rect, with the output flip X, flip Y and +transpose applied. The output size is given before the transpose, so a +transposed target is H x W pixels, which is how the DC then reads it. The +compose also records the target address and the turn applied, which the +display uses to undo it. Nyx's 270-degree rotation is flip X then transpose. +Block-linear VIC surfaces are not modelled, and nothing in bdk uses them. ### UART @@ -585,6 +624,15 @@ don't repeat the diagnosis: Now `fstat`-derived from `rawnand.bin.00`. - **Save header SHA-256** rejected by TE because the SE only modelled AES. Hence the SHA-256 path in `se_engine.cpp`. +- **Display stride and window state.** The DC model took the line stride + from `PRESCALED_SIZE` rather than `LINE_STRIDE`, kept one set of window + parameters shared by all four windows (window D's 656-pixel width leaked + into window A), and the block-linear decoder had two GOB address bits + swapped. The renderer compensated with per-address heuristics (a + "known menu stride" of 2624, forced block-linear decoding of the IPL + carveout, a hard-coded 1280x720 geometry for Nyx's framebuffer). Fix: + per-window register files latched on `WIN_x_ACT_REQ`, a TRM-exact + scan-out, and a VIC that really rotates. The heuristics are gone. - **PINMUX / PWM read-back** silently returned 0, so any probe that read back its own pad-mux setting (e.g. hwtest checking `LCD_BL_PWM` is in PWM0 mode) saw an unconfigured pin even after a successful write. Fix: diff --git a/README.md b/README.md index 44e2b42..6f33435 100644 --- a/README.md +++ b/README.md @@ -296,7 +296,7 @@ flowchart LR t210 --> se["se_engine.{h,cpp}
AES-128, SHA-256"] t210 --> i2c["i2c3.{h,cpp}
STMFTS / FTS4 touch"] - display --> sdl["sdl_display.{h,cpp}
block-linear de-swizzle
+ SDL2"] + display --> sdl["sdl_display.{h,cpp}
DC window scan-out
+ SDL2"] ``` For implementation details, see [DESIGN.md](DESIGN.md). diff --git a/display/sdl_display.cpp b/display/sdl_display.cpp index 5b2bd8d..d52e7da 100644 --- a/display/sdl_display.cpp +++ b/display/sdl_display.cpp @@ -6,6 +6,7 @@ #include #include +#include #include #include @@ -55,141 +56,335 @@ bool sdl_display_init() { return true; } +// ---- Scan-out ------------------------------------------------------------ +// +// The frame is built the way the display controller builds it (TRM 24): +// every enabled window's surface is fetched per its SURFACE_KIND (pitch, +// 16x16 tiled or block linear) and LINE_STRIDE, turned per WIN_OPTIONS +// (H/V direction, SCAN_COLUMN), scaled from PRESCALED_SIZE to SIZE and +// placed at POSITION, the windows stacked by layer depth and blended per +// BLEND_*. The result is the 720x1280 portrait picture the panel receives. +// +// For the host window that picture is then turned: when the surface on show +// was itself turned on its way to the panel - by the DC (SCAN_COLUMN) or by +// a VIC compose, as Nyx does - the turn is undone, so a GUI drawn landscape +// is shown landscape. A surface drawn straight into portrait (hekate's TUI, +// hwtest) is shown as the panel gets it. Ctrl+R / Ctrl+Shift+R override the +// turn. + +namespace { + +constexpr uint32_t kPanelW = 720, kPanelH = 1280; + +// A picture turn as a 2x2 matrix on centred coordinates: out = M * in. +struct Turn { + int a, b, c, d; // [[a b] [c d]] +}; + +Turn turn_of(uint32_t xf) { // dcwin::XF_* (flip, then transpose) + int fx = (xf & dcwin::XF_FLIP_X) ? -1 : 1; + int fy = (xf & dcwin::XF_FLIP_Y) ? -1 : 1; + if (xf & dcwin::XF_TRANSPOSE) + return {0, fy, fx, 0}; + return {fx, 0, 0, fy}; +} + +Turn operator*(const Turn &l, const Turn &r) { + return {l.a * r.a + l.b * r.c, l.a * r.b + l.b * r.d, + l.c * r.a + l.d * r.c, l.c * r.b + l.d * r.d}; +} + +// The view rotation (as the render loop applies it, see rot below) that +// undoes turn t, or 0 when t is a mirror image, which no rotation undoes. +int undo_rot(const Turn &t) { + if (t.a * t.d - t.b * t.c != 1) + return 0; + Turn inv = {t.a, t.c, t.b, t.d}; // a rotation's inverse is its transpose + if (inv.a == 0 && inv.b == -1) + return 1; + if (inv.a == -1) + return 2; + if (inv.a == 0 && inv.b == 1) + return 3; + return 0; +} + +uint32_t depth_bpp(uint32_t depth) { + if (depth <= 3) + return 1; // palettised + if (depth <= 7 || (depth >= 0x1E && depth <= 0x21)) + return 2; + return 4; +} + +// One pixel of a DC_WIN_COLOR_DEPTH format as ARGB8888. +uint32_t depth_argb(const uint8_t *p, uint32_t depth) { + auto x5 = [](uint32_t v) { return (v << 3) | (v >> 2); }; + auto x6 = [](uint32_t v) { return (v << 2) | (v >> 4); }; + switch (depth) { + case 0x4: { // B4G4R4A4 + uint32_t v = p[0] | (p[1] << 8); + return ((v >> 12) * 0x11u) << 24 | ((v >> 8) & 0xF) * 0x11u << 16 | + ((v >> 4) & 0xF) * 0x11u << 8 | (v & 0xF) * 0x11u; + } + case 0x5: { // B5G5R5A + uint32_t v = p[0] | (p[1] << 8); + return ((v & 0x8000) ? 0xFF000000u : 0) | x5((v >> 10) & 0x1F) << 16 | + x5((v >> 5) & 0x1F) << 8 | x5(v & 0x1F); + } + case 0x7: { // AB5G5R5 + uint32_t v = p[0] | (p[1] << 8); + return ((v & 1) ? 0xFF000000u : 0) | x5(v >> 11) << 16 | + x5((v >> 6) & 0x1F) << 8 | x5((v >> 1) & 0x1F); + } + case 0xD: // R8G8B8A8 + case 0xF: + return (uint32_t)p[3] << 24 | (uint32_t)p[0] << 16 | + (uint32_t)p[1] << 8 | p[2]; + default: + break; + } + switch (depth_bpp(depth)) { + case 1: + return 0xFF000000u | p[0] * 0x010101u; + case 2: { // B5G6R5 and anything else 16-bit + uint32_t v = p[0] | (p[1] << 8); + return 0xFF000000u | x5(v >> 11) << 16 | x6((v >> 5) & 0x3F) << 8 | + x5(v & 0x1F); + } + default: // B8G8R8A8 (bytes B, G, R, A) + return (uint32_t)p[3] << 24 | (uint32_t)p[2] << 16 | + (uint32_t)p[1] << 8 | p[0]; + } +} + +struct Win { + int idx = 0; + uint64_t addr = 0; + uint32_t depth = 0, bpp = 4, kind = 0, gob_h = 1, stride = 0, gobs = 0; + uint32_t src_w = 0, src_h = 0; // the surface, before the DC turns it + uint32_t pre_w = 0, pre_h = 0; // PRESCALED_SIZE, in pixels (post-turn) + uint32_t out_w = 0, out_h = 0; // SIZE + int32_t x = 0, y = 0; + uint32_t xf = 0, layer = 0, blend_layer = 0, blend_match = 0; + size_t len = 0; + const uint8_t *mem = nullptr; + std::vector copy; // when the surface is not in the DRAM window +}; + +// Byte offset of surface pixel (sx, sy). +inline size_t fetch_off(const Win &w, uint32_t sx, uint32_t sy) { + uint32_t xb = sx * w.bpp; + switch (w.kind) { + case 1: // 16x16-byte tiles, row-major + return (size_t)(sy / 16) * w.stride * 16 + (xb / 16) * 256 + + (sy % 16) * 16 + (xb % 16); + case 2: { // block linear, TRM 20.1.2 (Figure 47 sector order) + uint32_t gob_y = sy / 8; + size_t gob = ((size_t)(gob_y / w.gob_h) * w.gobs + xb / 64) * w.gob_h + + gob_y % w.gob_h; + uint32_t x = xb % 64, y = sy % 8; + return gob * 512 + (x / 32) * 256 + (y / 2) * 64 + ((x % 32) / 16) * 32 + + (y % 2) * 16 + (x % 16); + } + default: + return (size_t)sy * w.stride + xb; + } +} + +// Build window w from its active register file; false if it shows nothing. +bool load_window(EmuState *state, uc_engine *uc, int idx, const uint32_t *r, + int swizzle_override, Win &w) { + if (!(r[dcwin::OPTIONS] & dcwin::WIN_ENABLE)) + return false; + w.idx = idx; + w.depth = r[dcwin::COLOR_DEPTH] & 0x7F; + w.bpp = depth_bpp(w.depth); + uint32_t sk = r[dcwin::SURFACE_KIND]; + w.kind = sk & 3; + w.gob_h = 1u << ((sk >> 4) & 7); + if (swizzle_override == 0) { + w.kind = 0; + } else if (swizzle_override == 2 && w.kind != 2) { + w.kind = 2; + w.gob_h = 16; + } + w.out_w = r[dcwin::SIZE] & 0x1FFF; + w.out_h = (r[dcwin::SIZE] >> 16) & 0x1FFF; + w.pre_w = (r[dcwin::PRESCALED] & 0x7FFF) / w.bpp; + w.pre_h = (r[dcwin::PRESCALED] >> 16) & 0x1FFF; + if (!w.pre_w || !w.pre_h) { // never programmed: no scaling + w.pre_w = w.out_w; + w.pre_h = w.out_h; + } + if (!w.out_w || !w.out_h) + return false; + uint32_t opt = r[dcwin::OPTIONS]; + w.xf = ((opt & dcwin::H_DIRECTION) ? dcwin::XF_FLIP_X : 0) | + ((opt & dcwin::V_DIRECTION) ? dcwin::XF_FLIP_Y : 0) | + ((opt & dcwin::SCAN_COLUMN) ? dcwin::XF_TRANSPOSE : 0); + // SCAN_COLUMN walks the surface's columns: it is pre_h wide, pre_w tall. + bool column = w.xf & dcwin::XF_TRANSPOSE; + w.src_w = column ? w.pre_h : w.pre_w; + w.src_h = column ? w.pre_w : w.pre_h; + w.x = (int16_t)(r[dcwin::POSITION] & 0xFFFF); + w.y = (int16_t)(r[dcwin::POSITION] >> 16); + w.blend_layer = r[dcwin::BLEND_LAYER]; + w.blend_match = r[dcwin::BLEND_MATCH]; + w.layer = w.blend_layer & 0xFF; + w.stride = r[dcwin::LINE_STRIDE] & 0xFFFF; + if (!w.stride) + w.stride = w.src_w * w.bpp; + w.addr = (uint64_t)r[dcwin::START_ADDR] + (int64_t)state->manual_offset; + switch (w.kind) { + case 2: + w.gobs = (w.stride + 63) / 64; + w.len = (size_t)w.gobs * 512 * w.gob_h * + ((w.src_h + 8 * w.gob_h - 1) / (8 * w.gob_h)); + break; + case 1: + w.len = (size_t)w.stride * ((w.src_h + 15) / 16) * 16; + break; + default: + w.len = (size_t)w.stride * w.src_h; + break; + } + if (w.len == 0 || w.len > 64u * 1024 * 1024) + return false; + if (state->dram_low_ptr && w.addr >= DRAM_BASE && + w.addr + w.len <= DRAM_BASE + DRAM_WINDOW_SIZE) { + w.mem = state->dram_low_ptr + (w.addr - DRAM_BASE); + } else { + w.copy.resize(w.len); + if (uc_mem_read(uc, w.addr, w.copy.data(), w.len) != UC_ERR_OK) + return false; + w.mem = w.copy.data(); + } + return true; +} + +// Blend factor (0..255) per BLEND_MATCH_SELECT (TRM 24.10.13). +uint32_t src_factor(uint32_t sel, uint32_t k1, uint32_t sa) { + switch (sel) { + case 1: return 255; + case 2: case 3: return k1; // K1, K1 x dst alpha (opaque dst) + case 4: return 255 - k1; // 1 - K1 x dst alpha + case 5: return k1 * sa / 255; // K1 x src alpha + default: return 0; + } +} +uint32_t dst_factor(uint32_t sel, uint32_t k1, uint32_t k2, uint32_t sa) { + switch (sel) { + case 1: return 255; + case 2: case 4: return k1; + case 3: return k2; + case 5: case 7: return 255 - k1; + case 6: return 255 - k1 * sa / 255; + default: return 0; + } +} + +// Draw window w onto the panel picture. +void draw_window(const Win &w, std::vector &panel) { + bool blend = !(w.blend_layer & (1u << 24)); + uint32_t k1 = (w.blend_layer >> 8) & 0xFF, k2 = (w.blend_layer >> 16) & 0xFF; + uint32_t ssel = w.blend_match & 7, dsel = (w.blend_match >> 4) & 7; + bool hflip = w.xf & dcwin::XF_FLIP_X, vflip = w.xf & dcwin::XF_FLIP_Y; + bool column = w.xf & dcwin::XF_TRANSPOSE; + // Column scaling map, worked out once per window rather than per pixel. + static std::vector txs; + txs.resize(w.out_w); + for (uint32_t ox = 0; ox < w.out_w; ox++) + txs[ox] = (uint32_t)((uint64_t)ox * w.pre_w / w.out_w); + for (uint32_t oy = 0; oy < w.out_h; oy++) { + int32_t py = w.y + (int32_t)oy; + if (py < 0 || py >= (int32_t)kPanelH) + continue; + uint32_t ty = (uint32_t)((uint64_t)oy * w.pre_h / w.out_h); + for (uint32_t ox = 0; ox < w.out_w; ox++) { + int32_t px = w.x + (int32_t)ox; + if (px < 0 || px >= (int32_t)kPanelW) + continue; + uint32_t tx = txs[ox]; + // (tx, ty) is post-turn; walk it back to the surface. + uint32_t a = column ? ty : tx, b = column ? tx : ty; + uint32_t sx = hflip ? w.src_w - 1 - a : a; + uint32_t sy = vflip ? w.src_h - 1 - b : b; + size_t off = fetch_off(w, sx, sy); + if (off + w.bpp > w.len) + continue; + uint32_t s = depth_argb(w.mem + off, w.depth); + uint32_t &d = panel[(size_t)py * kPanelW + px]; + if (!blend) { + d = s | 0xFF000000u; + continue; + } + uint32_t sa = s >> 24; + uint32_t fs = src_factor(ssel, k1, sa), fd = dst_factor(dsel, k1, k2, sa); + uint32_t o = 0xFF000000u; + for (int sh = 0; sh < 24; sh += 8) { + uint32_t c = (((s >> sh) & 0xFF) * fs + ((d >> sh) & 0xFF) * fd) / 255; + o |= (c > 255 ? 255 : c) << sh; + } + d = o; + } + } +} + +} // namespace + void sdl_display_update(EmuState *state, uc_engine *uc) { if (!renderer) return; - uint32_t width = state->fb_width, height = state->fb_height, - stride = state->fb_stride; - if (width < 16 || height < 16) - return; - - // If the current fb_addr is empty but we have a saved Window A with - // content, prefer the Window A surface. This handles the case where - // Hekate's TUI renders to IPL_FB (0xF5A00000) but the DC was repointed - // to NYX_FB (0xF6200000) by a failed Nyx init sequence. - uint64_t eff_addr = state->fb_addr; - if (state->winA_addr && state->winA_addr != eff_addr) { - // Quick check: sample a few dwords from fb_addr. - uint32_t sample[4] = {0}; - uc_mem_read(uc, eff_addr, sample, sizeof(sample)); - bool empty = (sample[0] == 0 && sample[1] == 0 && - sample[2] == 0 && sample[3] == 0); - if (empty) { - // Check if winA_addr has content. - uc_mem_read(uc, state->winA_addr, sample, sizeof(sample)); - if (sample[0] != 0 || sample[1] != 0 || - sample[2] != 0 || sample[3] != 0) { - eff_addr = state->winA_addr; - width = state->winA_w; - height = state->winA_h; - stride = state->winA_stride; - } - } + // The windows on show, bottom first. Until the payload programs the DC, + // the emulator's own framebuffer stands in as window A. + std::vector wins; + uint32_t boot_win[dcwin::kRegs] = {}; + boot_win[dcwin::OPTIONS] = dcwin::WIN_ENABLE; + boot_win[dcwin::COLOR_DEPTH] = 0xC; // B8G8R8A8 + boot_win[dcwin::SIZE] = kPanelH << 16 | kPanelW; + boot_win[dcwin::LINE_STRIDE] = kPanelW * 4; + boot_win[dcwin::BLEND_LAYER] = dcwin::BLEND_LAYER_RESET; + boot_win[dcwin::START_ADDR] = (uint32_t)FB_BASE; + for (int i = 0; i < 4; i++) { + const uint32_t *r = state->dc_programmed ? state->dc_win_active[i] + : (i == 0 ? boot_win : nullptr); + if (!r) + continue; + Win w; + if (load_window(state, uc, i, r, g_swizzle_override, w)) + wins.push_back(std::move(w)); } + // Deeper layers first; equal depths stack A (bottom) to D (top). + std::stable_sort(wins.begin(), wins.end(), [](const Win &l, const Win &r) { + return l.layer > r.layer; + }); - // Helper: is the address inside the IPL framebuffer carveout? - auto addr_in_ipl_fb = [](uint64_t a) -> bool { - return a >= FB_BASE && a < FB_BASE + FB_SIZE; - }; - - // 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; - uint32_t bpp = 4; - uint32_t bh = state->fb_bh ? state->fb_bh : 16; // Block height in GOBs - - // --- OVERRIDES & AUTO-DETECTS --- - constexpr uint64_t kNyxFbBase = 0xF6200000ULL; - - if (g_swizzle_override != -1) { - sw = (uint32_t)g_swizzle_override; // Manual User Override (S Key) - } else if (eff_addr == kNyxFbBase) { - // Nyx GUI uses VIC to rotate its 1280x720 landscape UI into 720x1280 portrait mode (NYX_FB_ADDRESS). - // Our emulator's mock VIC only memcpys the data, so 0xF6200000 actually holds a 1280x720 landscape image! - // Since the DC is programmed for 720x1280, it will scramble it. - // We override the display geometry here to render the raw 1280x720 memory correctly. - sw = 0; - width = 1280; - height = 720; - eff_stride = 1280 * 4; // 32-bit XRGB - rot = 0; - bh = 4; - } else if (eff_addr == FB_BASE && sw == 0 && width == 720u && - height == 1280u && eff_stride == width * 4u) { - // Hekate TUI or static bootlogo: natively rendered as 720x1280 pitch-linear portrait. - // Do not apply any automatic layout overrides. - sw = 0; - rot = 0; // The UI is drawn sideways in memory to appear upright on a landscape physical Switch screen. - // On PC, we want to view it rotated so it resembles the physical landscape Switch! - } else if (addr_in_ipl_fb(eff_addr) && sw == 0) { - // IPL carveout with Sw=0: Hekate writes block-linear data but the DC - // surface kind says pitch. Detect when the stride/dimensions don't - // match a coherent pitch-linear layout and force block-linear decode. - bool coherent_pitch = - width > 0 && (eff_stride == width * 4u || eff_stride == width * 2u); - bool portrait_stride_mismatch = - height == 1280u && width == 720u && eff_stride != width * 4u; - bool known_menu_stride = (eff_stride == 2624u && !coherent_pitch); - - // crop_portrait only forces BL when stride is incoherent — if stride - // matches width*bpp, the data may already be VIC-de-swizzled pitch. - bool crop_portrait_incoherent = - height == 1280u && width < 720u && width >= 640u && !coherent_pitch; - - if (!coherent_pitch || portrait_stride_mismatch || known_menu_stride || - crop_portrait_incoherent) { - sw = 2; // Force block-linear decode - bh = 4; // Hekate menu uses BH=4 - } + // The largest window decides how the picture is turned for the host. + const Win *primary = nullptr; + for (const Win &w : wins) + if (!primary || (uint64_t)w.out_w * w.out_h > + (uint64_t)primary->out_w * primary->out_h || + ((uint64_t)w.out_w * w.out_h == + (uint64_t)primary->out_w * primary->out_h && + w.idx < primary->idx)) + primary = &w; + int rot = 0; + if (primary) { + Turn t = turn_of(primary->xf); + if (state->vic_out_addr && primary->addr == state->vic_out_addr) + t = t * turn_of(state->vic_out_xform); + rot = undo_rot(t); } - - // Final heuristic: NEVER auto-rotate 720x1280 portrait buffers to landscape! - if (rot == -1) { - if (width == 720 && height == 1280) { - rot = 0; // Hekate already drew it sideways for physical portrait, so rot=0 makes it look like a phone on PC monitor! - // Actually wait: if drawn upright in memory (row-by-row), then rot=0 produces a tall 720x1280 window on PC where it is perfectly upright! - // The user wants the white lines to be horizontal. This means we MUST let the window be 720x1280! - } else { - rot = (height > width) ? 1 : 0; // Legacy heuristic for other stuff - } - } - - // Manual rotation override always wins. The auto-detect branches above set - // rot = 0 for Nyx and Hekate TUI surfaces; if the user pressed R/Shift+R - // they expect the rotation to actually change, regardless of what the - // auto-detect picked. -1 means "use auto-detect", anything else overrides. - state->last_auto_rot.store((uint32_t)(rot & 3)); + state->last_auto_rot.store((uint32_t)rot); if (state->rotation_override != -1) rot = state->rotation_override & 3; - // --- Compute GOB stride for block-linear --- - uint32_t sw_gobs = (width * bpp + 63) / 64; - if (sw == 2) { - // For IPL carveout portrait surfaces, Hekate allocates a full 720px-wide - // BL surface even when the DC window is cropped to 656px. - if (addr_in_ipl_fb(state->fb_addr) && state->fb_addr != kNyxFbBase && - bpp == 4 && height == 1280u && width >= 640u && width <= 720u) { - uint32_t sw_720 = (720u * bpp + 63) / 64u; - if (sw_gobs < sw_720) - sw_gobs = sw_720; - } - // If DC provides a stride that's GOB-aligned, prefer it - if (eff_stride >= 64u && (eff_stride % 64u) == 0u) { - uint32_t stride_gobs = eff_stride / 64u; - if (stride_gobs > sw_gobs) - sw_gobs = stride_gobs; - } - } - - uint32_t out_w = (rot & 1) ? height : width; - uint32_t out_h = (rot & 1) ? width : height; - - // Cache the effective rotation and output dims so the SDL event handler can - // invert the framebuffer→window transform when mapping mouse → panel coords. - state->last_rot.store((uint32_t)((rot < 0) ? 0 : (rot & 3))); + uint32_t out_w = (rot & 1) ? kPanelH : kPanelW; + uint32_t out_h = (rot & 1) ? kPanelW : kPanelH; + // The SDL event handler inverts this view to map mouse -> panel coords. + state->last_rot.store((uint32_t)rot); state->last_out_w.store(out_w); state->last_out_h.store(out_h); @@ -197,8 +392,8 @@ void sdl_display_update(EmuState *state, uc_engine *uc) { if (!texture || out_w != last_w || out_h != last_h) { if (texture) SDL_DestroyTexture(texture); - // Use ARGB8888: natively matches Tegra's BGRA memory layout on Little - // Endian + // ARGB8888 matches the B8G8R8A8 bytes of a Tegra surface on a + // little-endian host. texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, out_w, out_h); last_w = out_w; @@ -206,194 +401,84 @@ void sdl_display_update(EmuState *state, uc_engine *uc) { SDL_SetWindowSize(window, out_w, out_h); } - static uint32_t last_log_p[6] = {0}; // Addr, W, H, Rot, Sw, BH - if (state->fb_addr != last_log_p[0] || width != last_log_p[1] || - height != last_log_p[2] || (uint32_t)rot != last_log_p[3] || - sw != last_log_p[4] || bh != last_log_p[5]) { - printf("[display] LATCH: 0x%X (%dx%d), Rot: %d (Manual: %d), Sw: %d, " - "GOBs: %u, BH: %u, BPP: %u\n", - (uint32_t)state->fb_addr, width, height, rot, - state->rotation_override, sw, sw_gobs, bh, bpp * 8); - last_log_p[0] = state->fb_addr; - last_log_p[1] = width; - last_log_p[2] = height; - last_log_p[3] = rot; - last_log_p[4] = sw; - last_log_p[5] = bh; + // Skip the rebuild and the texture upload when neither the surfaces' bytes + // nor the way they are laid out changed since the last frame - the common + // case for a payload sitting on a menu or waiting on hardware. + std::vector shape = {(uint64_t)rot, wins.size()}, where; + for (const Win &w : wins) { + shape.insert(shape.end(), + {(uint64_t)w.idx, w.addr, w.len, w.depth, w.kind, w.gob_h, + w.stride, (uint64_t)w.pre_w << 32 | w.pre_h, + (uint64_t)w.out_w << 32 | w.out_h, w.xf, w.blend_layer, + w.blend_match}); + where.push_back((uint64_t)(uint32_t)w.x << 32 | (uint32_t)w.y); } + static std::vector last_shape, last_where; + static std::vector last_bytes; + size_t total = 0; + for (const Win &w : wins) + total += w.len; + bool same = shape == last_shape && where == last_where && + last_bytes.size() == total; + for (size_t i = 0, pos = 0; same && i < wins.size(); pos += wins[i++].len) + same = memcmp(last_bytes.data() + pos, wins[i].mem, wins[i].len) == 0; - eff_addr = - (eff_addr ? eff_addr : FB_BASE) + - (uint64_t)(int64_t)state->manual_offset; - - // Compute framebuffer byte size - size_t fb_size = (sw == 2) ? ((size_t)sw_gobs * ((height + 7) / 8) * 512) - : ((size_t)eff_stride * height); - if (fb_size < 1024) - return; - if (sw != 2 && eff_stride < 16) - return; // Pitch-linear sanity check only - if (fb_size > 32 * 1024 * 1024) - fb_size = 32 * 1024 * 1024; - - // The surface is read straight out of the host memory backing emulated - // DRAM when it lives there (it always does for hekate/Nyx), instead of a - // uc_mem_read into a fresh 3.5 MB vector - and the converted frame reuses - // one buffer too. The old code allocated and zero-filled two such vectors - // on every frame, 60 times a second, which showed up in profiles as page- - // fault and munmap churn on the emulation thread. - static std::vector fallback; - const uint8_t *src = nullptr; - if (state->dram_low_ptr && eff_addr >= DRAM_BASE && - eff_addr + fb_size <= DRAM_BASE + DRAM_WINDOW_SIZE) { - src = state->dram_low_ptr + (eff_addr - DRAM_BASE); - } else { - fallback.resize(fb_size); - if (uc_mem_read(uc, eff_addr, fallback.data(), fb_size) == UC_ERR_OK) - src = fallback.data(); - } - - // Skip the de-swizzle and the texture upload when neither the surface - // bytes nor the way they are laid out has changed since the last frame - - // the common case for a payload sitting on a menu or waiting on hardware. - struct Layout { - uint64_t addr = 0; - uint32_t w = 0, h = 0, stride = 0, sw = 0, bh = 0, gobs = 0, out_w = 0, - out_h = 0; - int rot = 0; - bool operator==(const Layout &o) const { - return addr == o.addr && w == o.w && h == o.h && stride == o.stride && - sw == o.sw && bh == o.bh && gobs == o.gobs && out_w == o.out_w && - out_h == o.out_h && rot == o.rot; - } - }; - static Layout last_layout; - static std::vector last_src; - Layout layout; - layout.addr = eff_addr; - layout.w = width; - layout.h = height; - layout.stride = eff_stride; - layout.sw = sw; - layout.bh = bh; - layout.gobs = sw_gobs; - layout.out_w = out_w; - layout.out_h = out_h; - layout.rot = rot; - bool unchanged = src && layout == last_layout && last_src.size() == fb_size && - memcmp(last_src.data(), src, fb_size) == 0; static bool snapshot_pending = true; - - if (src && !unchanged) { - last_layout = layout; - last_src.assign(src, src + fb_size); + if (!same) { + // Log layout changes, but not moves: bdk slides its log window in. + if (shape != last_shape) + printf("[display] scan-out: %zu window(s), view %ux%u, rot %d (auto %u)\n", + wins.size(), out_w, out_h, rot, state->last_auto_rot.load()); + last_shape = shape; + last_where = where; + last_bytes.resize(total); + size_t pos = 0; + for (const Win &w : wins) { + memcpy(last_bytes.data() + pos, w.mem, w.len); + pos += w.len; + } snapshot_pending = true; - const uint8_t *buf_data = src; - std::vector &proc = g_frame; - proc.assign((size_t)out_w * out_h, 0xFF000000); // opaque black - for (uint32_t sy = 0; sy < height; sy++) { - for (uint32_t sx = 0; sx < width; sx++) { - uint32_t off = 0; - if (sw == 2) { - if (bpp == 4) { - // Use tegra_bl_byte_off_rgba8888 formula inline for 32bpp - uint32_t gob_x = sx / 16u; - uint32_t pixel_x = sx % 16u; - uint32_t gob_y = sy / 8u; - uint32_t line_y = sy % 8u; - uint32_t block_y = gob_y / bh; - uint32_t gob_in_block_y = gob_y % bh; + static std::vector panel; + panel.assign((size_t)kPanelW * kPanelH, 0xFF000000u); // black background + for (const Win &w : wins) + draw_window(w, panel); - uint32_t idx = - (block_y * sw_gobs * bh * 128u) + (gob_x * bh * 128u) + - (gob_in_block_y * 128u) + (pixel_x & 3u) + - ((line_y & 1u) << 2) + ((pixel_x & 4u) << 1) + - ((line_y & 2u) << 3) + ((pixel_x & 8u) << 2) + - ((line_y & 4u) << 4); - off = idx; // Already in uint32 units - } else { - // 16bpp block-linear (Nyx RGB565) - uint32_t byte_x = sx * bpp; - uint32_t gx = byte_x / 64; - uint32_t px_in = byte_x % 64; - uint32_t gy = sy / 8; - uint32_t ly = sy % 8; - uint32_t gob_off = ((ly >> 1) << 7) + ((px_in >> 4) << 5) + - ((ly & 1) << 4) + (px_in & 0xF); - uint32_t gob_idx = - (gy / bh) * (sw_gobs * bh) + gx * bh + (gy % bh); - uint32_t byte_off = gob_idx * 512 + gob_off; - // Read 16-bit pixel and expand to 32-bit ARGB - if (byte_off + 2 <= fb_size) { - uint16_t u16 = *(const uint16_t *)&buf_data[byte_off]; - uint32_t p = (((u16 >> 11) & 0x1F) << 19) | - (((u16 >> 5) & 0x3F) << 10) | - ((u16 & 0x1F) << 3) | 0xFF000000; - uint32_t dx = sx, dy = sy; - switch (rot) { - case 1: dx = height - 1 - sy; dy = sx; break; - case 2: dx = width - 1 - sx; dy = height - 1 - sy; break; - case 3: dx = sy; dy = width - 1 - sx; break; - default: break; - } - if (dx < out_w && dy < out_h) - proc[dy * out_w + dx] = p; - } - continue; // Skip the common 32bpp path below - } - } else { - off = (sy * eff_stride + sx * bpp) / 4; - } - - if (off < fb_size / 4) { - uint32_t p = ((const uint32_t *)buf_data)[off]; - uint32_t dx = sx, dy = sy; - - switch (rot) { - case 1: - dx = height - 1 - sy; - dy = sx; - break; - case 2: - dx = width - 1 - sx; - dy = height - 1 - sy; - break; - case 3: - dx = sy; - dy = width - 1 - sx; - break; - default: - break; // 0 - } - if (dx < out_w && dy < out_h) { - // Native BGRA to ARGB8888 conversion mapping (forces A to 0xFF) - proc[dy * out_w + dx] = p | 0xFF000000; - } + // Turn the panel picture for the view: a panel pixel (sx, sy) of the + // W x H picture lands at + // rot 1: (H-1-sy, sx) 2: (W-1-sx, H-1-sy) 3: (sy, W-1-sx) + g_frame.resize((size_t)out_w * out_h); + for (uint32_t sy = 0; sy < kPanelH; sy++) { + const uint32_t *row = &panel[(size_t)sy * kPanelW]; + for (uint32_t sx = 0; sx < kPanelW; sx++) { + uint32_t dx = sx, dy = sy; + switch (rot) { + case 1: dx = kPanelH - 1 - sy; dy = sx; break; + case 2: dx = kPanelW - 1 - sx; dy = kPanelH - 1 - sy; break; + case 3: dx = sy; dy = kPanelW - 1 - sx; break; + default: break; } + g_frame[(size_t)dy * out_w + dx] = row[sx]; } } - SDL_UpdateTexture(texture, nullptr, proc.data(), out_w * 4); + SDL_UpdateTexture(texture, nullptr, g_frame.data(), out_w * 4); } - if (src) { - // Snapshot for PNG conversion — at most once a second (~60 frames), and - // only when the frame has changed since the last one written, so an idle - // payload no longer rewrites a 3.5 MB file every second. - static int snap_counter = 0; - const std::vector &proc = g_frame; - if (++snap_counter >= 60 && snapshot_pending && !proc.empty()) { - snap_counter = 0; - snapshot_pending = false; - FILE *f = fopen("last_fb.rgba", "wb"); - if (f) { - fwrite(proc.data(), 1, proc.size() * 4, f); - fclose(f); - FILE *fm = fopen("last_fb.meta", "w"); - if (fm) { - fprintf(fm, "%u %u\n", out_w, out_h); - fclose(fm); - } + // Snapshot for PNG conversion - at most once a second (~60 frames), and + // only when the frame has changed since the last one written, so an idle + // payload does not rewrite a 3.5 MB file every second. + static int snap_counter = 0; + if (++snap_counter >= 60 && snapshot_pending && !g_frame.empty()) { + snap_counter = 0; + snapshot_pending = false; + FILE *f = fopen("last_fb.rgba", "wb"); + if (f) { + fwrite(g_frame.data(), 1, g_frame.size() * 4, f); + fclose(f); + FILE *fm = fopen("last_fb.meta", "w"); + if (fm) { + fprintf(fm, "%u %u\n", out_w, out_h); + fclose(fm); } } } @@ -426,12 +511,11 @@ 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; - // 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 + // With the auto-detected turn, the view shows the picture the way the + // payload drew it (Nyx: landscape, as on a Switch held landscape). A + // manual override (Ctrl+R / Ctrl+Shift+R) turns that view by a further + // quarter-turn or two, so undo exactly that extra turn first: the render + // maps a source pixel (sx, sy) of a W x H image to // 1: (H-1-sy, sx) 2: (W-1-sx, H-1-sy) 3: (sy, W-1-sx) uint32_t delta = (state->last_rot.load() - state->last_auto_rot.load()) & 3; uint32_t aw = (delta & 1) ? out_h : out_w; // auto-rotated view's size diff --git a/emu_state.h b/emu_state.h index cf18f04..bcda4ed 100644 --- a/emu_state.h +++ b/emu_state.h @@ -91,6 +91,40 @@ inline bool wifi_radio_parse(const char *s, uint8_t *out) { return false; } +// Tegra DC window registers (TRM 24.10-24.11) as slots in a window's +// register file: the indirect window page 0x700-0x7FF is slots 0x000-0x0FF, +// the WINBUF page 0x800-0x83F slots 0x100-0x13F. +namespace dcwin { +constexpr uint32_t kRegs = 0x140; +constexpr uint32_t OPTIONS = 0x000; // DC_WIN_WIN_OPTIONS +constexpr uint32_t COLOR_DEPTH = 0x003; // DC_WIN_COLOR_DEPTH +constexpr uint32_t POSITION = 0x004; // DC_WIN_POSITION +constexpr uint32_t SIZE = 0x005; // DC_WIN_SIZE (post-scaling) +constexpr uint32_t PRESCALED = 0x006; // DC_WIN_PRESCALED_SIZE (bytes x lines) +constexpr uint32_t LINE_STRIDE = 0x00A; // DC_WIN_LINE_STRIDE (bytes) +constexpr uint32_t BLEND_LAYER = 0x016; // DC_WINBUF_BLEND_LAYER_CONTROL +constexpr uint32_t BLEND_MATCH = 0x017; // DC_WINBUF_BLEND_MATCH_SELECT +constexpr uint32_t START_ADDR = 0x100; // DC_WINBUF_START_ADDR +constexpr uint32_t SURFACE_KIND = 0x10B; // DC_WINBUF_SURFACE_KIND + +// WIN_OPTIONS bits. +constexpr uint32_t H_DIRECTION = 1u << 0; +constexpr uint32_t V_DIRECTION = 1u << 2; +constexpr uint32_t SCAN_COLUMN = 1u << 4; +constexpr uint32_t WIN_ENABLE = 1u << 30; + +// BLEND_LAYER_CONTROL resets to BLEND_BYPASS (TRM 24.10.12). +constexpr uint32_t BLEND_LAYER_RESET = 0x01000000; + +// A picture turn, as flip-then-transpose: the source is mirrored left-right +// (XF_FLIP_X) and/or top-bottom (XF_FLIP_Y), then rows become columns +// (XF_TRANSPOSE). DC WIN_OPTIONS (H_DIRECTION, V_DIRECTION, SCAN_COLUMN) and +// VIC's OutputFlipX/FlipY/Transpose both follow this convention. +constexpr uint32_t XF_FLIP_X = 1u << 0; +constexpr uint32_t XF_FLIP_Y = 1u << 1; +constexpr uint32_t XF_TRANSPOSE = 1u << 2; +} // namespace dcwin + struct EmuState { uc_engine *uc = nullptr; // Button state (updated by SDL keyboard events). @@ -139,24 +173,21 @@ struct EmuState { std::atomic last_out_w{1280}; std::atomic last_out_h{720}; - // Display state. - uint64_t fb_addr = 0, pre_addr = 0; - uint32_t fb_width = 720, pre_w = 720; - uint32_t fb_height = 1280, pre_h = 1280; - uint32_t fb_stride = 2880, pre_stride = 2880; - uint32_t fb_swizzle = 0, pre_sw = 0; - uint32_t fb_rotation = 0, pre_rot = 0; - uint32_t pre_bh = 0; // block height in GOBs from DC surface-kind (0 = unset) - uint32_t fb_sw_gobs = 80; - uint32_t fb_bh = 0; // 0 = use display code default until DC surface-kind latches - - // DC window selection: tracks DC_CMD_DISPLAY_WINDOW_HEADER. - // Bit 4 = Window A, Bit 5 = Window B, Bit 6 = Window C, Bit 7 = Window D. - uint32_t dc_window_sel = 0x10; // Default: Window A - // Saved Window A parameters (primary display surface). - uint64_t winA_addr = 0; - uint32_t winA_w = 720, winA_h = 1280, winA_stride = 2880; - uint32_t winA_sw = 0, winA_rot = 0, winA_bh = 0; + // Display controller windows A-D (t210/mmio.cpp, Display). Each window + // has a register file indexed by dcwin:: slot. The CPU writes the + // assembly copy; DC_CMD_STATE_CONTROL's WIN_x_ACT_REQ copies it into the + // active copy, which is what the scan-out (display/sdl_display.cpp) + // decodes. + uint32_t dc_win[4][dcwin::kRegs] = {}; + uint32_t dc_win_active[4][dcwin::kRegs] = {}; + uint32_t dc_window_header = 0; // DC_CMD_DISPLAY_WINDOW_HEADER + // False from reset until the payload first activates a window. Until + // then the scan-out shows the emulator's own framebuffer (FB_BASE). + bool dc_programmed = false; + // Where the last VIC compose wrote, and how it turned the picture on the + // way (dcwin::XF_* bits). The scan-out undoes that turn for display. + uint64_t vic_out_addr = 0; + uint32_t vic_out_xform = 0; std::atomic display_dirty{false}; std::atomic display_initialized{false}; int32_t manual_offset = 0; diff --git a/main.cpp b/main.cpp index 00a6487..1e207ad 100644 --- a/main.cpp +++ b/main.cpp @@ -204,7 +204,6 @@ 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_fb_background(state); - state->fb_addr = FB_BASE; printf("[emu] Defined FB: 0x%08llX - 0x%08llX (%u MB)\n", (unsigned long long)FB_BASE, (unsigned long long)(FB_BASE + FB_SIZE), @@ -532,7 +531,6 @@ int main(int argc, char *argv[]) { 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; diff --git a/t210/mmio.cpp b/t210/mmio.cpp index 1ca7eae..780ec76 100644 --- a/t210/mmio.cpp +++ b/t210/mmio.cpp @@ -1570,112 +1570,132 @@ void i2c_write(EmuState *state, uint64_t addr, uint32_t val) { } // ==================== Display ==================== +// +// The display controller's windows (TRM 24.10-24.11) are modelled as one +// register file per window, A-D. The CPU reaches them either through the +// indirect window pages (0x700-0x7FF, 0x800-0x83F), which write every window +// DC_CMD_DISPLAY_WINDOW_HEADER selects and read back the lowest selected one, +// or through a window's own direct range (A: 0xB80/0xBC0, B: 0xD80/0xDC0, +// C: 0xF80/0xFC0). Writes go to the assembly copy. WIN_x_ACT_REQ in +// DC_CMD_STATE_CONTROL promotes window x to the active copy that the scan-out +// (display/sdl_display.cpp) decodes, so a half-programmed window never shows. +// (The hardware stages this twice, UPDATE then ACT_REQ; every payload writes +// both back to back, so one step is enough.) +// +// The rest of the DC is plain read-back storage, except the two words that +// payloads poll: STATE_CONTROL (requests complete at once) and INT_STATUS +// (a frame has always just ended). + +static constexpr uint32_t kDcCmdIntStatus = 0x037; +static constexpr uint32_t kDcCmdStateControl = 0x041; +static constexpr uint32_t kDcCmdWindowHeader = 0x042; +static constexpr uint32_t kDcIntFrameEndVBlank = (1u << 1) | (1u << 2); + +// Resolve a DC word index to the windows it addresses and the register-file +// slot. False for anything that is not a window register. +static bool dc_window_reg(const EmuState *state, uint32_t index, + uint32_t *mask, uint32_t *slot) { + if (index >= 0x700 && index < 0x800) { + *mask = (state->dc_window_header >> 4) & 0xF; + *slot = index - 0x700; + return true; + } + if (index >= 0x800 && index < 0x840) { + *mask = (state->dc_window_header >> 4) & 0xF; + *slot = 0x100 + (index - 0x800); + return true; + } + static const uint32_t kDirect[3] = {0xB80, 0xD80, 0xF80}; + for (uint32_t w = 0; w < 3; w++) { + uint32_t base = kDirect[w]; + if (index >= base && index < base + 0x80) { + *mask = 1u << w; + *slot = index < base + 0x40 ? index - base : 0x100 + (index - base - 0x40); + return true; + } + } + return false; +} + +static void dc_reset(EmuState *state) { + memset(state->dc_win, 0, sizeof(state->dc_win)); + memset(state->dc_win_active, 0, sizeof(state->dc_win_active)); + for (int w = 0; w < 4; w++) + state->dc_win[w][dcwin::BLEND_LAYER] = + state->dc_win_active[w][dcwin::BLEND_LAYER] = dcwin::BLEND_LAYER_RESET; + state->dc_window_header = 0; + state->dc_programmed = false; + state->vic_out_addr = 0; + state->vic_out_xform = 0; +} + +// One line per window whose picture changed (not for moves: bdk slides its +// log window in 16 pixels at a time). +static void dc_log_window(int w, const uint32_t *r) { + if (!(r[dcwin::OPTIONS] & dcwin::WIN_ENABLE)) { + printf("[display] window %c off\n", 'A' + w); + return; + } + static const char *const kKind[4] = {"pitch", "tiled", "block", "?"}; + uint32_t kind = r[dcwin::SURFACE_KIND]; + printf("[display] window %c: %ux%u @ 0x%08X, %s", 'A' + w, + r[dcwin::SIZE] & 0x1FFF, (r[dcwin::SIZE] >> 16) & 0x1FFF, + r[dcwin::START_ADDR], kKind[kind & 3]); + if ((kind & 3) == 2) + printf(" (%u-GOB blocks)", 1u << ((kind >> 4) & 7)); + printf(", stride %u, depth 0x%X, options 0x%X\n", + r[dcwin::LINE_STRIDE] & 0xFFFF, r[dcwin::COLOR_DEPTH] & 0x7F, + r[dcwin::OPTIONS]); +} uint32_t display_read(EmuState *state, uint64_t addr) { - uint32_t offset = (uint32_t)(addr - DISPLAY_A_BASE); - if (offset == 0x800 * 4 || offset == 0x2000) - return (uint32_t)state->fb_addr; - return 0; + uint32_t index = (uint32_t)(addr - DISPLAY_A_BASE) / 4; + uint32_t mask, slot; + if (dc_window_reg(state, index, &mask, &slot)) { + for (int w = 0; w < 4; w++) + if (mask & (1u << w)) + return state->dc_win[w][slot]; + return 0; + } + switch (index) { + case kDcCmdIntStatus: return kDcIntFrameEndVBlank; + case kDcCmdStateControl: return 0; + case kDcCmdWindowHeader: return state->dc_window_header; + default: return mmio_regs.get(addr); + } } void display_write(EmuState *state, uint64_t addr, uint32_t val) { - if (addr < 0x54200000 || addr >= 0x54240000) + uint32_t index = (uint32_t)(addr - DISPLAY_A_BASE) / 4; + uint32_t mask, slot; + if (dc_window_reg(state, index, &mask, &slot)) { + for (int w = 0; w < 4; w++) + if (mask & (1u << w)) + state->dc_win[w][slot] = val; return; - uint32_t offset = (uint32_t)(addr - 0x54200000); - uint32_t index = offset / 4; - - // DC_CMD_DISPLAY_WINDOW_HEADER (offset 0x042*4 = 0x108). - // Tracks which window's registers are currently selected. - if (offset == 0x108) - state->dc_window_sel = val; - - if (offset >= 0x1C00 && offset < 0x1E00) { - uint32_t win_off = offset - 0x1C00; - if (win_off == 0x00) - state->pre_rot = val; - if (win_off == 0x14) { - state->pre_w = (val & 0x1FFF); - state->pre_h = ((val >> 16) & 0x1FFF); + } + if (index == kDcCmdWindowHeader) { + state->dc_window_header = val; + } else if (index == kDcCmdStateControl) { + uint32_t req = (val >> 1) & 0xF; // WIN_A..D_ACT_REQ + for (int w = 0; w < 4; w++) { + if (!(req & (1u << w))) + continue; + uint32_t *act = state->dc_win_active[w]; + const uint32_t *asm_ = state->dc_win[w]; + static const uint32_t kShown[] = { + dcwin::OPTIONS, dcwin::COLOR_DEPTH, dcwin::SIZE, dcwin::LINE_STRIDE, + dcwin::START_ADDR, dcwin::SURFACE_KIND}; + bool changed = !state->dc_programmed; + for (uint32_t r : kShown) + changed |= act[r] != asm_[r]; + memcpy(act, asm_, sizeof(state->dc_win_active[w])); + if (changed) + dc_log_window(w, act); } - if (win_off == 0x18) - state->pre_stride = val & 0xFFFF; - if (win_off == 0x2C) { - state->pre_sw = ((val & 0x7) == 2) ? 2 : 0; - // Tegra DC surface kind: tile in low bits; bits 4–7 = log2(block height in - // GOBs) for block-linear (values 1..5 → 2,4,8,16,32 GOBs). - unsigned log2bh = (val >> 4) & 0xF; - if (log2bh >= 1 && log2bh <= 5) - state->pre_bh = 1u << log2bh; - else - state->pre_bh = 0; - } - } else if (offset >= 0x2000 && offset < 0x2100) { - uint32_t buf_off = offset - 0x2000; - if (buf_off == 0x00) { - state->pre_addr = val; - if (val == 0xF6200000) { - printf("[display] WARNING: Guest wrote 0xF6200000 to pre_addr!\n"); - // Print the guest PC to see where this comes from - uint32_t pc = 0; - uc_reg_read(state->uc, UC_ARM_REG_PC, &pc); - printf("[display] Guest PC: 0x%X\n", pc); - uint8_t code[16] = {0}; - if (uc_mem_read(state->uc, pc - 8, code, 16) == UC_ERR_OK) { - printf("[display] Code: "); - for (int i=0; i<16; i++) printf("%02X ", code[i]); - printf("\n"); - } - } - } - if (buf_off == 0x2C) { - state->pre_sw = ((val & 0x7) == 2) ? 2 : 0; - unsigned log2bh = (val >> 4) & 0xF; - if (log2bh >= 1 && log2bh <= 5) - state->pre_bh = 1u << log2bh; - else - state->pre_bh = 0; - } - } else if (index == 0x85) { // SIZE legacy - state->pre_w = (val & 0x1FFF); - state->pre_h = ((val >> 16) & 0x1FFF); - } else if (index == 0x41 || offset == 0x104) { // DC_CMD_STATE_CONTROL - // Latch when activation request bits are set (WIN_A_ACT_REQ=bit1, - // GENERAL_ACT_REQ=bit0) - if (val & 0x3) { - bool is_window_a = (state->dc_window_sel & 0x10) != 0; // Bit 4 = Window A - bool is_window_d = (state->dc_window_sel & 0x80) != 0; // Bit 7 = Window D - - if (is_window_a && state->pre_addr) { - // Save Window A parameters as primary display surface. - state->winA_addr = state->pre_addr; - state->winA_w = state->pre_w; - state->winA_h = state->pre_h; - state->winA_stride = state->pre_stride; - state->winA_sw = state->pre_sw; - state->winA_rot = state->pre_rot; - state->winA_bh = state->pre_bh; - } - - // Always latch to fb_* for display — but prefer Window A over Window D - // since Window D is just a transparent overlay in Hekate. - if (is_window_a || !is_window_d) { - state->fb_addr = state->pre_addr; - state->fb_width = state->pre_w; - state->fb_height = state->pre_h; - state->fb_stride = state->pre_stride; - state->fb_swizzle = state->pre_sw; - state->fb_rotation = state->pre_rot; - if (state->pre_bh) - state->fb_bh = state->pre_bh; - } - // If Window D is latched alone, don't override — keep Window A's surface. - + if (req) { + state->dc_programmed = true; state->display_dirty = true; - printf("[display] LATCH (ACT_REQ): 0x%llX (%dx%d), WinSel: 0x%X, Sw: %d, " - "Str: %d\n", - (unsigned long long)state->fb_addr, state->fb_width, - state->fb_height, state->dc_window_sel, state->fb_swizzle, - state->fb_stride); } } } @@ -3481,93 +3501,179 @@ static void se_write(EmuState *state, uint64_t addr, uint32_t val) { // ==================== MMIO Hook Callbacks ==================== -static uint64_t vic_src_addr = 0; -static uint64_t vic_dst_addr = 0; +// ==================== VIC ==================== +// +// bdk (vic.c) drives VIC through the Falcon private-register window: +// VIC(0x1000 + (priv >> 6)) = data. PVIC_FALCON_ADDR supplies the low bits +// for registers that need them; none of the ones modelled here do. The model +// keeps what a compose needs - the config struct's address (PRAMBASE), the +// slots' source surfaces and the target surface - and, on COMPOSE_START, +// reads the config struct from guest memory and draws the enabled pitch +// slots into the target with the output flip/transpose. That is what Nyx +// relies on: its 1280x720 GUI is turned into the panel's 720x1280 portrait +// framebuffer by a 270-degree VIC rotation (flip X, then transpose). +// +// Config struct layout (bdk vic_config_t; all fields little-endian u64 +// bitfields): +// 0x10 OutputConfig u64 0: FlipX b48, FlipY b49, Transpose b50 +// u64 1: TargetRect L b0, R b16, T b32, B b48 +// 0x20 OutputSurfaceConfig u64 0: format b0, BlkKind b11, W-1 b32, H-1 b46 +// 0x90 + n * 0xB0 slot n: u64 0: SlotEnable b0 +// u64 4/5: SourceRect L|R, T|B (16.16, b0/b32) +// u64 6: DestRect L b0, R b16, T b32, B b48 +// + 0x40 SlotSurfaceConfig: as OutputSurfaceConfig +// Rects are inclusive. The output surface size is given pre-transpose, so a +// transposed target is (H x W) pixels, which is how the DC reads it back. + +static constexpr uint32_t kVicPramBase = 0x1500; // VIC_SC_PRAMBASE 0x14000 +static constexpr uint32_t kVicSfcBase0 = 0x150C; // VIC_SC_SFC0_BASE_LUMA 0x14300 + n * 0x100 +static constexpr uint32_t kVicTarget = 0x1880; // VIC_BL_TARGET_BASADR 0x22000 +static constexpr uint32_t kVicCompose = 0x1400; // VIC_FC_COMPOSE 0x10000 + +struct VicRegs { + uint64_t cfg = 0; // config struct address + uint64_t sfc[8] = {}; // slot n luma surface + uint64_t target = 0; // output surface +}; +static VicRegs vic; static uint32_t vic_read(EmuState *state, uint64_t addr) { (void)state; (void)addr; + return 0; // PVIC_FALCON_IDLESTATE: composes finish at once +} + +// Bytes per pixel of a VIC pixel format (bdk vic.h), 0 if not modelled. +static uint32_t vic_bpp(uint32_t fmt) { + if (fmt == 1) + return 1; // L8 + if (fmt >= 21 && fmt <= 24) + return 2; // X1B5G5R5 .. B5G5R5X1 + if (fmt >= 31 && fmt <= 38) + return 4; // A8B8G8R8 .. R8G8B8X8 return 0; } -// VIC registers using Falcon PA translated offsets (1000 + untranslated >> 6) -// VIC registers using Falcon PA translated offsets (1000 + untranslated >> 6) -static uint64_t vic_config_addr = 0; -static uint32_t vic_config_size = 0; -static uint32_t vic_last_falcon_addr = 0; - -struct vic_out_config_struct { - uint32_t raw[2]; -}; - -struct vic_out_sfc_config_struct { - uint32_t raw[2]; -}; - -static void vic_write_internal(EmuState *state, uint32_t translated_off, - uint32_t val); - -static void vic_write(EmuState *state, uint64_t addr, uint32_t val) { - uint32_t offset = (uint32_t)(addr - VIC_BASE); - - if (offset == 0x10AC) { // PVIC_FALCON_ADDR - vic_last_falcon_addr = val; - } else if (offset == 0x10B0) { // PVIC_FALCON_DATA - uint32_t translated_off = (vic_last_falcon_addr >> 6) + 0x1000; - vic_write_internal(state, translated_off, val); - } else { - vic_write_internal(state, offset, val); - } +// A host pointer to [addr, addr + len) of emulated DRAM, or null. +static uint8_t *vic_dram(EmuState *state, uint64_t addr, uint64_t len) { + if (!state->dram_low_ptr || addr < DRAM_BASE || + addr + len > DRAM_BASE + DRAM_WINDOW_SIZE) + return nullptr; + return state->dram_low_ptr + (addr - DRAM_BASE); } -static void vic_write_internal(EmuState *state, uint32_t offset, uint32_t val) { +static void vic_compose(EmuState *state) { + uint64_t c[0x610 / 8]; + if (!vic.cfg || uc_mem_read(state->uc, vic.cfg, c, sizeof(c)) != UC_ERR_OK) + return; + auto bits = [](uint64_t v, unsigned lo, unsigned n) { + return (uint32_t)((v >> lo) & ((1ull << n) - 1)); + }; - if (offset == 0x1500) { // VIC_SC_PRAMBASE - vic_config_addr = (uint64_t)val << 8; - } else if (offset == 0x1504) { // VIC_SC_PRAMSIZE - vic_config_size = val << 6; - } else if (offset == 0x150C) { // VIC_SC_SFC0_BASE_LUMA - vic_src_addr = (uint64_t)val << 8; - } else if (offset == 0x1880) { // VIC_BL_TARGET_BASADR - vic_dst_addr = (uint64_t)val << 8; - } else if ((offset == 0x1400 || offset == 0x1440) && - val == 1) { // VIC_FC_COMPOSE - if (vic_src_addr >= 0x40000000 && vic_dst_addr >= 0x40000000) { - uint32_t sfc[2] = {0}; - uc_mem_read(state->uc, vic_config_addr + 0x18, sfc, 8); + bool flip_x = bits(c[2], 48, 1), flip_y = bits(c[2], 49, 1); + bool transpose = bits(c[2], 50, 1); + uint32_t tl = bits(c[3], 0, 14), tr = bits(c[3], 16, 14); + uint32_t tt = bits(c[3], 32, 14), tb = bits(c[3], 48, 14); + uint32_t ofmt = bits(c[4], 0, 7), okind = bits(c[4], 11, 4); + uint32_t ow = bits(c[4], 32, 14) + 1, oh = bits(c[4], 46, 14) + 1; + uint32_t bpp = vic_bpp(ofmt); - uint32_t dw = (sfc[1] & 0x3FFF), dh = ((sfc[1] >> 14) & 0x3FFF); - bool fb_fb = false; - if (dw < 16 || dh < 16 || dw > 2048 || dh > 2048) { - dw = state->fb_width; - dh = state->fb_height; - fb_fb = true; - if (dw < 16) - dw = 720; - if (dh < 16) - dh = 1280; - } + static uint64_t logged = ~0ull; + auto log_once = [&](const char *what) { + uint64_t key = vic.target ^ ((uint64_t)ofmt << 40) ^ ((uint64_t)okind << 48); + if (logged != key) { + logged = key; + printf("[vic] compose skipped: %s\n", what); + } + }; + if (!bpp || okind != 0) + return log_once("output surface not pitch or format not modelled"); - printf("[vic] Compose: 0x%llX -> 0x%llX (%dx%d) %s\n", - (unsigned long long)vic_src_addr, (unsigned long long)vic_dst_addr, - dw, dh, fb_fb ? "(FALLBACK)" : ""); + uint32_t out_pitch = (transpose ? oh : ow) * bpp; + uint64_t out_len = (uint64_t)out_pitch * (transpose ? ow : oh); + uint8_t *dst = vic_dram(state, vic.target, out_len); + if (!dst) + return log_once("target outside DRAM"); + if (tr >= ow) + tr = ow - 1; + if (tb >= oh) + tb = oh - 1; - // Hekate configures VIC with SlotBlkKind=PITCH, OutBlkKind=PITCH. - // This is a straight pitch-to-pitch copy (possibly with rotation/flip - // handled by the real VIC FCE microcode, but we just copy here). - size_t sz = (size_t)dw * dh * 4; - if (sz > 32 * 1024 * 1024) - return; - std::vector buf(sz); - if (uc_mem_read(state->uc, vic_src_addr, buf.data(), sz) == UC_ERR_OK) { - uc_mem_write(state->uc, vic_dst_addr, buf.data(), sz); - - - state->display_dirty = true; + for (int n = 0; n < 8; n++) { + const uint64_t *sl = &c[(0x90 + n * 0xB0) / 8]; + if (!(sl[0] & 1) || !vic.sfc[n]) + continue; + uint32_t sfmt = bits(sl[8], 0, 7), skind = bits(sl[8], 11, 4); + uint32_t sw = bits(sl[8], 32, 14) + 1, sh = bits(sl[8], 46, 14) + 1; + if (skind != 0 || vic_bpp(sfmt) != bpp) { + log_once("slot surface not pitch or not the output's size of pixel"); + continue; + } + const uint8_t *src = vic_dram(state, vic.sfc[n], (uint64_t)sw * sh * bpp); + if (!src) + continue; + uint32_t sl_l = bits(sl[4], 16, 14), sl_r = bits(sl[4], 48, 14); + uint32_t sl_t = bits(sl[5], 16, 14), sl_b = bits(sl[5], 48, 14); + uint32_t dl = bits(sl[6], 0, 14), dr = bits(sl[6], 16, 14); + uint32_t dt = bits(sl[6], 32, 14), db = bits(sl[6], 48, 14); + if (sl_r < sl_l || sl_b < sl_t || dr < dl || db < dt) + continue; + uint32_t x0 = std::max(dl, tl), x1 = std::min(dr, tr); + uint32_t y0 = std::max(dt, tt), y1 = std::min(db, tb); + if (x0 > x1 || y0 > y1) + continue; + // Nearest-neighbour scaling from the source rect onto the dest rect; + // the column map is worked out once per compose, not per pixel. + static std::vector sxs; + sxs.resize(x1 - x0 + 1); + for (uint32_t tx = x0; tx <= x1; tx++) + sxs[tx - x0] = sl_l + (uint32_t)((uint64_t)(tx - dl) * + (sl_r - sl_l + 1) / (dr - dl + 1)); + uint32_t src_pitch = sw * bpp; + for (uint32_t ty = y0; ty <= y1; ty++) { + uint32_t sy = sl_t + (uint32_t)((uint64_t)(ty - dt) * (sl_b - sl_t + 1) / + (db - dt + 1)); + if (sy >= sh) + continue; + const uint8_t *srow = src + (uint64_t)sy * src_pitch; + uint32_t fy = flip_y ? oh - 1 - ty : ty; + for (uint32_t tx = x0; tx <= x1; tx++) { + uint32_t sx = sxs[tx - x0]; + if (sx >= sw) + continue; + uint32_t fx = flip_x ? ow - 1 - tx : tx; + uint64_t o = transpose ? (uint64_t)fx * out_pitch + (uint64_t)fy * bpp + : (uint64_t)fy * out_pitch + (uint64_t)fx * bpp; + if (bpp == 4) + memcpy(dst + o, srow + (uint64_t)sx * 4, 4); + else + memcpy(dst + o, srow + (uint64_t)sx * bpp, bpp); } } } - printf("[vic] W: 0x%08X = 0x%08X\n", offset, val); + + uint32_t xf = (flip_x ? dcwin::XF_FLIP_X : 0) | + (flip_y ? dcwin::XF_FLIP_Y : 0) | + (transpose ? dcwin::XF_TRANSPOSE : 0); + if (state->vic_out_addr != vic.target || state->vic_out_xform != xf) + printf("[vic] compose: %ux%u -> 0x%08llX%s%s%s\n", ow, oh, + (unsigned long long)vic.target, flip_x ? ", flip X" : "", + flip_y ? ", flip Y" : "", transpose ? ", transpose" : ""); + state->vic_out_addr = vic.target; + state->vic_out_xform = xf; + state->display_dirty = true; +} + +static void vic_write(EmuState *state, uint64_t addr, uint32_t val) { + uint32_t offset = (uint32_t)(addr - VIC_BASE); + if (offset == kVicPramBase) + vic.cfg = (uint64_t)val << 8; + else if (offset >= kVicSfcBase0 && offset < kVicSfcBase0 + 8 * 4) + vic.sfc[(offset - kVicSfcBase0) / 4] = (uint64_t)val << 8; + else if (offset == kVicTarget) + vic.target = (uint64_t)val << 8; + else if (offset == kVicCompose && (val & 1)) + vic_compose(state); } // ==================== APE audio hub: I2S, ADMAIF, ADMA ==================== @@ -4516,6 +4622,7 @@ void mmio_init(uc_engine *uc, EmuState *state) { ccplex_reset(state); sdhci_reset_regs(sdhci_regs[0]); sdhci_reset_regs(sdhci_regs[1]); + dc_reset(state); uc_hook_add(uc, &h_unmapped, UC_HOOK_MEM_READ_UNMAPPED | UC_HOOK_MEM_WRITE_UNMAPPED, @@ -4585,8 +4692,7 @@ void mmio_soft_reset(EmuState *state, bool power_cycle) { 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; + vic = VicRegs(); for (auto &d : actmon_dev) d = ActmonDev(); actmon_glb_period = 0; @@ -4616,23 +4722,8 @@ void mmio_soft_reset(EmuState *state, bool power_cycle) { else emmc_ext_csd_card_reset(); - // 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; - + // Display controller and VIC back to their defaults. + dc_reset(state); state->bpmp_halted = false; } From 4f42e04f6ee93b1318750e80f79bbd3567496ad2 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 19:13:08 +0000 Subject: [PATCH 06/21] Model PLLMB and the EMC so Minerva can train and switch the DRAM clock hekate 6.5.3 with the stock bootloader folder never reached Nyx. Nyx trains the DRAM itself with Minerva, and Minerva spun forever on PLLMB_BASE.LOCK: the CAR model had no PLLMB and read it as 0. Behind that poll were more. Every EMC register but three read 0, so Minerva would have spun on the DLL-enable bit it writes to EMC_CFG_DIG_DLL and on EMC_DIG_DLL_STATUS lock, timed out on the clock-change handshake, and divided by a zero MR18/MR19 oscillator count. - CAR: PLLMB_BASE/MISC1 per TRM 5.2.230-231, locking once enabled. CLK_SOURCE_EMC, _EMC_DLL and _EMC_SAFE read back what was written, from their TRM resets. A written PLLM or PLLU reads back its dividers, which were dropped before while ENABLE was clear. - EMC: a register file with broadcast and per-channel banks, plus: - MRW capture and MRR data/MRR_DIVLD per channel. - MR4 at normal temperature, and MR18/MR19 computed from MR23's run time at the current DRAM clock over 2 x tDQS2DQ. - DLL lock. - The CAR/EMC clock-change handshake: a new CLK_SOURCE_EMC source or divisor replays the CCFIFO and raises CLKCHANGE_COMPLETE. With the stock folder, Nyx now trains 204, 800 and 1600 MHz and runs its 800/1600 MHz power-saving loop, on Erista and Mariko. hwtest's output is unchanged. The WDT cookie that keeps hekate's IPL from training is kept; its comments no longer claim the EMC can't do it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb --- DESIGN.md | 75 ++++++++++--- main.cpp | 15 +-- t210/mmio.cpp | 294 +++++++++++++++++++++++++++++++++++++++++--------- 3 files changed, 316 insertions(+), 68 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 37074ed..f976bfa 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -51,18 +51,23 @@ same peripheral models through one dispatch (see [CCPLEX CPU0](#ccplex-cpu0)). `uc_mem_write`. We also pre-write the 4-byte cookie `0x544457` ("WDT") at IRAM offset `0x4003FF18`. Hekate reads that location during early boot. When the cookie is present, it takes the `goto skip_lp0_minerva_config` - branch and skips loading both `libsys_lp0.bso` and the Minerva - DRAM-training module. Real DRAM training would touch the EMC (External - Memory Controller) and MC (Memory Controller), neither of which the - emulator models. The matching exception-enable cookie at `0x4003FF1C` - stays zero, so the "hang detected" warning is suppressed. + branch and skips loading `libsys_lp0.bso` and training the DRAM with the + Minerva module, as it does on hardware after a watchdog reset. The EMC + model runs Minerva (see [EMC and DRAM clock](#emc-and-dram-clock)), and + Nyx trains the DRAM itself when it starts; the cookie only spares a + minimal SD image the IPL's "missing lib" errors and shortens the boot. + The matching exception-enable cookie at `0x4003FF1C` stays zero, so the + "hang detected" warning is suppressed. 2. PC is set to `0x40010000`, SP to `IPL_STACK_ADDR`. CPSR enters ARM mode. -3. The IPL (Initial Program Loader) initialises clocks, fuses and the display, - then continues straight into the boot menu without loading LP0 or Minerva. +3. The IPL (Initial Program Loader) initialises clocks, fuses, the DRAM + (`sdram_init`, at 204 MHz) and the display, then continues into the boot + menu without loading LP0 or Minerva. 4. Hekate self-relocates into DRAM (`0xC0000000+`) and continues. It points DC (Display Controller) window A at its portrait framebuffer and draws its boot logo and menus there, sideways, for the landscape-mounted panel. -5. Nyx (the LVGL GUI) draws landscape into a second framebuffer and has VIC +5. Nyx (the LVGL GUI) loads Minerva, trains the DRAM at 204, 800 and + 1600 MHz, and from then on alternates 1600 and 800 MHz on every GUI loop + to save power. It draws landscape into a second framebuffer and has VIC turn every frame into the portrait surface that window A scans out. The display follows the DC's windows, whatever they point at (see Display pipeline). @@ -161,6 +166,38 @@ file with the TRM's reset values, plus the side effects bdk waits on: The SD card stays at High Speed (48 MHz). UHS-I needs ACMD41 to answer with S18A and a CMD11 voltage switch, which the SD model does not do. +### EMC and DRAM clock + +The EMC (External Memory Controller, `t210/mmio.cpp`) is a register file - +reads return what was written, as `sdram_init` programmed it from the BCT - +with the controller's own behaviour on top (TRM 18.11). That is what bdk's +mode-register reads and Minerva, hekate's DRAM training and +frequency-switching module, depend on: + +- **Banks.** A write to the broadcast bank (`EMC_BASE`) reaches both + channels; `EMC0_BASE` / `EMC1_BASE` address one channel each. +- **Mode registers.** MRWs (`EMC_MRW`, `EMC_MRW2..15`) are remembered. An + MRR latches the answer into the channel's `EMC_MRR` and sets + `EMC_EMC_STATUS.MRR_DIVLD` until it is read. MR4 reports a normal + temperature, MR5-8 the configured DRAM ID, and MR18/MR19 the DQS interval + oscillator count: MR23's run time at the current DRAM clock over twice a + 400 ps tDQS2DQ. Minerva divides by that count. +- **Digital DLL.** `EMC_DIG_DLL_STATUS` reports lock as soon as the DLL is + (re)started; `EMC_CFG_DIG_DLL.CFG_DLL_EN` reads back as written, which is + what Minerva spins on around each DLL restart. +- **Clock change.** A new source or divisor in CAR `CLK_SOURCE_EMC` (TRM + 5.2.73) is the CAR/EMC handshake: the EMC replays the writes queued in its + clock-change FIFO (`EMC_CCFIFO_DATA` / `_ADDR`) and raises + `CLKCHANGE_COMPLETE` in `EMC_INTSTATUS`. The DRAM clock follows from + `CLK_SOURCE_EMC` and the PLLM / PLLMB dividers; `PLLMB_BASE` (TRM 5.2.230) + locks once enabled, like the other PLLs. +- **Status.** `EMC_EMC_STATUS` otherwise reports timing updates done, the + DRAM active and the state machines idle. + +With the stock `bootloader/` folder, Nyx trains 204, 800 and 1600 MHz and +then switches between 800 and 1600 MHz on every GUI loop, each switch a full +handshake with a CCFIFO replay. + ### Security Engine (`t210/se_engine.cpp`) Models the SE (Security Engine) register block at `0x70012000`. Supports: @@ -449,8 +486,12 @@ needed. The 64 KB TX log trim happens in-place during the write hook. function nibble after `display_init`. The previous behaviour (hardcoded `return 0`) silently dropped the muxed function bits and made any read-back-style probe see all zeros. -- **PLLs.** Reads on `PLL_BASE` registers return `ENABLE | LOCK` for any of - the PLLs Minerva polls during DRAM training. +- **PLLs.** PLLP and PLLD always read as measured on a console in RCM (up + and locked). The other `_BASE` registers read as measured until the + payload programs them (PLLM up but unlocked on Erista, the rest down), + then read back what was written, dividers included, with LOCK set + whenever ENABLE is. That includes PLLMB, which Minerva moves the EMC onto + for a frequency change. - **KFUSE.** `STATE` returns `DONE | CRCPASS` immediately so the BDK function `kfuse_wait_ready` doesn't hang. - **TSEC.** `DMATRFCMD_IDLE` is reported set, and the keygen status word is @@ -471,7 +512,7 @@ needed. The 64 KB TX log trim happens in-place during the write hook. they are tweakable but because the chip-detection code expects exact cookies: `MAX17050.DevName=0x00AC`, `BQ24193.VendorPart=0x2F`, the BM92T36 `FW_TYPE`/`MAN_ID`/`DEV_ID` triple, `TSEC.STATUS=0xB0B0B0B0`, - `KFUSE.STATE=DONE|CRCPASS`, `PLL_BASE=ENABLE|LOCK`. Changing them breaks + `KFUSE.STATE=DONE|CRCPASS`, `PLL_BASE.LOCK` once enabled. Changing them breaks the Hekate init path. They are hardcoded by design. ## Determinism and the auto-script flag @@ -608,8 +649,16 @@ sweep; CI runs both. These are baked into the current source. Listed here so future maintainers don't repeat the diagnosis: -- **Minerva DRAM training** hangs in a `PLL_BASE.LOCK` poll. Fix: always - report `LOCK | ENABLE`. +- **Minerva DRAM training** hangs in a `PLL_BASE.LOCK` poll. Fix: report + LOCK once the PLL is enabled. +- **Minerva hung Nyx** (hekate 6.5.3 with the stock `bootloader/` folder + never reached its GUI). Nyx trains the DRAM itself, and Minerva spun on + `PLLMB_BASE.LOCK` (the CAR model had no PLLMB and read it as 0). Behind + that it would have spun on the DLL-enable bit it writes to + `EMC_CFG_DIG_DLL` and on `EMC_DIG_DLL_STATUS` lock, timed out on the + clock-change handshake, and divided by a zero MR18/MR19 oscillator count, + because every EMC register but three read 0. Fix: PLLMB, and the EMC + model described in [EMC and DRAM clock](#emc-and-dram-clock). - **`kfuse_wait_ready`** loops on `STATE.DONE`. Fix: stub `DONE | CRCPASS`. - **AMS keygen** retries `tsec_query` 15 times until timeout. Fix: stub `STATUS = 0xB0B0B0B0`. diff --git a/main.cpp b/main.cpp index 1e207ad..012074f 100644 --- a/main.cpp +++ b/main.cpp @@ -153,12 +153,13 @@ static uc_engine *setup_emulation(EmuState *state, uint8_t *payload, size_t payl // Pre-set Hekate's "watchdog fired" magic at IRAM 0x4003FF18 (cookie "WDT") // so its early boot does `goto skip_lp0_minerva_config`, skipping both - // libsys_lp0.bso and the Minerva DRAM-training path. The matching - // EXCP_EN_ADDR (0x4003FF1C) is intentionally left zeroed so ERR_EXCEPTION - // is *not* set and the user doesn't see a "hang detected" warning screen. - // We can't model EMC/MC well enough for real Minerva training, so this is - // the cleanest opt-out (the same path Hekate uses on hardware after a - // legitimate WDT reset). + // libsys_lp0.bso and the IPL's Minerva DRAM training - the same path + // Hekate takes on hardware after a WDT reset. The matching EXCP_EN_ADDR + // (0x4003FF1C) is intentionally left zeroed so ERR_EXCEPTION is *not* set + // and the user doesn't see a "hang detected" warning screen. The EMC + // model runs Minerva fine (Nyx trains the DRAM itself when it starts); + // this only spares a minimal SD image the IPL's "missing lib" errors and + // shortens the boot. { uint32_t wdt_magic = 0x544457; // "WDT" uc_mem_write(uc, 0x4003FF18, &wdt_magic, sizeof(wdt_magic)); @@ -495,7 +496,7 @@ int main(int argc, char *argv[]) { // Soft reboot: re-write the payload to IRAM, wipe DRAM (so Nyx and // the bootloader's file-static caches reset), reset PC/SP/clock and - // re-prime the WDT cookie so Hekate's early boot skips Minerva again. + // re-prime the WDT cookie so Hekate's IPL skips LP0/Minerva again. if (state.reboot_requested.exchange(false)) { uc_emu_stop(uc); bool cold = state.reboot_cold.exchange(false); diff --git a/t210/mmio.cpp b/t210/mmio.cpp index 780ec76..1d4f079 100644 --- a/t210/mmio.cpp +++ b/t210/mmio.cpp @@ -3187,22 +3187,42 @@ uint32_t clk_rst_read(EmuState *state, uint64_t addr) { return w; // measured: down on both } case 0x90: { // PLLM + // Until the payload programs it: Erista leaves PLLM enabled but + // unlocked at this point, Mariko has it off. Once written, it reads + // back what was written - the dividers too, before ENABLE is set. + if (!mmio_regs.count(addr)) + return mariko ? 0u : (1u << 30); uint32_t w = mmio_regs.get(addr); - if (w & (1u << 30)) - return w | (1u << 27); - // Erista leaves PLLM enabled but unlocked at this point; Mariko has it off. - return mariko ? 0u : (1u << 30); + return (w & (1u << 30)) ? w | (1u << 27) : w; } case 0xC0: { // PLLU + if (!mmio_regs.count(addr)) + return mariko ? 0u : ((1u << 30) | (1u << 27)); uint32_t w = mmio_regs.get(addr); - if (w & (1u << 30)) - return w | (1u << 27); - return mariko ? 0u : ((1u << 30) | (1u << 27)); + return (w & (1u << 30)) ? w | (1u << 27) : w; } case 0xA0: // PLLP_BASE - same value on both return 0x48115408u; case 0xD0: // PLLD_BASE - up on both return (1u << 30) | (1u << 27); + case 0x5E8: { // PLLMB_BASE (TRM 5.2.230), reset 0x00002A02: down + // Minerva moves the EMC onto PLLMB for a DRAM frequency change and + // spins on PLLMB_LOCK after enabling it. LOCK and FREQ_LOCK (bits 27, + // 26) are read-only: set once the PLL is enabled, or forced by + // PLLMB_MISC1.LOCK_OVERRIDE. + uint32_t w = mmio_regs.get(addr, 0x00002A02) & ~(3u << 26); + uint32_t misc1 = mmio_regs.get(CLK_RST_BASE + 0x5EC, 0x00010000); + if ((w & (1u << 30)) || (misc1 & (1u << 18))) + w |= 3u << 26; + return w; + } + case 0x5EC: // PLLMB_MISC1, reset 0x00010000 (EN_LCKDET) + return mmio_regs.get(addr, 0x00010000); + case 0x19C: // CLK_SOURCE_EMC, reset 0x60180000 (TRM 5.2.73) + return mmio_regs.get(addr, 0x60180000); + case 0x664: // CLK_SOURCE_EMC_DLL, reset 0x60000000 + case 0x724: // CLK_SOURCE_EMC_SAFE, reset 0x60000000 + return mmio_regs.get(addr, 0x60000000); } // Informational clock registers, measured on a real Mariko. These read back @@ -3297,12 +3317,16 @@ uint32_t clk_rst_read(EmuState *state, uint64_t addr) { return 0; } +// A CLK_SOURCE_EMC write is the CAR/EMC clock-change handshake (EMC below). +static void emc_clock_source_write(EmuState *state, uint32_t val); + void clk_rst_write(EmuState *state, uint64_t addr, uint32_t val) { (void)state; uint32_t offset = (uint32_t)(addr - CLK_RST_BASE); - // Only the _U pair is live so far; everything else stays a no-op, and the - // generic mmio_regs cache in the write hook still serves the CLK_SOURCE_* - // read-backs. bdk reaches these through the SET/CLR aliases exclusively. + // The _U pair is live (bdk reaches it through the SET/CLR aliases), and + // CLK_SOURCE_EMC starts an EMC clock change. Everything else only lands + // in the write hook's mmio_regs cache, which clk_rst_read consults for + // the registers it reads back (CLK_SOURCE_UARTD, the EMC clock sources). switch (offset) { case 0x00C: car_rst_u = val; break; // RST_DEVICES_U, direct write case 0x018: car_enb_u = val; break; // CLK_OUT_ENB_U, direct write @@ -3310,6 +3334,7 @@ void clk_rst_write(EmuState *state, uint64_t addr, uint32_t val) { case 0x314: car_rst_u &= ~val; break; // RST_DEV_U_CLR case 0x330: car_enb_u |= val; break; // CLK_ENB_U_SET case 0x334: car_enb_u &= ~val; break; // CLK_ENB_U_CLR + case 0x19C: emc_clock_source_write(state, val); break; // CLK_SOURCE_EMC default: break; } // The PCIe root complex depends on PLLE, PLLREFE and the PCIE/AFI/ @@ -3361,61 +3386,234 @@ void fuse_write(EmuState *state, uint64_t addr, uint32_t val) { if (offset == 0x04) g_fuse_ctrl_addr = val; // FUSE_ADDR } -// ==================== EMC (DRAM mode register reads) ==================== +// ==================== EMC ==================== // -// Hekate's HW-info screen calls sdram_read_mrx(MRx), which: -// 1. writes EMC(EMC_MRR) with (rank << 30) | (mrx << 16) on the broadcast -// bank at EMC_BASE, -// 2. polls EMC(EMC_EMC_STATUS) bit 20 (MRR_DIVLD) until set, -// 3. reads EMC_CH0(EMC_MRR) and EMC_CH1(EMC_MRR) from the per-channel -// banks at EMC0_BASE / EMC1_BASE. +// A register file - reads return what was written - with the controller's +// own behaviour on top (TRM 18.11): // -// We capture the requested mode register on the EMC_MRR write and route the -// per-channel reads back to the matching EmuState atomic. +// Banks. EMC_BASE is the broadcast bank: a write there reaches both +// channels. EMC0_BASE / EMC1_BASE address one channel each. mmio_regs +// holds every bank's words (the write hook stores the raw address), and a +// broadcast write is mirrored into both channel banks. +// +// Mode registers. EMC_MRW and EMC_MRW2..15 send an MRW to the DRAM. +// EMC_MRR sends an MRR, after which the channel's EMC_MRR holds the answer +// (both x16 dies' bytes, bits 15:0) and its EMC_EMC_STATUS.MRR_DIVLD stays +// set until that data is read. MR4 reports the normal-temperature refresh +// rate, MR5-8 the configured DRAM ID, MR18/MR19 the DQS interval +// oscillator count, and any other mode register what was last written. +// +// Digital DLL. It locks as soon as it is (re)started: EMC_DIG_DLL_STATUS +// reports DLL_LOCK and DLL_PRIV_UPDATED. The DLL code itself (DLL_OUT) is +// not modelled and reads 0. +// +// Clock change. A new source or divisor in CAR CLK_SOURCE_EMC starts the +// CAR/EMC clock-change handshake: the EMC replays the writes queued in its +// clock-change FIFO (EMC_CCFIFO_DATA, then EMC_CCFIFO_ADDR) and raises +// CLKCHANGE_COMPLETE in EMC_INTSTATUS (sticky, write 1 to clear). +// +// EMC_EMC_STATUS otherwise reports timing updates done, the DRAM active +// (not powered down, not in self-refresh) and the state machines idle. +// +// bdk's sdram_read_mrx needs the MRR path. Minerva, hekate's DRAM training +// and frequency-switching module, needs the rest: it spins on DLL lock and +// on the DLL-enable bit it writes, waits for the clock-change handshake, +// and divides by the oscillator count. -static constexpr uint32_t EMC_ADR_CFG = 0x010; -static constexpr uint32_t EMC_MRR = 0x0EC; -static constexpr uint32_t EMC_EMC_STATUS = 0x2B4; -static constexpr uint32_t EMC_FBIO_CFG7 = 0x584; -static constexpr uint32_t EMC_STATUS_MRR_DIVLD = 1u << 20; +static constexpr uint32_t EMC_INTSTATUS = 0x000; +static constexpr uint32_t EMC_MRW = 0x0E8; +static constexpr uint32_t EMC_MRR = 0x0EC; +static constexpr uint32_t EMC_EMC_STATUS = 0x2B4; +static constexpr uint32_t EMC_CFG_DIG_DLL = 0x2BC; +static constexpr uint32_t EMC_DIG_DLL_STATUS = 0x2C4; +static constexpr uint32_t EMC_CCFIFO_ADDR = 0x3E8; +static constexpr uint32_t EMC_CCFIFO_DATA = 0x3EC; +static constexpr uint32_t EMC_CCFIFO_STATUS = 0x3F0; +static constexpr uint32_t EMC_FBIO_CFG7 = 0x584; -static uint32_t g_last_mrr_mrx = 5; +static constexpr uint32_t EMC_INT_CLKCHANGE_COMPLETE = 1u << 4; +static constexpr uint32_t EMC_INT_MRR_DIVLD = 1u << 5; +static constexpr uint32_t EMC_INT_CCFIFO_OVERFLOW = 1u << 8; +static constexpr uint32_t EMC_STATUS_MRR_DIVLD = 1u << 20; +// The TRM calls the clock-change FIFO 32 deep, but CCFIFO_COUNT is 7 bits +// and NVIDIA's own DVFS sequence (which Minerva ports) queues up to 65 +// entries per change, so the model takes as many as the count can report. +static constexpr size_t kEmcCcfifoDepth = 127; -static uint8_t emc_mrx_value(EmuState *state, uint32_t mrx) { - switch (mrx) { - case 5: return state->dram_vendor.load(); - case 6: return state->dram_rev_id1.load(); - case 7: return state->dram_rev_id2.load(); - case 8: return state->dram_density.load(); - default: return 0; +// CAR CLK_SOURCE_EMC (TRM 5.2.73). A clock change starts when +// EMC_2X_CLK_SRC, MC_EMC_SAME_FREQ or EMC_2X_CLK_DIVISOR changes, or on +// FORCE_CC_TRIGGER; rewriting the same value does nothing. +static constexpr uint32_t CAR_CLK_SOURCE_EMC = 0x19C; +static constexpr uint32_t CAR_CLK_SOURCE_EMC_RESET = 0x60180000; // CLK_M +static constexpr uint32_t CAR_EMC_CC_FIELDS = 0xE00100FF; +static constexpr uint32_t CAR_EMC_FORCE_CC_TRIGGER = 1u << 27; + +// The LPDDR4's DQS-to-DQ delay, what the DQS interval oscillator measures. +// JEDEC allows 200-800 ps; this is mid-range. +static constexpr uint32_t kDramTdqs2dqPs = 400; + +struct EmcState { + uint8_t mr[256] = {}; // mode registers, as last written by MRW + uint32_t mrr_ma[2] = {5, 5}; // per channel: MA of the last MRR + bool mrr_valid[2] = {}; // per channel: MRR_DIVLD + uint32_t intstatus = 0; + uint32_t ccfifo_data = 0; + std::vector> ccfifo; // (offset, data) + uint32_t clk_source = CAR_CLK_SOURCE_EMC_RESET; // CAR, as last applied +}; +static EmcState emc; + +static bool emc_is_mrw(uint32_t offset) { + switch (offset) { + case 0x0E8: case 0x134: case 0x138: case 0x13C: // MRW, MRW2-4 + case 0x4A0: case 0x4A4: case 0x4A8: case 0x4AC: // MRW5-8 + case 0x4B0: case 0x4B4: case 0x4B8: case 0x4BC: // MRW9-12 + case 0x4C0: case 0x4C4: case 0x4D0: // MRW13-15 + return true; + default: + return false; } } +// The EMC clock, from CAR. EMC_2X_CLK_SRC picks the input; the _UD inputs +// bypass the 7.1 EMC_2X_CLK_DIVISOR. The PLLs run at +// 38.4 MHz / DIVM * DIVN / (DIVP + 1), as Minerva's own table computes. +static uint32_t emc_rate_khz() { + auto pll = [](uint32_t off) -> uint32_t { + uint32_t b = mmio_regs.get(CLK_RST_BASE + off); + uint32_t m = b & 0xFF, n = (b >> 8) & 0xFF, p = (b >> 20) & 0x1F; + return m ? (uint32_t)(38400ull * n / m / (p + 1)) : 0; + }; + uint32_t src = emc.clk_source, in = 0; + bool ud = false; + switch (src >> 29) { + case 0: in = pll(0x090); break; // PLLM_OUT0 + case 1: in = pll(0x080); break; // PLLC_OUT0 + case 2: in = 408000; break; // PLLP_OUT0 + case 3: in = 38400; break; // CLK_M + case 4: in = pll(0x090); ud = true; break; // PLLM_UD + case 5: in = pll(0x5E8); ud = true; break; // PLLMB_UD + case 6: in = pll(0x5E8); break; // PLLMB_OUT0 + case 7: in = 408000; ud = true; break; // PLLP_UD + } + return ud ? in : (uint32_t)(in * 2ull / ((src & 0xFF) + 2)); +} + +// MR18/MR19: the DQS interval oscillator count, run time / (2 x tDQS2DQ) +// (JEDEC LPDDR4). The run time is MR23's setting in clocks (16 x OP up to +// 63, then 2048, 4096 or 8192) at the current DRAM clock. MR23 = 0 means +// "stopped by MPC"; that is counted as the 2048-clock setting. +static uint32_t emc_dqs_osc_count() { + uint32_t op = emc.mr[23]; + uint32_t clocks = op == 0 ? 2048 : op < 64 ? 16 * op + : op < 128 ? 2048 : op < 192 ? 4096 : 8192; + uint32_t khz = emc_rate_khz(); + if (!khz) + khz = 204000; + uint64_t tck_ps = 1000000000ull / khz; + uint64_t count = clocks * tck_ps / (2 * kDramTdqs2dqPs); + return (uint32_t)std::min(std::max(count, 1), 0xFFFF); +} + +static uint32_t emc_mr_value(EmuState *state, uint32_t ma) { + uint32_t v; + switch (ma) { + case 4: v = 0x03; break; // refresh 1x: normal temp + case 5: v = state->dram_vendor.load(); break; + case 6: v = state->dram_rev_id1.load(); break; + case 7: v = state->dram_rev_id2.load(); break; + case 8: v = state->dram_density.load(); break; + case 18: v = emc_dqs_osc_count() & 0xFF; break; + case 19: v = emc_dqs_osc_count() >> 8; break; + default: v = emc.mr[ma & 0xFF]; break; + } + return (v & 0xFF) << 8 | (v & 0xFF); // both dies answer +} + +// Which bank an address is in: -1 broadcast, 0 / 1 a channel. +static int emc_bank(uint64_t addr) { + return addr >= EMC1_BASE ? 1 : addr >= EMC0_BASE ? 0 : -1; +} + uint32_t emc_read(EmuState *state, uint64_t addr) { uint32_t offset = (uint32_t)(addr & 0xFFF); - bool per_channel = (addr >= EMC0_BASE); - - if (per_channel) { - if (offset == EMC_MRR) - return emc_mrx_value(state, g_last_mrr_mrx); - return 0; - } - + int ch = std::max(emc_bank(addr), 0); // a broadcast read sees channel 0 switch (offset) { - case EMC_ADR_CFG: return 0; // single rank - case EMC_FBIO_CFG7: return (1u << 1) | (1u << 2); // ch0 + ch1 enabled - case EMC_EMC_STATUS: return EMC_STATUS_MRR_DIVLD; // MRR data always valid - case EMC_MRR: return emc_mrx_value(state, g_last_mrr_mrx); - default: return 0; + case EMC_INTSTATUS: + return emc.intstatus; + case EMC_MRR: + emc.mrr_valid[ch] = false; + return emc_mr_value(state, emc.mrr_ma[ch]); + case EMC_EMC_STATUS: { + // ACPD/DSR FSMs idle (27:24), ZQ FSM idle (22), no outstanding + // transactions (2), request FIFO empty (0). + uint32_t v = (0xFu << 24) | (1u << 22) | (1u << 2) | (1u << 0); + return emc.mrr_valid[ch] ? v | EMC_STATUS_MRR_DIVLD : v; + } + case EMC_CFG_DIG_DLL: + // Bits 31, 30, 26, 4 and 1 are write-1 triggers; they read 0. + return mmio_regs.get(addr) & ~0xC4000012u; + case EMC_DIG_DLL_STATUS: + return (1u << 17) | (1u << 15); // DLL_PRIV_UPDATED | DLL_LOCK + case EMC_CCFIFO_STATUS: + return (uint32_t)emc.ccfifo.size(); + case EMC_FBIO_CFG7: + return mmio_regs.get(addr, (1u << 1) | (1u << 2)); // both channels + default: + return mmio_regs.get(addr); } } void emc_write(EmuState *state, uint64_t addr, uint32_t val) { (void)state; uint32_t offset = (uint32_t)(addr & 0xFFF); - if (offset == EMC_MRR && addr < EMC0_BASE) { - g_last_mrr_mrx = (val >> 16) & 0xFF; + int bank = emc_bank(addr); + switch (offset) { + case EMC_INTSTATUS: + emc.intstatus &= ~val; // write 1 to clear + return; + case EMC_MRR: + for (int c = 0; c < 2; c++) { + if (bank < 0 || bank == c) { + emc.mrr_ma[c] = (val >> 16) & 0xFF; + emc.mrr_valid[c] = true; + } + } + emc.intstatus |= EMC_INT_MRR_DIVLD; + break; + case EMC_CCFIFO_DATA: + emc.ccfifo_data = val; + break; + case EMC_CCFIFO_ADDR: + if (emc.ccfifo.size() < kEmcCcfifoDepth) + emc.ccfifo.emplace_back(val & 0xFFFF, emc.ccfifo_data); + else + emc.intstatus |= EMC_INT_CCFIFO_OVERFLOW; + break; + default: + if (emc_is_mrw(offset)) + emc.mr[(val >> 16) & 0xFF] = (uint8_t)val; + break; } + mmio_regs[addr] = val; + if (bank < 0) { + mmio_regs[EMC0_BASE + offset] = val; + mmio_regs[EMC1_BASE + offset] = val; + } +} + +// CAR CLK_SOURCE_EMC was written (clk_rst_write). +static void emc_clock_source_write(EmuState *state, uint32_t val) { + bool change = ((val ^ emc.clk_source) & CAR_EMC_CC_FIELDS) || + (val & CAR_EMC_FORCE_CC_TRIGGER); + emc.clk_source = val; + if (!change) + return; + std::vector> fifo; + fifo.swap(emc.ccfifo); + for (const auto &e : fifo) + emc_write(state, EMC_BASE + (e.first & 0xFFF), e.second); + emc.intstatus |= EMC_INT_CLKCHANGE_COMPLETE; } // ==================== DSI (display panel ID over MIPI-DSI) ==================== @@ -4688,7 +4886,7 @@ void mmio_soft_reset(EmuState *state, bool power_cycle) { car_rst_u = CAR_RST_U_RCM; car_enb_u = CAR_ENB_U_RCM; g_fuse_ctrl_addr = 0; - g_last_mrr_mrx = 5; + emc = EmcState(); 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; From 306a86dbcb3324ab5afb772bf2ed51c848dcec06 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 19:29:24 +0000 Subject: [PATCH 07/21] Stop planting hekate's watchdog cookie in IRAM The emulator wrote hekate's "watchdog fired" magic (0x544457 at 0x4003FF18) before every boot. hekate then took its post-watchdog path and skipped LP0 and Minerva, because the EMC could not support DRAM training. It can now, so the cookie only made the boot differ from hardware, and it never covered Nyx, which trains the DRAM itself when it finds Minerva uninitialised. With the cookie gone, hekate's IPL saves the LP0 SDRAM config and trains 204, 800 and 1600 MHz itself, and Nyx takes over the trained context. An SD image without bootloader/sys now gets hekate's real "Missing LP0/Minerva lib" screen, which waits for a key press. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb --- DESIGN.md | 40 ++++++++++++++++++++-------------------- display/sdl_display.cpp | 2 +- main.cpp | 19 +------------------ 3 files changed, 22 insertions(+), 39 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index f976bfa..5d3f4d4 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -48,26 +48,23 @@ same peripheral models through one dispatch (see [CCPLEX CPU0](#ccplex-cpu0)). ## Boot flow (Hekate as the example) 1. The payload is loaded into IRAM (Internal RAM) at `0x40010000` via - `uc_mem_write`. We also pre-write the 4-byte cookie `0x544457` ("WDT") at - IRAM offset `0x4003FF18`. Hekate reads that location during early boot. - When the cookie is present, it takes the `goto skip_lp0_minerva_config` - branch and skips loading `libsys_lp0.bso` and training the DRAM with the - Minerva module, as it does on hardware after a watchdog reset. The EMC - model runs Minerva (see [EMC and DRAM clock](#emc-and-dram-clock)), and - Nyx trains the DRAM itself when it starts; the cookie only spares a - minimal SD image the IPL's "missing lib" errors and shortens the boot. - The matching exception-enable cookie at `0x4003FF1C` stays zero, so the - "hang detected" warning is suppressed. + `uc_mem_write`. Nothing else is planted: IRAM holds what it holds after a + cold boot. 2. PC is set to `0x40010000`, SP to `IPL_STACK_ADDR`. CPSR enters ARM mode. 3. The IPL (Initial Program Loader) initialises clocks, fuses, the DRAM - (`sdram_init`, at 204 MHz) and the display, then continues into the boot - menu without loading LP0 or Minerva. + (`sdram_init`, at 204 MHz) and the display, mounts the SD card, loads + `bootloader/sys/libsys_lp0.bso` (it saves the LP0 SDRAM config to PMC + scratch) and trains the DRAM with Minerva + (`bootloader/sys/libsys_minerva.bso`) at 204, 800 and 1600 MHz, all as on + hardware (see [EMC and DRAM clock](#emc-and-dram-clock)). An SD image + without those modules gets hekate's "Missing LP0 (sleep) lib! / Missing + Minerva lib!" screen, which waits for a key press before the menu. 4. Hekate self-relocates into DRAM (`0xC0000000+`) and continues. It points DC (Display Controller) window A at its portrait framebuffer and draws its boot logo and menus there, sideways, for the landscape-mounted panel. -5. Nyx (the LVGL GUI) loads Minerva, trains the DRAM at 204, 800 and - 1600 MHz, and from then on alternates 1600 and 800 MHz on every GUI loop - to save power. It draws landscape into a second framebuffer and has VIC +5. Nyx (the LVGL GUI) takes over the trained Minerva context and from then + on alternates the DRAM between 1600 and 800 MHz on every GUI loop to save + power. It draws landscape into a second framebuffer and has VIC turn every frame into the portrait surface that window A scans out. The display follows the DC's windows, whatever they point at (see Display pipeline). @@ -194,9 +191,9 @@ frequency-switching module, depend on: - **Status.** `EMC_EMC_STATUS` otherwise reports timing updates done, the DRAM active and the state machines idle. -With the stock `bootloader/` folder, Nyx trains 204, 800 and 1600 MHz and -then switches between 800 and 1600 MHz on every GUI loop, each switch a full -handshake with a CCFIFO replay. +With the stock `bootloader/` folder, hekate's IPL trains 204, 800 and +1600 MHz, and Nyx then switches between 800 and 1600 MHz on every GUI loop, +each switch a full handshake with a CCFIFO replay. ### Security Engine (`t210/se_engine.cpp`) @@ -652,13 +649,16 @@ don't repeat the diagnosis: - **Minerva DRAM training** hangs in a `PLL_BASE.LOCK` poll. Fix: report LOCK once the PLL is enabled. - **Minerva hung Nyx** (hekate 6.5.3 with the stock `bootloader/` folder - never reached its GUI). Nyx trains the DRAM itself, and Minerva spun on + never reached its GUI). The emulator planted hekate's "watchdog fired" + cookie in IRAM so the IPL would skip Minerva; Nyx then trained the DRAM + itself, and Minerva spun on `PLLMB_BASE.LOCK` (the CAR model had no PLLMB and read it as 0). Behind that it would have spun on the DLL-enable bit it writes to `EMC_CFG_DIG_DLL` and on `EMC_DIG_DLL_STATUS` lock, timed out on the clock-change handshake, and divided by a zero MR18/MR19 oscillator count, because every EMC register but three read 0. Fix: PLLMB, and the EMC - model described in [EMC and DRAM clock](#emc-and-dram-clock). + model described in [EMC and DRAM clock](#emc-and-dram-clock). With + Minerva working, the cookie is gone too, and hekate boots as on hardware. - **`kfuse_wait_ready`** loops on `STATE.DONE`. Fix: stub `DONE | CRCPASS`. - **AMS keygen** retries `tsec_query` 15 times until timeout. Fix: stub `STATUS = 0xB0B0B0B0`. diff --git a/display/sdl_display.cpp b/display/sdl_display.cpp index d52e7da..acefc35 100644 --- a/display/sdl_display.cpp +++ b/display/sdl_display.cpp @@ -642,7 +642,7 @@ bool sdl_display_poll_events(EmuState *state, uc_engine *uc) { case SDLK_r: { if (!ctrl) { // Plain R: soft reboot. Same path as the config window's "Reboot" - // button — re-prime IRAM payload + WDT cookie, wipe DRAM, reset PC. + // button — reload the payload into IRAM, wipe DRAM, reset PC. state->reboot_cold = true; // the user's reset is a power cycle state->reboot_requested = true; printf("[diag] Reboot requested (R)\n"); diff --git a/main.cpp b/main.cpp index 012074f..09d6cd0 100644 --- a/main.cpp +++ b/main.cpp @@ -151,20 +151,6 @@ static uc_engine *setup_emulation(EmuState *state, uint8_t *payload, size_t payl (unsigned long long)(IRAM_BASE + IRAM_SIZE), (unsigned)(IRAM_SIZE / 1024)); - // Pre-set Hekate's "watchdog fired" magic at IRAM 0x4003FF18 (cookie "WDT") - // so its early boot does `goto skip_lp0_minerva_config`, skipping both - // libsys_lp0.bso and the IPL's Minerva DRAM training - the same path - // Hekate takes on hardware after a WDT reset. The matching EXCP_EN_ADDR - // (0x4003FF1C) is intentionally left zeroed so ERR_EXCEPTION is *not* set - // and the user doesn't see a "hang detected" warning screen. The EMC - // model runs Minerva fine (Nyx trains the DRAM itself when it starts); - // this only spares a minimal SD image the IPL's "missing lib" errors and - // shortens the boot. - { - uint32_t wdt_magic = 0x544457; // "WDT" - uc_mem_write(uc, 0x4003FF18, &wdt_magic, sizeof(wdt_magic)); - } - // ---- Map DRAM as one contiguous region ---- // 0x80000000 .. 0x100000000, i.e. the whole 32-bit-addressable DRAM window // the BPMP can reach. This used to be two islands (256 MB at 0x80000000 @@ -495,8 +481,7 @@ int main(int argc, char *argv[]) { if (!sdl_display_poll_events(&state, uc)) break; // Soft reboot: re-write the payload to IRAM, wipe DRAM (so Nyx and - // the bootloader's file-static caches reset), reset PC/SP/clock and - // re-prime the WDT cookie so Hekate's IPL skips LP0/Minerva again. + // the bootloader's file-static caches reset) and reset PC/SP/clock. if (state.reboot_requested.exchange(false)) { uc_emu_stop(uc); bool cold = state.reboot_cold.exchange(false); @@ -513,8 +498,6 @@ int main(int argc, char *argv[]) { 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 From 7607dd9f695bad096a29d5e8c61153b83b0e0f09 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 20:02:01 +0000 Subject: [PATCH 08/21] Note which fuses Minerva needs, since hekate blames a missing file hekate prints "Missing Minerva lib!" whenever minerva_init fails. That covers the module refusing to start, which it does unless HIDREV reads chip 0x21 and FUSE_SKU_INFO reads 0x83 (ODIN). The emulator's defaults satisfy both, but editing fuse 0x110 in the config window or rcm_emu.ini brings the screen back with the module present. Say so on the fuse's label and in the boot-flow notes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb --- DESIGN.md | 5 +++++ display/config_window.cpp | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/DESIGN.md b/DESIGN.md index 5d3f4d4..5e077cd 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -59,6 +59,11 @@ same peripheral models through one dispatch (see [CCPLEX CPU0](#ccplex-cpu0)). hardware (see [EMC and DRAM clock](#emc-and-dram-clock)). An SD image without those modules gets hekate's "Missing LP0 (sleep) lib! / Missing Minerva lib!" screen, which waits for a key press before the menu. + hekate prints "Missing Minerva lib!" for any Minerva failure, not only a + missing file: Minerva also refuses to start unless HIDREV reads chip + 0x21 and `FUSE_SKU_INFO` (0x110) reads 0x83 (ODIN). Both hold by + default; a `[fuses]` edit to 0x110 in the config window or + `rcm_emu.ini` brings the screen back. 4. Hekate self-relocates into DRAM (`0xC0000000+`) and continues. It points DC (Display Controller) window A at its portrait framebuffer and draws its boot logo and menus there, sideways, for the landscape-mounted panel. diff --git a/display/config_window.cpp b/display/config_window.cpp index 1e9cedc..fc61d34 100644 --- a/display/config_window.cpp +++ b/display/config_window.cpp @@ -759,7 +759,7 @@ void build_ui(EmuState *state) { // Each row corresponds to a FUSE_BASE offset in Hekate's // bdk/soc/fuse.h. Defaults match a typical Erista golden sample. atomic_hex_input("0x100 PRODUCTION_MODE", state->fuse_at(0x100)); - atomic_hex_input("0x110 SKU_INFO", state->fuse_at(0x110)); + atomic_hex_input("0x110 SKU_INFO (0x83 ODIN; Minerva needs it)", state->fuse_at(0x110)); atomic_hex_input("0x114 CPU_SPEEDO_0", state->fuse_at(0x114)); atomic_hex_input("0x118 CPU_IDDQ", state->fuse_at(0x118)); atomic_hex_input("0x128 OPT_FT_REV", state->fuse_at(0x128)); From c6b532fdbd98054a0da00e825e5ebd9bbb7bf349 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 21:21:30 +0000 Subject: [PATCH 09/21] Read back CAR and MC registers, and measure the EMC at its modelled clock Most CAR registers the model does not handle, and every MC register but two, read 0 even after a write. Payloads saw a CLK_SOURCE divider, a PLL misc word or an audio clock source they had just programmed come back as 0. - CAR: the fallthrough returns what was written. The SET/CLR alias registers are write strobes and keep reading 0. No CAR poll in bdk or hwtest waits for hardware to clear a bit it wrote, so read-back cannot turn a poll into a hang. - MC: configuration registers read back (no MC register is polled). - The PTO counter measures the EMC at the clock CAR and the PLLs give it, so it follows Minerva to 1600 MHz. At the 204 MHz boot clock it keeps the measured 203.991 / 204.001 MHz. hwtest now reports the AUD_MCLK source, PLLA misc word and a clock source divider it programs. Its verdict is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb --- DESIGN.md | 8 ++++++++ t210/mmio.cpp | 41 ++++++++++++++++++++++++++++++++++++----- 2 files changed, 44 insertions(+), 5 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 5e077cd..522f50f 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -195,6 +195,10 @@ frequency-switching module, depend on: locks once enabled, like the other PLLs. - **Status.** `EMC_EMC_STATUS` otherwise reports timing updates done, the DRAM active and the state machines idle. +- **Measured clock.** bdk's PTO counter measures the EMC at the modelled + clock (the measured 204 MHz figure at the boot clock). +- **Not modelled.** The DLL's delay code (`DLL_OUT`) reads 0: the TRM gives + no tap delay to derive it from. With the stock `bootloader/` folder, hekate's IPL trains 204, 800 and 1600 MHz, and Nyx then switches between 800 and 1600 MHz on every GUI loop, @@ -481,6 +485,10 @@ needed. The 64 KB TX log trim happens in-place during the write hook. ### Other peripherals (mostly stubs) +- **CAR and MC.** Registers without behaviour of their own read back what + was written - the `CLK_SOURCE_*` dividers, PLL MISC words, the MC's + arbitration and address-map configuration - instead of 0. The CAR's + SET/CLR alias registers are write strobes and read 0. - **PINMUX (`APB_MISC` pad config) and PWM controller (`0x7000A000`).** No active behaviour, but reads return whatever the payload last wrote via the global `mmio_regs` cache. Hwtest's "Display backlight & PWM" diff --git a/t210/mmio.cpp b/t210/mmio.cpp index 1d4f079..934f264 100644 --- a/t210/mmio.cpp +++ b/t210/mmio.cpp @@ -2185,7 +2185,10 @@ uint32_t misc_read(EmuState *state, uint64_t addr) { // (Erista/Mariko/Lite/OLED). if (offset == 0x50) return 4096; - return 0; + // The rest are configuration registers (arbitration, latency allowance, + // carveouts, the EMEM address map sdram_init programs from the BCT): + // they read back what was written. + return mmio_regs.get(addr); } // PWM controller (LCD backlight on PWM0, optional fan on PWM1). Same // story as PINMUX above — the writes are captured by the global cache @@ -3145,6 +3148,29 @@ 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; +// The EMC clock as CAR sets it (EMC section below). +static uint32_t emc_rate_khz(); + +// The SET/CLR aliases of the reset and clock-enable banks (TRM 5.2): write +// strobes that nothing reads back. They read 0. +static bool car_is_set_clr_alias(uint32_t off) { + switch (off) { + case 0x284: case 0x288: case 0x290: case 0x294: // CLK_ENB_X, RST_DEV_X + case 0x29C: case 0x2A0: case 0x2A8: case 0x2AC: // CLK_ENB_Y, RST_DEV_Y + case 0x300: case 0x304: case 0x308: case 0x30C: // RST_DEV_L, _H + case 0x310: case 0x314: // RST_DEV_U + case 0x320: case 0x324: case 0x328: case 0x32C: // CLK_ENB_L, _H + case 0x330: case 0x334: // CLK_ENB_U + case 0x340: case 0x344: // RST_CPU_CMPLX + case 0x430: case 0x434: case 0x438: case 0x43C: // RST_DEV_V, _W + case 0x440: case 0x444: case 0x448: case 0x44C: // CLK_ENB_V, _W + case 0x450: case 0x454: case 0x460: case 0x464: // RST/CLK_CPUG_CMPLX + return true; + default: + return false; + } +} + uint32_t clk_rst_read(EmuState *state, uint64_t addr) { uint32_t offset = (uint32_t)(addr - CLK_RST_BASE); // PLL_BASE registers (per Hekate bdk/soc/clock.h): each PLL has an _BASE @@ -3269,7 +3295,11 @@ uint32_t clk_rst_read(EmuState *state, uint64_t addr) { uint32_t khz = 0; switch (src) { case 0x1C: khz = mariko ? 407971 : 407980; break; // SCLK / BPMP - case 0x24: khz = mariko ? 203991 : 204001; break; // EMC (DRAM) + case 0x24: // EMC (DRAM): the modelled clock; measured at the boot clock + khz = emc_rate_khz(); + if (khz == 204000) + khz = mariko ? 203991 : 204001; + break; case 0x23: khz = mariko ? 199673 : 199677; break; // SDMMC4 (eMMC) case 0x20: khz = mariko ? 199671 : 199694; break; // SDMMC1 (SD) case 0x12: khz = 0; break; // CCLK_G - A57 cluster is off in RCM @@ -3313,8 +3343,10 @@ uint32_t clk_rst_read(EmuState *state, uint64_t addr) { if (pcie_car_read(offset, &v)) return v; } + // Everything else is a plain R/W register (the CLK_SOURCE_* dividers, + // PLL MISC words, ...): it reads back what was written. (void)state; - return 0; + return car_is_set_clr_alias(offset) ? 0 : mmio_regs.get(addr); } // A CLK_SOURCE_EMC write is the CAR/EMC clock-change handshake (EMC below). @@ -3325,8 +3357,7 @@ void clk_rst_write(EmuState *state, uint64_t addr, uint32_t val) { uint32_t offset = (uint32_t)(addr - CLK_RST_BASE); // The _U pair is live (bdk reaches it through the SET/CLR aliases), and // CLK_SOURCE_EMC starts an EMC clock change. Everything else only lands - // in the write hook's mmio_regs cache, which clk_rst_read consults for - // the registers it reads back (CLK_SOURCE_UARTD, the EMC clock sources). + // in the write hook's mmio_regs cache, which clk_rst_read hands back. switch (offset) { case 0x00C: car_rst_u = val; break; // RST_DEVICES_U, direct write case 0x018: car_enb_u = val; break; // CLK_OUT_ENB_U, direct write From fae29019ae4506f9a7cd21e54f36645f7fbdbb7c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 21:21:44 +0000 Subject: [PATCH 10/21] Model DC window address offsets and block-linear VIC surfaces, with a test - DC: a window's fetch starts at ADDR_V_OFFSET * LINE_STRIDE + ADDR_H_OFFSET (TRM 24.11.1). That is the window's top-left pixel, or top-right with H_DIRECTION, or bottom-left with V_DIRECTION, and the fetch walks away from it; before, the offsets were ignored and flips mirrored within the window. HOS's column-scan offset (0x13FF) and hekate's inverted-pitch offset (1279) both land where they should. Layer order is documented: the TRM sorts windows by depth without saying which way. - VIC: slot and output surfaces may be block linear (BlkKind 1, 2^BlkHeight GOBs per block) as well as pitch. - GOB addressing moves to t210/block_linear.h, shared by the scan-out and VIC. - tests/display: one bare-metal payload built per scenario (a pitch window, Nyx's VIC turn into pitch and into block-linear surfaces, a block-linear VIC source, the DC's own column scan with an address offset, a mirrored window with window D blended over). check.py compares every pixel of the frame the emulator shows with the picture drawn. It runs in make test and in CI. hwtest's frame is unchanged, and Nyx's differs only in its clock. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb --- .github/workflows/build.yml | 8 +- DESIGN.md | 41 +++++--- Makefile | 11 ++- README.md | 2 +- display/sdl_display.cpp | 47 +++++---- emu_state.h | 2 + t210/block_linear.h | 27 +++++ t210/mmio.cpp | 48 +++++---- tests/display/check.py | 76 +++++++++++++++ tests/display/link.ld | 10 ++ tests/display/payload.c | 190 ++++++++++++++++++++++++++++++++++++ tests/display/run.sh | 59 +++++++++++ 12 files changed, 466 insertions(+), 55 deletions(-) create mode 100644 t210/block_linear.h create mode 100755 tests/display/check.py create mode 100644 tests/display/link.ld create mode 100644 tests/display/payload.c create mode 100755 tests/display/run.sh diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 09fcb32..fb00d8a 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -45,11 +45,13 @@ jobs: grep -q "RCM Payload Emulator" out.txt \ || { echo "banner missing - binary did not start"; exit 1; } - - name: CCPLEX regression test - # A small self-contained payload boots CPU0 through bdk's + - name: CCPLEX and display regression tests + # Small self-contained payloads. One boots CPU0 through bdk's # ccplex_boot_cpu0() register sequence: an unpowered release must be # refused, a powered one must run an AArch64 blob at EL3, and WFE must - # park the core. + # park the core. The others drive the display controller and VIC in + # six scenarios, and the frame the emulator shows must match the + # picture drawn, pixel for pixel. run: make test - name: hwtest end to end diff --git a/DESIGN.md b/DESIGN.md index 522f50f..2371c98 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -385,18 +385,25 @@ reports a frame end and a vblank, which bdk polls before DSI commands. Each display tick builds the picture the panel would receive, 720x1280 and portrait, the way the DC builds it: -1. Every enabled window's surface is fetched at `START_ADDR`. The layout +1. Every enabled window's surface is fetched from `START_ADDR`. The layout comes from `SURFACE_KIND`: pitch, 16x16 tiled, or block linear with 2^`BLOCK_HEIGHT` GOBs (Groups of Bytes, 64x8-byte tiles) per block. The line pitch is `LINE_STRIDE`, and pixels are decoded per `COLOR_DEPTH`. - Block-linear byte order follows TRM 20.1.2 and Figure 47. -2. `WIN_OPTIONS` turns the surface: H_DIRECTION and V_DIRECTION mirror it, - and SCAN_COLUMN walks its columns (90/270 degrees, TRM Table 122). The - result is scaled from `PRESCALED_SIZE` to `SIZE`, nearest-neighbour, and - placed at `POSITION`. -3. The windows are stacked by layer depth (A under D when equal) and blended - per `BLEND_LAYER_CONTROL` and `BLEND_MATCH_SELECT`. Hekate's log console - (window D, K1 = 200) shows through as it does on the console. + Block-linear byte order follows TRM 20.1.2 and Figure 47 + (`t210/block_linear.h`, shared with VIC). +2. The fetch starts at `ADDR_V_OFFSET * LINE_STRIDE + ADDR_H_OFFSET` (TRM + 24.11.1): the window's top-left pixel, top-right with H_DIRECTION, + bottom-left with V_DIRECTION, in surface terms. It walks away from there + per the direction bits, and SCAN_COLUMN walks columns instead of rows + (90/270 degrees, TRM Table 122). Pixels before `START_ADDR` or past the + surface are black. The result is scaled from `PRESCALED_SIZE` to `SIZE`, + nearest-neighbour, and placed at `POSITION`. +3. The windows are stacked by layer depth and blended per + `BLEND_LAYER_CONTROL` and `BLEND_MATCH_SELECT`. The TRM sorts windows by + depth into its blend stages without saying which way; lower depth is + nearer the top here, as Linux programs later Tegras, and equal depths + stack A under D. Hekate's log console (window D, K1 = 200) shows + through as it does on the console. The panel picture is then turned for the host window. When the surface on show was turned on its way to the panel, by the DC (SCAN_COLUMN) or by a @@ -420,13 +427,14 @@ bdk drives VIC through the Falcon private-register window. The model keeps the config struct's address (`VIC_SC_PRAMBASE`), the slots' source surfaces (`VIC_SC_SFC0_BASE_LUMA(n)`) and the target (`VIC_BL_TARGET_BASADR`). On `VIC_FC_COMPOSE` it reads bdk's `vic_config_t` from guest memory and draws -every enabled pitch slot into the target, scaling the source rect onto the +every enabled slot into the target, scaling the source rect onto the dest rect, clipped to the target rect, with the output flip X, flip Y and transpose applied. The output size is given before the transpose, so a transposed target is H x W pixels, which is how the DC then reads it. The compose also records the target address and the turn applied, which the display uses to undo it. Nyx's 270-degree rotation is flip X then transpose. -Block-linear VIC surfaces are not modelled, and nothing in bdk uses them. +Slot and output surfaces are pitch or block linear (BlkKind 1, with +2^BlkHeight GOBs per block). ### UART @@ -650,9 +658,14 @@ final `for(;;) wfe;` would otherwise spin through a billion instructions per emulated second. `make test` runs `tests/ccplex/`, a self-contained payload that checks the -refusal, the EL3 entry, the mailbox, WFE parking and the reset. -`tests/hwtest/` builds hwtest-rcm with distro toolchains and runs its whole -sweep; CI runs both. +refusal, the EL3 entry, the mailbox, WFE parking and the reset, and +`tests/display/`, one payload built per scenario that drives the display +controller and VIC the way bdk does (a pitch window; Nyx's VIC turn into +pitch and into block-linear surfaces; a block-linear VIC source; the DC's +own column scan with an address offset; a mirrored window with window D +blended over it). `check.py` compares every pixel of the frame the emulator +shows with the picture the payload drew. `tests/hwtest/` builds hwtest-rcm +with distro toolchains and runs its whole sweep; CI runs all three. ## Bug history diff --git a/Makefile b/Makefile index df8126e..59d1328 100644 --- a/Makefile +++ b/Makefile @@ -98,10 +98,19 @@ tests/ccplex/payload.bin: tests/ccplex/payload.c tests/ccplex/link.ld $(TEST_CC) $(TEST_CFLAGS) -T tests/ccplex/link.ld -o tests/ccplex/payload.elf $< $(TEST_OBJCOPY) -O binary tests/ccplex/payload.elf $@ -test: $(OUTPUT) tests/ccplex/payload.bin +DISPLAY_SCENARIOS = 1 2 3 4 5 6 +DISPLAY_PAYLOADS = $(DISPLAY_SCENARIOS:%=tests/display/payload_%.bin) + +tests/display/payload_%.bin: tests/display/payload.c tests/display/link.ld + $(TEST_CC) $(TEST_CFLAGS) -DSCENARIO=$* -T tests/display/link.ld -o tests/display/payload_$*.elf $< + $(TEST_OBJCOPY) -O binary tests/display/payload_$*.elf $@ + +test: $(OUTPUT) tests/ccplex/payload.bin $(DISPLAY_PAYLOADS) sh tests/ccplex/run.sh ./$(OUTPUT) tests/ccplex/payload.bin + sh tests/display/run.sh ./$(OUTPUT) tests/display clean: rm -f $(OUTPUT) $(OBJS) $(OBJS:.o=.d) \ tests/ccplex/payload.elf tests/ccplex/payload.bin tests/ccplex/out.log \ + tests/display/payload_*.elf tests/display/payload_*.bin \ $(WIN_OUT) $(WIN_OBJS) $(WIN_OBJS:.o=.d) diff --git a/README.md b/README.md index 6f33435..3c55a5b 100644 --- a/README.md +++ b/README.md @@ -175,7 +175,7 @@ real consoles. Details in [DESIGN.md](DESIGN.md#ccplex-cpu0). ## Tests ```bash -make test # CCPLEX regression payload (needs arm-none-eabi-gcc) +make test # CCPLEX + display regression payloads (arm-none-eabi-gcc, python3) tests/hwtest/build.sh build-hwtest # build hwtest-rcm (+ gcc-aarch64-linux-gnu) tests/hwtest/run.sh ./rcm_emu build-hwtest/hwtest-rcm/build/hwtest.bin ``` diff --git a/display/sdl_display.cpp b/display/sdl_display.cpp index acefc35..00bc449 100644 --- a/display/sdl_display.cpp +++ b/display/sdl_display.cpp @@ -2,6 +2,7 @@ #include "config_window.h" #include "console_window.h" #include "../emu_state.h" +#include "../t210/block_linear.h" #include "../t210/memory_map.h" #include @@ -162,7 +163,9 @@ struct Win { int idx = 0; uint64_t addr = 0; uint32_t depth = 0, bpp = 4, kind = 0, gob_h = 1, stride = 0, gobs = 0; - uint32_t src_w = 0, src_h = 0; // the surface, before the DC turns it + uint32_t src_w = 0, src_h = 0; // the fetch, before the DC turns it + uint32_t x0 = 0, y0 = 0; // first pixel fetched (ADDR_H/V_OFFSET) + uint32_t cols = 0, rows = 0; // surface extent from START_ADDR uint32_t pre_w = 0, pre_h = 0; // PRESCALED_SIZE, in pixels (post-turn) uint32_t out_w = 0, out_h = 0; // SIZE int32_t x = 0, y = 0; @@ -179,14 +182,8 @@ inline size_t fetch_off(const Win &w, uint32_t sx, uint32_t sy) { case 1: // 16x16-byte tiles, row-major return (size_t)(sy / 16) * w.stride * 16 + (xb / 16) * 256 + (sy % 16) * 16 + (xb % 16); - case 2: { // block linear, TRM 20.1.2 (Figure 47 sector order) - uint32_t gob_y = sy / 8; - size_t gob = ((size_t)(gob_y / w.gob_h) * w.gobs + xb / 64) * w.gob_h + - gob_y % w.gob_h; - uint32_t x = xb % 64, y = sy % 8; - return gob * 512 + (x / 32) * 256 + (y / 2) * 64 + ((x % 32) / 16) * 32 + - (y % 2) * 16 + (x % 16); - } + case 2: // block linear + return bl_offset(xb, sy, w.gobs, w.gob_h); default: return (size_t)sy * w.stride + xb; } @@ -236,17 +233,26 @@ bool load_window(EmuState *state, uc_engine *uc, int idx, const uint32_t *r, if (!w.stride) w.stride = w.src_w * w.bpp; w.addr = (uint64_t)r[dcwin::START_ADDR] + (int64_t)state->manual_offset; + // The fetch starts at START_ADDR + ADDR_V_OFFSET * LINE_STRIDE + + // ADDR_H_OFFSET (TRM 24.11.1): the window's top-left pixel, or top-right + // with H_DIRECTION, bottom-left with V_DIRECTION - in surface terms, + // before SCAN_COLUMN turns it - and walks away from it. + uint64_t start = (uint64_t)r[dcwin::ADDR_V_OFF] * w.stride + + r[dcwin::ADDR_H_OFF]; + w.y0 = (uint32_t)std::min(start / w.stride, 0xFFFF); + w.x0 = (uint32_t)(start % w.stride) / w.bpp; + w.cols = w.stride / w.bpp; + w.rows = (w.xf & dcwin::XF_FLIP_Y) ? w.y0 + 1 : w.y0 + w.src_h; switch (w.kind) { case 2: w.gobs = (w.stride + 63) / 64; - w.len = (size_t)w.gobs * 512 * w.gob_h * - ((w.src_h + 8 * w.gob_h - 1) / (8 * w.gob_h)); + w.len = bl_size(w.gobs, w.gob_h, w.rows); break; case 1: - w.len = (size_t)w.stride * ((w.src_h + 15) / 16) * 16; + w.len = (size_t)w.stride * ((w.rows + 15) / 16) * 16; break; default: - w.len = (size_t)w.stride * w.src_h; + w.len = (size_t)w.stride * w.rows; break; } if (w.len == 0 || w.len > 64u * 1024 * 1024) @@ -308,9 +314,11 @@ void draw_window(const Win &w, std::vector &panel) { uint32_t tx = txs[ox]; // (tx, ty) is post-turn; walk it back to the surface. uint32_t a = column ? ty : tx, b = column ? tx : ty; - uint32_t sx = hflip ? w.src_w - 1 - a : a; - uint32_t sy = vflip ? w.src_h - 1 - b : b; - size_t off = fetch_off(w, sx, sy); + int64_t sx = hflip ? (int64_t)w.x0 - a : (int64_t)w.x0 + a; + int64_t sy = vflip ? (int64_t)w.y0 - b : (int64_t)w.y0 + b; + if (sx < 0 || sy < 0 || sx >= w.cols || sy >= w.rows) + continue; // before START_ADDR or past the surface + size_t off = fetch_off(w, (uint32_t)sx, (uint32_t)sy); if (off + w.bpp > w.len) continue; uint32_t s = depth_argb(w.mem + off, w.depth); @@ -356,7 +364,10 @@ void sdl_display_update(EmuState *state, uc_engine *uc) { if (load_window(state, uc, i, r, g_swizzle_override, w)) wins.push_back(std::move(w)); } - // Deeper layers first; equal depths stack A (bottom) to D (top). + // The TRM sorts windows by depth into the blend stages (24.3.12) without + // saying which way; lower depth nearer the top, as Linux programs later + // Tegras (depth = 255 - zpos). Equal depths stack A (bottom) to D (top), + // which puts hekate's log window D over A, as its blending expects. std::stable_sort(wins.begin(), wins.end(), [](const Win &l, const Win &r) { return l.layer > r.layer; }); @@ -410,7 +421,7 @@ void sdl_display_update(EmuState *state, uc_engine *uc) { {(uint64_t)w.idx, w.addr, w.len, w.depth, w.kind, w.gob_h, w.stride, (uint64_t)w.pre_w << 32 | w.pre_h, (uint64_t)w.out_w << 32 | w.out_h, w.xf, w.blend_layer, - w.blend_match}); + w.blend_match, (uint64_t)w.x0 << 32 | w.y0}); where.push_back((uint64_t)(uint32_t)w.x << 32 | (uint32_t)w.y); } static std::vector last_shape, last_where; diff --git a/emu_state.h b/emu_state.h index bcda4ed..14fba46 100644 --- a/emu_state.h +++ b/emu_state.h @@ -105,6 +105,8 @@ constexpr uint32_t LINE_STRIDE = 0x00A; // DC_WIN_LINE_STRIDE (bytes) constexpr uint32_t BLEND_LAYER = 0x016; // DC_WINBUF_BLEND_LAYER_CONTROL constexpr uint32_t BLEND_MATCH = 0x017; // DC_WINBUF_BLEND_MATCH_SELECT constexpr uint32_t START_ADDR = 0x100; // DC_WINBUF_START_ADDR +constexpr uint32_t ADDR_H_OFF = 0x106; // DC_WINBUF_ADDR_H_OFFSET (bytes) +constexpr uint32_t ADDR_V_OFF = 0x108; // DC_WINBUF_ADDR_V_OFFSET (lines) constexpr uint32_t SURFACE_KIND = 0x10B; // DC_WINBUF_SURFACE_KIND // WIN_OPTIONS bits. diff --git a/t210/block_linear.h b/t210/block_linear.h new file mode 100644 index 0000000..615bc17 --- /dev/null +++ b/t210/block_linear.h @@ -0,0 +1,27 @@ +#pragma once + +#include +#include + +// Tegra X1 block-linear surfaces (TRM 20.1.2), as the display controller and +// VIC read and write them. A GOB is 64 bytes x 8 lines (512 bytes) of 16Bx2 +// sectors; GOBs stack gob_h high into a block, and blocks run left to right, +// then down, gobs_per_row GOBs to a row. + +// Byte offset of byte column xb (pixel x * bytes per pixel) on line y. +inline size_t bl_offset(uint32_t xb, uint32_t y, uint32_t gobs_per_row, + uint32_t gob_h) { + uint32_t gob_y = y / 8; + size_t gob = ((size_t)(gob_y / gob_h) * gobs_per_row + xb / 64) * gob_h + + gob_y % gob_h; + // Within the GOB, TRM Figure 47's sector order. + uint32_t x = xb % 64, l = y % 8; + return gob * 512 + (x / 32) * 256 + (l / 2) * 64 + ((x % 32) / 16) * 32 + + (l % 2) * 16 + (x % 16); +} + +// Bytes a surface h lines tall occupies (whole blocks). +inline size_t bl_size(uint32_t gobs_per_row, uint32_t gob_h, uint32_t h) { + return (size_t)gobs_per_row * 512 * gob_h * + ((h + 8 * gob_h - 1) / (8 * gob_h)); +} diff --git a/t210/mmio.cpp b/t210/mmio.cpp index 934f264..303ba71 100644 --- a/t210/mmio.cpp +++ b/t210/mmio.cpp @@ -1,4 +1,5 @@ #include "mmio.h" +#include "block_linear.h" #include "trace.h" #include "../emu_state.h" #include "../platform.h" @@ -3737,8 +3738,9 @@ static void se_write(EmuState *state, uint64_t addr, uint32_t val) { // for registers that need them; none of the ones modelled here do. The model // keeps what a compose needs - the config struct's address (PRAMBASE), the // slots' source surfaces and the target surface - and, on COMPOSE_START, -// reads the config struct from guest memory and draws the enabled pitch -// slots into the target with the output flip/transpose. That is what Nyx +// reads the config struct from guest memory and draws the enabled slots +// into the target with the output flip/transpose. Surfaces are pitch or +// block linear (BlkKind 1, BlkHeight = log2 GOBs per block). That is what Nyx // relies on: its 1280x720 GUI is turned into the panel's 720x1280 portrait // framebuffer by a 270-degree VIC rotation (flip X, then transpose). // @@ -3746,7 +3748,8 @@ static void se_write(EmuState *state, uint64_t addr, uint32_t val) { // bitfields): // 0x10 OutputConfig u64 0: FlipX b48, FlipY b49, Transpose b50 // u64 1: TargetRect L b0, R b16, T b32, B b48 -// 0x20 OutputSurfaceConfig u64 0: format b0, BlkKind b11, W-1 b32, H-1 b46 +// 0x20 OutputSurfaceConfig u64 0: format b0, BlkKind b11, BlkHeight b15, +// W-1 b32, H-1 b46 // 0x90 + n * 0xB0 slot n: u64 0: SlotEnable b0 // u64 4/5: SourceRect L|R, T|B (16.16, b0/b32) // u64 6: DestRect L b0, R b16, T b32, B b48 @@ -3804,6 +3807,7 @@ static void vic_compose(EmuState *state) { uint32_t tl = bits(c[3], 0, 14), tr = bits(c[3], 16, 14); uint32_t tt = bits(c[3], 32, 14), tb = bits(c[3], 48, 14); uint32_t ofmt = bits(c[4], 0, 7), okind = bits(c[4], 11, 4); + uint32_t ogob = 1u << std::min(bits(c[4], 15, 4), 5u); uint32_t ow = bits(c[4], 32, 14) + 1, oh = bits(c[4], 46, 14) + 1; uint32_t bpp = vic_bpp(ofmt); @@ -3815,11 +3819,16 @@ static void vic_compose(EmuState *state) { printf("[vic] compose skipped: %s\n", what); } }; - if (!bpp || okind != 0) - return log_once("output surface not pitch or format not modelled"); + // BlkKind 0 is pitch, 1 the Tegra 16Bx2 block-linear layout; BlkHeight is + // log2 of the block height in GOBs. + if (!bpp || okind > 1) + return log_once("output surface format or layout not modelled"); - uint32_t out_pitch = (transpose ? oh : ow) * bpp; - uint64_t out_len = (uint64_t)out_pitch * (transpose ? ow : oh); + // The output as laid out in memory: a transposed target is oh x ow. + uint32_t out_w = transpose ? oh : ow, out_h = transpose ? ow : oh; + uint32_t out_pitch = out_w * bpp, out_gobs = (out_pitch + 63) / 64; + uint64_t out_len = okind ? bl_size(out_gobs, ogob, out_h) + : (uint64_t)out_pitch * out_h; uint8_t *dst = vic_dram(state, vic.target, out_len); if (!dst) return log_once("target outside DRAM"); @@ -3833,12 +3842,17 @@ static void vic_compose(EmuState *state) { if (!(sl[0] & 1) || !vic.sfc[n]) continue; uint32_t sfmt = bits(sl[8], 0, 7), skind = bits(sl[8], 11, 4); + uint32_t sgob = 1u << std::min(bits(sl[8], 15, 4), 5u); uint32_t sw = bits(sl[8], 32, 14) + 1, sh = bits(sl[8], 46, 14) + 1; - if (skind != 0 || vic_bpp(sfmt) != bpp) { - log_once("slot surface not pitch or not the output's size of pixel"); + if (skind > 1 || vic_bpp(sfmt) != bpp) { + log_once("slot surface layout not modelled, or not the output's size " + "of pixel"); continue; } - const uint8_t *src = vic_dram(state, vic.sfc[n], (uint64_t)sw * sh * bpp); + uint32_t src_pitch = sw * bpp, src_gobs = (src_pitch + 63) / 64; + const uint8_t *src = vic_dram(state, vic.sfc[n], + skind ? bl_size(src_gobs, sgob, sh) + : (uint64_t)src_pitch * sh); if (!src) continue; uint32_t sl_l = bits(sl[4], 16, 14), sl_r = bits(sl[4], 48, 14); @@ -3858,25 +3872,23 @@ static void vic_compose(EmuState *state) { for (uint32_t tx = x0; tx <= x1; tx++) sxs[tx - x0] = sl_l + (uint32_t)((uint64_t)(tx - dl) * (sl_r - sl_l + 1) / (dr - dl + 1)); - uint32_t src_pitch = sw * bpp; for (uint32_t ty = y0; ty <= y1; ty++) { uint32_t sy = sl_t + (uint32_t)((uint64_t)(ty - dt) * (sl_b - sl_t + 1) / (db - dt + 1)); if (sy >= sh) continue; - const uint8_t *srow = src + (uint64_t)sy * src_pitch; uint32_t fy = flip_y ? oh - 1 - ty : ty; for (uint32_t tx = x0; tx <= x1; tx++) { uint32_t sx = sxs[tx - x0]; if (sx >= sw) continue; uint32_t fx = flip_x ? ow - 1 - tx : tx; - uint64_t o = transpose ? (uint64_t)fx * out_pitch + (uint64_t)fy * bpp - : (uint64_t)fy * out_pitch + (uint64_t)fx * bpp; - if (bpp == 4) - memcpy(dst + o, srow + (uint64_t)sx * 4, 4); - else - memcpy(dst + o, srow + (uint64_t)sx * bpp, bpp); + uint32_t col = transpose ? fy : fx, row = transpose ? fx : fy; + uint64_t o = okind ? bl_offset(col * bpp, row, out_gobs, ogob) + : (uint64_t)row * out_pitch + (uint64_t)col * bpp; + uint64_t i = skind ? bl_offset(sx * bpp, sy, src_gobs, sgob) + : (uint64_t)sy * src_pitch + (uint64_t)sx * bpp; + memcpy(dst + o, src + i, bpp); } } } diff --git a/tests/display/check.py b/tests/display/check.py new file mode 100755 index 0000000..62ae06b --- /dev/null +++ b/tests/display/check.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +"""Compare the emulator's frame snapshot with what a display scenario drew. + +Usage: check.py + +last_fb.rgba is the host view, ARGB8888 little-endian, as last_fb.meta's +"W H" gives it. The expected picture follows tests/display/payload.c. +""" +import sys +from array import array + + +def pat(x, y): + return 0xFF000000 | ((x * 7) & 0xFF) << 16 | ((y * 3) & 0xFF) << 8 | ((x ^ y) & 0xFF) + + +def patq(x, y): + return 0xFF000000 | ((x * 5 + y) & 0xFF) << 16 | 0x4000 | ((y * 9) & 0xFF) + + +def blend(s, d, k1): + # BLEND_MATCH_SELECT SRC K1, DST NEG_K1 (1 - K1), per channel, opaque. + out = 0xFF000000 + for sh in (0, 8, 16): + c = (((s >> sh) & 0xFF) * k1 + ((d >> sh) & 0xFF) * (255 - k1)) // 255 + out |= min(c, 255) << sh + return out + + +def expected(scenario, w, h): + if scenario == 1: + return (720, 1280), lambda x, y: pat(x, y) + if scenario in (2, 3, 4, 5): + # The picture was drawn landscape and turned on its way to the + # panel; the view turns it back. + return (1280, 720), lambda x, y: pat(x, y) + if scenario == 6: + def f(x, y): + a = pat(x, 1279 - y) + if 100 <= x < 300 and 200 <= y < 500: + return blend(patq(x - 100, y - 200), a, 128) + return a + return (720, 1280), f + raise SystemExit("unknown scenario %d" % scenario) + + +def main(): + scenario = int(sys.argv[1]) + w, h = map(int, open(sys.argv[3]).read().split()) + frame = array("I") + with open(sys.argv[2], "rb") as fh: + frame.frombytes(fh.read()) + (ew, eh), f = expected(scenario, w, h) + if (w, h) != (ew, eh): + print(" FAIL scenario %d: view is %dx%d, expected %dx%d" % (scenario, w, h, ew, eh)) + return 1 + bad = 0 + first = None + for y in range(h): + row = y * w + for x in range(w): + want = f(x, y) + if frame[row + x] != want: + bad += 1 + if first is None: + first = (x, y, frame[row + x], want) + if bad: + x, y, got, want = first + print(" FAIL scenario %d: %d of %d pixels differ; first at (%d,%d): %08X, expected %08X" + % (scenario, bad, w * h, x, y, got, want)) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/display/link.ld b/tests/display/link.ld new file mode 100644 index 0000000..bdc1203 --- /dev/null +++ b/tests/display/link.ld @@ -0,0 +1,10 @@ +/* Loaded and entered at 0x40010000, like any RCM payload. */ +ENTRY(_start) +SECTIONS { + . = 0x40010000; + .text : { KEEP(*(.text.start)) *(.text*) } + .rodata : { *(.rodata*) } + .data : { *(.data*) } + .bss : { *(.bss*) *(COMMON) } + /DISCARD/ : { *(.comment) *(.note*) *(.ARM.attributes) *(.ARM.exidx*) } +} diff --git a/tests/display/payload.c b/tests/display/payload.c new file mode 100644 index 0000000..6316fc7 --- /dev/null +++ b/tests/display/payload.c @@ -0,0 +1,190 @@ +/* + * Display regression payload. + * + * A freestanding BPMP payload that drives the emulator's display controller + * and VIC models the way bdk does - window registers through + * DISPLAY_WINDOW_HEADER and STATE_CONTROL, VIC through its Falcon register + * window and a vic_config_t in DRAM - then parks. tests/display/run.sh + * compares the frame the emulator shows (last_fb.rgba) with the picture the + * payload drew. Built once per scenario with -DSCENARIO=n: + * + * 1 a pitch window (hekate's TUI setup) + * 2 VIC turns a 1280x720 picture 270 degrees into a pitch surface that + * window A shows (Nyx's setup); the view undoes the turn + * 3 as 2, but VIC writes a block-linear surface (16-GOB blocks) + * 4 VIC copies the picture into a block-linear surface, and window A + * shows it turned by the DC itself: SCAN_COLUMN | H_DIRECTION with + * ADDR_H_OFFSET at the top-right pixel's last byte (HOS's setup) + * 5 as 2, but VIC reads a block-linear source surface + * 6 window A mirrored top-bottom (V_DIRECTION, ADDR_V_OFFSET at the + * last line), with window D blended over it at K1 = 128 + * + * Every surface holds pat(x, y), which differs between neighbouring + * pixels in both directions, so a wrong stride, turn, flip or offset shows + * up almost everywhere. + */ + +#ifndef SCENARIO +#define SCENARIO 1 +#endif + +typedef unsigned int u32; + +#define REG(a) (*(volatile u32 *)(a)) + +#define UARTB_THR 0x70006040u +#define DC 0x54200000u +#define VIC 0x54340000u + +#define DCR(i) REG(DC + (i) * 4u) +/* bdk's _vic_write_priv() for registers with no low address bits. */ +#define VICP(r) REG(VIC + 0x1000u + ((r) >> 6)) + +#define SRC_L 0xC0000000u /* 1280x720 landscape picture, pitch */ +#define SURF_B 0xC0400000u /* block-linear intermediate */ +#define DST 0xC0800000u /* what window A scans out */ +#define SRC_P 0xC0C00000u /* 720x1280 portrait picture, pitch */ +#define SRC_Q 0xC1000000u /* 200x300 overlay for window D */ +#define CFG 0xC1400000u /* vic_config_t, 256-byte aligned */ + +/* DC window registers (word indices) and bits. */ +#define WINDOW_HEADER 0x042u +#define STATE_CONTROL 0x041u +#define WIN_OPTIONS 0x700u +#define COLOR_DEPTH 0x703u +#define POSITION 0x704u +#define SIZE 0x705u +#define PRESCALED 0x706u +#define LINE_STRIDE 0x70Au +#define BLEND_LAYER 0x716u +#define BLEND_MATCH 0x717u +#define START_ADDR 0x800u +#define ADDR_H_OFFSET 0x806u +#define ADDR_V_OFFSET 0x808u +#define SURFACE_KIND 0x80Bu + +#define H_DIRECTION BIT(0) +#define V_DIRECTION BIT(2) +#define SCAN_COLUMN BIT(4) +#define WIN_ENABLE BIT(30) +#define BIT(n) (1u << (n)) + +#define KIND_PITCH 0u +#define KIND_BLOCK (2u | (4u << 4)) /* block linear, 16-GOB blocks */ + +static void puts_(const char *s) { + while (*s) + REG(UARTB_THR) = (u32)(unsigned char)*s++; +} + +static u32 pat(u32 x, u32 y) { + return 0xFF000000u | ((x * 7u) & 0xFFu) << 16 | ((y * 3u) & 0xFFu) << 8 | + ((x ^ y) & 0xFFu); +} + +static u32 patq(u32 x, u32 y) { + return 0xFF000000u | ((x * 5u + y) & 0xFFu) << 16 | 0x4000u | + ((y * 9u) & 0xFFu); +} + +static void fill(u32 base, u32 w, u32 h, u32 (*f)(u32, u32)) { + volatile u32 *p = (volatile u32 *)base; + for (u32 y = 0; y < h; y++) + for (u32 x = 0; x < w; x++) + p[y * w + x] = f(x, y); +} + +/* One u64 bitfield word of vic_config_t, written as two halves. */ +static void cfg64(u32 off, u32 lo, u32 hi) { + REG(CFG + off) = lo; + REG(CFG + off + 4) = hi; +} + +/* + * One VIC compose of a sw x sh X8R8G8B8 surface (slot 0) into a target of + * the same size, with bdk's vic_set_surface() field layout. kind: 0 pitch, + * 1 block linear; gob: log2 GOBs per block. + */ +static void vic_compose(u32 src, u32 skind, u32 sgob, u32 dst, u32 okind, + u32 ogob, u32 sw, u32 sh, u32 flip_x, u32 transpose) { + for (u32 i = 0; i < 0x610; i += 4) + REG(CFG + i) = 0; + /* OutputConfig: FlipX b48, Transpose b50; TargetRect R b16, B b48. */ + cfg64(0x10, 0, (flip_x ? BIT(16) : 0) | (transpose ? BIT(18) : 0)); + cfg64(0x18, (sw - 1) << 16, (sh - 1) << 16); + /* OutputSurfaceConfig: X8R8G8B8 (36), BlkKind b11, BlkHeight b15, + * width - 1 b32, height - 1 b46. */ + cfg64(0x20, 36u | okind << 11 | ogob << 15, (sw - 1) | (sh - 1) << 14); + /* Slot 0: enable; SourceRect in 16.16; DestRect. */ + cfg64(0x90, 1, 0); + cfg64(0xB0, 0, (sw - 1) << 16); + cfg64(0xB8, 0, (sh - 1) << 16); + cfg64(0xC0, (sw - 1) << 16, (sh - 1) << 16); + cfg64(0xD0, 36u | skind << 11 | sgob << 15, (sw - 1) | (sh - 1) << 14); + + VICP(0x14000) = CFG >> 8; /* VIC_SC_PRAMBASE */ + VICP(0x14300) = src >> 8; /* VIC_SC_SFC0_BASE_LUMA(0) */ + VICP(0x22000) = dst >> 8; /* VIC_BL_TARGET_BASADR */ + VICP(0x10000) = 1; /* VIC_FC_COMPOSE */ +} + +/* Program window w (0 = A .. 3 = D) and activate it. */ +static void window(u32 w, u32 opts, u32 pos, u32 width, u32 height, + u32 stride, u32 kind, u32 addr, u32 h_off, u32 v_off, + u32 blend_layer, u32 blend_match) { + DCR(WINDOW_HEADER) = BIT(4 + w); + DCR(WIN_OPTIONS) = 0; + DCR(COLOR_DEPTH) = 0xC; /* B8G8R8A8 */ + DCR(POSITION) = pos; + DCR(SIZE) = height << 16 | width; + DCR(PRESCALED) = height << 16 | width * 4; + DCR(LINE_STRIDE) = stride; + DCR(SURFACE_KIND) = kind; + DCR(START_ADDR) = addr; + DCR(ADDR_H_OFFSET) = h_off; + DCR(ADDR_V_OFFSET) = v_off; + DCR(BLEND_LAYER) = blend_layer; + DCR(BLEND_MATCH) = blend_match; + DCR(WIN_OPTIONS) = opts | WIN_ENABLE; + DCR(STATE_CONTROL) = BIT(8) | BIT(9 + w); /* GENERAL + WIN_x_UPDATE */ + DCR(STATE_CONTROL) = BIT(0) | BIT(1 + w); /* GENERAL + WIN_x_ACT_REQ */ +} + +#define BYPASS 0x01000000u /* BLEND_LAYER_CONTROL reset: blending bypassed */ + +__attribute__((section(".text.start"), noreturn)) +void _start(void) { +#if SCENARIO == 1 + fill(SRC_P, 720, 1280, pat); + window(0, 0, 0, 720, 1280, 720 * 4, KIND_PITCH, SRC_P, 0, 0, BYPASS, 0); +#elif SCENARIO == 2 + fill(SRC_L, 1280, 720, pat); + vic_compose(SRC_L, 0, 0, DST, 0, 0, 1280, 720, 1, 1); + window(0, 0, 0, 720, 1280, 720 * 4, KIND_PITCH, DST, 0, 0, BYPASS, 0); +#elif SCENARIO == 3 + fill(SRC_L, 1280, 720, pat); + vic_compose(SRC_L, 0, 0, DST, 1, 4, 1280, 720, 1, 1); + window(0, 0, 0, 720, 1280, 720 * 4, KIND_BLOCK, DST, 0, 0, BYPASS, 0); +#elif SCENARIO == 4 + fill(SRC_L, 1280, 720, pat); + vic_compose(SRC_L, 0, 0, SURF_B, 1, 4, 1280, 720, 0, 0); + window(0, SCAN_COLUMN | H_DIRECTION, 0, 720, 1280, 1280 * 4, KIND_BLOCK, + SURF_B, 1280 * 4 - 1, 0, BYPASS, 0); +#elif SCENARIO == 5 + fill(SRC_L, 1280, 720, pat); + vic_compose(SRC_L, 0, 0, SURF_B, 1, 4, 1280, 720, 0, 0); + vic_compose(SURF_B, 1, 4, DST, 0, 0, 1280, 720, 1, 1); + window(0, 0, 0, 720, 1280, 720 * 4, KIND_PITCH, DST, 0, 0, BYPASS, 0); +#elif SCENARIO == 6 + fill(SRC_P, 720, 1280, pat); + fill(SRC_Q, 200, 300, patq); + window(0, V_DIRECTION, 0, 720, 1280, 720 * 4, KIND_PITCH, SRC_P, 0, 1279, + BYPASS, 0); + /* K1 = 128, blending on, depth 0; SRC x K1 + DST x (1 - K1). */ + window(3, 0, 200u << 16 | 100u, 200, 300, 200 * 4, KIND_PITCH, SRC_Q, + 0, 0, 128u << 8, 0x72u); +#endif + puts_("display test: ready\n"); + for (;;) + ; +} diff --git a/tests/display/run.sh b/tests/display/run.sh new file mode 100755 index 0000000..0a52177 --- /dev/null +++ b/tests/display/run.sh @@ -0,0 +1,59 @@ +#!/bin/sh +# Display regression test: run each scenario payload (tests/display/payload.c, +# built with -DSCENARIO=n) and compare the frame the emulator shows with the +# picture the payload drew. +# Usage: tests/display/run.sh [rcm_emu] [payload dir] +EMU=$(cd "$(dirname "${1:-./rcm_emu}")" && pwd)/$(basename "${1:-./rcm_emu}") +DIR=$(cd "${2:-tests/display}" && pwd) +HERE=$(cd "$(dirname "$0")" && pwd) +LIMIT=${LIMIT:-60} + +names="pitch window|VIC 270-degree turn into a pitch surface|VIC turn into a block-linear surface|DC column scan with an address offset|VIC block-linear source|V mirror with window D blended over" + +run() { + n=$1 + work=$(mktemp -d) + # The frame snapshot lands in the working directory. + (cd "$work" && SDL_VIDEODRIVER=dummy RCM_EMU_NO_AUDIO=1 \ + "$EMU" "$DIR/payload_$n.bin" > out.log 2>&1) & + pid=$! + t=0 + until grep -q 'display test: ready' "$work/out.log" 2>/dev/null; do + sleep 1 + t=$((t + 1)) + [ $t -ge "$LIMIT" ] && break + done + # The renderer writes a snapshot about a second after the frame changes. + sleep 3 + kill $pid 2>/dev/null + wait $pid 2>/dev/null + name=$(echo "$names" | cut -d'|' -f"$n") + if [ ! -f "$work/last_fb.rgba" ]; then + echo " FAIL $n: $name (no frame snapshot)" + rc=1 + elif python3 "$HERE/check.py" "$n" "$work/last_fb.rgba" "$work/last_fb.meta"; then + echo " ok $n: $name" + rc=0 + else + echo " FAIL $n: $name (log: $work/out.log)" + rc=1 + fi + [ $rc -eq 0 ] && rm -rf "$work" + return $rc +} + +echo "display test:" +fail=0 +pids="" +for n in 1 2 3 4 5 6; do + run "$n" > "$DIR/result_$n.txt" 2>&1 & + pids="$pids $!" +done +n=0 +for p in $pids; do + n=$((n + 1)) + wait "$p" || fail=1 + cat "$DIR/result_$n.txt" + rm -f "$DIR/result_$n.txt" +done +[ $fail -eq 0 ] && echo "display test: PASS" || { echo "display test: FAIL"; exit 1; } From fd98939ccaa07d513b230fc8159e3552a9bb6fc7 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 21:21:56 +0000 Subject: [PATCH 11/21] Make the SD card a UHS-I card, so bdk runs it at SDR104 The SD card ran at 3.3 V High Speed, 48 MHz. It never offered 1.8 V in ACMD41, CMD11 was not handled, and CMD6 always reported High Speed as selected whatever was asked. It also carried the eMMC's CSD, so hwtest saw an 896128 MiB card without application commands, and its SD status was never read. - ACMD41 answers S18A to S18R while the card signals at 3.3 V, and CMD11 moves it to 1.8 V. It stays there until its supply GPIO (PE4) drops or the SoC resets; a card re-initialised without a power cycle answers S18A = 0. - CMD6 reports and selects functions per group, per SD 4.3.10: bus speed (SDR50, SDR104 and DDR50 added at 1.8 V), driver strength and power limit. CMD0 resets the functions, not the voltage. - The CSD is an SD CSD 2.0 sized from the image, with command class 8. ACMD13 reports the bus width set and a Class 10, U1, V10 card, and the SCR sets SD_SPEC3. hwtest now reports the SD card at 199.68 MHz after SDR104 tuning, with the image's real size, and LDO2 at 1.8 V. Nyx boots with it, including after cold and warm reboots, each of which re-runs the voltage switch. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb --- DESIGN.md | 26 ++++++-- t210/mmio.cpp | 160 +++++++++++++++++++++++++++++++++++++++++++++----- 2 files changed, 168 insertions(+), 18 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 2371c98..28e977c 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -20,7 +20,7 @@ flowchart TB uc -->|MMIO callbacks| mmio["t210/mmio.cpp
mmio_bus_read / mmio_bus_write
shared by both masters"] - mmio --> sdmmc["sdmmc
SDMMC1 / SDMMC4
CMD0..21, EXT_CSD, ADMA2
HS200 tuning, HS400"] + mmio --> sdmmc["sdmmc
SDMMC1 / SDMMC4
CMD0..21, EXT_CSD, ADMA2
SD UHS-I, eMMC HS400"] mmio --> se["se_engine
AES-128, SHA-256
BIS keyslot override"] mmio --> i2c["i2c3
STMFTS / FTS4 touch"] mmio --> i2c1["I2C_1 slaves (inline)
MAX17050, TMP451,
BQ24193, BM92T36"] @@ -116,7 +116,8 @@ of the spec is modelled for the Hekate, Lockpick and TE init paths: - CMD0 GO_IDLE, CMD1 SEND_OP_COND, CMD2 ALL_SEND_CID, CMD3 SEND_RELATIVE_ADDR, CMD6 SWITCH, CMD7 SELECT_CARD, CMD8 SEND_EXT_CSD (eMMC) or SEND_IF_COND (SD), CMD9 SEND_CSD, CMD13 SEND_STATUS, CMD16 SET_BLOCKLEN, CMD17 and CMD18 - READ_(MULTI_)BLOCK, CMD19 / CMD21 SEND_TUNING_BLOCK, CMD55 APP_CMD. + READ_(MULTI_)BLOCK, CMD11 VOLTAGE_SWITCH, CMD19 / CMD21 SEND_TUNING_BLOCK, + CMD55 APP_CMD. - ADMA2 (Advanced DMA 2) with 64-bit descriptors, multi-block reads chunked into the host file IO via `pread`-style calls. - `--rawnand` opens the matching `rawnand.bin.NN` chunks and `fstat`s the first @@ -165,8 +166,25 @@ file with the TRM's reset values, plus the side effects bdk waits on: HS400, and reports a 199.68 MHz card clock. BOOT0, BOOT1 and RPMB are 4 MiB each, as on a Switch. -The SD card stays at High Speed (48 MHz). UHS-I needs ACMD41 to answer with -S18A and a CMD11 voltage switch, which the SD model does not do. +#### The SD card: UHS-I + +The SD card is a UHS-I card (SD Physical Layer 3.01), so bdk runs it at +SDR104 like the real slot: + +- ACMD41 with S18R answers S18A while the card still signals at 3.3 V, and + CMD11 moves it to 1.8 V. It stays there until it loses power: bdk's + supply GPIO (PE4) going low, or a reset. A card re-initialised without a + power cycle answers S18A = 0 but keeps offering its UHS speeds. +- CMD6 (SWITCH_FUNC) reports and selects a function per group, per SD + 4.3.10: bus speed (SDR12 and SDR25/HS, plus SDR50, SDR104 and DDR50 at + 1.8 V), driver strength and power limit. CMD0 puts the functions back to + their defaults, not the voltage. +- CMD19 tunes the SDR104 sampling point through the same tuning circuit as + the eMMC. hwtest reports a 199.68 MHz card clock. +- The CSD is an SD CSD 2.0 (SD 5.3.3): the image's size (32 GiB with none) + and command classes that include class 8, so bdk reads the SD status. + That (ACMD13) reports the bus width ACMD6 set and a Class 10, U1, V10 + card with 4 MB AUs; the SCR sets SD_SPEC3. ### EMC and DRAM clock diff --git a/t210/mmio.cpp b/t210/mmio.cpp index 303ba71..07ca22f 100644 --- a/t210/mmio.cpp +++ b/t210/mmio.cpp @@ -609,6 +609,9 @@ uint32_t gpio_read(EmuState *state, uint64_t addr) { return 0; } +// The SD card loses power with PE4 (SDMMC section below). +static void sd_card_gpio_update(); + void gpio_write(EmuState *state, uint64_t addr, uint32_t val) { uint32_t offset = (uint32_t)(addr - GPIO_BASE); uint32_t bank_off = offset & 0xFF; @@ -632,10 +635,13 @@ void gpio_write(EmuState *state, uint64_t addr, uint32_t val) { TRACE("[gpio] W: offset 0x%X = 0x%08X\n", offset, val); } - // Bank 1 holds ports E..H, and port H carries BT_REG_ON, so re-sample the - // radio's power pin after anything that could have moved it. - if (offset >= 0x100 && offset < 0x200) + // Bank 1 holds ports E..H: port H carries BT_REG_ON and port E the SD + // card's supply (PE4), so re-sample both after anything that could have + // moved them. + if (offset >= 0x100 && offset < 0x200) { gpio_h_update(state); + sd_card_gpio_update(); + } } // ==================== I2C ==================== @@ -1982,6 +1988,110 @@ static void sdhci_tuning_command(EmuState *s, uint32_t base) { r.tune_pending = true; } +// ---- The SD card's signalling voltage and switch functions ---------------- +// +// A UHS-I card (SD Physical Layer 3.01). ACMD41 with S18R set answers S18A +// while the card still signals at 3.3 V; CMD11 then moves it to 1.8 V, where +// it stays until it loses power - bdk's supply GPIO (PE4) going low, or a +// reset. A card re-initialised without a power cycle answers S18A = 0 but +// keeps offering its UHS bus speeds, which is how hosts tell. CMD6 +// (SWITCH_FUNC) reports and selects one function per group: bus speed +// (group 1: SDR12 and SDR25/HS, plus SDR50, SDR104 and DDR50 at 1.8 V), +// driver strength (3: type B, plus A, C and D at 1.8 V) and power limit +// (4: 0.72 W, plus 1.44 W at 1.8 V). CMD0 puts the functions back to their +// defaults but not the signalling voltage. +struct SdCard { + bool s18a_offered = false; // the last ACMD41 answered S18A + bool v18 = false; // signalling at 1.8 V + bool bus4 = false; // ACMD6 set a 4-bit bus + uint8_t func[6] = {}; // current function, groups 1..6 + bool supplied = false; // PE4 driving the card's VDD +}; +static SdCard sd_card; + +static uint16_t sd_func_support(int group) { + static const uint16_t k33[6] = {0x8003, 0x8001, 0x8001, 0x8001, 0x8001, 0x8001}; + static const uint16_t k18[6] = {0x801F, 0x8001, 0x800F, 0x8003, 0x8001, 0x8001}; + return (sd_card.v18 ? k18 : k33)[group]; +} + +// The 64-byte CMD6 status (SD 4.3.10.4). arg bit 31: 0 check, 1 switch; +// bits 4g+3..4g: the function wanted in group g+1, 0xF for "no change". +static void sd_switch_func(uint32_t arg, uint8_t st[64]) { + memset(st, 0, 64); + st[1] = 100; // mA the selected functions draw; bdk refuses over 800 + uint8_t res[6]; + for (int g = 0; g < 6; g++) { + uint16_t sup = sd_func_support(g); + st[2 + (5 - g) * 2] = (uint8_t)(sup >> 8); + st[3 + (5 - g) * 2] = (uint8_t)sup; + uint32_t want = (arg >> (4 * g)) & 0xF; + res[g] = want == 0xF ? sd_card.func[g] + : ((sup >> want) & 1) ? (uint8_t)want : 0xF; + } + if (arg >> 31) + for (int g = 0; g < 6; g++) + if (res[g] != 0xF) + sd_card.func[g] = res[g]; + st[14] = (uint8_t)(res[5] << 4 | res[4]); + st[15] = (uint8_t)(res[3] << 4 | res[2]); + st[16] = (uint8_t)(res[1] << 4 | res[0]); + st[17] = 1; // data structure version 1: busy status valid (none busy) +} + +// The 64-byte SD status (ACMD13, SD 4.10.2): the bus width ACMD6 set, and +// the card's grades - a Class 10, U1, V10 UHS-I card with 4 MB AUs. +static void sd_status(uint8_t ss[64]) { + memset(ss, 0, 64); + ss[0] = sd_card.bus4 ? 0x80 : 0x00; // DAT_BUS_WIDTH + ss[8] = 4; // SPEED_CLASS: Class 10 + ss[10] = 9 << 4; // AU_SIZE: 4 MB + ss[14] = 1 << 4 | 9; // UHS_SPEED_GRADE U1, UHS_AU_SIZE 4 MB + ss[15] = 10; // VIDEO_SPEED_CLASS: V10 +} + +// The SD card's CSD, version 2.0 (SD 5.3.3): an SDHC/SDXC card as big as +// the image (32 GiB with none), command classes 0, 2, 4, 5, 7, 8 and 10 - +// class 8, application commands, is what makes bdk read the SD status. +// Laid out as the R2 response registers carry it, CSD[127:8]: bdk shifts +// each word left by 8 to put the stripped CRC back. +static void sd_csd(EmuState *state, uint32_t r[4]) { + uint64_t bytes = state->sd_fd >= 0 ? (uint64_t)file_size64(state->sd_fd) + : 32ull << 30; + uint64_t units = bytes / (512u << 10); + uint32_t c_size = units ? (uint32_t)std::min(units - 1, 0x3FFFFF) + : 0; + unsigned __int128 c = 0; + auto put = [&](unsigned hi, unsigned lo, uint64_t v) { + c |= (unsigned __int128)(v & ((1ull << (hi - lo + 1)) - 1)) << lo; + }; + put(127, 126, 1); // CSD_STRUCTURE: version 2.0 + put(119, 112, 0x0E); // TAAC: 1 ms + put(103, 96, 0x32); // TRAN_SPEED: 25 MHz + put(95, 84, 0x5B5); // CCC + put(83, 80, 9); // READ_BL_LEN: 512 + put(69, 48, c_size); // C_SIZE: (C_SIZE + 1) x 512 KiB + put(46, 46, 1); // ERASE_BLK_EN + put(45, 39, 0x7F); // SECTOR_SIZE + put(28, 26, 2); // R2W_FACTOR + put(25, 22, 9); // WRITE_BL_LEN: 512 + put(0, 0, 1); // always 1 + for (int i = 0; i < 4; i++) + r[i] = (uint32_t)(c >> (8 + 32 * i)); +} + +// Port E sits in GPIO bank 1: CNF 0x100, OE 0x110, OUT 0x120. PE4 high +// powers the card; falling, the card loses its state. +static void sd_card_gpio_update() { + uint32_t m = 1u << 4; + bool on = (mmio_regs.get(GPIO_BASE + 0x100) & m) && + (mmio_regs.get(GPIO_BASE + 0x110) & m) && + (mmio_regs.get(GPIO_BASE + 0x120) & m); + if (sd_card.supplied && !on) + sd_card = SdCard(); + sd_card.supplied = on; +} + // ---- The eMMC's EXT_CSD ----------------------------------------------------- // // The properties segment is fixed; the fields CMD6 SWITCH writes (bus @@ -2440,6 +2550,20 @@ void misc_write(uc_engine *uc, EmuState *state, uint64_t addr, int64_t value, if (base == SDMMC4_BASE) { state->emmc_partition = 0; emmc_ext_csd_card_reset(); + } else { + // Functions back to default; the signalling voltage stays. + memset(sd_card.func, 0, sizeof(sd_card.func)); + sd_card.s18a_offered = false; + sd_card.bus4 = false; + } + break; + case 11: // SD VOLTAGE_SWITCH (R1, card in READY) + if (base == SDMMC1_BASE && sd_card.s18a_offered) { + sd_card.v18 = true; + sd_card.s18a_offered = false; + rsp[0] = r1_base | (1 << 9); + } else { + rsp[0] = r1_base | (1 << 9) | (1u << 22); // ILLEGAL_COMMAND } break; case 19: // SD SEND_TUNING_BLOCK @@ -2549,6 +2673,10 @@ void misc_write(uc_engine *uc, EmuState *state, uint64_t addr, int64_t value, // bits 18-21 of my rspreg3. Set those to 0100 (=4) so storage->csd. // mmca_vsn >= CSD_SPEC_VER_4 and sdmmc_storage_init_mmc reaches // storage->initialized = 1 instead of the early-return at line 688. + if (base == SDMMC1_BASE) { + sd_csd(state, rsp); + break; + } rsp[0] = 0x400E0032; rsp[1] = 0x5B590000; rsp[2] = 0x00007F80; @@ -2558,8 +2686,8 @@ void misc_write(uc_engine *uc, EmuState *state, uint64_t addr, int64_t value, bool is_acmd = (base == SDMMC1_BASE) ? state->last_cmd_was_55 : state->last_cmd4_was_55; if (is_acmd) { - uint8_t ss[64] = {0}; - ss[0] = 0x80; // 4-bit support (bit 511:510 = 10) + uint8_t ss[64]; + sd_status(ss); uint64_t dma_addr = sdmmc_dma_target(uc, hostctl, adma_addr, sysad); if (dma_addr) uc_mem_write(uc, dma_addr, ss, 64); @@ -2587,14 +2715,14 @@ void misc_write(uc_engine *uc, EmuState *state, uint64_t addr, int64_t value, bool is_acmd = (base == SDMMC1_BASE) ? state->last_cmd_was_55 : state->last_cmd4_was_55; if (is_acmd) { - // ACMD6: SET_BUS_WIDTH + // ACMD6: SET_BUS_WIDTH (arg 2 = 4-bit) + if (base == SDMMC1_BASE) + sd_card.bus4 = (arg & 3) == 2; rsp[0] = r1_base | (4 << 9); } else if (base == SDMMC1_BASE) { // CMD6: SWITCH_FUNC (SD) - uint8_t status[64] = {0}; - status[12] = 0x00; - status[13] = 0x02; // HS Support - status[16] = 0x01; // Group 1 switched to HS + uint8_t status[64]; + sd_switch_func(arg, status); uint64_t dma_addr = sdmmc_dma_target(uc, hostctl, adma_addr, sysad); if (dma_addr) @@ -2621,8 +2749,10 @@ void misc_write(uc_engine *uc, EmuState *state, uint64_t addr, int64_t value, state->last_cmd4_was_55 = true; break; } - case 41: - rsp[0] = 0xC0FF8000; + case 41: // SD_SEND_OP_COND: powered up, CCS, 2.7-3.6 V; S18A per S18R + sd_card.s18a_offered = base == SDMMC1_BASE && (arg & (1u << 24)) && + !sd_card.v18; + rsp[0] = 0xC0FF8000 | (sd_card.s18a_offered ? (1u << 24) : 0); break; case 42: rsp[0] = r1_base | (4 << 9); @@ -2634,8 +2764,9 @@ void misc_write(uc_engine *uc, EmuState *state, uint64_t addr, int64_t value, // SD SCR: byte 0 low nibble = SD_SPEC (2 => v2.00), byte 1 low // nibble = SD_BUS_WIDTHS (5 => 1-bit + 4-bit). This is what makes // hekate switch the bus to 4-bit; without it the init falls back to - // 1-bit HS25 and hwtest flags "1-bit (dirty slot?)". - uint8_t scr[8] = {0x02, 0x35, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + // 1-bit HS25 and hwtest flags "1-bit (dirty slot?)". Byte 2 bit 7, + // SD_SPEC3: Physical Layer 3.0x, as a UHS-I card is. + uint8_t scr[8] = {0x02, 0x35, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00}; // 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. @@ -4962,6 +5093,7 @@ void mmio_soft_reset(EmuState *state, bool power_cycle) { g_ext_csd_ready = false; else emmc_ext_csd_card_reset(); + sd_card = SdCard(); // the reset drops PE4, and the card's VDD with it // Display controller and VIC back to their defaults. dc_reset(state); From 1aa0ee9f236c2e1debe67673d5b7ac86edbeb866 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 22:40:08 +0000 Subject: [PATCH 12/21] Model the SE's RSA and random number generator Both ops finished with OP_DONE and produced nothing. se_rng_pseudo() left its buffer as it was, so Nyx's partition manager wrote whatever was on the stack into GPT partition GUIDs, and the SD benchmark drew its random offsets from uninitialised memory. se_rsa_exp_mod() read back zeros. - RSA, as Lockpick's bdk drives it: two keyslots of up to 2048 bits loaded through SE_RSA_KEYTABLE_ADDR/DATA, KEY_SIZE in 512-bit steps, EXP_SIZE in words, the input a little-endian number over DMA and the result in SE_RSA_OUTPUT (or memory). Montgomery multiplication on 32-bit words; an even modulus fails the op. - RNG into memory or a keyslot quad, LAST_BLOCK + 1 blocks cut to the buffer. The bytes come from SplitMix64 with a fixed seed, reset with the SE, so runs stay reproducible. tests/se/ is a new make test payload: RSA-2048 and RSA-1024 in the two slots, each m^d and s^e checked against Python (gen_vectors.py writes vectors.h), SHA-256 one-shot and in two parts, AES-128 ECB, and the RNG filling a zeroed buffer, changing between calls and stopping at the size asked for. Run against the previous binary it fails the RSA and RNG checks. The README's "RSA, RNG and chunked SHA are stubs" is gone; chunked SHA was already modelled. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb --- .github/workflows/build.yml | 10 +- DESIGN.md | 25 +++- Makefile | 8 +- README.md | 9 +- t210/se_engine.cpp | 231 ++++++++++++++++++++++++++++++++- tests/se/gen_vectors.py | 55 ++++++++ tests/se/link.ld | 10 ++ tests/se/payload.c | 252 ++++++++++++++++++++++++++++++++++++ tests/se/run.sh | 26 ++++ tests/se/vectors.h | 190 +++++++++++++++++++++++++++ 10 files changed, 799 insertions(+), 17 deletions(-) create mode 100755 tests/se/gen_vectors.py create mode 100644 tests/se/link.ld create mode 100644 tests/se/payload.c create mode 100755 tests/se/run.sh create mode 100644 tests/se/vectors.h diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index fb00d8a..a02faa4 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -45,13 +45,14 @@ jobs: grep -q "RCM Payload Emulator" out.txt \ || { echo "banner missing - binary did not start"; exit 1; } - - name: CCPLEX and display regression tests + - name: CCPLEX, SE and display regression tests # Small self-contained payloads. One boots CPU0 through bdk's # ccplex_boot_cpu0() register sequence: an unpowered release must be # refused, a powered one must run an AArch64 blob at EL3, and WFE must - # park the core. The others drive the display controller and VIC in - # six scenarios, and the frame the emulator shows must match the - # picture drawn, pixel for pixel. + # park the core. One runs the Security Engine's RSA, SHA-256, AES and + # RNG against vectors computed in Python. The others drive the + # display controller and VIC in six scenarios, and the frame the + # emulator shows must match the picture drawn, pixel for pixel. run: make test - name: hwtest end to end @@ -69,6 +70,7 @@ jobs: name: test-logs path: | tests/ccplex/out.log + tests/se/out.log tests/hwtest/out.log if-no-files-found: ignore diff --git a/DESIGN.md b/DESIGN.md index 28e977c..3dfa097 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -21,7 +21,7 @@ flowchart TB uc -->|MMIO callbacks| mmio["t210/mmio.cpp
mmio_bus_read / mmio_bus_write
shared by both masters"] mmio --> sdmmc["sdmmc
SDMMC1 / SDMMC4
CMD0..21, EXT_CSD, ADMA2
SD UHS-I, eMMC HS400"] - mmio --> se["se_engine
AES-128, SHA-256
BIS keyslot override"] + mmio --> se["se_engine
AES-128, SHA-256, RSA, RNG
BIS keyslot override"] mmio --> i2c["i2c3
STMFTS / FTS4 touch"] mmio --> i2c1["I2C_1 slaves (inline)
MAX17050, TMP451,
BQ24193, BM92T36"] mmio --> i2c5["I2C_5 slaves (inline)
MAX77620, MAX77621"] @@ -245,6 +245,18 @@ Models the SE (Security Engine) register block at `0x70012000`. Supports: save container hash. - **DST_KEYTABLE unwrap path.** The result of a single block is written into the destination slot's selected word quad. +- **RSA** modular exponentiation, as Lockpick's bdk drives it + (`se_rsa_key_set()` / `se_rsa_exp_mod()`): two keyslots of up to 2048 + bits, loaded a word at a time through `SE_RSA_KEYTABLE_ADDR/DATA` (least + significant word first), `KEY_SIZE` in 512-bit steps and `EXP_SIZE` in + words, the input a little-endian number over DMA and the result in + `SE_RSA_OUTPUT` (or memory). Montgomery multiplication on 32-bit words; + an even modulus fails the operation. +- **RNG** into memory or a keyslot quad (`se_rng_pseudo()`, TegraExplorer's + `se_generate_random()`): `LAST_BLOCK + 1` blocks, cut to the buffer size. + The bytes come from a SplitMix64 generator with a fixed seed, reset with + the SE, so runs repeat. Nyx uses them for GPT partition GUIDs and the SD + benchmark's random offsets. - **Context save** (`SE_OP_CTX_SAVE`), as bdk's `se_aes_ctx_get_keys()` uses it to read keyslots back: an RNG op seeds a secure random key (fixed, for reproducibility), each saved keyslot quad is written out encrypted under it @@ -258,10 +270,11 @@ Models the SE (Security Engine) register block at `0x70012000`. Supports: 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 and RNG output are stubbed: they -return `OP_DONE` without producing data. Block counts are bounded by what one +`key[32] / iv_orig[16] / iv_upd[16]`. Block counts are bounded by what one linked-list entry can describe (16 MiB), and an operation whose buffers are unreachable finishes with `SE_INT_ERR_STAT` instead of computing on zeros. +`tests/se/` checks RSA-2048 and RSA-1024 both ways against Python, SHA-256 +one-shot and in parts, AES-ECB and the RNG. ### Touchscreen (`t210/i2c3.cpp`) @@ -676,14 +689,16 @@ 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, and +refusal, the EL3 entry, the mailbox, WFE parking and the reset; +`tests/se/`, which runs the SE's RSA, SHA-256, AES and RNG against vectors +computed in Python (`gen_vectors.py` writes `vectors.h`); and `tests/display/`, one payload built per scenario that drives the display controller and VIC the way bdk does (a pitch window; Nyx's VIC turn into pitch and into block-linear surfaces; a block-linear VIC source; the DC's own column scan with an address offset; a mirrored window with window D blended over it). `check.py` compares every pixel of the frame the emulator shows with the picture the payload drew. `tests/hwtest/` builds hwtest-rcm -with distro toolchains and runs its whole sweep; CI runs all three. +with distro toolchains and runs its whole sweep; CI runs all four. ## Bug history diff --git a/Makefile b/Makefile index 59d1328..f05f547 100644 --- a/Makefile +++ b/Makefile @@ -98,6 +98,10 @@ tests/ccplex/payload.bin: tests/ccplex/payload.c tests/ccplex/link.ld $(TEST_CC) $(TEST_CFLAGS) -T tests/ccplex/link.ld -o tests/ccplex/payload.elf $< $(TEST_OBJCOPY) -O binary tests/ccplex/payload.elf $@ +tests/se/payload.bin: tests/se/payload.c tests/se/vectors.h tests/se/link.ld + $(TEST_CC) $(TEST_CFLAGS) -T tests/se/link.ld -o tests/se/payload.elf $< + $(TEST_OBJCOPY) -O binary tests/se/payload.elf $@ + DISPLAY_SCENARIOS = 1 2 3 4 5 6 DISPLAY_PAYLOADS = $(DISPLAY_SCENARIOS:%=tests/display/payload_%.bin) @@ -105,12 +109,14 @@ tests/display/payload_%.bin: tests/display/payload.c tests/display/link.ld $(TEST_CC) $(TEST_CFLAGS) -DSCENARIO=$* -T tests/display/link.ld -o tests/display/payload_$*.elf $< $(TEST_OBJCOPY) -O binary tests/display/payload_$*.elf $@ -test: $(OUTPUT) tests/ccplex/payload.bin $(DISPLAY_PAYLOADS) +test: $(OUTPUT) tests/ccplex/payload.bin tests/se/payload.bin $(DISPLAY_PAYLOADS) sh tests/ccplex/run.sh ./$(OUTPUT) tests/ccplex/payload.bin + sh tests/se/run.sh ./$(OUTPUT) tests/se/payload.bin sh tests/display/run.sh ./$(OUTPUT) tests/display clean: rm -f $(OUTPUT) $(OBJS) $(OBJS:.o=.d) \ tests/ccplex/payload.elf tests/ccplex/payload.bin tests/ccplex/out.log \ + tests/se/payload.elf tests/se/payload.bin tests/se/out.log \ tests/display/payload_*.elf tests/display/payload_*.bin \ $(WIN_OUT) $(WIN_OBJS) $(WIN_OBJS:.o=.d) diff --git a/README.md b/README.md index 3c55a5b..6ea9c77 100644 --- a/README.md +++ b/README.md @@ -175,7 +175,7 @@ real consoles. Details in [DESIGN.md](DESIGN.md#ccplex-cpu0). ## Tests ```bash -make test # CCPLEX + display regression payloads (arm-none-eabi-gcc, python3) +make test # CCPLEX, SE + display regression payloads (arm-none-eabi-gcc, python3) tests/hwtest/build.sh build-hwtest # build hwtest-rcm (+ gcc-aarch64-linux-gnu) tests/hwtest/run.sh ./rcm_emu build-hwtest/hwtest-rcm/build/hwtest.bin ``` @@ -288,12 +288,12 @@ flowchart LR root --> top["main.cpp
emu_state.h
Makefile
Dockerfile
README.md / DESIGN.md"] root --> t210["t210/
(SoC peripheral models)"] root --> display["display/"] - root --> tests["tests/
ccplex/, hwtest/"] + root --> tests["tests/
ccplex/, se/, display/, hwtest/"] t210 --> mmio["mmio.{h,cpp}
memory_map.h
regcache.h, tegra_bl.h"] t210 --> cpus["bpmp.{h,cpp} BPMP clock
ccplex.{h,cpp} CPU0 (A57)"] t210 --> pcie["pcie.{h,cpp}
root complex + CYW4356"] - t210 --> se["se_engine.{h,cpp}
AES-128, SHA-256"] + t210 --> se["se_engine.{h,cpp}
AES-128, SHA-256, RSA, RNG"] t210 --> i2c["i2c3.{h,cpp}
STMFTS / FTS4 touch"] display --> sdl["sdl_display.{h,cpp}
DC window scan-out
+ SDL2"] @@ -314,7 +314,8 @@ For implementation details, see [DESIGN.md](DESIGN.md). firmware and the full master-key unwrapping flow are not faithfully emulated. `--prod-keys` is a pragmatic shortcut: when Lockpick writes a derived BIS (Boot Image Storage) key into a keyslot, the value from the user-supplied key - file is substituted. RSA, RNG, and chunked SHA are stubs. + file is substituted. The random number generator starts from a fixed + seed, so runs repeat. - **Single-threaded.** Both cores run in batches on the main thread between SDL event polls. That is also what keeps them deterministic. diff --git a/t210/se_engine.cpp b/t210/se_engine.cpp index 00e5163..8f65f25 100644 --- a/t210/se_engine.cpp +++ b/t210/se_engine.cpp @@ -260,6 +260,12 @@ constexpr uint32_t SE_CONTEXT_SAVE_CONFIG_REG = 0x070; constexpr uint32_t SE_SHA_CONFIG_REG = 0x200; constexpr uint32_t SE_SHA_MSG_LENGTH_REG = 0x204; // 4 dwords, in bits constexpr uint32_t SE_SHA_MSG_LEFT_REG = 0x214; // 4 dwords, in bits +constexpr uint32_t SE_RSA_CONFIG_REG = 0x400; +constexpr uint32_t SE_RSA_KEY_SIZE_REG = 0x404; +constexpr uint32_t SE_RSA_EXP_SIZE_REG = 0x408; +constexpr uint32_t SE_RSA_KEYTABLE_ADDR_REG = 0x420; +constexpr uint32_t SE_RSA_KEYTABLE_DATA_REG = 0x424; +constexpr uint32_t SE_RSA_OUTPUT_REG = 0x428; // 64 dwords constexpr uint32_t SE_INT_OP_DONE = 1u << 4; constexpr uint32_t SE_INT_ERR_STAT = 1u << 16; @@ -269,6 +275,7 @@ constexpr uint32_t SE_OP_CTX_SAVE = 3; constexpr uint32_t ALG_RNG = 2; constexpr uint32_t ALG_SHA = 3; +constexpr uint32_t ALG_RSA = 4; constexpr uint32_t MODE_SHA256 = 5; constexpr uint32_t DST_SRK = 3; constexpr uint32_t DST_RSAREG = 4; @@ -344,6 +351,23 @@ static uint32_t reg_err_status = 0; static uint32_t reg_rng_config = 0; static uint32_t spare_regs[256] = {0}; // catch-all for less critical regs +// The two RSA keyslots, as bdk's se_rsa_key_set() loads them: 32-bit words, +// least significant first (it writes the big-endian key backwards, each word +// byte-swapped). SE_RSA_KEYTABLE_ADDR picks the word: PKT in 5:0, EXP (0) or +// MOD (1) in bit 6, the slot in bit 7. +constexpr int kRsaWords = 64; // 2048 bits +struct RsaKey { uint32_t exp[kRsaWords]; uint32_t mod[kRsaWords]; }; +static RsaKey rsa_keys[2]; +static uint32_t rsa_config = 0; +static uint32_t rsa_key_size = 0; +static uint32_t rsa_exp_size = 0; +static uint32_t rsa_keytable_addr = 0; +static uint32_t rsa_output[kRsaWords] = {0}; + +// The random number generator's state. The SE's DRBG is seeded from an +// entropy source; this one starts from a constant, so runs repeat. +static uint64_t rng_state = 0; + // Secure random key for context save, and the CBC chain the saved blocks // are encrypted under. See ctx_save(). static uint8_t srk[16] = {0}; @@ -438,6 +462,181 @@ static void run_aes_blocks(uint32_t slot, bool encrypt, if (chained && blocks) std::memcpy(ks_table[slot].iv_upd, v, 16); } +// ---- RSA: x^e mod n, Montgomery multiplication on 32-bit words ------------- +// +// Numbers are arrays of words, least significant first, n words long. + +static bool big_geq(const uint32_t *a, const uint32_t *b, int n) { + for (int i = n - 1; i >= 0; --i) + if (a[i] != b[i]) return a[i] > b[i]; + return true; +} + +static void big_sub(uint32_t *a, const uint32_t *b, int n) { + uint64_t borrow = 0; + for (int i = 0; i < n; ++i) { + uint64_t d = (uint64_t)a[i] - b[i] - borrow; + a[i] = (uint32_t)d; + borrow = d >> 63; + } +} + +// x = (2x + bit) mod m, for x < m. +static void big_shl1_mod(uint32_t *x, uint32_t bit, const uint32_t *m, int n) { + uint32_t carry = bit; + for (int i = 0; i < n; ++i) { + uint32_t top = x[i] >> 31; + x[i] = x[i] << 1 | carry; + carry = top; + } + if (carry || big_geq(x, m, n)) big_sub(x, m, n); +} + +// r = a mod m, a being na words long. +static void big_mod(const uint32_t *a, int na, const uint32_t *m, int n, + uint32_t *r) { + std::memset(r, 0, n * sizeof(uint32_t)); + for (int i = na * 32 - 1; i >= 0; --i) + big_shl1_mod(r, a[i / 32] >> (i % 32) & 1, m, n); +} + +// t = a * b / 2^(32n) mod m, for a, b < m and m odd (CIOS). +static void mont_mul(const uint32_t *a, const uint32_t *b, const uint32_t *m, + uint32_t minv, int n, uint32_t *out) { + uint32_t t[kRsaWords + 2] = {0}; + for (int i = 0; i < n; ++i) { + uint64_t c = 0; + for (int j = 0; j < n; ++j) { + uint64_t s = (uint64_t)t[j] + (uint64_t)a[j] * b[i] + c; + t[j] = (uint32_t)s; + c = s >> 32; + } + uint64_t s = (uint64_t)t[n] + c; + t[n] = (uint32_t)s; + t[n + 1] = (uint32_t)(s >> 32); + uint32_t u = t[0] * minv; + c = ((uint64_t)t[0] + (uint64_t)u * m[0]) >> 32; + for (int j = 1; j < n; ++j) { + s = (uint64_t)t[j] + (uint64_t)u * m[j] + c; + t[j - 1] = (uint32_t)s; + c = s >> 32; + } + s = (uint64_t)t[n] + c; + t[n - 1] = (uint32_t)s; + t[n] = t[n + 1] + (uint32_t)(s >> 32); + } + if (t[n] || big_geq(t, m, n)) big_sub(t, m, n); + std::memcpy(out, t, n * sizeof(uint32_t)); +} + +// out = x^e mod m. m must be odd (every RSA modulus is); false if it is not. +static bool mod_exp(const uint32_t *x, const uint32_t *e, int ne, + const uint32_t *m, int n, uint32_t *out) { + if (!(m[0] & 1)) return false; + // -1/m mod 2^32 by Newton's iteration; m0 is its own inverse mod 8. + uint32_t inv = m[0]; + for (int i = 0; i < 4; ++i) inv *= 2 - m[0] * inv; + uint32_t minv = 0u - inv; + + // R^2 mod m, R = 2^(32n): 1 doubled 64n times. + uint32_t r2[kRsaWords] = {0}, one[kRsaWords] = {0}; + one[0] = 1; + big_mod(one, 1, m, n, r2); + for (int i = 0; i < 64 * n; ++i) big_shl1_mod(r2, 0, m, n); + + uint32_t xm[kRsaWords], acc[kRsaWords]; + big_mod(x, n, m, n, xm); + mont_mul(xm, r2, m, minv, n, xm); // x in Montgomery form + mont_mul(one, r2, m, minv, n, acc); // 1 in Montgomery form + for (int i = ne * 32 - 1; i >= 0; --i) { + mont_mul(acc, acc, m, minv, n, acc); + if (e[i / 32] >> (i % 32) & 1) mont_mul(acc, xm, m, minv, n, acc); + } + mont_mul(acc, one, m, minv, n, out); + return true; +} + +// SE_OP_START with ALG_RSA, as bdk's se_rsa_exp_mod() drives it: the input +// arrives over DMA as a little-endian number the size of the modulus, the +// key comes from the slot in SE_RSA_CONFIG, KEY_SIZE gives the modulus in +// 512-bit steps and EXP_SIZE the exponent in words. The result goes to +// SE_RSA_OUTPUT (least significant word first), or to memory. +static void rsa_op(EmuState *state, uint32_t dst_kind) { + const RsaKey &k = rsa_keys[(rsa_config >> 24) & 1]; + int n = (int)((rsa_key_size & 3) + 1) * 16; + int ne = (int)(rsa_exp_size > (uint32_t)kRsaWords ? kRsaWords : rsa_exp_size); + + uint32_t x[kRsaWords] = {0}; + LLDesc in_ll{}; + if (read_ll(state->uc, reg_in_ll_addr, &in_ll) && in_ll.size) { + uint32_t copy = in_ll.size < (uint32_t)n * 4 ? in_ll.size : n * 4; + if (uc_mem_read(state->uc, in_ll.addr, x, copy) != UC_ERR_OK) { + op_fail("RSA input", in_ll.addr); + return; + } + } + + std::memset(rsa_output, 0, sizeof(rsa_output)); + if (!mod_exp(x, k.exp, ne, k.mod, n, rsa_output)) { + std::printf("[se] RSA-%d: even modulus, no result\n", n * 32); + reg_int_status |= SE_INT_OP_DONE | SE_INT_ERR_STAT; + return; + } + std::printf("[se] RSA-%d exp mod, %d-bit exponent -> ...%08X\n", n * 32, + ne * 32, rsa_output[0]); + + if (dst_kind == DST_MEMORY) { + LLDesc out_ll{}; + if (read_ll(state->uc, reg_out_ll_addr, &out_ll) && out_ll.size) { + uint32_t copy = out_ll.size < (uint32_t)n * 4 ? out_ll.size : n * 4; + if (uc_mem_write(state->uc, out_ll.addr, rsa_output, copy) != UC_ERR_OK) { + op_fail("RSA output", out_ll.addr); + return; + } + } + } + reg_int_status |= SE_INT_OP_DONE; +} + +// SplitMix64: small, and its output has no visible pattern. +static uint64_t rng_next() { + uint64_t z = (rng_state += 0x9E3779B97F4A7C15ull); + z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull; + z = (z ^ (z >> 27)) * 0x94D049BB133111EBull; + return z ^ (z >> 31); +} + +static void rng_fill(uint8_t *p, size_t len) { + for (size_t i = 0; i < len; i += 8) { + uint64_t v = rng_next(); + std::memcpy(p + i, &v, len - i < 8 ? len - i : 8); + } +} + +// SE_OP_START with ALG_RNG into memory or a keyslot: bdk's se_rng_pseudo() +// and TegraExplorer's se_generate_random() fill a buffer, SE_CRYPTO_LAST_BLOCK +// + 1 blocks of it; Atmosphère-style drivers fill a key quad. +static void rng_op(EmuState *state, uint32_t dst_kind) { + uint32_t blocks = (reg_block_count % MAX_AES_BLOCKS) + 1; + if (dst_kind == DST_KEYTABLE) { + Keyslot &k = ks_table[(reg_keytable_dst >> 8) & 0xF]; + uint8_t *target[4] = {k.key, k.key + 16, k.iv_orig, k.iv_upd}; + rng_fill(target[reg_keytable_dst & 0x3], 16); + } else if (dst_kind == DST_MEMORY) { + LLDesc out_ll{}; + if (read_ll(state->uc, reg_out_ll_addr, &out_ll) && out_ll.size) { + uint32_t len = out_ll.size < blocks * 16 ? out_ll.size : blocks * 16; + std::vector buf(len); + rng_fill(buf.data(), len); + if (uc_mem_write(state->uc, out_ll.addr, buf.data(), len) != UC_ERR_OK) { + op_fail("RNG output", out_ll.addr); + return; + } + } + } + reg_int_status |= SE_INT_OP_DONE; +} + // SHA-256, one-shot or in parts (bdk _se_sha_hash_256). SHA_INIT_HASH starts // from the standard initial state, SHA_CONTINUE from the state the previous // part left in SE_HASH_RESULT - which is where the hardware keeps it, too. @@ -504,9 +703,13 @@ static void op_start(EmuState *state) { return; } - if (dst_kind == DST_RSAREG) { - // RSA not implemented — leave output zero. - reg_int_status |= SE_INT_OP_DONE; + if (enc_alg == ALG_RNG) { + rng_op(state, dst_kind); + return; + } + + if (enc_alg == ALG_RSA) { + rsa_op(state, dst_kind); return; } @@ -667,6 +870,11 @@ static uint32_t keytable_read(uint32_t addr) { return v; } +static uint32_t &rsa_keytable_word() { + RsaKey &k = rsa_keys[(rsa_keytable_addr >> 7) & 1]; + return ((rsa_keytable_addr >> 6) & 1 ? k.mod : k.exp)[rsa_keytable_addr & 0x3F]; +} + } // namespace uint32_t se_engine_read(EmuState *state, uint64_t addr) { @@ -677,6 +885,9 @@ uint32_t se_engine_read(EmuState *state, uint64_t addr) { if (off >= SE_CRYPTO_LINEAR_CTR_REG && off < SE_CRYPTO_LINEAR_CTR_REG + 16) { return linear_ctr[(off - SE_CRYPTO_LINEAR_CTR_REG) / 4]; } + if (off >= SE_RSA_OUTPUT_REG && off < SE_RSA_OUTPUT_REG + kRsaWords * 4) { + return rsa_output[(off - SE_RSA_OUTPUT_REG) / 4]; + } switch (off) { case SE_OPERATION_REG: return reg_op; case SE_INT_ENABLE_REG: return reg_int_enable; @@ -692,6 +903,11 @@ uint32_t se_engine_read(EmuState *state, uint64_t addr) { case SE_RNG_CONFIG_REG: return reg_rng_config; case SE_STATUS_REG: return 0; // IDLE case SE_ERR_STATUS_REG: return reg_err_status; + case SE_RSA_CONFIG_REG: return rsa_config; + case SE_RSA_KEY_SIZE_REG: return rsa_key_size; + case SE_RSA_EXP_SIZE_REG: return rsa_exp_size; + case SE_RSA_KEYTABLE_ADDR_REG: return rsa_keytable_addr; + case SE_RSA_KEYTABLE_DATA_REG: return rsa_keytable_word(); default: if (off < sizeof(spare_regs)/sizeof(spare_regs[0])*4) return spare_regs[off / 4]; @@ -734,6 +950,11 @@ void se_engine_write(EmuState *state, uint64_t addr, uint32_t val) { case SE_CRYPTO_KEYTABLE_DST: reg_keytable_dst = val; return; case SE_RNG_CONFIG_REG: reg_rng_config = val; return; case SE_ERR_STATUS_REG: reg_err_status &= ~val; return; + case SE_RSA_CONFIG_REG: rsa_config = val; return; + case SE_RSA_KEY_SIZE_REG: rsa_key_size = val; return; + case SE_RSA_EXP_SIZE_REG: rsa_exp_size = val; return; + case SE_RSA_KEYTABLE_ADDR_REG: rsa_keytable_addr = val; return; + case SE_RSA_KEYTABLE_DATA_REG: rsa_keytable_word() = val; return; default: if (off < sizeof(spare_regs)/sizeof(spare_regs[0])*4) spare_regs[off / 4] = val; @@ -763,6 +984,10 @@ void se_engine_reset() { std::memset(spare_regs, 0, sizeof(spare_regs)); std::memset(srk, 0, sizeof(srk)); std::memset(ctx_chain, 0, sizeof(ctx_chain)); + std::memset(rsa_keys, 0, sizeof(rsa_keys)); + std::memset(rsa_output, 0, sizeof(rsa_output)); + rsa_config = rsa_key_size = rsa_exp_size = rsa_keytable_addr = 0; + rng_state = 0; } // ---- prod.keys parser ------------------------------------------------------- diff --git a/tests/se/gen_vectors.py b/tests/se/gen_vectors.py new file mode 100755 index 0000000..6e6c347 --- /dev/null +++ b/tests/se/gen_vectors.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +# Writes vectors.h for tests/se/payload.c: two RSA keys (e = 65537), a message +# and its m^d mod n for each, and SHA-256 digests. Seeded, so the output is +# the same every run; vectors.h is checked in and this only needs rerunning +# to change the vectors. +import hashlib, os, random +rnd = random.Random(0x5E) +def is_prime(n): + if n < 2: return False + for p in [2,3,5,7,11,13,17,19,23,29,31,37]: + if n % p == 0: return n == p + d, s = n-1, 0 + while d % 2 == 0: d//=2; s+=1 + for _ in range(40): + a = rnd.randrange(2, n-2) + x = pow(a, d, n) + if x in (1, n-1): continue + for _ in range(s-1): + x = x*x % n + if x == n-1: break + else: return False + return True +def prime(bits): + while True: + p = rnd.getrandbits(bits) | (1 << (bits-1)) | (1 << (bits-2)) | 1 + if is_prime(p): return p +def key(bits, e=65537): + while True: + p, q = prime(bits//2), prime(bits//2) + phi = (p-1)*(q-1) + if p != q and phi % e: + n = p*q + if n.bit_length() == bits: + return n, pow(e, -1, phi) +def arr(name, v, nbytes): + b = v.to_bytes(nbytes, 'big') + lines = ['static const unsigned char %s[%d] = {' % (name, nbytes)] + for i in range(0, nbytes, 12): + lines.append(' ' + ', '.join('0x%02X' % x for x in b[i:i+12]) + ',') + lines.append('};') + return '\n'.join(lines) +out = [] +for bits, tag in ((2048, 'k2048'), (1024, 'k1024')): + n, d = key(bits) + m = int.from_bytes(hashlib.sha256(tag.encode()).digest() * (bits // 256), 'big') % n + s = pow(m, d, n) + assert pow(s, 65537, n) == m + nb = bits // 8 + out += [arr(tag + '_mod', n, nb), arr(tag + '_exp', d, nb), arr(tag + '_msg', m, nb), arr(tag + '_sig', s, nb)] +msg = bytes((i * 7 + 3) & 0xFF for i in range(200)) +out.append(arr('sha_msg', int.from_bytes(msg, 'big'), 200)) +out.append(arr('sha_msg_digest', int.from_bytes(hashlib.sha256(msg).digest(), 'big'), 32)) +out.append(arr('sha_abc_digest', int.from_bytes(hashlib.sha256(b'abc').digest(), 'big'), 32)) +open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'vectors.h'), 'w').write('/* Generated by gen_vectors.py: RSA keys (e = 65537) with\n * m^d mod n, and SHA-256 digests, computed with Python integers and hashlib. */\n\n' + '\n\n'.join(out) + '\n') + diff --git a/tests/se/link.ld b/tests/se/link.ld new file mode 100644 index 0000000..bdc1203 --- /dev/null +++ b/tests/se/link.ld @@ -0,0 +1,10 @@ +/* Loaded and entered at 0x40010000, like any RCM payload. */ +ENTRY(_start) +SECTIONS { + . = 0x40010000; + .text : { KEEP(*(.text.start)) *(.text*) } + .rodata : { *(.rodata*) } + .data : { *(.data*) } + .bss : { *(.bss*) *(COMMON) } + /DISCARD/ : { *(.comment) *(.note*) *(.ARM.attributes) *(.ARM.exidx*) } +} diff --git a/tests/se/payload.c b/tests/se/payload.c new file mode 100644 index 0000000..387fae0 --- /dev/null +++ b/tests/se/payload.c @@ -0,0 +1,252 @@ +/* + * Security Engine regression payload. + * + * A freestanding BPMP payload that drives the emulator's SE model with the + * register sequences bdk uses, checks every result against vectors computed + * outside the emulator (vectors.h, from gen_vectors.py), and reports on + * UART-B. tests/se/run.sh checks the log. + * + * rsa se_rsa_key_set() / se_rsa_exp_mod() as Lockpick's bdk has them: + * a 2048-bit and a 1024-bit key in the two slots, each signing with + * its private exponent and verifying with e = 65537 + * sha SHA-256 one-shot, and in two parts (INIT, then CONTINUE) + * aes AES-128 ECB, Lockpick's keyslot-access vector + * rng se_rng_pseudo(): output that is not all zeros, differs from call + * to call, and stops at the size asked for + */ + +typedef unsigned int u32; +typedef unsigned char u8; + +#define REG(a) (*(volatile u32 *)(a)) + +#define UARTB_THR 0x70006040u +#define I2C5 0x7000D000u +#define SE 0x70012000u +#define SER(o) REG(SE + (o)) + +#define SE_OPERATION 0x008 +#define SE_INT_STATUS 0x010 +#define SE_CONFIG 0x014 +#define SE_IN_LL_ADDR 0x018 +#define SE_OUT_LL_ADDR 0x024 +#define SE_HASH_RESULT 0x030 +#define SE_SHA_CONFIG 0x200 +#define SE_SHA_MSG_LENGTH 0x204 +#define SE_SHA_MSG_LEFT 0x214 +#define SE_CRYPTO_CONFIG 0x304 +#define SE_LAST_BLOCK 0x318 +#define SE_KEYTABLE_ADDR 0x31C +#define SE_KEYTABLE_DATA 0x320 +#define SE_RNG_CONFIG 0x340 +#define SE_RSA_CONFIG 0x400 +#define SE_RSA_KEY_SIZE 0x404 +#define SE_RSA_EXP_SIZE 0x408 +#define SE_RSA_KT_ADDR 0x420 +#define SE_RSA_KT_DATA 0x424 +#define SE_RSA_OUTPUT 0x428 +#define SE_ERR_STATUS 0x804 + +#define OP_DONE (1u << 4) +#define ERR_STAT (1u << 16) + +#define DST(x) ((x) << 2) +#define DEC_ALG(x) ((x) << 8) +#define ENC_ALG(x) ((x) << 12) +#define ENC_MODE(x) ((x) << 24) +#define DST_MEMORY 0 +#define DST_HASHREG 1 +#define DST_RSAREG 4 +#define ALG_AES 1 +#define ALG_RNG 2 +#define ALG_SHA 3 +#define ALG_RSA 4 +#define MODE_SHA256 5 + +#include "vectors.h" + +static void puts_(const char *s) { + while (*s) + REG(UARTB_THR) = (u32)(unsigned char)*s++; +} + +static void i2c5_write(u32 dev, u32 reg, u32 val) { + REG(I2C5 + 0x04) = dev << 1; /* CMD_ADDR0 */ + REG(I2C5 + 0x0C) = reg | (val << 8); /* CMD_DATA1 */ + REG(I2C5 + 0x00) = (1u << 1) | (1u << 9); /* CNFG: 2 bytes, write, GO */ +} + +static int failed; + +static void check(int ok, const char *what) { + puts_(ok ? "se test: ok " : "se test: FAIL "); + puts_(what); + puts_("\n"); + if (!ok) + failed = 1; +} + +static int same(const u8 *a, const u8 *b, u32 n) { + for (u32 i = 0; i < n; i++) + if (a[i] != b[i]) + return 0; + return 1; +} + +static u32 be32(const u8 *p) { + return (u32)p[0] << 24 | (u32)p[1] << 16 | (u32)p[2] << 8 | p[3]; +} + +static void put_be32(u8 *p, u32 v) { + p[0] = v >> 24; + p[1] = v >> 16; + p[2] = v >> 8; + p[3] = v; +} + +/* bdk's _se_execute_oneshot(): one linked-list entry each way. */ +static volatile u32 ll_in[3], ll_out[3]; + +static int se_exec(void *dst, u32 dst_size, const void *src, u32 src_size) { + ll_in[0] = 0; + ll_in[1] = (u32)src; + ll_in[2] = src_size; + ll_out[0] = 0; + ll_out[1] = (u32)dst; + ll_out[2] = dst_size; + SER(SE_IN_LL_ADDR) = src ? (u32)ll_in : 0; + SER(SE_OUT_LL_ADDR) = dst ? (u32)ll_out : 0; + SER(SE_ERR_STATUS) = SER(SE_ERR_STATUS); + SER(SE_INT_STATUS) = SER(SE_INT_STATUS); + SER(SE_OPERATION) = 1; /* START */ + while (!(SER(SE_INT_STATUS) & OP_DONE)) + ; + return (SER(SE_INT_STATUS) & ERR_STAT) || SER(SE_ERR_STATUS); +} + +/* se_rsa_key_set(): the big-endian key goes in backwards, word by word. */ +static void rsa_key_set(u32 ks, const u8 *mod, u32 mod_size, const u8 *exp, + u32 exp_size) { + for (u32 i = 0; i < mod_size / 4; i++) { + SER(SE_RSA_KT_ADDR) = ks << 7 | 1u << 6 | i; /* MOD */ + SER(SE_RSA_KT_DATA) = be32(mod + mod_size - 4 - 4 * i); + } + for (u32 i = 0; i < exp_size / 4; i++) { + SER(SE_RSA_KT_ADDR) = ks << 7 | i; /* EXP */ + SER(SE_RSA_KT_DATA) = be32(exp + exp_size - 4 - 4 * i); + } +} + +/* se_rsa_exp_mod(): the input reversed into a little-endian number, the + * output read back from SE_RSA_OUTPUT into big-endian bytes. */ +static int rsa_exp_mod(u32 ks, u8 *dst, const u8 *src, u32 size, + u32 exp_size) { + static u8 buf[256]; + for (u32 i = 0; i < size; i++) + buf[i] = src[size - 1 - i]; + SER(SE_CONFIG) = ENC_ALG(ALG_RSA) | DST(DST_RSAREG); + SER(SE_RSA_CONFIG) = ks << 24; + SER(SE_RSA_KEY_SIZE) = (size >> 6) - 1; + SER(SE_RSA_EXP_SIZE) = exp_size >> 2; + int res = se_exec(0, 0, buf, size); + for (u32 i = 0; i < size / 4; i++) + put_be32(dst + size - 4 - 4 * i, SER(SE_RSA_OUTPUT + 4 * i)); + return res; +} + +/* _se_sha_hash_256(): total 0 or equal to the part means INIT; a part + * that is not the last says one byte more is left than it carries. */ +static int sha256(u8 *hash, u32 total, const u8 *src, u32 size) { + u32 left = total < size ? size + 1 : size; + SER(SE_CONFIG) = ENC_MODE(MODE_SHA256) | ENC_ALG(ALG_SHA) | DST(DST_HASHREG); + SER(SE_SHA_MSG_LENGTH) = total << 3; + SER(SE_SHA_MSG_LENGTH + 4) = total >> 29; + SER(SE_SHA_MSG_LENGTH + 8) = 0; + SER(SE_SHA_MSG_LENGTH + 12) = 0; + SER(SE_SHA_MSG_LEFT) = left << 3; + SER(SE_SHA_MSG_LEFT + 4) = left >> 29; + SER(SE_SHA_MSG_LEFT + 8) = 0; + SER(SE_SHA_MSG_LEFT + 12) = 0; + SER(SE_SHA_CONFIG) = (total == size || !total) ? 1 : 0; + int res = se_exec(0, 0, src, size); + for (u32 i = 0; i < 8; i++) + put_be32(hash + 4 * i, SER(SE_HASH_RESULT + 4 * i)); + return res; +} + +/* se_rng_pseudo() for a whole number of blocks. */ +static int rng(u8 *dst, u32 size) { + SER(SE_CONFIG) = ENC_ALG(ALG_RNG) | DST(DST_MEMORY); + SER(SE_CRYPTO_CONFIG) = 1u << 3; /* INPUT_RANDOM */ + SER(SE_RNG_CONFIG) = 1u << 2; /* SRC_ENTROPY, MODE_NORMAL */ + SER(SE_LAST_BLOCK) = (size >> 4) - 1; + return se_exec(dst, size, 0, 0); +} + +static const u8 e65537[4] = {0x00, 0x01, 0x00, 0x01}; + +__attribute__((section(".text.start"), noreturn)) +void _start(void) { + static u8 out[256], hash[32], blk[16], a[48], b[48]; + + puts_("se test: start\n"); + + /* RSA: both slots loaded before either is used. */ + rsa_key_set(0, k2048_mod, 256, k2048_exp, 256); + rsa_key_set(1, k1024_mod, 128, k1024_exp, 128); + check(!rsa_exp_mod(0, out, k2048_msg, 256, 256) && + same(out, k2048_sig, 256), "RSA-2048 m^d mod n"); + check(!rsa_exp_mod(1, out, k1024_msg, 128, 128) && + same(out, k1024_sig, 128), "RSA-1024 m^d mod n in slot 1"); + rsa_key_set(0, k2048_mod, 256, e65537, 4); + check(!rsa_exp_mod(0, out, k2048_sig, 256, 4) && + same(out, k2048_msg, 256), "RSA-2048 s^e mod n gives m back"); + rsa_key_set(1, k1024_mod, 128, e65537, 4); + check(!rsa_exp_mod(1, out, k1024_sig, 128, 4) && + same(out, k1024_msg, 128), "RSA-1024 s^e mod n gives m back"); + + /* SHA-256. */ + static const u8 abc[3] = {'a', 'b', 'c'}; + check(!sha256(hash, 3, abc, 3) && same(hash, sha_abc_digest, 32), + "SHA-256 one-shot"); + check(!sha256(hash, 0, sha_msg, 128) && + !sha256(hash, 200, sha_msg + 128, 72) && + same(hash, sha_msg_digest, 32), "SHA-256 in two parts"); + + /* AES-128 ECB decrypt of a zero block under 00..0F. */ + static const u8 aes_exp[16] = {0x7B, 0x1D, 0x29, 0xA1, 0x6C, 0xF8, + 0xCC, 0xAB, 0x84, 0xF0, 0xB8, 0xA5, + 0x98, 0xE4, 0x2F, 0xA6}; + for (u32 i = 0; i < 4; i++) { + SER(SE_KEYTABLE_ADDR) = 5u << 4 | i; /* slot 5, KEYS_0_3 */ + SER(SE_KEYTABLE_DATA) = (4 * i) | (4 * i + 1) << 8 | + (4 * i + 2) << 16 | (u32)(4 * i + 3) << 24; + } + for (u32 i = 0; i < 16; i++) + blk[i] = 0; + SER(SE_CONFIG) = DEC_ALG(ALG_AES) | DST(DST_MEMORY); + SER(SE_CRYPTO_CONFIG) = 5u << 24; /* KEY_INDEX 5, CORE_DECRYPT */ + SER(SE_LAST_BLOCK) = 0; + check(!se_exec(blk, 16, blk, 16) && same(blk, aes_exp, 16), + "AES-128 ECB decrypt"); + + /* RNG: 32 bytes twice, into zeroed buffers with a sentinel tail. */ + for (u32 i = 0; i < 48; i++) + a[i] = b[i] = i < 32 ? 0 : 0x5A; + int res = rng(a, 32) | rng(b, 32); + int zero = 1, tail = 1; + for (u32 i = 0; i < 32; i++) + if (a[i]) + zero = 0; + for (u32 i = 32; i < 48; i++) + if (a[i] != 0x5A || b[i] != 0x5A) + tail = 0; + check(!res && !zero, "RNG fills the buffer"); + check(!same(a, b, 32), "RNG output changes between calls"); + check(tail, "RNG stops at the size asked for"); + + puts_(failed ? "se test: done, with failures\n" : "se test: done\n"); + i2c5_write(0x3C, 0x41, 0x02); /* MAX77620 ONOFFCNFG1: PWR_OFF */ + for (;;) + ; +} diff --git a/tests/se/run.sh b/tests/se/run.sh new file mode 100755 index 0000000..854da3d --- /dev/null +++ b/tests/se/run.sh @@ -0,0 +1,26 @@ +#!/bin/sh +# Security Engine regression test: run tests/se/payload.c and check what it +# reports. Usage: tests/se/run.sh [rcm_emu] [payload] +EMU=${1:-./rcm_emu} +PAYLOAD=${2:-tests/se/payload.bin} +LOG=${LOG:-tests/se/out.log} + +SDL_VIDEODRIVER=dummy RCM_EMU_NO_AUDIO=1 timeout 60 "$EMU" "$PAYLOAD" \ + > "$LOG" 2>&1 +status=$? + +echo "se test (emulator exit $status):" +# The payload's lines arrive through the UART-B log, tagged [uartB]. +grep '^\[uartB\] se test: \(ok\|FAIL\) ' "$LOG" | + sed -e 's/^.*se test: ok */ ok /' -e 's/^.*se test: FAIL */ FAIL /' +fail=0 +grep -q 'se test: FAIL' "$LOG" && fail=1 +if ! grep -q '^\[uartB\] se test: done$' "$LOG"; then + echo " FAIL the payload did not finish cleanly" + fail=1 +fi +if [ "$status" -ne 0 ]; then + echo " FAIL the emulator exited with status $status (124 = timed out)" + fail=1 +fi +[ $fail -eq 0 ] && echo "se test: PASS" || { echo "se test: FAIL (log: $LOG)"; exit 1; } diff --git a/tests/se/vectors.h b/tests/se/vectors.h new file mode 100644 index 0000000..3d483ba --- /dev/null +++ b/tests/se/vectors.h @@ -0,0 +1,190 @@ +/* Generated by gen_vectors.py: RSA keys (e = 65537) with + * m^d mod n, and SHA-256 digests, computed with Python integers and hashlib. */ + +static const unsigned char k2048_mod[256] = { + 0xDB, 0x84, 0xB5, 0x8A, 0xA4, 0x6A, 0xC2, 0x45, 0x45, 0x22, 0x94, 0x72, + 0x4B, 0xAC, 0xC7, 0xB9, 0x34, 0x68, 0x99, 0xA8, 0x81, 0x91, 0x99, 0x8D, + 0xEF, 0x69, 0xA2, 0xFE, 0xAC, 0x99, 0xD5, 0x36, 0x8D, 0x80, 0x27, 0x17, + 0x39, 0xC2, 0x33, 0xE5, 0x12, 0x23, 0xF0, 0x81, 0x28, 0xD8, 0x30, 0x5B, + 0x20, 0x7E, 0x9B, 0xD2, 0xE1, 0xA0, 0xE4, 0xBB, 0x12, 0x9C, 0xB9, 0x44, + 0x45, 0x99, 0x02, 0xEF, 0xDE, 0x5E, 0x21, 0x9B, 0x5E, 0x3E, 0xBF, 0x91, + 0x9E, 0x07, 0xBA, 0x6D, 0xE1, 0x5E, 0xBB, 0x2D, 0x10, 0x26, 0x20, 0x97, + 0xFC, 0x7F, 0xD4, 0x51, 0xA7, 0x17, 0x94, 0xB1, 0x07, 0x56, 0xD5, 0x7E, + 0xE9, 0xBE, 0xD4, 0x8A, 0x0B, 0xA6, 0xF9, 0x2A, 0x7A, 0x78, 0xE6, 0xC0, + 0x36, 0xE7, 0x53, 0xD4, 0x77, 0x3D, 0x8A, 0x79, 0x7B, 0xAF, 0x72, 0x80, + 0x82, 0x37, 0x00, 0x7E, 0xE4, 0x40, 0xBB, 0x75, 0x85, 0xB1, 0x34, 0xC3, + 0x3B, 0xC4, 0xE7, 0xCF, 0xCA, 0x7B, 0xA3, 0x7B, 0xEF, 0x49, 0xC7, 0x52, + 0x15, 0x79, 0xDC, 0xF9, 0x6C, 0xAE, 0xFB, 0xDC, 0xA5, 0x7A, 0x5B, 0x35, + 0x4C, 0x74, 0xAD, 0x1F, 0x7A, 0xDB, 0x8A, 0x1E, 0x2B, 0xDC, 0xD4, 0x3B, + 0x65, 0x21, 0x15, 0x21, 0xB5, 0xD3, 0x20, 0x62, 0x94, 0xAC, 0x11, 0x9F, + 0x11, 0xEA, 0x8B, 0xB6, 0xE8, 0xCA, 0xD1, 0x54, 0x26, 0x16, 0xEB, 0xED, + 0xF4, 0x7A, 0xFB, 0x92, 0x5C, 0xD7, 0x72, 0xE8, 0x3B, 0xAF, 0x63, 0x58, + 0xCC, 0x8B, 0x2B, 0x8A, 0x1D, 0x78, 0x5F, 0xC2, 0xFA, 0xD9, 0xFB, 0x59, + 0x50, 0x43, 0x96, 0x1C, 0x03, 0x6C, 0x2D, 0x99, 0x8A, 0xE8, 0x92, 0xA2, + 0xE4, 0x62, 0x0A, 0x29, 0x35, 0x93, 0x02, 0x26, 0x31, 0x2D, 0x07, 0xE7, + 0x99, 0xE5, 0xDA, 0x37, 0x2B, 0xD4, 0xA4, 0x39, 0x9B, 0xC8, 0x2B, 0x8D, + 0x2A, 0x51, 0x34, 0x23, +}; + +static const unsigned char k2048_exp[256] = { + 0xB3, 0xBD, 0x44, 0xDC, 0x41, 0x65, 0xBC, 0xAD, 0xF5, 0x3E, 0xAC, 0x27, + 0xAD, 0xB8, 0xCA, 0x4B, 0xE6, 0x12, 0xA3, 0x86, 0x2A, 0x99, 0x2A, 0x0E, + 0xE2, 0x72, 0x2F, 0x68, 0xB1, 0xB0, 0xBF, 0xB8, 0x8C, 0x41, 0xDB, 0x40, + 0x14, 0x25, 0xE4, 0x51, 0xF2, 0xF9, 0x84, 0x6A, 0x6D, 0x24, 0x1E, 0xEB, + 0xEE, 0x7E, 0x5C, 0x5E, 0x5E, 0x2A, 0x5C, 0x3E, 0xA4, 0xAD, 0xB8, 0xB0, + 0xA2, 0xFF, 0xF7, 0x3C, 0xAA, 0x69, 0x8E, 0xC0, 0xE5, 0x79, 0x21, 0x68, + 0x3C, 0xE9, 0xFD, 0x07, 0x0D, 0x5A, 0x80, 0x8E, 0x14, 0x43, 0xF3, 0xBA, + 0x1E, 0xA0, 0x18, 0x1B, 0xC7, 0x61, 0xF2, 0x78, 0xC5, 0x16, 0x9F, 0x76, + 0xEC, 0x33, 0x39, 0x59, 0xD2, 0xD2, 0xA3, 0xFF, 0xD9, 0x09, 0xF7, 0x7E, + 0x79, 0x36, 0x0E, 0x18, 0xD0, 0x8D, 0x8E, 0x3D, 0x8C, 0x3D, 0x8A, 0xD6, + 0x98, 0x48, 0x2A, 0xDA, 0xBB, 0x50, 0x19, 0x6C, 0x4B, 0x8B, 0x24, 0x84, + 0xF4, 0x28, 0x0B, 0xFA, 0x6E, 0x64, 0xC4, 0x63, 0xDC, 0x3C, 0xDF, 0x90, + 0xF4, 0x8D, 0x02, 0xEC, 0x58, 0xFB, 0x3E, 0xAE, 0x05, 0x3C, 0xFC, 0x20, + 0xB8, 0x93, 0x02, 0x8E, 0x62, 0x3B, 0x29, 0xDA, 0x3E, 0xF7, 0x8C, 0xCC, + 0x16, 0x30, 0x83, 0xF1, 0xFD, 0xA4, 0x56, 0x0C, 0xD1, 0x09, 0x77, 0x61, + 0x58, 0xC0, 0xCE, 0xE7, 0x5E, 0xA1, 0x0F, 0x66, 0x18, 0x81, 0x96, 0x06, + 0xD1, 0xCF, 0xCC, 0x5B, 0x1F, 0x9A, 0x1F, 0x25, 0x79, 0xCB, 0x66, 0x28, + 0x6A, 0xE1, 0x61, 0x60, 0x16, 0x0E, 0x73, 0x5A, 0x50, 0xDC, 0x9C, 0xE4, + 0xB3, 0x0E, 0xFD, 0x50, 0x90, 0xD3, 0x63, 0x2D, 0x9E, 0xDB, 0xEA, 0x61, + 0x90, 0x65, 0xB0, 0xE0, 0xB8, 0xFF, 0xE6, 0x9D, 0x78, 0xB3, 0x8F, 0x68, + 0x19, 0xFE, 0x45, 0x2B, 0x91, 0xD8, 0x0F, 0xB2, 0x2E, 0x90, 0x47, 0xA7, + 0x80, 0xA0, 0x73, 0xB9, +}; + +static const unsigned char k2048_msg[256] = { + 0x7E, 0x8E, 0x33, 0x8D, 0x7B, 0xD2, 0xAE, 0x8D, 0x55, 0xB2, 0xFF, 0x7E, + 0x47, 0x6F, 0x6C, 0x3F, 0x8F, 0xAA, 0x20, 0x78, 0xEB, 0xF8, 0x6D, 0xA4, + 0x36, 0xF1, 0x6E, 0x98, 0x64, 0x00, 0xCC, 0x4A, 0x7E, 0x8E, 0x33, 0x8D, + 0x7B, 0xD2, 0xAE, 0x8D, 0x55, 0xB2, 0xFF, 0x7E, 0x47, 0x6F, 0x6C, 0x3F, + 0x8F, 0xAA, 0x20, 0x78, 0xEB, 0xF8, 0x6D, 0xA4, 0x36, 0xF1, 0x6E, 0x98, + 0x64, 0x00, 0xCC, 0x4A, 0x7E, 0x8E, 0x33, 0x8D, 0x7B, 0xD2, 0xAE, 0x8D, + 0x55, 0xB2, 0xFF, 0x7E, 0x47, 0x6F, 0x6C, 0x3F, 0x8F, 0xAA, 0x20, 0x78, + 0xEB, 0xF8, 0x6D, 0xA4, 0x36, 0xF1, 0x6E, 0x98, 0x64, 0x00, 0xCC, 0x4A, + 0x7E, 0x8E, 0x33, 0x8D, 0x7B, 0xD2, 0xAE, 0x8D, 0x55, 0xB2, 0xFF, 0x7E, + 0x47, 0x6F, 0x6C, 0x3F, 0x8F, 0xAA, 0x20, 0x78, 0xEB, 0xF8, 0x6D, 0xA4, + 0x36, 0xF1, 0x6E, 0x98, 0x64, 0x00, 0xCC, 0x4A, 0x7E, 0x8E, 0x33, 0x8D, + 0x7B, 0xD2, 0xAE, 0x8D, 0x55, 0xB2, 0xFF, 0x7E, 0x47, 0x6F, 0x6C, 0x3F, + 0x8F, 0xAA, 0x20, 0x78, 0xEB, 0xF8, 0x6D, 0xA4, 0x36, 0xF1, 0x6E, 0x98, + 0x64, 0x00, 0xCC, 0x4A, 0x7E, 0x8E, 0x33, 0x8D, 0x7B, 0xD2, 0xAE, 0x8D, + 0x55, 0xB2, 0xFF, 0x7E, 0x47, 0x6F, 0x6C, 0x3F, 0x8F, 0xAA, 0x20, 0x78, + 0xEB, 0xF8, 0x6D, 0xA4, 0x36, 0xF1, 0x6E, 0x98, 0x64, 0x00, 0xCC, 0x4A, + 0x7E, 0x8E, 0x33, 0x8D, 0x7B, 0xD2, 0xAE, 0x8D, 0x55, 0xB2, 0xFF, 0x7E, + 0x47, 0x6F, 0x6C, 0x3F, 0x8F, 0xAA, 0x20, 0x78, 0xEB, 0xF8, 0x6D, 0xA4, + 0x36, 0xF1, 0x6E, 0x98, 0x64, 0x00, 0xCC, 0x4A, 0x7E, 0x8E, 0x33, 0x8D, + 0x7B, 0xD2, 0xAE, 0x8D, 0x55, 0xB2, 0xFF, 0x7E, 0x47, 0x6F, 0x6C, 0x3F, + 0x8F, 0xAA, 0x20, 0x78, 0xEB, 0xF8, 0x6D, 0xA4, 0x36, 0xF1, 0x6E, 0x98, + 0x64, 0x00, 0xCC, 0x4A, +}; + +static const unsigned char k2048_sig[256] = { + 0x84, 0xFE, 0x52, 0x90, 0x0E, 0x74, 0xA7, 0x53, 0xCC, 0xEB, 0x46, 0x40, + 0x2D, 0x8A, 0x38, 0xFC, 0x14, 0x52, 0xD7, 0x8E, 0xC9, 0xC8, 0x17, 0xB7, + 0xE3, 0x17, 0x8E, 0x8D, 0x4C, 0xB8, 0xB1, 0xDB, 0x2D, 0xCA, 0xD5, 0x34, + 0xDE, 0xEC, 0x4B, 0x60, 0x7A, 0x53, 0xBC, 0x96, 0x62, 0xCA, 0xA5, 0x26, + 0xB3, 0x35, 0x9C, 0x4F, 0x30, 0xB4, 0xAC, 0x6A, 0x74, 0xDB, 0x6E, 0x13, + 0x70, 0xC6, 0xE4, 0x7F, 0xB5, 0x76, 0x4A, 0x41, 0x9D, 0x2C, 0x86, 0xDA, + 0x9C, 0xE6, 0x87, 0x32, 0x62, 0x71, 0xB6, 0xE7, 0xDB, 0x79, 0xC2, 0x07, + 0xF4, 0x24, 0x33, 0xC4, 0x60, 0x3E, 0xC8, 0x10, 0x17, 0x69, 0xA0, 0x95, + 0xBE, 0x6F, 0xD8, 0x69, 0x79, 0x25, 0xB0, 0x4D, 0x20, 0x9B, 0x33, 0xF1, + 0x86, 0x56, 0x2F, 0x8D, 0x79, 0xB8, 0xB7, 0x78, 0x63, 0x84, 0xB5, 0x4E, + 0xBA, 0x6A, 0xB0, 0x4D, 0xA0, 0x7E, 0x48, 0xDF, 0xD4, 0xC0, 0x96, 0xAD, + 0x2E, 0x23, 0x06, 0x7A, 0xE5, 0xC0, 0x79, 0x57, 0xBB, 0x60, 0xF5, 0x15, + 0x02, 0xBA, 0xED, 0x65, 0x54, 0x7B, 0x9D, 0x20, 0x03, 0xEB, 0x76, 0xDF, + 0xB5, 0xE1, 0xD1, 0x3D, 0x90, 0xD3, 0x73, 0x80, 0xA6, 0x52, 0x27, 0x01, + 0x02, 0x72, 0x4D, 0xCA, 0xBA, 0x30, 0xA8, 0xEF, 0x01, 0xC8, 0xC3, 0x3E, + 0xFA, 0xC4, 0x12, 0x00, 0x2F, 0x02, 0x12, 0x0F, 0xC4, 0x11, 0x74, 0x30, + 0x30, 0x68, 0x4F, 0x16, 0x74, 0x38, 0xBE, 0x25, 0xDA, 0x44, 0xE7, 0xE4, + 0xFF, 0x92, 0x3A, 0x20, 0xC5, 0x32, 0xCB, 0x86, 0xAE, 0x10, 0x47, 0x9B, + 0x71, 0x43, 0xD8, 0x2C, 0x66, 0xE4, 0x13, 0x93, 0xF6, 0xBE, 0x60, 0x15, + 0x51, 0x02, 0x61, 0xD0, 0xAA, 0xAF, 0x13, 0xA1, 0x38, 0x50, 0xF7, 0x0E, + 0x66, 0x4C, 0x8B, 0xF7, 0x46, 0x8A, 0x76, 0xD6, 0xC1, 0x6F, 0x87, 0xC2, + 0x37, 0x5A, 0x47, 0xB9, +}; + +static const unsigned char k1024_mod[128] = { + 0xA9, 0x97, 0xBA, 0xDB, 0x61, 0x4B, 0x0E, 0x12, 0x16, 0x22, 0xC5, 0xD9, + 0x65, 0xD3, 0x01, 0x6E, 0x08, 0xDF, 0x1B, 0x29, 0xFD, 0x01, 0x88, 0xAC, + 0xF3, 0x36, 0xE0, 0xA6, 0x21, 0xC2, 0xE5, 0xB9, 0x21, 0x33, 0xB4, 0x22, + 0x47, 0xEE, 0x31, 0x66, 0xF8, 0x57, 0x9D, 0xC7, 0x6F, 0x72, 0x7C, 0xD7, + 0x30, 0x9B, 0xE7, 0xDF, 0x2E, 0x81, 0xDF, 0xA5, 0x2D, 0x68, 0x0D, 0x5F, + 0xFC, 0x0C, 0xEF, 0xFF, 0x06, 0x27, 0x8A, 0xCF, 0xD5, 0xA2, 0x57, 0xB3, + 0xAB, 0xDE, 0xF6, 0x37, 0x0A, 0x63, 0xCF, 0xC2, 0xF5, 0x19, 0x03, 0x9D, + 0x1E, 0x3C, 0x61, 0xE0, 0x40, 0xAB, 0xAA, 0xC5, 0x39, 0x68, 0x05, 0x9F, + 0x6E, 0xE6, 0x8E, 0x0E, 0x08, 0x9F, 0x2C, 0x78, 0x11, 0xEA, 0xA6, 0x7E, + 0x16, 0xED, 0x58, 0xBF, 0x55, 0x0C, 0x6B, 0xB1, 0x4D, 0x3E, 0x64, 0x0A, + 0x49, 0x47, 0xB7, 0xE3, 0x8F, 0xCF, 0x91, 0x05, +}; + +static const unsigned char k1024_exp[128] = { + 0x61, 0xE6, 0xE6, 0x86, 0xC8, 0x96, 0xB4, 0x6B, 0xBA, 0x7D, 0x9E, 0x6B, + 0x8E, 0xBD, 0x8D, 0xC0, 0xC0, 0xBC, 0x53, 0x09, 0x1D, 0x36, 0x6A, 0x79, + 0x34, 0xFA, 0x44, 0x1B, 0x83, 0xB7, 0xE8, 0x37, 0xC4, 0x33, 0xFD, 0xD4, + 0x20, 0x64, 0x1F, 0xFE, 0xCA, 0x74, 0x81, 0xEF, 0xE4, 0xA5, 0x59, 0xEE, + 0x3B, 0xF0, 0x74, 0x9D, 0xC1, 0x52, 0x56, 0x12, 0x1B, 0xB1, 0x4A, 0xAF, + 0x53, 0x69, 0x00, 0x8D, 0xEE, 0x06, 0x63, 0x28, 0xA0, 0x34, 0xF8, 0x70, + 0xB6, 0x78, 0x5C, 0x0C, 0x9C, 0x16, 0x7D, 0xED, 0x59, 0xA5, 0x05, 0xD4, + 0x4B, 0x82, 0x6A, 0x86, 0x09, 0x1B, 0xC3, 0x85, 0x98, 0xE9, 0x71, 0x38, + 0x5E, 0x07, 0x3A, 0xF4, 0x51, 0xE2, 0xAF, 0xB3, 0xA6, 0x9C, 0x66, 0x6D, + 0x0F, 0x5D, 0xFF, 0x61, 0xF4, 0x45, 0x3B, 0xAE, 0x59, 0xA9, 0xCA, 0xAE, + 0x87, 0x95, 0x91, 0x65, 0xB9, 0x87, 0xD5, 0x01, +}; + +static const unsigned char k1024_msg[128] = { + 0x03, 0x64, 0xE7, 0xA2, 0x21, 0x6E, 0xB6, 0x96, 0x08, 0x46, 0xDD, 0x04, + 0xAB, 0xB9, 0xD7, 0x96, 0x2B, 0xCE, 0x7C, 0xE7, 0x11, 0xC9, 0x11, 0xD8, + 0xEB, 0x51, 0xFA, 0xA5, 0x21, 0xC3, 0xDC, 0x82, 0x03, 0x64, 0xE7, 0xA2, + 0x21, 0x6E, 0xB6, 0x96, 0x08, 0x46, 0xDD, 0x04, 0xAB, 0xB9, 0xD7, 0x96, + 0x2B, 0xCE, 0x7C, 0xE7, 0x11, 0xC9, 0x11, 0xD8, 0xEB, 0x51, 0xFA, 0xA5, + 0x21, 0xC3, 0xDC, 0x82, 0x03, 0x64, 0xE7, 0xA2, 0x21, 0x6E, 0xB6, 0x96, + 0x08, 0x46, 0xDD, 0x04, 0xAB, 0xB9, 0xD7, 0x96, 0x2B, 0xCE, 0x7C, 0xE7, + 0x11, 0xC9, 0x11, 0xD8, 0xEB, 0x51, 0xFA, 0xA5, 0x21, 0xC3, 0xDC, 0x82, + 0x03, 0x64, 0xE7, 0xA2, 0x21, 0x6E, 0xB6, 0x96, 0x08, 0x46, 0xDD, 0x04, + 0xAB, 0xB9, 0xD7, 0x96, 0x2B, 0xCE, 0x7C, 0xE7, 0x11, 0xC9, 0x11, 0xD8, + 0xEB, 0x51, 0xFA, 0xA5, 0x21, 0xC3, 0xDC, 0x82, +}; + +static const unsigned char k1024_sig[128] = { + 0x36, 0xF0, 0x8F, 0xE4, 0xDD, 0x4A, 0x6C, 0x54, 0x6F, 0xC7, 0x87, 0xC5, + 0xD3, 0x5E, 0x08, 0x6F, 0x07, 0x65, 0xDA, 0xCD, 0xC2, 0x05, 0xE7, 0x83, + 0x6D, 0x92, 0x6A, 0xB5, 0x26, 0xBA, 0xB0, 0xED, 0xC3, 0x09, 0x11, 0x27, + 0xD0, 0x4C, 0x67, 0xF1, 0xC7, 0xF7, 0xA2, 0xA2, 0x46, 0x7E, 0xCB, 0x58, + 0x48, 0x21, 0xAB, 0x77, 0x85, 0x75, 0x17, 0xDF, 0xD6, 0xE6, 0xEC, 0x25, + 0x3D, 0x77, 0x45, 0x31, 0xAB, 0x0B, 0xD8, 0x6F, 0xF8, 0xCD, 0xD6, 0x11, + 0x7B, 0xEF, 0xA5, 0xBB, 0xFC, 0xE6, 0xCB, 0x97, 0x0F, 0x2A, 0xA4, 0x11, + 0x25, 0xDA, 0xAC, 0x16, 0x2F, 0x2A, 0x85, 0x28, 0x7C, 0x62, 0xBD, 0xAB, + 0x44, 0xC3, 0x34, 0x33, 0x0B, 0x8B, 0x0C, 0x77, 0xEB, 0xDE, 0x07, 0xF3, + 0xC3, 0xAA, 0x9C, 0xA6, 0xE3, 0x62, 0x97, 0xF1, 0xA1, 0x05, 0x3C, 0x78, + 0x37, 0x99, 0xDE, 0xB7, 0x08, 0x4F, 0x9F, 0x46, +}; + +static const unsigned char sha_msg[200] = { + 0x03, 0x0A, 0x11, 0x18, 0x1F, 0x26, 0x2D, 0x34, 0x3B, 0x42, 0x49, 0x50, + 0x57, 0x5E, 0x65, 0x6C, 0x73, 0x7A, 0x81, 0x88, 0x8F, 0x96, 0x9D, 0xA4, + 0xAB, 0xB2, 0xB9, 0xC0, 0xC7, 0xCE, 0xD5, 0xDC, 0xE3, 0xEA, 0xF1, 0xF8, + 0xFF, 0x06, 0x0D, 0x14, 0x1B, 0x22, 0x29, 0x30, 0x37, 0x3E, 0x45, 0x4C, + 0x53, 0x5A, 0x61, 0x68, 0x6F, 0x76, 0x7D, 0x84, 0x8B, 0x92, 0x99, 0xA0, + 0xA7, 0xAE, 0xB5, 0xBC, 0xC3, 0xCA, 0xD1, 0xD8, 0xDF, 0xE6, 0xED, 0xF4, + 0xFB, 0x02, 0x09, 0x10, 0x17, 0x1E, 0x25, 0x2C, 0x33, 0x3A, 0x41, 0x48, + 0x4F, 0x56, 0x5D, 0x64, 0x6B, 0x72, 0x79, 0x80, 0x87, 0x8E, 0x95, 0x9C, + 0xA3, 0xAA, 0xB1, 0xB8, 0xBF, 0xC6, 0xCD, 0xD4, 0xDB, 0xE2, 0xE9, 0xF0, + 0xF7, 0xFE, 0x05, 0x0C, 0x13, 0x1A, 0x21, 0x28, 0x2F, 0x36, 0x3D, 0x44, + 0x4B, 0x52, 0x59, 0x60, 0x67, 0x6E, 0x75, 0x7C, 0x83, 0x8A, 0x91, 0x98, + 0x9F, 0xA6, 0xAD, 0xB4, 0xBB, 0xC2, 0xC9, 0xD0, 0xD7, 0xDE, 0xE5, 0xEC, + 0xF3, 0xFA, 0x01, 0x08, 0x0F, 0x16, 0x1D, 0x24, 0x2B, 0x32, 0x39, 0x40, + 0x47, 0x4E, 0x55, 0x5C, 0x63, 0x6A, 0x71, 0x78, 0x7F, 0x86, 0x8D, 0x94, + 0x9B, 0xA2, 0xA9, 0xB0, 0xB7, 0xBE, 0xC5, 0xCC, 0xD3, 0xDA, 0xE1, 0xE8, + 0xEF, 0xF6, 0xFD, 0x04, 0x0B, 0x12, 0x19, 0x20, 0x27, 0x2E, 0x35, 0x3C, + 0x43, 0x4A, 0x51, 0x58, 0x5F, 0x66, 0x6D, 0x74, +}; + +static const unsigned char sha_msg_digest[32] = { + 0x2C, 0x7E, 0x18, 0xC9, 0x42, 0xEF, 0x06, 0x5B, 0x52, 0x6A, 0x2D, 0x4E, + 0x55, 0x46, 0x28, 0x37, 0x49, 0xCD, 0x3D, 0xDF, 0xB5, 0x1D, 0x8F, 0xC7, + 0x1F, 0x42, 0x71, 0x73, 0x63, 0x68, 0x5F, 0x46, +}; + +static const unsigned char sha_abc_digest[32] = { + 0xBA, 0x78, 0x16, 0xBF, 0x8F, 0x01, 0xCF, 0xEA, 0x41, 0x41, 0x40, 0xDE, + 0x5D, 0xAE, 0x22, 0x23, 0xB0, 0x03, 0x61, 0xA3, 0x96, 0x17, 0x7A, 0x9C, + 0xB4, 0x10, 0xFF, 0x61, 0xF2, 0x00, 0x15, 0xAD, +}; From e592ec2d8823c60f32a673acb366c5961d08f7a2 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 22:40:19 +0000 Subject: [PATCH 13/21] Make every CAR reset and clock-enable bank live Only bank U followed the payload's writes. L, H and X read fixed values, RST_DEVICES_L read 0, and every SET/CLR strobe read 0 - but TRM 5.2.100 says any of the three registers reads back the bank, and bdk relies on it: clock_sdmmc_is_active() reads RST_DEV_L_SET and CLK_ENB_L_SET. The fixed CLK_OUT_ENB_L/H/X values were real-console readings taken after a payload had brought the display up. So every payload found DISP1 already clocked at RCM entry, and bdk's display_init() began each boot by tearing down a panel that was never on. The banks now follow direct writes and SET/CLR strobes, and all three read the bank. The rest start at the TRM reset values, unknown bits as 0; bank U keeps its real-console reading. The PCIe and CPU models still hold reset banks V, W and Y and clock bank V, since their preconditions depend on them; reads of those banks' strobes go to them. hwtest's report is unchanged apart from fan-tach phase, and hekate into Nyx gives the same frame as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb --- DESIGN.md | 15 +++++- t210/mmio.cpp | 135 ++++++++++++++++++++++++++------------------------ 2 files changed, 84 insertions(+), 66 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 3dfa097..9142cb6 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -526,8 +526,15 @@ needed. The 64 KB TX log trim happens in-place during the write hook. - **CAR and MC.** Registers without behaviour of their own read back what was written - the `CLK_SOURCE_*` dividers, PLL MISC words, the MC's - arbitration and address-map configuration - instead of 0. The CAR's - SET/CLR alias registers are write strobes and read 0. + arbitration and address-map configuration - instead of 0. +- **CAR reset and clock-enable banks.** `RST_DEVICES_x` and `CLK_OUT_ENB_x` + (L, H, U, V, W, X, Y) follow direct writes and their SET/CLR strobes, and + a read of any of the three returns the bank (TRM 5.2.100) - bdk's + `clock_sdmmc_is_active()` reads `RST_DEV_L_SET` and `CLK_ENB_L_SET`. The + PCIe and CPU models keep reset banks V, W, Y and clock bank V. The rest + start at the TRM reset values (bank U at a real console's reading), so at + RCM entry the display is unclocked and `display_init()` does not begin + with a panel teardown. - **PINMUX (`APB_MISC` pad config) and PWM controller (`0x7000A000`).** No active behaviour, but reads return whatever the payload last wrote via the global `mmio_regs` cache. Hwtest's "Display backlight & PWM" @@ -707,6 +714,10 @@ don't repeat the diagnosis: - **Minerva DRAM training** hangs in a `PLL_BASE.LOCK` poll. Fix: report LOCK once the PLL is enabled. +- **Every payload began with a display teardown.** `CLK_OUT_ENB_L` read a + real console's value taken after a payload had brought the display up, so + `display_init()` found DISP1 already clocked at RCM entry. Fix: the bank + starts at the TRM reset value and follows the payload's writes. - **Minerva hung Nyx** (hekate 6.5.3 with the stock `bootloader/` folder never reached its GUI). The emulator planted hekate's "watchdog fired" cookie in IRAM so the IPL would skip Minerva; Nyx then trained the DRAM diff --git a/t210/mmio.cpp b/t210/mmio.cpp index 07ca22f..f15235a 100644 --- a/t210/mmio.cpp +++ b/t210/mmio.cpp @@ -3260,51 +3260,73 @@ static void flow_write(EmuState *state, uint64_t addr, uint32_t val) { // ==================== Clock/Reset ==================== -// ---- RST_DEVICES_U / CLK_OUT_ENB_U ----------------------------------------- +// ---- Reset and clock-enable banks (TRM 5.2) --------------------------------- // -// bdk never writes these two directly: clock_enable() goes through the SET and -// CLR aliases (RST_DEV_U_SET 0x310 / _CLR 0x314, CLK_ENB_U_SET 0x330 / _CLR -// 0x334). With clk_rst_write a no-op and both reads hardcoded, enabling a _U -// peripheral had no observable effect at all -- clock_enable_uart(UART_D) ran -// to completion and the payload's own "is this port clocked?" gate then read -// CLK_U_UARTD clear and aborted. Both seeds are the values measured on a real -// console at that point in the sweep. +// RST_DEVICES_x and CLK_OUT_ENB_x for banks L, H, U, V, W, X and Y. Each is +// written directly or through its SET and CLR strobes, and all three read +// back the bank: "for reads, you can use either method to retrieve the +// reset/clock-enable state" (TRM 5.2.100). bdk relies on both halves - +// clock_enable() goes through the strobes, clock_sdmmc_is_active() reads +// RST_DEV_L_SET and CLK_ENB_L_SET, and display_init() tears the panel down +// first when CLK_OUT_ENB_L already has DISP1 on. // -// Note the previous CLK_OUT_ENB_U value force-set bit 15 with a comment about -// keeping SDMMC4 alive; bit 15 of the _U register is DTV (deprecated). SDMMC4 -// 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 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; +// The PCIe and CPU models keep reset banks V, W and Y and clock bank V, +// because their preconditions depend on them; the table only routes reads +// of those strobes to them. The rest start from the TRM reset values +// (unknown bits as 0), except bank U, which is what a real console read. +// The L, H and X clock banks used to be real-console readings too, but +// taken after a payload had brought the display up - so every payload +// found DISP1 already clocked at RCM entry and began with a panel teardown. +struct CarBank { + uint16_t reg, set, clr; + bool own; // false: another model holds this bank + uint32_t seed; +}; +static const CarBank kCarBanks[] = { + {0x004, 0x300, 0x304, true, 0x1CD3D2C8}, // RST_DEVICES_L + {0x008, 0x308, 0x30C, true, 0x87D1F326}, // RST_DEVICES_H + {0x00C, 0x310, 0x314, true, 0x828EC5F8}, // RST_DEVICES_U (measured) + {0x358, 0x430, 0x434, false, 0}, // RST_DEVICES_V (pcie.cpp) + {0x35C, 0x438, 0x43C, false, 0}, // RST_DEVICES_W (pcie.cpp) + {0x28C, 0x290, 0x294, true, 0x01E42049}, // RST_DEVICES_X + {0x2A4, 0x2A8, 0x2AC, false, 0}, // RST_DEVICES_Y (pcie.cpp) + {0x010, 0x320, 0x324, true, 0x80000130}, // CLK_OUT_ENB_L + {0x014, 0x328, 0x32C, true, 0x00000080}, // CLK_OUT_ENB_H + {0x018, 0x330, 0x334, true, 0x01F00200}, // CLK_OUT_ENB_U (measured) + {0x360, 0x440, 0x444, false, 0}, // CLK_OUT_ENB_V (ccplex.cpp) + {0x364, 0x448, 0x44C, true, 0x402000FC}, // CLK_OUT_ENB_W + {0x280, 0x284, 0x288, true, 0x23000780}, // CLK_OUT_ENB_X + {0x298, 0x29C, 0x2A0, true, 0x00000300}, // CLK_OUT_ENB_Y +}; +constexpr size_t kCarBankCount = sizeof(kCarBanks) / sizeof(kCarBanks[0]); + +struct CarBanks { + uint32_t v[kCarBankCount]; + CarBanks() { + for (size_t i = 0; i < kCarBankCount; ++i) + v[i] = kCarBanks[i].seed; + } +}; +static CarBanks car_banks; + +static const CarBank *car_bank_of(uint32_t off) { + for (const CarBank &b : kCarBanks) + if (off == b.reg || off == b.set || off == b.clr) + return &b; + return nullptr; +} // The EMC clock as CAR sets it (EMC section below). static uint32_t emc_rate_khz(); -// The SET/CLR aliases of the reset and clock-enable banks (TRM 5.2): write -// strobes that nothing reads back. They read 0. -static bool car_is_set_clr_alias(uint32_t off) { - switch (off) { - case 0x284: case 0x288: case 0x290: case 0x294: // CLK_ENB_X, RST_DEV_X - case 0x29C: case 0x2A0: case 0x2A8: case 0x2AC: // CLK_ENB_Y, RST_DEV_Y - case 0x300: case 0x304: case 0x308: case 0x30C: // RST_DEV_L, _H - case 0x310: case 0x314: // RST_DEV_U - case 0x320: case 0x324: case 0x328: case 0x32C: // CLK_ENB_L, _H - case 0x330: case 0x334: // CLK_ENB_U - case 0x340: case 0x344: // RST_CPU_CMPLX - case 0x430: case 0x434: case 0x438: case 0x43C: // RST_DEV_V, _W - case 0x440: case 0x444: case 0x448: case 0x44C: // CLK_ENB_V, _W - case 0x450: case 0x454: case 0x460: case 0x464: // RST/CLK_CPUG_CMPLX - return true; - default: - return false; - } -} - uint32_t clk_rst_read(EmuState *state, uint64_t addr) { uint32_t offset = (uint32_t)(addr - CLK_RST_BASE); + if (const CarBank *b = car_bank_of(offset)) { + if (b->own) + return car_banks.v[b - kCarBanks]; + if (offset != b->reg) // a strobe of a bank another model keeps + return clk_rst_read(state, CLK_RST_BASE + b->reg); + } // PLL_BASE registers (per Hekate bdk/soc/clock.h): each PLL has an _BASE // register where bit 30 = ENABLE and bit 27 = LOCK. After enabling a PLL // the boot code polls bit 27 until set. Real silicon locks within ~1ms; we @@ -3393,15 +3415,6 @@ uint32_t clk_rst_read(EmuState *state, uint64_t addr) { case 0x28: return mariko ? 0x20003333u : 0x20003330u; case 0x2C: return 0x80000000; // SUPER_SCLK_DIVIDER case 0x30: return 0x00000002; // CLK_SYSTEM_RATE - case 0x14: return 0x030180C1; // CLK_OUT_ENB_H - case 0x280: return 0x23024780; // CLK_OUT_ENB_X - // _L carries the SDMMC clock-enable bits the storage model depends on: - // SDMMC1 is bit 14 and SDMMC4 is bit 15, and the measured value has both. - case 0x10: return 0x9802D1B0; - // _U and its reset counterpart are live, so a payload that enables a _U - // peripheral (UART-D, I2C3, SDMMC3, ...) can see that it worked. - case 0x0C: return car_rst_u; // RST_DEVICES_U - case 0x18: return car_enb_u; // CLK_OUT_ENB_U // CLK_SOURCE_UARTD. clock_uart_use_src_div() programs PLLP_OUT0 with // CLK_SRC_DIV(2) here (0x00000002) and sets UART_SRC_CLK_DIV_EN for the // 1M/3M rates; the payload reads it back to confirm the port's source. @@ -3458,8 +3471,6 @@ uint32_t clk_rst_read(EmuState *state, uint64_t addr) { // answer 4, which decodes as 19.2 MHz and contradicted OSC_FREQ_DET. if (offset == 0x50) return mmio_regs.get(addr, 0x500003F1); - if (offset == 0x04) - return 0; // RST_DEVICES_L (none in reset) // CPU complex clock/reset state (CLK_OUT_ENB_V, RST_CPUG_CMPLX, ...). { @@ -3477,8 +3488,7 @@ uint32_t clk_rst_read(EmuState *state, uint64_t addr) { } // Everything else is a plain R/W register (the CLK_SOURCE_* dividers, // PLL MISC words, ...): it reads back what was written. - (void)state; - return car_is_set_clr_alias(offset) ? 0 : mmio_regs.get(addr); + return mmio_regs.get(addr); } // A CLK_SOURCE_EMC write is the CAR/EMC clock-change handshake (EMC below). @@ -3487,19 +3497,17 @@ static void emc_clock_source_write(EmuState *state, uint32_t val); void clk_rst_write(EmuState *state, uint64_t addr, uint32_t val) { (void)state; uint32_t offset = (uint32_t)(addr - CLK_RST_BASE); - // The _U pair is live (bdk reaches it through the SET/CLR aliases), and - // CLK_SOURCE_EMC starts an EMC clock change. Everything else only lands - // in the write hook's mmio_regs cache, which clk_rst_read hands back. - switch (offset) { - case 0x00C: car_rst_u = val; break; // RST_DEVICES_U, direct write - case 0x018: car_enb_u = val; break; // CLK_OUT_ENB_U, direct write - case 0x310: car_rst_u |= val; break; // RST_DEV_U_SET - case 0x314: car_rst_u &= ~val; break; // RST_DEV_U_CLR - case 0x330: car_enb_u |= val; break; // CLK_ENB_U_SET - case 0x334: car_enb_u &= ~val; break; // CLK_ENB_U_CLR - case 0x19C: emc_clock_source_write(state, val); break; // CLK_SOURCE_EMC - default: break; + // The reset and clock-enable banks, and CLK_SOURCE_EMC, which starts an + // EMC clock change. Everything else only lands in the write hook's + // mmio_regs cache, which clk_rst_read hands back. + if (const CarBank *b = car_bank_of(offset); b && b->own) { + uint32_t &bank = car_banks.v[b - kCarBanks]; + if (offset == b->reg) bank = val; + else if (offset == b->set) bank |= val; + else bank &= ~val; } + if (offset == 0x19C) + emc_clock_source_write(state, 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(state, offset, val); @@ -5057,8 +5065,7 @@ void mmio_soft_reset(EmuState *state, bool power_cycle) { 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; + car_banks = CarBanks(); g_fuse_ctrl_addr = 0; emc = EmcState(); g_dsi_pending_dcs_cmd = 0; From 6d5ccb5328d881bc9c7226377db365a660c75b8b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 22:40:33 +0000 Subject: [PATCH 14/21] Lock PLLC4 and the other PLLs bdk waits on, and the USB PLL TegraExplorer hung for good the first time it touched the eMMC. Moving SDMMC4 to HS200 enables PLLC4, and TegraExplorer's bdk waits for PLLC4_BASE.LOCK with no timeout; the CAR model had no PLLC4, so the bit never came. On Erista that stopped it at startup, before its key dump; on both SoCs "Browse EMMC" hung. hekate's newer bdk times the wait out, which is why nothing else showed it. - PLLC4 locks once enabled and out of IDDQ (bit 18), setting LOCK and FREQLOCK (27, 28); LOCK_OVERRIDE (24) forces them. - PLLC2, PLLC3, PLLDP and PLLA1 lock on ENABLE like PLLC/A/X/D2 (bit 27; PLLA1 also 26, PLLDP also 28). The read-only lock bits are no longer stored from a payload's read-modify-write. - UTMIPLL_HW_PWRDN_CFG0.LOCK is set unless software holds the USB PLL in IDDQ, its reset state, so clock_enable_utmipll() sees the lock instead of timing out. TegraExplorer now reaches its main menu on both SoCs and lists the eMMC's partitions under "Browse EMMC". With no BOOT0 image it cannot read package1, so the Erista key dump falls back to prod.keys. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb --- DESIGN.md | 11 ++++++++++- t210/mmio.cpp | 39 +++++++++++++++++++++++++++++++-------- 2 files changed, 41 insertions(+), 9 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 9142cb6..11e3b90 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -535,6 +535,8 @@ needed. The 64 KB TX log trim happens in-place during the write hook. start at the TRM reset values (bank U at a real console's reading), so at RCM entry the display is unclocked and `display_init()` does not begin with a panel teardown. +- **USB PLL.** `UTMIPLL_HW_PWRDN_CFG0.LOCK` is set unless software holds + the PLL in IDDQ (the reset state), for bdk's `clock_enable_utmipll()`. - **PINMUX (`APB_MISC` pad config) and PWM controller (`0x7000A000`).** No active behaviour, but reads return whatever the payload last wrote via the global `mmio_regs` cache. Hwtest's "Display backlight & PWM" @@ -547,7 +549,9 @@ needed. The 64 KB TX log trim happens in-place during the write hook. payload programs them (PLLM up but unlocked on Erista, the rest down), then read back what was written, dividers included, with LOCK set whenever ENABLE is. That includes PLLMB, which Minerva moves the EMC onto - for a frequency change. + for a frequency change, and PLLC4, which clocks the eMMC at HS200/HS400 + (not while its IDDQ bit is set); PLLC2, PLLC3, PLLDP and PLLA1 lock the + same way. - **KFUSE.** `STATE` returns `DONE | CRCPASS` immediately so the BDK function `kfuse_wait_ready` doesn't hang. - **TSEC.** `DMATRFCMD_IDLE` is reported set, and the keygen status word is @@ -714,6 +718,11 @@ don't repeat the diagnosis: - **Minerva DRAM training** hangs in a `PLL_BASE.LOCK` poll. Fix: report LOCK once the PLL is enabled. +- **TegraExplorer hung on the eMMC.** Switching SDMMC4 to HS200 enables + PLLC4, and TegraExplorer's bdk waits for `PLLC4_BASE.LOCK` with no + timeout; the CAR model had no PLLC4, so Erista hung at the key dump and + both SoCs at "Browse EMMC". (hekate's newer bdk times the wait out, which + hid it.) Fix: PLLC4 locks once enabled, out of IDDQ. - **Every payload began with a display teardown.** `CLK_OUT_ENB_L` read a real console's value taken after a payload had brought the display up, so `display_init()` found DISP1 already clocked at RCM entry. Fix: the bank diff --git a/t210/mmio.cpp b/t210/mmio.cpp index f15235a..128fd3c 100644 --- a/t210/mmio.cpp +++ b/t210/mmio.cpp @@ -3329,10 +3329,11 @@ uint32_t clk_rst_read(EmuState *state, uint64_t addr) { } // PLL_BASE registers (per Hekate bdk/soc/clock.h): each PLL has an _BASE // register where bit 30 = ENABLE and bit 27 = LOCK. After enabling a PLL - // the boot code polls bit 27 until set. Real silicon locks within ~1ms; we - // simulate "always locked + always enabled" so the polls return immediately. + // the boot code polls bit 27 until set. Real silicon locks within ~1ms; + // here a PLL is locked as soon as it is enabled. // Offsets: PLLC=0x80, PLLM=0x90, PLLP=0xA0, PLLA=0xB0, PLLU=0xC0, PLLD=0xD0, - // PLLX=0xE0, PLLE=0xE8, PLLD2=0x4B8, PLLREFE=0x4C4. + // PLLX=0xE0, PLLE=0xE8, PLLD2=0x4B8, PLLREFE=0x4C4, PLLC2=0x4E8, + // PLLC3=0x4FC, PLLDP=0x590, PLLC4=0x5A4, PLLMB=0x5E8, PLLA1=0x6A4. bool mariko = state && state->pmic_otp.load() == 0x53; // On a real console in RCM most PLLs are DOWN - measured on a Mariko, only @@ -3360,11 +3361,25 @@ uint32_t clk_rst_read(EmuState *state, uint64_t addr) { if (offset == 0xE8 || offset == 0x4C4) return mmio_regs.get(addr); switch (offset) { - 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 - return w; // measured: down on both + case 0x80: case 0xB0: case 0xE0: case 0x4B8: case 0x4E8: case 0x4FC: + case 0x590: case 0x5A4: case 0x6A4: { + // PLLC, PLLA, PLLX, PLLD2 (measured down on both), PLLC2, PLLC3, + // PLLDP, PLLC4 and PLLA1: locked once the payload enables them (bit + // 30). Bit 27 is LOCK or FREQ_LOCK on all of them; PLLA1 also has LOCK + // in 26, and PLLDP and PLLC4 FREQLOCK in 28 and a LOCK_OVERRIDE in 24 + // (TRM 5.2). PLLC4 does not run in IDDQ (bit 18): bdk clears that, + // enables it for the eMMC's HS200/HS400 clock and waits for the lock + // with no timeout. + uint32_t lock = 1u << 27; + if (offset == 0x6A4) + lock |= 1u << 26; + if (offset == 0x590 || offset == 0x5A4) + lock |= 1u << 28; + uint32_t w = mmio_regs.get(addr) & ~lock; + bool on = (w & (1u << 30)) && !(offset == 0x5A4 && (w & (1u << 18))); + if ((offset == 0x590 || offset == 0x5A4) && (w & (1u << 24))) + on = true; + return on ? w | lock : w; } case 0x90: { // PLLM // Until the payload programs it: Erista leaves PLLM enabled but @@ -3396,6 +3411,14 @@ uint32_t clk_rst_read(EmuState *state, uint64_t addr) { w |= 3u << 26; return w; } + case 0x52C: { // UTMIPLL_HW_PWRDN_CFG0 (TRM 5.2.202), reset 0x0000000F + // UTMIPLL_LOCK (bit 31) and SEQ_STATE (27:26) are read-only. The USB + // PLL locks unless software holds it in IDDQ (IDDQ_SWCTL with + // IDDQ_OVERRIDE_VALUE, the reset state); bdk's usb code clears the + // override, then clock_enable_utmipll() waits for the lock. + uint32_t w = mmio_regs.get(addr, 0x0000000F) & ~(1u << 31 | 3u << 26); + return (w & 3) == 3 ? w : w | (1u << 31); + } case 0x5EC: // PLLMB_MISC1, reset 0x00010000 (EN_LCKDET) return mmio_regs.get(addr, 0x00010000); case 0x19C: // CLK_SOURCE_EMC, reset 0x60180000 (TRM 5.2.73) From 803729580b2a93fbd003c950cac7c19e4944a565 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 26 Sep 2026 10:23:31 +0000 Subject: [PATCH 15/21] Report the EMC DLL's code from its calibration start value EMC_DIG_DLL_STATUS.DLL_OUT (10:0) read 0. TRM 18.11.2.219 gives the basis the earlier note said was missing: EMC_DLL_CFG_1's DDLLCAL_CTRL_START_TRIM (10:0, reset 0x20) is the DLL calibration's start value, which the timing table sets per frequency. With no delay line to drift, calibration has nothing to move it by, so DLL_OUT now reports the channel's start trim once the DLL locks. EMC_DLL_CFG_1 reads its reset value until written. Minerva's _digital_dll_prelock() returns the value and nothing reads it further; DRAM training and the 800/1600 MHz switching are unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb --- DESIGN.md | 9 ++++++--- t210/mmio.cpp | 17 +++++++++++++---- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 11e3b90..834ee0a 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -204,7 +204,12 @@ frequency-switching module, depend on: 400 ps tDQS2DQ. Minerva divides by that count. - **Digital DLL.** `EMC_DIG_DLL_STATUS` reports lock as soon as the DLL is (re)started; `EMC_CFG_DIG_DLL.CFG_DLL_EN` reads back as written, which is - what Minerva spins on around each DLL restart. + what Minerva spins on around each DLL restart. The DLL's code, `DLL_OUT` + (10:0), is where its calibration starts: the channel's + `EMC_DLL_CFG_1.DDLLCAL_CTRL_START_TRIM` (10:0, reset 0x20, TRM + 18.11.2.219), which the timing table programs per frequency. With no + delay line to drift, calibration has nothing to move it by. (Minerva's + `_digital_dll_prelock()` returns it; nothing reads it further.) - **Clock change.** A new source or divisor in CAR `CLK_SOURCE_EMC` (TRM 5.2.73) is the CAR/EMC handshake: the EMC replays the writes queued in its clock-change FIFO (`EMC_CCFIFO_DATA` / `_ADDR`) and raises @@ -215,8 +220,6 @@ frequency-switching module, depend on: DRAM active and the state machines idle. - **Measured clock.** bdk's PTO counter measures the EMC at the modelled clock (the measured 204 MHz figure at the boot clock). -- **Not modelled.** The DLL's delay code (`DLL_OUT`) reads 0: the TRM gives - no tap delay to derive it from. With the stock `bootloader/` folder, hekate's IPL trains 204, 800 and 1600 MHz, and Nyx then switches between 800 and 1600 MHz on every GUI loop, diff --git a/t210/mmio.cpp b/t210/mmio.cpp index 128fd3c..d244bda 100644 --- a/t210/mmio.cpp +++ b/t210/mmio.cpp @@ -3598,8 +3598,10 @@ void fuse_write(EmuState *state, uint64_t addr, uint32_t val) { // oscillator count, and any other mode register what was last written. // // Digital DLL. It locks as soon as it is (re)started: EMC_DIG_DLL_STATUS -// reports DLL_LOCK and DLL_PRIV_UPDATED. The DLL code itself (DLL_OUT) is -// not modelled and reads 0. +// reports DLL_LOCK and DLL_PRIV_UPDATED. Its code, DLL_OUT (10:0), is +// where calibration starts, the channel's EMC_DLL_CFG_1 +// DDLLCAL_CTRL_START_TRIM (10:0, reset 0x20, TRM 18.11.2.219): with no +// delay line to drift, calibration has nothing to move it by. // // Clock change. A new source or divisor in CAR CLK_SOURCE_EMC starts the // CAR/EMC clock-change handshake: the EMC replays the writes queued in its @@ -3624,6 +3626,7 @@ static constexpr uint32_t EMC_CCFIFO_ADDR = 0x3E8; static constexpr uint32_t EMC_CCFIFO_DATA = 0x3EC; static constexpr uint32_t EMC_CCFIFO_STATUS = 0x3F0; static constexpr uint32_t EMC_FBIO_CFG7 = 0x584; +static constexpr uint32_t EMC_DLL_CFG_1 = 0x5E8; static constexpr uint32_t EMC_INT_CLKCHANGE_COMPLETE = 1u << 4; static constexpr uint32_t EMC_INT_MRR_DIVLD = 1u << 5; @@ -3747,8 +3750,14 @@ uint32_t emc_read(EmuState *state, uint64_t addr) { case EMC_CFG_DIG_DLL: // Bits 31, 30, 26, 4 and 1 are write-1 triggers; they read 0. return mmio_regs.get(addr) & ~0xC4000012u; - case EMC_DIG_DLL_STATUS: - return (1u << 17) | (1u << 15); // DLL_PRIV_UPDATED | DLL_LOCK + case EMC_DIG_DLL_STATUS: { + // DLL_PRIV_UPDATED | DLL_LOCK, and DLL_OUT at the calibration start. + uint32_t cfg1 = mmio_regs.get((ch ? EMC1_BASE : EMC0_BASE) + EMC_DLL_CFG_1, + 0x20); + return (1u << 17) | (1u << 15) | (cfg1 & 0x7FF); + } + case EMC_DLL_CFG_1: + return mmio_regs.get(addr, 0x20); case EMC_CCFIFO_STATUS: return (uint32_t)emc.ccfifo.size(); case EMC_FBIO_CFG7: From 33d16976febc5b0913bbdd01aae3e1088b96f5fb Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 26 Sep 2026 10:23:45 +0000 Subject: [PATCH 16/21] Model the CPU complex's reset view and per-core clock stop RST_CPU_CMPLX_SET/CLR (0x340/0x344) and CLK_CPUG_CMPLX_SET/CLR (0x460/0x464) read back the last value written, like plain registers. - RST_CPU_CMPLX_SET has RST_CPUG_CMPLX's fields and reset value (TRM 5.2.113): it is the active cluster's view, and the Switch runs the G cluster. It and its CLR partner now act on the same reset state as the CPUG pair, releasing and stopping CPU0 alike, and read it back. - CLK_CPUG_CMPLX (0x378, TRM 5.2.122) and its SET/CLR strobes track CPUGn_CLK_STP, and all three read the register. A stopped CPU0 keeps its state and executes nothing while emulated time passes; clearing the stop resumes it where it was. The CCPLEX test now releases CPU0 with its clock stopped, checks it does not run and that the registers read back, then clears the stop. Against the previous binary those three checks fail. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb --- DESIGN.md | 11 ++++++++++- t210/ccplex.cpp | 33 ++++++++++++++++++++++++++++++++- tests/ccplex/payload.c | 18 ++++++++++++++++++ tests/ccplex/run.sh | 3 +++ 4 files changed, 63 insertions(+), 2 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 834ee0a..3dc040c 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -659,6 +659,14 @@ cannot run: ` and the core stays dark, which is what silicon does, minus the explanation. Asserting a reset bit, gating a partition or dropping the rail stops a running core. +`RST_CPU_CMPLX_SET` (0x340, TRM 5.2.113) carries `RST_CPUG_CMPLX`'s fields and +reset value: it is the active cluster's view, and the Switch runs the G +cluster, so it and its CLR partner at 0x344 act on the same reset state. +`CLK_CPUG_CMPLX` (0x378, TRM 5.2.122) and its SET/CLR strobes (0x460/0x464) +stop a core's clock with `CPUGn_CLK_STP`; all three read the register back. +CPU0 with its clock stopped keeps its state and executes nothing while +emulated time passes, and carries on where it was once the stop is cleared. + **Entry at EL3.** A real A57 leaves reset at EL3, AArch64, MMU off. Unicorn builds its ARM64 core at EL1 and cannot be moved: a PSTATE write does not rebuild the translator's cached `hflags`, and Unicorn never delivers guest @@ -703,7 +711,8 @@ 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; +refusal, the EL3 entry, a core released with its clock stopped, the +mailbox, WFE parking and the reset; `tests/se/`, which runs the SE's RSA, SHA-256, AES and RNG against vectors computed in Python (`gen_vectors.py` writes `vectors.h`); and `tests/display/`, one payload built per scenario that drives the display diff --git a/t210/ccplex.cpp b/t210/ccplex.cpp index 8e566dd..a4fea19 100644 --- a/t210/ccplex.cpp +++ b/t210/ccplex.cpp @@ -30,6 +30,18 @@ #define CLK_V_MSELECT 3 #define CAR_RST_CPUG_CMPLX_SET 0x450 #define CAR_RST_CPUG_CMPLX_CLR 0x454 +// RST_CPU_CMPLX_SET (TRM 5.2.113) has RST_CPUG_CMPLX's fields and reset value: +// it is the active cluster's view, and the Switch runs the G cluster. Its +// CLR partner at 0x344 is not in the TRM; it pairs the way every SET does. +#define CAR_RST_CPU_CMPLX_SET 0x340 +#define CAR_RST_CPU_CMPLX_CLR 0x344 +// CLK_CPUG_CMPLX (TRM 5.2.122, reset 0) and its SET/CLR strobes (5.2.154/155): +// CPUGn_CLK_STP (bits 11:8) stops core n's clock. Like the peripheral banks, +// all three read back the register. +#define CAR_CLK_CPUG_CMPLX 0x378 +#define CAR_CLK_CPUG_CMPLX_SET 0x460 +#define CAR_CLK_CPUG_CMPLX_CLR 0x464 +#define CPU0_CLK_STP (1u << 8) // RST_CPUG_CMPLX (TRM 5.2.152, reset 0x2000feef). CPU0 runs once nCPUPORESET // (CPURESET0, bit 0), nCORERESET (CORERESET0, bit 16), nL2RESET (bit 24) and // the nonCPU region's reset (NONCPURESET, bit 29) are all released. @@ -102,6 +114,7 @@ enum class Cpu0 { Off, Running, Hung }; struct Model { uint32_t rst_cpug = RST_CPUG_CMPLX_RESET; + uint32_t clk_cpug = 0; uint32_t clk_enb_v = 0; uint32_t cclk_burst = 0; uint32_t pllx_base = 0; @@ -457,11 +470,16 @@ void ccplex_car_write(EmuState *state, uint32_t offset, uint32_t val) { } break; case CAR_RST_CPUG_CMPLX_SET: + case CAR_RST_CPU_CMPLX_SET: m.rst_cpug |= val; if (val & (RST_CPU0_MASK | RST_NONCPU)) stop_cpu0("held in reset"); break; - case CAR_RST_CPUG_CMPLX_CLR: { + case CAR_CLK_CPUG_CMPLX: m.clk_cpug = val; break; + case CAR_CLK_CPUG_CMPLX_SET: m.clk_cpug |= val; break; + case CAR_CLK_CPUG_CMPLX_CLR: m.clk_cpug &= ~val; break; + case CAR_RST_CPUG_CMPLX_CLR: + case CAR_RST_CPU_CMPLX_CLR: { bool was_held = held(); m.rst_cpug &= ~val; if (was_held && !held() && m.cpu0 == Cpu0::Off) @@ -480,8 +498,15 @@ bool ccplex_car_read(uint32_t offset, uint32_t *out) { return true; case CAR_RST_CPUG_CMPLX_SET: case CAR_RST_CPUG_CMPLX_CLR: + case CAR_RST_CPU_CMPLX_SET: + case CAR_RST_CPU_CMPLX_CLR: *out = m.rst_cpug; return true; + case CAR_CLK_CPUG_CMPLX: + case CAR_CLK_CPUG_CMPLX_SET: + case CAR_CLK_CPUG_CMPLX_CLR: + *out = m.clk_cpug; + return true; default: return false; } @@ -544,6 +569,12 @@ void ccplex_run(EmuState *state, uint64_t until_us) { uint64_t target = until_us * 1000; if (m.ns >= target) return; + // CPU0's clock stopped: the core keeps its state, time passes, nothing + // executes. Clearing CPU0_CLK_STP resumes it where it was. + if (m.clk_cpug & CPU0_CLK_STP) { + m.ns = target; + return; + } // While CPU0 runs, it is the bus master and "now" is its clock: every // register model reads state->emu_usec, and must see CPU0's time - a diff --git a/tests/ccplex/payload.c b/tests/ccplex/payload.c index 9afbddb..42ec1a9 100644 --- a/tests/ccplex/payload.c +++ b/tests/ccplex/payload.c @@ -13,6 +13,8 @@ * of reset, PLLX, RAM repair, SB_AA64_RESET_LOW - then release it. An * AArch64 blob copied to DRAM records CurrentEL and a TIMERUS delta in * a mailbox, writes a magic word last, and parks in WFE. + * Released first with its clock stopped (CLK_CPUG_CMPLX), it must + * stay still until the stop is cleared. * 3. Put CPU0 back into reset and power the console off. * * Built by `make test` with arm-none-eabi-gcc; no other toolchain needed, as @@ -139,7 +141,23 @@ void _start(void) { while (!(REG(FLOW + 0x40) & 2)) ; REG(CAR + 0x434) = 1u << 3; /* RST_DEV_V_CLR: MSELECT */ + + /* Released with its clock stopped, CPU0 must not run until the stop is + * cleared; the strobes and the active-cluster reset view read back. */ + REG(CAR + 0x460) = 1u << 8; /* CLK_CPUG_CMPLX_SET: CPU0 */ release_cpu0(); + udelay(5000); + puts_(mb[0] == PCIE_MAGIC ? "clock stopped: CPU0 RAN (wrong)\n" + : "clock stopped: CPU0 held still\n"); + puts_("clock stop reads "); + puthex(REG(CAR + 0x378)); /* CLK_CPUG_CMPLX */ + putc_(' '); + puthex(REG(CAR + 0x464)); /* CLK_CPUG_CMPLX_CLR */ + putc_('\n'); + puts_(REG(CAR + 0x340) == REG(CAR + 0x450) /* RST_CPU(G)_CMPLX_SET */ + ? "reset view: RST_CPU_CMPLX matches RST_CPUG_CMPLX\n" + : "reset view: RST_CPU_CMPLX differs\n"); + REG(CAR + 0x464) = 1u << 8; /* CLK_CPUG_CMPLX_CLR */ u32 start = REG(TIMERUS); while (mb[0] != PCIE_MAGIC && REG(TIMERUS) - start < 100000) diff --git a/tests/ccplex/run.sh b/tests/ccplex/run.sh index 64d8848..0d21d27 100755 --- a/tests/ccplex/run.sh +++ b/tests/ccplex/run.sh @@ -23,6 +23,9 @@ echo "ccplex test (emulator exit $status):" expect 'cannot run: CPU rail off' 'an unpowered release is refused, with the reason' expect 'unpowered: CPU0 stayed dark' 'and the core really did not execute' expect 'CPU0 released: AArch64 EL3, MMU off, entry 0xA0000000' 'a powered release boots CPU0 at the SB vector' +expect 'clock stopped: CPU0 held still' 'a core released with its clock stopped does not run' +expect 'clock stop reads 00000100 00000100' 'CLK_CPUG_CMPLX and its CLR strobe read back the stop' +expect 'RST_CPU_CMPLX matches RST_CPUG_CMPLX' 'the active-cluster reset register reads the G cluster' expect 'powered: magic=50434945' 'CPU0 ran the blob and wrote the mailbox' expect 'el=0000000C' 'CPU0 came up at EL3' expect 'CPU0 stopped (held in reset)' 'RST_CPUG_CMPLX_SET stops the core' From f31175f19a0a9be45a8a74eb42c8e2ecb3d0897c Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 26 Sep 2026 10:23:58 +0000 Subject: [PATCH 17/21] Leave the SD slot empty when there is no SD image Without --sd (and no sd.img in the working directory) the emulator still presented a card: a blank one, which SDMMC1 initialised at SDR104 and FatFs then found no volume on. A console with nothing in the slot shows the payload no card at all. Now the slot starts empty when there is no image: card detect (PZ1) reads no card and every SDMMC1 command times out, which the existing [sd] inserted = 0 path already modelled. The config window's SD toggle can still insert a blank card at runtime. hwtest, which CI runs without --sd, now reports sd_initialize failing and the SD as not ready instead of an unformatted 32 GiB card; its verdict goes from 35 to 34 passes with no failures, and every CI expectation still holds. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb --- DESIGN.md | 6 +++++- README.md | 5 +++-- main.cpp | 8 ++++++++ 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 3dc040c..df39c55 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -181,7 +181,11 @@ SDR104 like the real slot: their defaults, not the voltage. - CMD19 tunes the SDR104 sampling point through the same tuning circuit as the eMMC. hwtest reports a 199.68 MHz card clock. -- The CSD is an SD CSD 2.0 (SD 5.3.3): the image's size (32 GiB with none) +- With no image (`--sd`, or `sd.img` in the working directory) the slot is + empty: card detect (PZ1) reads no card and every SDMMC1 command times + out, as on a console with no card in. The config window can still insert + a blank card. +- The CSD is an SD CSD 2.0 (SD 5.3.3): the image's size (32 GiB for a blank card) and command classes that include class 8, so bdk reads the SD status. That (ACMD13) reports the bus width ACMD6 set and a Class 10, U1, V10 card with 4 MB AUs; the SCR sets SD_SPEC3. diff --git a/README.md b/README.md index 6ea9c77..5a1fe54 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,8 @@ slow or destructive. - Read real eMMC (embedded MMC) dumps (`BOOT0`, multi-part `rawnand.bin.NN`) and decrypt them with XTS-AES-128 (XEX-based Tweaked-codebook with ciphertext stealing) against keys from `prod.keys`. -- Serve a real FAT32 SD image to the payload (`--sd sd.img`). +- Serve a real FAT32 SD image to the payload (`--sd sd.img`). Without one the + SD slot is empty. ## Quick start @@ -270,7 +271,7 @@ needed. | Flag | Argument | Purpose | | --------------------- | ------------- | --------------------------------------------------------- | -| `--sd` | `sd.img` | Back the SD card (SDMMC1) with this raw FAT32 image. | +| `--sd` | `sd.img` | Back the SD card (SDMMC1) with this raw FAT32 image. Without it (and with no `sd.img` in the working directory) the slot is empty. | | `--boot0` | `BOOT0` | eMMC BOOT0 partition file (SDMMC4). | | `--rawnand` | `rawnand.bin` | eMMC GPP partition prefix (auto-detects `.00`, `.01`, …). | | `--prod-keys` | `prod.keys` | Override BIS keys from a Lockpick-style key file. | diff --git a/main.cpp b/main.cpp index 09d6cd0..c51f905 100644 --- a/main.cpp +++ b/main.cpp @@ -412,6 +412,14 @@ int main(int argc, char *argv[]) { if (state.sd_fd < 0) perror("[emu] Failed to open SD image"); else printf("[emu] SD image opened: %s\n", sd_path); } + // No image, no card: the slot starts empty, so card detect (PZ1) reads + // empty and SDMMC1 commands time out, as on a console with no card in. + // This used to present a blank card that FatFs then found no volume on. + // The config window's SD toggle can still insert a blank card. + if (state.sd_fd < 0 && state.sd_inserted.load()) { + state.sd_inserted = false; + printf("[emu] No SD image: the SD slot is empty\n"); + } if (boot0_path) { state.emmc_boot0_fd = open(boot0_path, O_RDWR | O_BINARY); if (state.emmc_boot0_fd < 0) perror("[emu] Failed to open BOOT0 image"); From 66600dafc11edce89ff53e036e7a8c492c1acbdf Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 26 Sep 2026 10:24:10 +0000 Subject: [PATCH 18/21] Tap the touchscreen from --input-script The input script pressed POWER and the volume buttons only, so touch- driven payloads - Nyx above all - could not be driven headless. ` TAP [hold_ms]` touches the screen at (x, y) in the 1280x720 picture bdk's touch driver reports, inverted through its 15..1264 / 15..704 scaling to the FTS4 panel's raw coordinates, and lifts after hold_ms. The press and release go through the same event queue as a mouse click in the window. This is how Nyx's Tools > USB Tools > SD Card is reached headless: "12000 TAP 516 531, 15000 TAP 640 32, 17000 TAP 640 423, 19000 TAP 850 420, 22000 TAP 170 202" on hekate 6.5.3. The README now documents --input-script, which it did not mention before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb --- DESIGN.md | 6 +++++- README.md | 4 +++- input_script.cpp | 55 +++++++++++++++++++++++++++++++++++++++++++++--- 3 files changed, 60 insertions(+), 5 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index df39c55..d3739b5 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -631,7 +631,11 @@ while (te_idx < n && state.emu_usec >= te_events[te_idx].at_us) { Because `emu_usec` is deterministic, the same timestamps land at the same UI states across runs. Adding a new automated flow is "press the buttons once -with `[input]` logging on, copy the timestamps". +with `[input]` logging on, copy the timestamps". `--input-script` does the +same for any payload without a rebuild (`input_script.cpp`): button presses +and touchscreen taps (` TAP `, in the 1280x720 picture, inverted +through bdk's touch scaling) keyed to `emu_usec`. That is how Nyx's USB tools +are reached headless. ## CCPLEX CPU0 diff --git a/README.md b/README.md index 5a1fe54..7f3a85d 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,8 @@ slow or destructive. [CCPLEX CPU0](#ccplex-cpu0). - Replay deterministic button sequences via `--auto-pin-recovery` or `--auto-te-script`, so a payload flow can be exercised from a CI run or a - one-shot script. + one-shot script. `--input-script` scripts buttons and touchscreen taps for + any payload. - Tweak emulated hardware live (battery, charger, thermal, USB-PD, PMIC, fuses, SD insertion) from a side window. See [Live hardware tweaks](#live-hardware-tweaks). - Inspect each Tegra UART port (TX history) and inject keystrokes into the @@ -278,6 +279,7 @@ needed. | `--oem` | `erista` \| `mariko` | Switch SoC generation. Drives `APB_MISC_GP_HIDREV` so Hekate's `h_cfg.t210b01` matches and pkg1 identification skips the right OEM header. Default `erista`. | | `--bt-radio` | `healthy` \| `faulty` \| `absent` | Broadcom CYW4356 behaviour on UART-D. `healthy` powers up on the `BT_REG_ON` edge, holds `BT_HOST_WAKE` high, asserts `RTS_N` and answers HCI; `faulty` reproduces the 2110-1118 console (module fitted, never leaves POR); `absent` additionally leaves `BT_UART_RXD` in a break condition. Overrides `[bluetooth] radio` in the ini. Default `healthy`. | | `--wifi-radio` | `healthy` \| `faulty` \| `absent` | The WLAN half of the same CYW4356: a PCI Express endpoint on root port 1, reachable only from CPU0 (the BPMP reads all ones, as on silicon). `healthy` trains the link, enumerates as `14E4:43EC` and answers a ChipCommon ChipID read with `0x4356`; `faulty` still trains and enumerates but reads all ones on the backplane (live PCIe front-end, dead radio die); `absent` never leaves detect. The model also enforces the datasheet's power-up ordering, so a payload that releases PERST# too early gets a link that stays down and a `[pcie]` line naming the reason. Overrides `[wifi] radio` in the ini. Default `healthy`. | +| `--input-script` | file or spec | Scripted input keyed to emulated time: ` P\|U\|D [hold_ms]` presses POWER / VOL+ / VOL-, ` TAP [hold_ms]` taps the touchscreen at (x, y) in the 1280x720 picture, `+N` times an event N ms after the previous one. Events are separated by `,`, `;` or newlines. | | `--auto-pin-recovery` | (none) | Drive the Lockpick PIN-recovery menu without user input. | | `--auto-te-script` | (none) | Drive `recover_pin.te` in TegraExplorer without input. | diff --git a/input_script.cpp b/input_script.cpp index b4a5692..163c174 100644 --- a/input_script.cpp +++ b/input_script.cpp @@ -12,6 +12,11 @@ // VOL_UP | VOLUP | UP | U // hold_ms how long to hold the button, default 200 ms. // +// TAP [hold_ms] +// +// touches the screen at (x, y) in the 1280x720 landscape picture bdk's +// touch driver reports (Nyx's coordinates), and lifts after hold_ms. +// // '#' starts a comment. Example - walk 6 entries down a menu and select: // // rcm_emu payload.bin --input-script "3000 D, + D, + D, + D, + D, + D, + P" @@ -27,6 +32,7 @@ #include "input_script.h" #include "emu_state.h" +#include #include #include #include @@ -36,7 +42,7 @@ namespace { -enum class Key { Power, VolUp, VolDown, Uart, UartFile }; +enum class Key { Power, VolUp, VolDown, Uart, UartFile, Tap }; struct Event { uint64_t at_us = 0; // press time @@ -45,6 +51,7 @@ struct Event { bool pressed = false; bool released = false; std::string data; // UART / UARTFILE payload + uint16_t x = 0, y = 0; // TAP: panel-raw coordinates }; std::vector g_events; @@ -60,6 +67,7 @@ const char *key_name(Key k) { case Key::VolUp: return "VOL+"; case Key::Uart: return "UART"; case Key::UartFile: return "UARTFILE"; + case Key::Tap: return "TAP"; default: return "VOL-"; } } @@ -80,6 +88,7 @@ bool parse_key(const std::string &tok, Key *out) { // UARTFILE pushes a file's raw contents, for binary protocol work. if (s == "UART") { *out = Key::Uart; return true; } if (s == "UARTFILE") { *out = Key::UartFile; return true; } + if (s == "TAP" || s == "T") { *out = Key::Tap; return true; } return false; } @@ -184,8 +193,24 @@ bool parse_text(const std::string &text) { continue; } - uint64_t hold_ms = (tok.size() >= 3) ? strtoull(tok[2].c_str(), nullptr, 10) - : kDefaultHoldMs; + size_t hold_tok = 2; + if (ev.key == Key::Tap) { + if (tok.size() < 4) { + fprintf(stderr, "[input-script] entry %d: expected ' TAP [hold_ms]'\n", + lineno); + return false; + } + // bdk's touch.c clamps raw samples to 15..1264 and 15..704 and + // stretches that span over 1280x720; invert it. + uint32_t x = std::min(strtoul(tok[2].c_str(), nullptr, 10), 1279); + uint32_t y = std::min(strtoul(tok[3].c_str(), nullptr, 10), 719); + ev.x = (uint16_t)(15 + (x * (1264 - 15) + 1279) / 1280); + ev.y = (uint16_t)(15 + (y * (704 - 15) + 719) / 720); + hold_tok = 4; + } + uint64_t hold_ms = (tok.size() > hold_tok) + ? strtoull(tok[hold_tok].c_str(), nullptr, 10) + : kDefaultHoldMs; if (hold_ms == 0) hold_ms = kDefaultHoldMs; ev.until_us = ev.at_us + hold_ms * 1000ULL; prev_release_us = ev.until_us; @@ -271,6 +296,30 @@ void input_script_tick(EmuState &state) { break; } + if (ev.key == Key::Tap) { + if (!ev.pressed && now >= ev.at_us) { + state.tc_pressed.store(true); + state.touch_post(0x03, ev.x, ev.y); // FTS4 ENTER + ev.pressed = true; + printf("[input-script] TAP down panel=(%u,%u) @%llu us (%zu/%zu)\n", + ev.x, ev.y, (unsigned long long)now, i + 1, g_events.size()); + fflush(stdout); + break; + } + if (ev.pressed && !ev.released && now >= ev.until_us) { + state.tc_pressed.store(false); + state.touch_post(0x04, ev.x, ev.y); // FTS4 LEAVE + ev.released = true; + if (i == g_done) { + g_done++; + if (g_done == g_events.size()) + printf("[input-script] sequence complete\n"); + } + } + if (!ev.released) break; + continue; + } + std::atomic *btn = (ev.key == Key::Power) ? &state.btn_power : (ev.key == Key::VolUp) ? &state.btn_vol_up : &state.btn_vol_down; From d661f2738c22716f5487e13db89136a64d1e8aa6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 26 Sep 2026 10:24:45 +0000 Subject: [PATCH 19/21] Model USB device mode, with an emulated PC on the cable Both USB controllers were plain register caches: USBCMD.RESET never cleared, so bdk's usb_device_init() timed out and none of Nyx's USB tools could even wait for a cable. - The Erista USB2 controller (USB1, 0x7D000000, bdk usbd.c): queue heads at ENDPOINTLISTADDR (bdk's are in the controller at +0x1000), transfer descriptors in DRAM, ENDPTPRIME / ENDPTSTATUS / ENDPTCOMPLETE, SETUP packets in queue head 0 with ENDPTSETUPSTAT, a self-clearing controller reset and the PHY's clock-valid bit. Byte and halfword accesses work, since bdk memcpy()s SETUP packets out. - The Mariko XUSB device controller (0x700D0000, bdk xusbd.c): endpoint contexts and TRB rings with Link TRBs and cycle bits, the doorbell, a two-segment event ring with Port Status Change, Setup and Transfer events, EP_HALT / EP_STCHG, EP_RELOAD, and PORTSC's write-1-to-clear changes and link-state writes. - The host (--usb-host, [usb] host, or the config window) plays the PC on whichever controller attaches: debounce, bus reset at high speed, enumeration with SET_ADDRESS recovery, then after 100 ms for its class driver to bind - bdk's XUSB driver stalls an early GET_MAX_LUN - the class. For mass storage it runs Bulk-Only Transport: GET_MAX_LUN, INQUIRY, TEST UNIT READY with REQUEST SENSE for the unit attention, READ CAPACITY, READ(10) of the first 64 and last 8 blocks with their CRC32s, checked against the SD image when the size matches, then allow removal, eject, and poll until the gadget detaches. For HID it reads the report descriptor, sets idle 0 and polls the interrupt endpoint. It only reads, and it runs on the controllers' register accesses, so runs repeat. [usb-host] lines log it; RCM_USB_TRACE=1 logs every descriptor, TRB and doorbell. With hekate 6.5.3, Nyx's SD card mass storage enumerates as 11EC:A7E0, reads back identical to the SD image and ends at "Disk ejected" on both Erista and Mariko; the gamepad enumerates and serves its report descriptor (with no Joy-Cons it has nothing to report). Without a host Nyx waits and reports a timeout, as with no cable. tests/usb/ runs a mass storage gadget over a RAM disk on each controller and a HID gadget on the USB2 one, checks what the host logs - the enumeration, the SCSI commands, CRC32s equal to the payload's, the eject and the detach - and a run with nothing on the cable. The Windows pread/pwrite shim moves from mmio.cpp to platform.h, as the host reads the SD image too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb --- .github/workflows/build.yml | 11 +- .gitignore | 1 + DESIGN.md | 68 +- Makefile | 10 +- README.md | 28 +- display/config_window.cpp | 10 + emu_state.h | 4 + main.cpp | 5 + platform.h | 20 + t210/memory_map.h | 10 + t210/mmio.cpp | 32 +- t210/usb.cpp | 1464 +++++++++++++++++++++++++++++++++++ t210/usb.h | 18 + tests/usb/link.ld | 10 + tests/usb/payload.c | 613 +++++++++++++++ tests/usb/run.sh | 72 ++ 16 files changed, 2342 insertions(+), 34 deletions(-) create mode 100644 t210/usb.cpp create mode 100644 t210/usb.h create mode 100644 tests/usb/link.ld create mode 100644 tests/usb/payload.c create mode 100755 tests/usb/run.sh diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index a02faa4..b49ec72 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -45,14 +45,16 @@ jobs: grep -q "RCM Payload Emulator" out.txt \ || { echo "banner missing - binary did not start"; exit 1; } - - name: CCPLEX, SE and display regression tests + - name: CCPLEX, SE, USB and display regression tests # Small self-contained payloads. One boots CPU0 through bdk's # ccplex_boot_cpu0() register sequence: an unpowered release must be # refused, a powered one must run an AArch64 blob at EL3, and WFE must # park the core. One runs the Security Engine's RSA, SHA-256, AES and - # RNG against vectors computed in Python. The others drive the - # display controller and VIC in six scenarios, and the frame the - # emulator shows must match the picture drawn, pixel for pixel. + # RNG against vectors computed in Python. One brings up USB gadgets on + # both device controllers for the --usb-host PC to enumerate and read + # back. The others drive the display controller and VIC in six + # scenarios, and the frame the emulator shows must match the picture + # drawn, pixel for pixel. run: make test - name: hwtest end to end @@ -71,6 +73,7 @@ jobs: path: | tests/ccplex/out.log tests/se/out.log + tests/usb/out_*.log tests/hwtest/out.log if-no-files-found: ignore diff --git a/.gitignore b/.gitignore index 0c77899..2803d36 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,7 @@ last_fb.rgba last_fb.meta last_fb*.png out.log +out_*.log out*.txt emu_run*.log emu_capture*.txt diff --git a/DESIGN.md b/DESIGN.md index d3739b5..61fa119 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -28,6 +28,7 @@ flowchart TB mmio --> dc["DC + VIC (inline)
window registers A-D
VIC compose, flip/transpose"] mmio --> stubs["inline stubs
GPIO, PMC, TSEC, KFUSE,
PWM, CLK, TMR, FUSE, UART"] mmio --> pcie["pcie
AFI, root ports, CYW4356
(CPU-complex master only)"] + mmio --> usb["usb
USB2 + XUSB device controllers
and the --usb-host PC"] cfg -.->|writes atomics| state["EmuState
(emu_state.h)"] con -.->|RX inject / TX log| state @@ -529,6 +530,62 @@ All TX append / RX pop is single-threaded -- both the CPU emulation and ImGui rendering run on the main thread between SDL polls -- so no locking is needed. The 64 KB TX log trim happens in-place during the write hook. +### USB device mode (`t210/usb.cpp`) + +bdk runs its gadgets - Nyx's USB mass storage for the SD card, eMMC and +emuMMC, and its Joy-Con gamepad - on one of two device controllers, and both +are modelled: + +- **Erista: the USB2 controller USB1** (0x7D000000, bdk `usbd.c`), an + EHCI-derived device controller. Each endpoint half has a 64-byte queue + head at `ENDPOINTLISTADDR` (bdk keeps them in the controller's own memory + at +0x1000) and a chain of transfer descriptors in DRAM. `ENDPTPRIME` + loads the first descriptor and sets its bit in `ENDPTSTATUS` until the + transfer retires; each descriptor it reaches is written back with the + bytes it did not move, and the endpoint's bit set in `ENDPTCOMPLETE`. A + SETUP lands in queue head 0 with `ENDPTSETUPSTAT` bit 0. `USBCMD.RESET` + resets the controller and clears itself; `PHY_CLK_VALID` follows the + UTMI PHY's enable and reset. bdk copies SETUP packets out with `memcpy()`, + so byte and halfword accesses are handled. +- **Mariko: the XUSB device controller** (0x700D0000, bdk `xusbd.c`), the + device side of xHCI. Endpoints are device context indexes (0 control, 2 + bulk OUT, 3 bulk IN), each with a context (the dequeue pointer and DCS in + word 2) and a ring of TRBs the driver fills and closes with a Link TRB, + ringing the doorbell. The controller posts events on a two-segment event + ring, flipping its cycle bit per pass and raising `ST.IP`: a Port Status + Change on a bus reset, a Setup event with a sequence number per SETUP, a + Transfer event with the residue and SUCCESS or SHORT_PKT per TRB. + `EP_HALT` halts an endpoint (`EP_STCHG` reports it), `EP_RELOAD` reloads a + context, and a `PORTSC` write with LWS and RxDetect arms the port. + +**The host.** `--usb-host` (or `[usb] host`, or the config window's USB +device mode box) plugs in a PC; without it nothing is on the cable and a +gadget waits for a connection until it gives up, as with no cable. The host +sees whichever controller attaches, waits out the attach debounce, resets +the bus at high speed and enumerates: device descriptor, `SET_ADDRESS` (with +its 2 ms recovery), configuration, strings, `SET_CONFIGURATION`. It then gives +the class driver 100 ms to bind, as a PC does - bdk's XUSB driver stalls a +`GET_MAX_LUN` that arrives before the gadget asks for it - and runs the +class: + +- *Mass storage (Bulk-Only Transport):* `GET_MAX_LUN`, INQUIRY, TEST UNIT + READY (answering the first unit attention with REQUEST SENSE), READ + CAPACITY, READ(10) of the first 64 and the last 8 blocks, each logged with + its CRC32 and checked against the SD image when the disk is its size; then + PREVENT ALLOW MEDIUM REMOVAL, an eject (START STOP UNIT, LoEj) and TEST + UNIT READY every 500 ms until the gadget detaches, as Linux does. It only + reads. +- *HID:* the report descriptor, `SET_IDLE` with an idle rate of 0 (report on + change), then the interrupt IN endpoint is polled. Nyx's gamepad has + nothing to report without Joy-Cons. + +The host advances on every access to either controller - it runs as far as +the device and the emulated clock allow - so it needs no thread or main-loop +hook and runs repeat exactly. It logs `[usb-host]` lines; `RCM_USB_TRACE=1` +also logs each transfer descriptor, TRB and doorbell. Nyx's SD card mass +storage reads back identical to the image and reports "Disk ejected" on +both SoCs. + ### Other peripherals (mostly stubs) - **CAR and MC.** Registers without behaviour of their own read back what @@ -722,8 +779,11 @@ emulated second. refusal, the EL3 entry, a core released with its clock stopped, the mailbox, WFE parking and the reset; `tests/se/`, which runs the SE's RSA, SHA-256, AES and RNG against vectors -computed in Python (`gen_vectors.py` writes `vectors.h`); and -`tests/display/`, one payload built per scenario that drives the display +computed in Python (`gen_vectors.py` writes `vectors.h`); `tests/usb/`, a +mass storage gadget over a RAM disk on each device controller and a HID +gadget, which the `--usb-host` PC must enumerate, read back (the CRC32s it +logs match the payload's) and see detach, plus a run with nothing on the +cable; and `tests/display/`, one payload built per scenario that drives the display controller and VIC the way bdk does (a pitch window; Nyx's VIC turn into pitch and into block-linear surfaces; a block-linear VIC source; the DC's own column scan with an address offset; a mirrored window with window D @@ -747,6 +807,10 @@ don't repeat the diagnosis: real console's value taken after a payload had brought the display up, so `display_init()` found DISP1 already clocked at RCM entry. Fix: the bank starts at the TRM reset value and follows the payload's writes. +- **Every USB gadget failed to start.** The USB controllers were plain + register caches, so `USBCMD.RESET` never cleared and bdk's + `usb_device_init()` timed out; Nyx's USB tools could not even wait for a + cable. Fix: both device controllers are modelled, with a PC to plug in. - **Minerva hung Nyx** (hekate 6.5.3 with the stock `bootloader/` folder never reached its GUI). The emulator planted hekate's "watchdog fired" cookie in IRAM so the IPL would skip Minerva; Nyx then trained the DRAM diff --git a/Makefile b/Makefile index f05f547..d5bae68 100644 --- a/Makefile +++ b/Makefile @@ -102,6 +102,12 @@ tests/se/payload.bin: tests/se/payload.c tests/se/vectors.h tests/se/link.ld $(TEST_CC) $(TEST_CFLAGS) -T tests/se/link.ld -o tests/se/payload.elf $< $(TEST_OBJCOPY) -O binary tests/se/payload.elf $@ +USB_PAYLOADS = tests/usb/payload_1.bin tests/usb/payload_2.bin tests/usb/payload_3.bin + +tests/usb/payload_%.bin: tests/usb/payload.c tests/usb/link.ld + $(TEST_CC) $(TEST_CFLAGS) -DSCENARIO=$* -T tests/usb/link.ld -o tests/usb/payload_$*.elf $< + $(TEST_OBJCOPY) -O binary tests/usb/payload_$*.elf $@ + DISPLAY_SCENARIOS = 1 2 3 4 5 6 DISPLAY_PAYLOADS = $(DISPLAY_SCENARIOS:%=tests/display/payload_%.bin) @@ -109,14 +115,16 @@ tests/display/payload_%.bin: tests/display/payload.c tests/display/link.ld $(TEST_CC) $(TEST_CFLAGS) -DSCENARIO=$* -T tests/display/link.ld -o tests/display/payload_$*.elf $< $(TEST_OBJCOPY) -O binary tests/display/payload_$*.elf $@ -test: $(OUTPUT) tests/ccplex/payload.bin tests/se/payload.bin $(DISPLAY_PAYLOADS) +test: $(OUTPUT) tests/ccplex/payload.bin tests/se/payload.bin $(USB_PAYLOADS) $(DISPLAY_PAYLOADS) sh tests/ccplex/run.sh ./$(OUTPUT) tests/ccplex/payload.bin sh tests/se/run.sh ./$(OUTPUT) tests/se/payload.bin + sh tests/usb/run.sh ./$(OUTPUT) tests/usb sh tests/display/run.sh ./$(OUTPUT) tests/display clean: rm -f $(OUTPUT) $(OBJS) $(OBJS:.o=.d) \ tests/ccplex/payload.elf tests/ccplex/payload.bin tests/ccplex/out.log \ tests/se/payload.elf tests/se/payload.bin tests/se/out.log \ + tests/usb/payload_*.elf tests/usb/payload_*.bin tests/usb/out_*.log \ tests/display/payload_*.elf tests/display/payload_*.bin \ $(WIN_OUT) $(WIN_OBJS) $(WIN_OBJS:.o=.d) diff --git a/README.md b/README.md index 7f3a85d..c5fc673 100644 --- a/README.md +++ b/README.md @@ -30,8 +30,12 @@ slow or destructive. `--auto-te-script`, so a payload flow can be exercised from a CI run or a one-shot script. `--input-script` scripts buttons and touchscreen taps for any payload. +- Plug an emulated PC into the USB-C port (`--usb-host`): Nyx's USB mass + storage and gamepad gadgets enumerate on both the Erista (USB2) and Mariko + (XUSB) device controllers, and the PC reads a mass storage disk back, + checks it against the SD image and ejects it. - Tweak emulated hardware live (battery, charger, thermal, USB-PD, PMIC, - fuses, SD insertion) from a side window. See [Live hardware tweaks](#live-hardware-tweaks). + fuses, SD insertion, the USB host) from a side window. See [Live hardware tweaks](#live-hardware-tweaks). - Inspect each Tegra UART port (TX history) and inject keystrokes into the payload's RX FIFO from a separate console window. See [UART console](#uart-console). - Read real eMMC (embedded MMC) dumps (`BOOT0`, multi-part `rawnand.bin.NN`) @@ -177,15 +181,20 @@ real consoles. Details in [DESIGN.md](DESIGN.md#ccplex-cpu0). ## Tests ```bash -make test # CCPLEX, SE + display regression payloads (arm-none-eabi-gcc, python3) +make test # CCPLEX, SE, USB + display regression payloads (arm-none-eabi-gcc, python3) tests/hwtest/build.sh build-hwtest # build hwtest-rcm (+ gcc-aarch64-linux-gnu) tests/hwtest/run.sh ./rcm_emu build-hwtest/hwtest-rcm/build/hwtest.bin ``` -The first boots CPU0 from a small self-contained payload and checks the -refusal of an unpowered release, the EL3 entry, the mailbox, WFE parking and -the reset. The second runs hwtest-rcm's whole hardware sweep headless and -checks that the CPU0-driven Wi-Fi probe enumerates the endpoint. CI runs both. +`make test` runs small self-contained payloads: one boots CPU0 and checks the +refusal of an unpowered release, the EL3 entry, the mailbox, a stopped clock, +WFE parking and the reset; one checks the Security Engine's RSA, SHA-256, AES +and RNG against vectors computed in Python; one brings up a USB mass storage +gadget on each device controller (and a HID gadget) for the `--usb-host` PC to +enumerate and read back; one drives the display controller and VIC and +compares the frame pixel for pixel. The hwtest scripts run hwtest-rcm's whole +hardware sweep headless and check that the CPU0-driven Wi-Fi probe enumerates +the endpoint. CI runs both. ## Live hardware tweaks @@ -279,6 +288,7 @@ needed. | `--oem` | `erista` \| `mariko` | Switch SoC generation. Drives `APB_MISC_GP_HIDREV` so Hekate's `h_cfg.t210b01` matches and pkg1 identification skips the right OEM header. Default `erista`. | | `--bt-radio` | `healthy` \| `faulty` \| `absent` | Broadcom CYW4356 behaviour on UART-D. `healthy` powers up on the `BT_REG_ON` edge, holds `BT_HOST_WAKE` high, asserts `RTS_N` and answers HCI; `faulty` reproduces the 2110-1118 console (module fitted, never leaves POR); `absent` additionally leaves `BT_UART_RXD` in a break condition. Overrides `[bluetooth] radio` in the ini. Default `healthy`. | | `--wifi-radio` | `healthy` \| `faulty` \| `absent` | The WLAN half of the same CYW4356: a PCI Express endpoint on root port 1, reachable only from CPU0 (the BPMP reads all ones, as on silicon). `healthy` trains the link, enumerates as `14E4:43EC` and answers a ChipCommon ChipID read with `0x4356`; `faulty` still trains and enumerates but reads all ones on the backplane (live PCIe front-end, dead radio die); `absent` never leaves detect. The model also enforces the datasheet's power-up ordering, so a payload that releases PERST# too early gets a link that stays down and a `[pcie]` line naming the reason. Overrides `[wifi] radio` in the ini. Default `healthy`. | +| `--usb-host` | (none) | A PC on the USB-C port. It enumerates whatever USB gadget the payload brings up; a mass storage disk is read back (checked against the SD image), then ejected, and HID reports are polled. Logged as `[usb-host]`; `RCM_USB_TRACE=1` traces every transfer. Overrides `[usb] host` in the ini. | | `--input-script` | file or spec | Scripted input keyed to emulated time: ` P\|U\|D [hold_ms]` presses POWER / VOL+ / VOL-, ` TAP [hold_ms]` taps the touchscreen at (x, y) in the 1280x720 picture, `+N` times an event N ms after the previous one. Events are separated by `,`, `;` or newlines. | | `--auto-pin-recovery` | (none) | Drive the Lockpick PIN-recovery menu without user input. | | `--auto-te-script` | (none) | Drive `recover_pin.te` in TegraExplorer without input. | @@ -291,13 +301,14 @@ flowchart LR root --> top["main.cpp
emu_state.h
Makefile
Dockerfile
README.md / DESIGN.md"] root --> t210["t210/
(SoC peripheral models)"] root --> display["display/"] - root --> tests["tests/
ccplex/, se/, display/, hwtest/"] + root --> tests["tests/
ccplex/, se/, usb/, display/, hwtest/"] t210 --> mmio["mmio.{h,cpp}
memory_map.h
regcache.h, tegra_bl.h"] t210 --> cpus["bpmp.{h,cpp} BPMP clock
ccplex.{h,cpp} CPU0 (A57)"] t210 --> pcie["pcie.{h,cpp}
root complex + CYW4356"] t210 --> se["se_engine.{h,cpp}
AES-128, SHA-256, RSA, RNG"] t210 --> i2c["i2c3.{h,cpp}
STMFTS / FTS4 touch"] + t210 --> usb["usb.{h,cpp}
USB device controllers + host PC"] display --> sdl["sdl_display.{h,cpp}
DC window scan-out
+ SDL2"] ``` @@ -321,6 +332,9 @@ For implementation details, see [DESIGN.md](DESIGN.md). seed, so runs repeat. - **Single-threaded.** Both cores run in batches on the main thread between SDL event polls. That is also what keeps them deterministic. +- **The USB host is scripted.** `--usb-host` runs a fixed session - enumerate, + read back, eject - rather than bridging the gadget to the machine running + the emulator, so the disk cannot be mounted on it. ## Acknowledgements diff --git a/display/config_window.cpp b/display/config_window.cpp index fc61d34..0b60b06 100644 --- a/display/config_window.cpp +++ b/display/config_window.cpp @@ -138,6 +138,7 @@ void reset_to_defaults(EmuState *s) { X(usb_pd_inserted, "usb_pd", "inserted", 0) \ X(usb_pd_voltage_mv, "usb_pd", "voltage_mv", 0) \ X(usb_pd_amperage_ma, "usb_pd", "amperage_ma", 0) \ + X(usb_host, "usb", "host", 0) \ /* SoC / PMIC */ \ X(pmic_otp, "soc", "pmic_otp", 0) \ X(is_mariko, "soc", "is_mariko", 0) \ @@ -645,6 +646,15 @@ void build_ui(EmuState *state) { atomic_slider_int("PDO amperage (mA)", state->usb_pd_amperage_ma, 500, 3000, "%d mA"); } + if (ImGui::CollapsingHeader("USB device mode")) { + // The PC in t210/usb.cpp: it enumerates a gadget the payload brings up. + bool host = state->usb_host.load(); + if (ImGui::Checkbox("PC on the USB-C port (--usb-host)", &host)) { + state->usb_host.store(host); + } + ImGui::TextDisabled("Mass storage is read back and ejected; HID is polled."); + } + if (ImGui::CollapsingHeader("Display")) { int bl = (int)state->backlight; if (ImGui::SliderInt("Backlight", &bl, 0, 255)) { diff --git a/emu_state.h b/emu_state.h index 14fba46..9a2c63d 100644 --- a/emu_state.h +++ b/emu_state.h @@ -320,6 +320,10 @@ struct EmuState { // SD card insertion (GPIO Port Z bit 1 = 0 means inserted). std::atomic sd_inserted{true}; + // A PC on the USB-C port (--usb-host): it enumerates whatever gadget the + // payload brings up (t210/usb.cpp). Off, nothing is on the cable. + std::atomic usb_host{false}; + // SD card identity (returned for SDMMC1 CMD2 ALL_SEND_CID). // Hekate parses these out of the R2 response per bdk/storage/sdmmc.c // _sd_storage_parse_cid; the I2C handler builds the 16-byte CID payload diff --git a/main.cpp b/main.cpp index c51f905..5fa8a7a 100644 --- a/main.cpp +++ b/main.cpp @@ -356,6 +356,11 @@ int main(int argc, char *argv[]) { fprintf(stderr, "[emu] Unknown --bt-radio value '%s'; expected" " 'healthy', 'faulty' or 'absent'\n", mode); } + } else if (strcmp(argv[i], "--usb-host") == 0) { + // A PC on the USB-C port: it enumerates whatever gadget the + // payload brings up and, for mass storage, reads it back. + state.usb_host = true; + printf("[emu] USB host connected [overrides ini]\n"); } else if (strcmp(argv[i], "--wifi-radio") == 0 && i + 1 < argc) { // WLAN half of the same package, on PCIe. 'faulty' means // something different here from the Bluetooth side: the link diff --git a/platform.h b/platform.h index d80eb2e..4df407d 100644 --- a/platform.h +++ b/platform.h @@ -36,6 +36,26 @@ static inline int64_t file_size64(int fd) { #endif } +// pread/pwrite are POSIX and MinGW does not have them. Seek-then-read is +// equivalent here: the emulated storage is touched only from the CPU thread, +// so the atomicity real pread() buys against a shared file offset is not in +// play. +#ifdef _WIN32 +#include +static inline ssize_t pread(int fd, void *buf, size_t n, long long off) { + if (_lseeki64(fd, off, SEEK_SET) < 0) + return -1; + return _read(fd, buf, (unsigned int)n); +} +static inline ssize_t pwrite(int fd, const void *buf, size_t n, long long off) { + if (_lseeki64(fd, off, SEEK_SET) < 0) + return -1; + return _write(fd, buf, (unsigned int)n); +} +#else +#include +#endif + // Large zero-filled memory that only becomes resident where it is touched // (platform.cpp). zeroed_reset() makes all of it zero again, at the same // address, without touching it. diff --git a/t210/memory_map.h b/t210/memory_map.h index 3d12bab..927be60 100644 --- a/t210/memory_map.h +++ b/t210/memory_map.h @@ -193,6 +193,16 @@ constexpr uint64_t SE_SIZE = 0x2000; constexpr uint64_t MSELECT_BASE = 0x50060000; constexpr uint64_t MSELECT_SIZE = 0x1000; +// USB2 controller USB1 ("OTG"): the device controller bdk's usbd.c drives on +// Erista. Registers, the UTMI PHY at +0x400/+0x800, queue heads at +0x1000. +constexpr uint64_t USB_OTG_BASE = 0x7D000000; +constexpr uint64_t USB_OTG_SIZE = 0x4000; + +// XUSB device controller: bdk's xusbd.c on Mariko. XHCI registers, then its +// PCI configuration space at +0x8000 and device registers at +0x9000. +constexpr uint64_t XUSB_DEV_BASE = 0x700D0000; +constexpr uint64_t XUSB_DEV_SIZE = 0xA000; + // XUSB pad controller. Owns the UPHY SERDES lanes shared by PCIe (pcie-0..4) // and USB 3.0 SuperSpeed (pcie-5/6 on this board), plus UPHY PLL P0. constexpr uint64_t XUSB_PADCTL_BASE = 0x7009F000; diff --git a/t210/mmio.cpp b/t210/mmio.cpp index d244bda..72c6d02 100644 --- a/t210/mmio.cpp +++ b/t210/mmio.cpp @@ -8,6 +8,7 @@ #include "bpmp.h" #include "ccplex.h" #include "pcie.h" +#include "usb.h" #include "regcache.h" #include "se_engine.h" #include "tegra_bl.h" @@ -24,26 +25,6 @@ #include #include -// pread/pwrite are POSIX and MinGW does not have them, so the SD/eMMC image -// access below would not compile for Windows. Seek-then-read is equivalent -// here: the emulated storage is touched only from the CPU thread, so the -// atomicity real pread() buys against a shared file offset is not in play. -// Kept next to the includes rather than in a header because these four call -// sites are the only users in the tree. -#ifdef _WIN32 -#include -static inline ssize_t pread(int fd, void *buf, size_t n, long long off) { - if (_lseeki64(fd, off, SEEK_SET) < 0) - return -1; - return _read(fd, buf, (unsigned int)n); -} -static inline ssize_t pwrite(int fd, const void *buf, size_t n, long long off) { - if (_lseeki64(fd, off, SEEK_SET) < 0) - return -1; - return _write(fd, buf, (unsigned int)n); -} -#endif - #define BIT(n) (1U << (n)) static RegCache mmio_regs; @@ -4618,6 +4599,10 @@ uint32_t mmio_bus_read(EmuState *state, uint64_t address, unsigned size) { if (address >= XUSB_PADCTL_BASE && address < XUSB_PADCTL_BASE + XUSB_PADCTL_SIZE) return padctl_read(state, address); + if (address >= USB_OTG_BASE && address < USB_OTG_BASE + USB_OTG_SIZE) + return usb2d_read(state, address, size); + if (address >= XUSB_DEV_BASE && address < XUSB_DEV_BASE + XUSB_DEV_SIZE) + return xusbd_read(state, address, size); if (address >= MSELECT_BASE && address < MSELECT_BASE + MSELECT_SIZE) return mselect_read(state, address); if (address >= VIC_BASE && address < VIC_BASE + VIC_SIZE) @@ -4777,6 +4762,10 @@ void mmio_bus_write(EmuState *state, uint64_t address, unsigned size, } else if (address >= XUSB_PADCTL_BASE && address < XUSB_PADCTL_BASE + XUSB_PADCTL_SIZE) { padctl_write(state, address, val); + } else if (address >= USB_OTG_BASE && address < USB_OTG_BASE + USB_OTG_SIZE) { + usb2d_write(state, address, size, val); + } else if (address >= XUSB_DEV_BASE && address < XUSB_DEV_BASE + XUSB_DEV_SIZE) { + xusbd_write(state, address, size, val); } else if (address >= MSELECT_BASE && address < MSELECT_BASE + MSELECT_SIZE) { mselect_write(state, address, val); } else if ((address >= SDMMC1_BASE && address < SDMMC1_BASE + 0x200) || @@ -4947,6 +4936,8 @@ const struct { {SYSCTR0_BASE, SYSCTR0_SIZE}, {BPMP_CACHE_BASE, BPMP_CACHE_SIZE}, {XUSB_PADCTL_BASE, XUSB_PADCTL_SIZE}, + {USB_OTG_BASE, USB_OTG_SIZE}, + {XUSB_DEV_BASE, XUSB_DEV_SIZE}, {MSELECT_BASE, MSELECT_SIZE}, // PCIe. T210 puts the root complex at the BOTTOM of the address map, // below every other peripheral. @@ -5056,6 +5047,7 @@ void mmio_soft_reset(EmuState *state, bool power_cycle) { pcie_reset(state); se_engine_reset(); i2c3_reset(state); + usb_reset(state); mmio_regs.clear(); for (auto &u : uart_ports) diff --git a/t210/usb.cpp b/t210/usb.cpp new file mode 100644 index 0000000..6a80d47 --- /dev/null +++ b/t210/usb.cpp @@ -0,0 +1,1464 @@ +// USB device mode, and the PC on the other end of the cable. +// +// bdk runs its gadgets (mass storage, HID) on one of two device controllers: +// the USB2 controller USB1 ("OTG", 0x7D000000) on Erista - bdk usbd.c, an +// EHCI-style device controller - and the XUSB device controller on Mariko +// (xusbd.c). A controller model implements UsbDc, which is all the host sees +// of it: attach, bus reset, SETUP packets, and data IN or OUT of an endpoint. +// +// The host plays the PC. It is plugged in with --usb-host (or [usb] host in +// the ini); without it nothing is on the cable, and a gadget waits for a +// connection the way it does on a console with no cable. Once the device +// attaches, the host resets the bus, enumerates, sets the configuration and +// runs the class: +// +// mass storage GET_MAX_LUN, then over Bulk-Only Transport INQUIRY, TEST +// UNIT READY, READ CAPACITY and two READ(10)s (the first 64 +// sectors and the last 8), checked against the SD image when +// the capacity matches it; then it allows medium removal, +// ejects (START STOP UNIT, LoEj) and polls TEST UNIT READY +// until the gadget lets go, as Linux does +// HID the report descriptor, SET_IDLE, then interrupt IN reports +// +// Everything is logged as [usb-host]. The host only reads: nothing is ever +// written to the storage a gadget exports. +// +// The host advances whenever the payload touches the controller - every +// register access runs it as far as the device and the emulated clock allow +// - so it needs no thread and no main-loop hook, and runs are reproducible. + +#include "usb.h" + +#include +#include +#include +#include +#include +#include + +#include + +#include "../emu_state.h" +#include "../platform.h" +#include "memory_map.h" + +namespace { + +// ---- What the host sees of a device controller ------------------------------ + +// Transfer results: bytes moved, or one of these. +constexpr int XFER_NAK = -1; // endpoint not ready; try again later +constexpr int XFER_STALL = -2; // endpoint halted + +struct UsbDc { + virtual ~UsbDc() = default; + virtual bool attached() = 0; // pull-up on, controller running + virtual void bus_reset() = 0; // reset, then high speed + virtual bool reset_taken() = 0; // the device handled the reset + virtual void setup(const uint8_t pkt[8]) = 0; + virtual bool setup_taken() = 0; // the device read the SETUP + // Data from IN endpoint `ep` into buf, at most max bytes. *short_pkt: the + // device sent less than max, which ends a data stage. + virtual int in(int ep, uint8_t *buf, int max, bool *short_pkt) = 0; + // Data to OUT endpoint `ep`. Returns what the device accepted. + virtual int out(int ep, const uint8_t *buf, int len) = 0; + virtual uint32_t address() = 0; // the USB address the device set + virtual void detach() = 0; // the host saw the device go +}; + +EmuState *g_state = nullptr; + +// RCM_USB_TRACE=1 logs every transfer, event and doorbell. +bool trace_on() { + static int on = -1; + if (on < 0) { + const char *e = getenv("RCM_USB_TRACE"); + on = e && *e && *e != '0'; + } + return on; +} +#define UTRACE(...) \ + do { \ + if (trace_on()) \ + printf("[usb-trace] " __VA_ARGS__); \ + } while (0) + +uint64_t now_us() { return g_state ? g_state->emu_usec : 0; } + +bool mem_read(uint64_t addr, void *buf, size_t n) { + return g_state && g_state->uc && + uc_mem_read(g_state->uc, addr, buf, n) == UC_ERR_OK; +} + +bool mem_write(uint64_t addr, const void *buf, size_t n) { + return g_state && g_state->uc && + uc_mem_write(g_state->uc, addr, buf, n) == UC_ERR_OK; +} + +// ---- The host --------------------------------------------------------------- + +constexpr uint64_t kDebounceUs = 100000; // USB 2.0 7.1.7.3: attach debounce +constexpr uint64_t kRecoveryUs = 10000; // reset recovery +constexpr uint64_t kSetAddrUs = 2000; // USB 2.0 9.2.6.3: SET_ADDRESS recovery +// Between SET_CONFIGURATION and the first class request a PC binds its +// class driver; bdk's XUSB driver stalls GET_MAX_LUN until the gadget has +// come back from enumeration and asked for it, so an instant one fails. +constexpr uint64_t kBindUs = 100000; +constexpr uint64_t kTimeoutUs = 5000000; +constexpr uint64_t kEjectPollUs = 500000; + +struct Endpoint { + uint8_t addr = 0, attr = 0, interval = 0; + uint16_t max_packet = 0; +}; + +// One control transfer: SETUP, an optional data stage, the status stage. +struct Control { + enum Stage { SETUP, DATA, STATUS, DONE } stage = DONE; + uint8_t pkt[8] = {}; + bool dir_in = false; + uint16_t len = 0; + std::vector data; // IN: what came back; OUT: what to send + size_t moved = 0; + bool stalled = false; +}; + +// One Bulk-Only Transport command: CBW, an optional data phase, CSW. +struct Bot { + enum Phase { CBW, DATA, CSW, DONE } phase = DONE; + uint8_t cbw[31] = {}; + bool dir_in = true; + uint32_t len = 0; + std::vector data; + uint8_t csw[13] = {}; + size_t moved = 0; + bool stalled = false; +}; + +enum class Step { + Unplugged, WaitAttach, Debounce, WaitReset, Recover, + GetDevice8, SetAddress, AddrRecovery, GetDevice, GetConfig9, GetConfig, + GetLangs, GetVendor, GetProduct, GetSerial, SetConfig, Bind, + MscMaxLun, MscInquiry, MscTur, MscSense, MscCapacity, MscReadFirst, MscReadLast, + MscAllow, MscEject, MscAfterEject, MscEjectWait, + HidReport, HidIdle, HidPoll, + Idle, Failed, +}; + +class Host { +public: + // Both device controllers; the host talks to whichever one attaches. + void set_controllers(UsbDc *a, UsbDc *b) { + dcs_[0] = a; + dcs_[1] = b; + } + + void run() { + if (!g_state || !dcs_[0]) + return; + bool plugged = g_state->usb_host.load(); + if (!plugged) { + if (step_ != Step::Unplugged) { + if (dc_) + dc_->detach(); + step_ = Step::Unplugged; + printf("[usb-host] unplugged\n"); + } + return; + } + if (step_ == Step::Unplugged) + step_ = Step::WaitAttach; + if (step_ == Step::WaitAttach) { + dc_ = nullptr; + for (UsbDc *dc : dcs_) + if (dc && dc->attached()) + dc_ = dc; + if (!dc_) + return; + } + // A device that goes away (controller stopped or reset) ends the session; + // the next attach starts a new one. + if (step_ != Step::WaitAttach && !dc_->attached()) { + printf("[usb-host] device detached\n"); + dc_->detach(); + step_ = Step::WaitAttach; + ctl_.stage = Control::DONE; + bot_.phase = Bot::DONE; + } + // Several steps can complete in one call; stop once one has to wait. + for (int guard = 0; guard < 64; guard++) { + Step before = step_; + tick(); + if (step_ == before && !progressed_) + break; + progressed_ = false; + } + } + + void reset() { + step_ = Step::Unplugged; + ctl_ = Control(); + bot_ = Bot(); + } + +private: + UsbDc *dcs_[2] = {}; + UsbDc *dc_ = nullptr; + Step step_ = Step::Unplugged; + bool progressed_ = false; + uint64_t wait_until_ = 0, deadline_ = 0; + Control ctl_; + Bot bot_; + + // What enumeration found. + std::vector dev_, cfg_; + uint8_t ep0_max_ = 64, cfg_value_ = 1, iface_ = 0; + uint8_t iface_class_ = 0, iface_sub_ = 0, iface_proto_ = 0; + uint16_t hid_report_len_ = 0; + Endpoint bulk_in_, bulk_out_, intr_in_; + std::string vendor_, product_, serial_; + + // Mass storage. + uint32_t tag_ = 0, blocks_ = 0, block_len_ = 0; + int tur_tries_ = 0; + uint64_t eject_deadline_ = 0; + int reports_ = 0; + + void go(Step s) { + step_ = s; + progressed_ = true; + } + + void fail(const char *what) { + printf("[usb-host] %s - giving up on this device\n", what); + go(Step::Failed); + } + + // ---- Control transfers ---- + + void control(uint8_t bm, uint8_t req, uint16_t val, uint16_t idx, + uint16_t len, const std::vector &out = {}) { + ctl_ = Control(); + ctl_.pkt[0] = bm; + ctl_.pkt[1] = req; + ctl_.pkt[2] = val & 0xFF; + ctl_.pkt[3] = val >> 8; + ctl_.pkt[4] = idx & 0xFF; + ctl_.pkt[5] = idx >> 8; + ctl_.pkt[6] = len & 0xFF; + ctl_.pkt[7] = len >> 8; + ctl_.dir_in = bm & 0x80; + ctl_.len = len; + ctl_.data = ctl_.dir_in ? std::vector(len) : out; + ctl_.stage = Control::SETUP; + deadline_ = now_us() + kTimeoutUs; + dc_->setup(ctl_.pkt); + } + + // True once the transfer is over (done or stalled); false while waiting. + bool control_poll() { + Control &c = ctl_; + for (;;) { + switch (c.stage) { + case Control::SETUP: + if (!dc_->setup_taken()) + return false; + c.stage = c.len ? Control::DATA : Control::STATUS; + break; + case Control::DATA: { + int n; + bool short_pkt = false; + if (c.dir_in) + n = dc_->in(0, c.data.data() + c.moved, (int)(c.len - c.moved), + &short_pkt); + else + n = dc_->out(0, c.data.data() + c.moved, (int)(c.len - c.moved)); + if (n == XFER_STALL) { + c.stalled = true; + c.stage = Control::DONE; + return true; + } + if (n == XFER_NAK) + return false; + c.moved += n; + if (c.moved >= c.len || short_pkt) { + c.data.resize(c.moved); + c.stage = Control::STATUS; + } + break; + } + case Control::STATUS: { + // The status stage runs the other way: a zero-length OUT after an + // IN data stage, a zero-length IN otherwise. + int n; + bool short_pkt = false; + uint8_t none = 0; + if (c.dir_in && c.len) + n = dc_->out(0, nullptr, 0); + else + n = dc_->in(0, &none, 0, &short_pkt); + if (n == XFER_STALL) + c.stalled = true; + else if (n == XFER_NAK) + return false; + c.stage = Control::DONE; + return true; + } + case Control::DONE: + return true; + } + } + } + + // ---- Bulk-Only Transport ---- + + void bot(const uint8_t *cdb, int cdb_len, bool dir_in, uint32_t len) { + bot_ = Bot(); + uint8_t *w = bot_.cbw; + uint32_t tag = ++tag_; + memcpy(w, "USBC", 4); + memcpy(w + 4, &tag, 4); + memcpy(w + 8, &len, 4); + w[12] = dir_in ? 0x80 : 0x00; + w[13] = 0; // LUN 0 + w[14] = (uint8_t)cdb_len; + memcpy(w + 15, cdb, cdb_len); + bot_.dir_in = dir_in; + bot_.len = len; + bot_.data.resize(len); + bot_.phase = Bot::CBW; + deadline_ = now_us() + kTimeoutUs; + } + + // True once the command is over; false while waiting. + bool bot_poll() { + Bot &b = bot_; + int out_ep = bulk_out_.addr & 0xF, in_ep = bulk_in_.addr & 0xF; + for (;;) { + switch (b.phase) { + case Bot::CBW: { + int n = dc_->out(out_ep, b.cbw + b.moved, (int)(31 - b.moved)); + if (n == XFER_STALL) { + b.stalled = true; + b.phase = Bot::DONE; + return true; + } + if (n == XFER_NAK) + return false; + b.moved += n; + if (b.moved == 31) { + b.moved = 0; + b.phase = b.len ? Bot::DATA : Bot::CSW; + } + break; + } + case Bot::DATA: { + bool short_pkt = false; + int n = b.dir_in + ? dc_->in(in_ep, b.data.data() + b.moved, (int)(b.len - b.moved), + &short_pkt) + : dc_->out(out_ep, b.data.data() + b.moved, (int)(b.len - b.moved)); + if (n == XFER_STALL) { + // A halted data phase is still followed by the CSW. + b.stalled = true; + b.phase = Bot::CSW; + break; + } + if (n == XFER_NAK) + return false; + b.moved += n; + if (b.moved >= b.len || short_pkt) { + b.data.resize(b.moved); + b.moved = 0; + b.phase = Bot::CSW; + } + break; + } + case Bot::CSW: { + bool short_pkt = false; + int n = dc_->in(in_ep, b.csw + b.moved, (int)(13 - b.moved), &short_pkt); + if (n == 0 && b.moved == 0) + return false; // a zero-length packet ending the data + if (n == XFER_STALL) { + b.stalled = true; + b.phase = Bot::DONE; + return true; + } + if (n == XFER_NAK) + return false; + b.moved += n; + if (b.moved >= 13 || short_pkt) { + b.phase = Bot::DONE; + return true; + } + break; + } + case Bot::DONE: + return true; + } + } + } + + // The CSW's status byte, or -1 if it is not a valid CSW for this command. + int bot_status() const { + uint32_t tag; + memcpy(&tag, bot_.csw + 4, 4); + if (memcmp(bot_.csw, "USBS", 4) != 0 || tag != tag_) + return -1; + return bot_.csw[12]; + } + + // ---- Descriptors ---- + + static std::string string_desc(const std::vector &d) { + std::string s; + for (size_t i = 2; i + 1 < d.size() && i < d[0]; i += 2) + s += (d[i] >= 0x20 && d[i] < 0x7F && !d[i + 1]) ? (char)d[i] : '?'; + return s; + } + + void parse_config() { + iface_class_ = iface_sub_ = iface_proto_ = 0; + bulk_in_ = bulk_out_ = intr_in_ = Endpoint(); + hid_report_len_ = 0; + if (cfg_.size() >= 9) + cfg_value_ = cfg_[5]; + bool first_iface = true; + for (size_t i = 0; i + 2 <= cfg_.size() && cfg_[i] >= 2; + i += cfg_[i]) { + const uint8_t *d = &cfg_[i]; + size_t n = std::min(d[0], cfg_.size() - i); + if (d[1] == 4 && n >= 9) { // interface + if (!first_iface) + break; // the first interface is enough + first_iface = false; + iface_ = d[2]; + iface_class_ = d[5]; + iface_sub_ = d[6]; + iface_proto_ = d[7]; + } else if (d[1] == 0x21 && n >= 9) { // HID descriptor + hid_report_len_ = d[7] | d[8] << 8; + } else if (d[1] == 5 && n >= 7) { // endpoint + Endpoint e; + e.addr = d[2]; + e.attr = d[3]; + e.max_packet = d[4] | d[5] << 8; + e.interval = d[6]; + int type = e.attr & 3; + if (type == 2 && (e.addr & 0x80)) + bulk_in_ = e; + else if (type == 2) + bulk_out_ = e; + else if (type == 3 && (e.addr & 0x80)) + intr_in_ = e; + } + } + } + + const char *class_name() const { + if (iface_class_ == 0x08 && iface_proto_ == 0x50) + return "mass storage, bulk-only"; + if (iface_class_ == 0x03) + return "HID"; + return "a class this host does not drive"; + } + + // ---- Mass storage checks ---- + + // Compare what was read with the SD image, when the disk is the size of it. + const char *compare_sd(uint32_t lba, const std::vector &got) { + if (!g_state || g_state->sd_fd < 0) + return "no SD image to compare with"; + int64_t size = file_size64(g_state->sd_fd); + if (size / 512 != (int64_t)blocks_ + 1) + return "not the SD image's size, not compared"; + std::vector want(got.size()); + if (pread(g_state->sd_fd, want.data(), want.size(), + (long long)lba * 512) != (ssize_t)want.size()) + return "SD image unreadable"; + return memcmp(want.data(), got.data(), got.size()) == 0 + ? "matches the SD image" + : "DIFFERS from the SD image"; + } + + static uint32_t crc32(const std::vector &d) { + uint32_t c = 0xFFFFFFFF; + for (uint8_t b : d) { + c ^= b; + for (int k = 0; k < 8; k++) + c = (c >> 1) ^ (0xEDB88320u & (0u - (c & 1))); + } + return ~c; + } + + static uint32_t be32(const uint8_t *p) { + return (uint32_t)p[0] << 24 | p[1] << 16 | p[2] << 8 | p[3]; + } + + void read10(uint32_t lba, uint16_t count) { + uint8_t cdb[10] = {0x28, 0, (uint8_t)(lba >> 24), (uint8_t)(lba >> 16), + (uint8_t)(lba >> 8), (uint8_t)lba, 0, + (uint8_t)(count >> 8), (uint8_t)count, 0}; + bot(cdb, 10, true, (uint32_t)count * block_len_); + } + + // A BOT command finished: false (and the session failed) if it did not end + // with a good CSW. + bool bot_ok(const char *what) { + int st = bot_status(); + if (bot_.stalled || st != 0) { + printf("[usb-host] %s: %s\n", what, + st < 0 ? "no valid CSW" : bot_.stalled ? "stalled" : "failed"); + fail("mass storage command failed"); + return false; + } + return true; + } + + // ---- The session ---- + + void tick() { + switch (step_) { + case Step::Unplugged: + case Step::Idle: + case Step::Failed: + return; + + case Step::WaitAttach: + if (!dc_->attached()) + return; + printf("[usb-host] device attached\n"); + wait_until_ = now_us() + kDebounceUs; + go(Step::Debounce); + return; + + case Step::Debounce: + if (now_us() < wait_until_) + return; + dc_->bus_reset(); + deadline_ = now_us() + kTimeoutUs; + go(Step::WaitReset); + return; + + case Step::WaitReset: + if (!dc_->reset_taken()) { + if (now_us() > deadline_) + fail("the device never took the bus reset"); + return; + } + wait_until_ = now_us() + kRecoveryUs; + go(Step::Recover); + return; + + case Step::Recover: + if (now_us() < wait_until_) + return; + control(0x80, 6, 0x0100, 0, 64); // GET_DESCRIPTOR device + go(Step::GetDevice8); + return; + + case Step::AddrRecovery: + if (now_us() < wait_until_) + return; + control(0x80, 6, 0x0100, 0, 18); + go(Step::GetDevice); + return; + + case Step::Bind: + if (now_us() < wait_until_) + return; + start_class(); + return; + + case Step::MscEjectWait: { + if (now_us() < wait_until_) + return; + if (now_us() > deadline_) + return fail("the device never let go after the eject"); + uint8_t cdb[6] = {0x00, 0, 0, 0, 0, 0}; // TEST UNIT READY + bot(cdb, 6, false, 0); + go(Step::MscAfterEject); + return; + } + + case Step::HidPoll: + finish(); // polls the endpoint itself + return; + + default: + break; + } + + // Everything else waits on a transfer: a BOT command in the mass storage + // steps, a control transfer otherwise. + bool is_bot = step_ >= Step::MscInquiry && step_ <= Step::MscAfterEject; + if (!(is_bot ? bot_poll() : control_poll())) { + if (now_us() > deadline_ && step_ != Step::MscAfterEject) + fail("transfer timed out"); + return; + } + finish(); + } + + // The class driver binds: its first request. + void start_class() { + if (iface_class_ == 0x08 && iface_proto_ == 0x50 && bulk_in_.addr && + bulk_out_.addr) { + control(0xA1, 0xFE, 0, iface_, 1); // GET_MAX_LUN + return go(Step::MscMaxLun); + } + if (iface_class_ == 0x03 && intr_in_.addr) { + control(0x81, 6, 0x2200, iface_, hid_report_len_ ? hid_report_len_ : 256); + return go(Step::HidReport); + } + printf("[usb-host] configured; nothing more to do\n"); + go(Step::Idle); + } + + // The transfer of the current step is over: act on it and start the next. + void finish() { + switch (step_) { + case Step::GetDevice8: + if (ctl_.stalled || ctl_.data.size() < 8) + return fail("GET_DESCRIPTOR(device) failed"); + ep0_max_ = ctl_.data[7]; + control(0x00, 5, 1, 0, 0); // SET_ADDRESS 1 + return go(Step::SetAddress); + + case Step::SetAddress: + if (ctl_.stalled) + return fail("SET_ADDRESS stalled"); + wait_until_ = now_us() + kSetAddrUs; + return go(Step::AddrRecovery); + + case Step::GetDevice: + if (ctl_.stalled || ctl_.data.size() < 18) + return fail("GET_DESCRIPTOR(device) failed"); + dev_ = ctl_.data; + control(0x80, 6, 0x0200, 0, 9); // configuration header + return go(Step::GetConfig9); + + case Step::GetConfig9: { + if (ctl_.stalled || ctl_.data.size() < 9) + return fail("GET_DESCRIPTOR(configuration) failed"); + uint16_t total = ctl_.data[2] | ctl_.data[3] << 8; + control(0x80, 6, 0x0200, 0, total); + return go(Step::GetConfig); + } + + case Step::GetConfig: + if (ctl_.stalled || ctl_.data.size() < 9) + return fail("GET_DESCRIPTOR(configuration) failed"); + cfg_ = ctl_.data; + parse_config(); + control(0x80, 6, 0x0300, 0, 255); // string 0: languages + return go(Step::GetLangs); + + case Step::GetLangs: + vendor_ = product_ = serial_ = ""; + if (dev_[14]) { + control(0x80, 6, 0x0300 | dev_[14], 0x0409, 255); + return go(Step::GetVendor); + } + [[fallthrough]]; + case Step::GetVendor: + if (step_ == Step::GetVendor && !ctl_.stalled) + vendor_ = string_desc(ctl_.data); + if (dev_[15]) { + control(0x80, 6, 0x0300 | dev_[15], 0x0409, 255); + return go(Step::GetProduct); + } + [[fallthrough]]; + case Step::GetProduct: + if (step_ == Step::GetProduct && !ctl_.stalled) + product_ = string_desc(ctl_.data); + if (dev_[16]) { + control(0x80, 6, 0x0300 | dev_[16], 0x0409, 255); + return go(Step::GetSerial); + } + [[fallthrough]]; + case Step::GetSerial: + if (step_ == Step::GetSerial && !ctl_.stalled) + serial_ = string_desc(ctl_.data); + printf("[usb-host] high-speed device %04X:%04X \"%s\" \"%s\" serial " + "\"%s\", address %u\n", + dev_[8] | dev_[9] << 8, dev_[10] | dev_[11] << 8, vendor_.c_str(), + product_.c_str(), serial_.c_str(), dc_->address()); + printf("[usb-host] configuration %u: %s", cfg_value_, class_name()); + if (bulk_in_.addr) + printf(" (EP %02X IN, EP %02X OUT, %u-byte packets)", bulk_in_.addr, + bulk_out_.addr, bulk_in_.max_packet); + if (intr_in_.addr) + printf(" (EP %02X IN, interrupt every %u)", intr_in_.addr, + intr_in_.interval); + printf("\n"); + control(0x00, 9, cfg_value_, 0, 0); // SET_CONFIGURATION + return go(Step::SetConfig); + + case Step::SetConfig: + if (ctl_.stalled) + return fail("SET_CONFIGURATION stalled"); + wait_until_ = now_us() + kBindUs; + return go(Step::Bind); + + // ---- Mass storage ---- + + case Step::MscMaxLun: { + int luns = ctl_.stalled || ctl_.data.empty() ? 1 : ctl_.data[0] + 1; + printf("[usb-host] %d LUN%s\n", luns, luns == 1 ? "" : "s"); + uint8_t cdb[6] = {0x12, 0, 0, 0, 36, 0}; // INQUIRY + bot(cdb, 6, true, 36); + return go(Step::MscInquiry); + } + + case Step::MscInquiry: { + if (!bot_ok("INQUIRY")) + return; + std::string id; + for (size_t i = 8; i < 32 && i < bot_.data.size(); i++) + id += (bot_.data[i] >= 0x20 && bot_.data[i] < 0x7F) ? (char)bot_.data[i] + : ' '; + printf("[usb-host] LUN 0: \"%s\"%s\n", id.c_str(), + bot_.data.size() > 1 && (bot_.data[1] & 0x80) ? ", removable" : ""); + uint8_t cdb[6] = {0x00, 0, 0, 0, 0, 0}; // TEST UNIT READY + bot(cdb, 6, false, 0); + tur_tries_ = 0; + return go(Step::MscTur); + } + + case Step::MscTur: { + // A fresh device answers the first TEST UNIT READY with a unit + // attention; ask for the sense data and try again, as a PC does. + if (!bot_.stalled && bot_status() == 1 && ++tur_tries_ < 5) { + uint8_t cdb[6] = {0x03, 0, 0, 0, 18, 0}; // REQUEST SENSE + bot(cdb, 6, true, 18); + return go(Step::MscSense); + } + if (!bot_ok("TEST UNIT READY")) + return; + uint8_t cdb[10] = {0x25}; // READ CAPACITY(10) + bot(cdb, 10, true, 8); + return go(Step::MscCapacity); + } + + case Step::MscSense: { + if (!bot_ok("REQUEST SENSE")) + return; + if (bot_.data.size() >= 14) + printf("[usb-host] TEST UNIT READY: sense key %X, ASC %02X/%02X\n", + bot_.data[2] & 0xF, bot_.data[12], bot_.data[13]); + uint8_t cdb[6] = {0x00, 0, 0, 0, 0, 0}; + bot(cdb, 6, false, 0); + return go(Step::MscTur); + } + + case Step::MscCapacity: { + if (!bot_ok("READ CAPACITY")) + return; + if (bot_.data.size() < 8) + return fail("short READ CAPACITY"); + blocks_ = be32(&bot_.data[0]); + block_len_ = be32(&bot_.data[4]); + uint64_t bytes = ((uint64_t)blocks_ + 1) * block_len_; + printf("[usb-host] %u blocks of %u bytes (%llu MiB)\n", blocks_ + 1, + block_len_, (unsigned long long)(bytes >> 20)); + if (block_len_ != 512 || blocks_ < 72) + return fail("unexpected capacity"); + read10(0, 64); + return go(Step::MscReadFirst); + } + + case Step::MscReadFirst: + if (!bot_ok("READ(10)")) + return; + printf("[usb-host] read blocks 0-63 (crc32 %08X): %s\n", + crc32(bot_.data), compare_sd(0, bot_.data)); + read10(blocks_ - 7, 8); + return go(Step::MscReadLast); + + case Step::MscReadLast: { + if (!bot_ok("READ(10)")) + return; + printf("[usb-host] read blocks %u-%u (crc32 %08X): %s\n", blocks_ - 7, + blocks_, crc32(bot_.data), compare_sd(blocks_ - 7, bot_.data)); + uint8_t cdb[6] = {0x1E, 0, 0, 0, 0, 0}; // PREVENT ALLOW: allow + bot(cdb, 6, false, 0); + return go(Step::MscAllow); + } + + case Step::MscAllow: { + if (!bot_ok("PREVENT ALLOW MEDIUM REMOVAL")) + return; + uint8_t cdb[6] = {0x1B, 0, 0, 0, 0x02, 0}; // START STOP UNIT: eject + bot(cdb, 6, false, 0); + return go(Step::MscEject); + } + + case Step::MscEject: { + if (!bot_ok("START STOP UNIT")) + return; + printf("[usb-host] ejected; polling until the device lets go\n"); + eject_deadline_ = now_us() + 60000000; + wait_until_ = now_us() + kEjectPollUs; + deadline_ = eject_deadline_; + return go(Step::MscEjectWait); + } + + case Step::MscAfterEject: + // The gadget now reports the medium gone. Keep asking, as Linux does, + // until it detaches; the answer does not matter. + wait_until_ = now_us() + kEjectPollUs; + deadline_ = eject_deadline_; + return go(Step::MscEjectWait); + + // ---- HID ---- + + case Step::HidReport: + printf("[usb-host] HID report descriptor: %zu bytes%s\n", + ctl_.data.size(), ctl_.stalled ? " (stalled)" : ""); + control(0x21, 0x0A, 0, iface_, 0); // SET_IDLE + return go(Step::HidIdle); + + case Step::HidIdle: + // Idle rate 0: the device reports only when its input changes. + printf("[usb-host] SET_IDLE %s; polling EP %02X for reports\n", + ctl_.stalled ? "stalled" : "done", intr_in_.addr); + reports_ = 0; + deadline_ = now_us() + kTimeoutUs; + return go(Step::HidPoll); + + case Step::HidPoll: { + uint8_t buf[512]; + bool short_pkt = false; + int n = dc_->in(intr_in_.addr & 0xF, buf, + std::min(intr_in_.max_packet, sizeof(buf)), + &short_pkt); + if (n == XFER_NAK || n == XFER_STALL) + return; + if (reports_ < 3) { + printf("[usb-host] HID report %d:", reports_ + 1); + for (int i = 0; i < n && i < 16; i++) + printf(" %02X", buf[i]); + printf("\n"); + } + if (++reports_ == 3) + printf("[usb-host] HID reports arriving; polling on\n"); + progressed_ = true; + return; + } + + default: + return; + } + } +}; + +Host g_host; + +// ---- USB2 device controller (USB1 / OTG, 0x7D000000) ------------------------ +// +// The EHCI-derived device controller bdk's usbd.c drives (register layout in +// its usb_t210.h). Endpoint n has an OUT ("RX", bit n) and an IN ("TX", bit +// 16 + n) half, each with a 64-byte queue head at ENDPOINTLISTADDR + (2n + +// in) * 64 - bdk keeps them in the controller's own memory at +0x1000 - and +// a chain of transfer descriptors (dTDs) in DRAM: +// +// dTD +0 next dTD (bit 0 terminates) +// +4 token: bytes left (30:16), IOC (15), ACTIVE (7), HALTED (6) +// +8 five buffer page pointers +// dQH +0 capabilities +4 current dTD +8 next dTD +C token +// +28 the last SETUP packet +// +// Priming an endpoint (ENDPTPRIME) loads the first dTD and sets its bit in +// ENDPTSTATUS until the transfer retires; the host then moves the data +// through the dTD buffers, writes back what was left in each token, and sets +// the bit in ENDPTCOMPLETE. A SETUP lands in queue head 0 with ENDPTSETUPSTAT +// bit 0 set. The rest of the block - the UTMI PHY's registers at 0x400 and +// 0x800 - reads back what was written, bar PHY_CLK_VALID. + +constexpr uint32_t R_USBCMD = 0x130; +constexpr uint32_t R_USBSTS = 0x134; +constexpr uint32_t R_DEVICEADDR = 0x144; // PERIODICLISTBASE in device mode +constexpr uint32_t R_EPLISTADDR = 0x148; // ASYNCLISTADDR in device mode +constexpr uint32_t R_PORTSC1 = 0x174; +constexpr uint32_t R_HOSTPC1_DEVLC = 0x1B4; +constexpr uint32_t R_OTGSC = 0x1F4; +constexpr uint32_t R_USBMODE = 0x1F8; +constexpr uint32_t R_SETUPSTAT = 0x208; +constexpr uint32_t R_PRIME = 0x20C; +constexpr uint32_t R_FLUSH = 0x210; +constexpr uint32_t R_STATUS = 0x214; +constexpr uint32_t R_COMPLETE = 0x218; +constexpr uint32_t R_EPCTRL0 = 0x21C; +constexpr uint32_t R_SUSP_CTRL = 0x400; + +constexpr uint32_t USBCMD_RUN = 1u << 0, USBCMD_RESET = 1u << 1; +constexpr uint32_t USBSTS_UI = 1u << 0, USBSTS_PCI = 1u << 2, + USBSTS_URI = 1u << 6; +constexpr uint32_t PORTSC_CCS = 1u << 0, PORTSC_PE = 1u << 2, + PORTSC_HSP = 1u << 9; +constexpr uint32_t DEVLC_PHCD = 1u << 22, DEVLC_PSPD_HS = 2u << 25; +constexpr uint32_t EPCTRL_RX_STALL = 1u << 0, EPCTRL_RX_RESET = 1u << 6, + EPCTRL_RX_ENABLE = 1u << 7, EPCTRL_TX_STALL = 1u << 16, + EPCTRL_TX_RESET = 1u << 22, EPCTRL_TX_ENABLE = 1u << 23; +constexpr uint32_t SUSP_PHY_CLK_VALID = 1u << 7, SUSP_UTMIP_RESET = 1u << 11, + SUSP_UTMIP_PHY_ENB = 1u << 12; +constexpr uint32_t DTD_ACTIVE = 1u << 7, DTD_IOC = 1u << 15; + +class Usb2d : public UsbDc { +public: + Usb2d() { reset_controller(); } + + uint32_t read(uint32_t off) { + switch (off) { + case R_PORTSC1: + return connected_ ? (PORTSC_CCS | PORTSC_PE | PORTSC_HSP) : 0; + case R_HOSTPC1_DEVLC: + return (reg(off) & ~(3u << 25)) | (connected_ ? DEVLC_PSPD_HS : 0); + case R_SUSP_CTRL: { + uint32_t v = reg(off) & ~SUSP_PHY_CLK_VALID; + return phy_valid() ? v | SUSP_PHY_CLK_VALID : v; + } + default: + return reg(off); + } + } + + void write(uint32_t off, uint32_t val) { + switch (off) { + case R_USBCMD: + if (val & USBCMD_RESET) { + reset_controller(); + return; + } + reg(off) = val; + return; + case R_USBSTS: + case R_SETUPSTAT: + case R_COMPLETE: + reg(off) &= ~val; // write 1 to clear + return; + case R_OTGSC: + // Interrupt status (22:16) is write 1 to clear; the rest reads back. + reg(off) = (val & ~(0x7Fu << 16)) | (reg(off) & ~val & (0x7Fu << 16)); + return; + case R_PRIME: + prime(val); + return; + case R_FLUSH: + reg(R_STATUS) &= ~val; + reg(R_PRIME) &= ~val; + return; + case R_STATUS: + case R_PORTSC1: + return; // read-only here + default: + break; + } + if (off >= R_EPCTRL0 && off < R_EPCTRL0 + 16 * 4) { + // The data-toggle resets are strobes; endpoint 0 is always enabled. + val &= ~(EPCTRL_RX_RESET | EPCTRL_TX_RESET); + if (off == R_EPCTRL0) + val |= EPCTRL_RX_ENABLE | EPCTRL_TX_ENABLE; + reg(off) = val; + return; + } + if (off < kSize) + reg(off) = val; + } + + // USBCMD.RESET: the controller's registers (0x000-0x3FF) to their reset + // state; the PHY's and the queue head memory are not part of it. + void reset_controller() { + memset(regs_, 0, 0x400); + reg(R_EPCTRL0) = EPCTRL_RX_ENABLE | EPCTRL_TX_ENABLE; + connected_ = false; + } + + void full_reset() { + memset(regs_, 0, sizeof(regs_)); + reset_controller(); + } + + // ---- UsbDc ---- + + bool attached() override { + return (reg(R_USBMODE) & 3) == 2 && (reg(R_USBCMD) & USBCMD_RUN) && + phy_valid() && !(reg(R_HOSTPC1_DEVLC) & DEVLC_PHCD); + } + + void bus_reset() override { + connected_ = true; + reg(R_USBSTS) |= USBSTS_URI | USBSTS_PCI; + } + + bool reset_taken() override { return !(reg(R_USBSTS) & USBSTS_URI); } + + void setup(const uint8_t pkt[8]) override { + // A SETUP clears a stalled endpoint 0 and whatever was primed on it. + reg(R_EPCTRL0) &= ~(EPCTRL_RX_STALL | EPCTRL_TX_STALL); + reg(R_STATUS) &= ~(1u | 1u << 16); + uint64_t qh = qh_addr(0); + qh_write(qh + 0x28, pkt, 8); + reg(R_SETUPSTAT) |= 1; + reg(R_USBSTS) |= USBSTS_UI; + } + + bool setup_taken() override { return !(reg(R_SETUPSTAT) & 1); } + + int in(int ep, uint8_t *buf, int max, bool *short_pkt) override { + uint32_t bit = 1u << (16 + ep); + if (reg(R_EPCTRL0 + ep * 4) & EPCTRL_TX_STALL) + return XFER_STALL; + if (!(reg(R_STATUS) & bit)) + return XFER_NAK; + int moved = transfer(2 * ep + 1, buf, max, true); + *short_pkt = moved < max; + return moved; + } + + int out(int ep, const uint8_t *buf, int len) override { + uint32_t bit = 1u << ep; + if (reg(R_EPCTRL0 + ep * 4) & EPCTRL_RX_STALL) + return XFER_STALL; + if (!(reg(R_STATUS) & bit)) + return XFER_NAK; + return transfer(2 * ep, const_cast(buf), len, false); + } + + uint32_t address() override { return reg(R_DEVICEADDR) >> 25; } + + void detach() override { connected_ = false; } + +private: + static constexpr uint32_t kSize = 0x4000; + uint32_t regs_[kSize / 4] = {}; + bool connected_ = false; + + uint32_t ®(uint32_t off) { return regs_[(off & (kSize - 1)) / 4]; } + + bool phy_valid() { + uint32_t s = reg(R_SUSP_CTRL); + return (s & SUSP_UTMIP_PHY_ENB) && !(s & SUSP_UTMIP_RESET); + } + + // Queue heads live wherever ENDPOINTLISTADDR points: bdk uses the + // controller's own memory, but DRAM works the same way. + uint64_t qh_addr(int index) { return (uint64_t)reg(R_EPLISTADDR) + index * 64; } + + bool in_controller(uint64_t a) { + return a >= USB_OTG_BASE && a + 4 <= USB_OTG_BASE + kSize; + } + + uint32_t qh_read32(uint64_t a) { + if (in_controller(a)) + return reg((uint32_t)(a - USB_OTG_BASE)); + uint32_t v = 0; + mem_read(a, &v, 4); + return v; + } + + void qh_write32(uint64_t a, uint32_t v) { + if (in_controller(a)) + reg((uint32_t)(a - USB_OTG_BASE)) = v; + else + mem_write(a, &v, 4); + } + + void qh_write(uint64_t a, const uint8_t *p, int n) { + for (int i = 0; i < n; i += 4) { + uint32_t v = 0; + memcpy(&v, p + i, std::min(4, n - i)); + qh_write32(a + i, v); + } + } + + void prime(uint32_t mask) { + for (int bit = 0; bit < 32; bit++) { + if (!(mask & (1u << bit))) + continue; + int ep = bit & 15, in = bit >> 4; + uint64_t qh = qh_addr(2 * ep + in); + uint32_t next = qh_read32(qh + 8); + if (next & 1) + continue; // nothing queued + uint32_t dtd = next & ~0x1Fu; + uint32_t token = 0; + mem_read(dtd + 4, &token, 4); + qh_write32(qh + 4, dtd); + qh_write32(qh + 0xC, token); + reg(R_STATUS) |= 1u << bit; + } + reg(R_PRIME) = 0; // priming is instant + } + + // Move data through the primed dTD chain of queue head `index`: into buf + // for an IN endpoint, out of it for OUT. Each dTD it reaches retires with + // what it did not move left in its token. The transfer completes on a + // short dTD or at the end of the chain; if the data runs out exactly at a + // dTD boundary with more dTDs queued, the endpoint stays primed on the + // next one. A zero-length transfer retires the first dTD. + int transfer(int index, uint8_t *buf, int len, bool to_host) { + uint64_t qh = qh_addr(index); + uint32_t dtd = qh_read32(qh + 4) & ~0x1Fu; + UTRACE("ep %d %s: dTD @%08X, host %s %d bytes\n", index / 2, + to_host ? "IN" : "OUT", dtd, to_host ? "takes up to" : "sends", len); + int moved = 0; + bool ioc = false, primed_on = false; + uint32_t last = dtd, last_token = qh_read32(qh + 0xC), next = 1; + for (int guard = 0; guard < 64; guard++) { + uint32_t d[7] = {}; + if (!dtd || !mem_read(dtd, d, sizeof(d)) || !(d[1] & DTD_ACTIVE)) + break; + uint32_t size = (d[1] >> 16) & 0x7FFF; + uint32_t n = std::min(size, (uint32_t)(len - moved)); + // Page 0 carries the starting offset; pages 1-4 are 4 KiB frames. + uint32_t off0 = d[2] & 0xFFF; + for (uint32_t i = 0; i < n;) { + uint32_t pos = off0 + i; + if ((pos >> 12) > 4) + break; + uint32_t addr = (d[2 + (pos >> 12)] & ~0xFFFu) | (pos & 0xFFF); + uint32_t chunk = std::min(n - i, 0x1000 - (pos & 0xFFF)); + if (to_host) + mem_read(addr, buf + moved + i, chunk); + else + mem_write(addr, buf + moved + i, chunk); + i += chunk; + } + moved += (int)n; + uint32_t token = (d[1] & ~(0x7FFFu << 16) & ~DTD_ACTIVE) | + ((size - n) & 0x7FFF) << 16; + mem_write(dtd + 4, &token, 4); + ioc |= (d[1] & DTD_IOC) != 0; + last = dtd; + last_token = token; + next = d[0]; + if (n < size || (next & 1)) + break; // short, or the chain ended + dtd = next & ~0x1Fu; + if (moved == len) { + primed_on = true; // more queued, nothing to give + break; + } + } + if (primed_on) { + uint32_t token = 0; + mem_read(dtd + 4, &token, 4); + qh_write32(qh + 4, dtd); + qh_write32(qh + 8, dtd); + qh_write32(qh + 0xC, token); + return moved; + } + qh_write32(qh + 4, last); + qh_write32(qh + 8, next); + qh_write32(qh + 0xC, last_token); + uint32_t bit = index & 1 ? 1u << (16 + index / 2) : 1u << (index / 2); + reg(R_STATUS) &= ~bit; + reg(R_COMPLETE) |= bit; + if (ioc) + reg(R_USBSTS) |= USBSTS_UI; + return moved; + } +}; + +Usb2d g_usb2d; + +// ---- XUSB device controller (0x700D0000) ------------------------------------ +// +// The device side of an xHCI controller, as bdk's xusbd.c drives it on +// Mariko (register layout in usb_t210.h, TRB and context layouts in xusbd.c). +// Endpoints are numbered as device context indexes: 0 is the control +// endpoint, 2 and 3 bulk OUT and IN. Each has a context (16 words at ECP + +// 64 * index: word 2 holds its transfer ring's dequeue pointer and DCS) and a +// ring of 16-byte TRBs the driver fills - Data and Status TRBs on the control +// ring, Normal TRBs on the bulk ones, a Link TRB closing each ring - ringing +// the doorbell (DB) after each. The controller answers on the event ring: two +// segments (ERST0/ERST1, sizes in ERSTSZ) it fills at EREP, flipping its +// cycle bit on each pass, raising ST.IP; the driver consumes up to ERDP. It +// posts a Port Status Change event on a bus reset, a Setup event for each +// SETUP (with a sequence number the driver echoes on the doorbell), and a +// Transfer event, with the bytes left and SUCCESS or SHORT_PKT, for each TRB +// the host completes. EP_HALT halts endpoints (EP_STCHG reports the change), +// EP_RELOAD reloads a context. PORTSC's change bits are write 1 to clear, and +// a write with LWS sets the link state: the driver arms the port by moving it +// to RxDetect, which is when the host sees it attach. + +constexpr uint32_t X_DB = 0x04, X_ERSTSZ = 0x08, X_ERST0 = 0x10, X_ERST1 = 0x18, + X_ERDP = 0x20, X_EREP = 0x28, X_CTRL = 0x30, X_ST = 0x34, + X_PORTSC = 0x3C, X_ECP = 0x40, X_EP_HALT = 0x50, + X_EP_RELOAD = 0x58, X_EP_STCHG = 0x5C, X_EP_STOPPED = 0x78; +constexpr uint32_t XCTRL_ENABLE = 1u << 31; +constexpr uint32_t XST_RC = 1u << 0, XST_IP = 1u << 4; +constexpr uint32_t XPS_CCS = 1u << 0, XPS_PED = 1u << 1, XPS_PR = 1u << 4, + XPS_PLS_SHIFT = 5, XPS_PLS_MASK = 0xFu << 5, + XPS_PS_HS = 3u << 10, XPS_LWS = 1u << 16, + XPS_CHANGE = (1u << 17) | (1u << 19) | (0xFu << 20) | + (1u << 23), + XPS_CSC = 1u << 17, XPS_PRC = 1u << 21; +constexpr uint32_t PLS_U0 = 0, PLS_RXDETECT = 5; +constexpr uint32_t TRB_NORMAL = 1, TRB_DATA = 3, TRB_STATUS = 4, TRB_LINK = 6, + TRB_TRANSFER_EV = 32, TRB_PORT_EV = 34, TRB_SETUP_EV = 63; +constexpr uint32_t COMP_SUCCESS = 1, COMP_SHORT_PKT = 13; + +class Xusbd : public UsbDc { +public: + Xusbd() { reset_all(); } + + uint32_t read(uint32_t off) { return reg(off); } + + void write(uint32_t off, uint32_t val) { + switch (off) { + case X_DB: + UTRACE("doorbell %08X\n", val); + return; // TRBs are picked up when due + case X_ST: + reg(off) &= ~(val & (XST_RC | XST_IP)); + return; + case X_PORTSC: { + uint32_t v = reg(off) & ~(val & XPS_CHANGE); // write 1 to clear + if (val & XPS_LWS) { + v = (v & ~XPS_PLS_MASK) | (val & XPS_PLS_MASK); + armed_ = ((val & XPS_PLS_MASK) >> XPS_PLS_SHIFT) == PLS_RXDETECT; + } + reg(off) = v; + return; + } + case X_EP_HALT: + reg(X_EP_STCHG) |= reg(off) ^ val; // the halt state changed + reg(off) = val; + return; + case X_EP_STCHG: + case X_EP_STOPPED: + reg(off) &= ~val; + return; + case X_EP_RELOAD: + for (int i = 0; i < 4; i++) + if (val & (1u << i)) { + load_ring(i); + UTRACE("reload ep %d: ring %08X dcs %u\n", i, rings_[i].deq, + rings_[i].dcs); + } + return; // reads back 0: done + case X_ECP: + reg(off) = val; + load_ring(0); // the control endpoint's context + return; + case X_EREP: + reg(off) = val; + enq_ = val & ~0xFu; + ecs_ = val & 1; + return; + default: + if (off < kSize) + reg(off) = val; + return; + } + } + + void reset_all() { + memset(regs_, 0, sizeof(regs_)); + for (auto &r : rings_) + r = Ring(); + armed_ = connected_ = false; + enq_ = 0; + ecs_ = 1; + seq_ = 0; + } + + // ---- UsbDc ---- + + bool attached() override { return (reg(X_CTRL) & XCTRL_ENABLE) && armed_; } + + void bus_reset() override { + connected_ = true; + uint32_t ps = reg(X_PORTSC) & ~(XPS_PLS_MASK | (0xFu << 10) | XPS_PR); + reg(X_PORTSC) = ps | XPS_CCS | XPS_PED | XPS_PS_HS | + (PLS_U0 << XPS_PLS_SHIFT) | XPS_CSC | XPS_PRC; + post_event(0, 0, COMP_SUCCESS << 24, TRB_PORT_EV << 10); + } + + bool reset_taken() override { + return !(reg(X_PORTSC) & (XPS_CSC | XPS_PRC)); + } + + void setup(const uint8_t pkt[8]) override { + uint32_t lo, hi; + memcpy(&lo, pkt, 4); + memcpy(&hi, pkt + 4, 4); + reg(X_EP_HALT) &= ~1u; // a SETUP clears a stalled EP0 + post_event(lo, hi, (seq_++ & 0xFFFF) | COMP_SUCCESS << 24, + TRB_SETUP_EV << 10); + } + + // The Setup event is on the ring; the data and status stages wait on the + // TRBs the driver queues in answer. + bool setup_taken() override { return true; } + + int in(int ep, uint8_t *buf, int max, bool *short_pkt) override { + int n = transfer(ep ? 3 : 0, true, buf, max); + if (n >= 0) + *short_pkt = n < max; + return n; + } + + int out(int ep, const uint8_t *buf, int len) override { + return transfer(ep ? 2 : 0, false, const_cast(buf), len); + } + + uint32_t address() override { return (reg(X_CTRL) >> 24) & 0x7F; } + + void detach() override { connected_ = false; } + +private: + static constexpr uint32_t kSize = 0xA000; // XHCI regs, then PCI (+0x8000), DEV (+0x9000) + uint32_t regs_[kSize / 4] = {}; + bool armed_ = false, connected_ = false; + uint32_t enq_ = 0, ecs_ = 1, seq_ = 0; + + struct Ring { + uint32_t deq = 0; + uint32_t dcs = 0; + bool valid = false; + } rings_[4]; + + uint32_t ®(uint32_t off) { return regs_[(off % kSize) / 4]; } + + uint32_t ctx_addr(int dci) { return (reg(X_ECP) & ~0xFu) + dci * 64; } + + void load_ring(int dci) { + uint32_t w2 = 0; + if (!reg(X_ECP) || !mem_read(ctx_addr(dci) + 8, &w2, 4)) + return; + rings_[dci].deq = w2 & ~0xFu; + rings_[dci].dcs = w2 & 1; + rings_[dci].valid = rings_[dci].deq != 0; + } + + // Write an event at the enqueue pointer, with the producer cycle bit. + void post_event(uint32_t w0, uint32_t w1, uint32_t w2, uint32_t w3) { + if (!enq_) + return; + uint32_t trb[4] = {w0, w1, w2, (w3 & ~1u) | ecs_}; + mem_write(enq_, trb, sizeof(trb)); + uint32_t seg0 = reg(X_ERST0) & ~0xFu, seg1 = reg(X_ERST1) & ~0xFu; + uint32_t n0 = reg(X_ERSTSZ) & 0xFFFF, n1 = reg(X_ERSTSZ) >> 16; + enq_ += 16; + if (enq_ == seg0 + n0 * 16) { + enq_ = seg1; + } else if (enq_ == seg1 + n1 * 16) { + enq_ = seg0; + ecs_ ^= 1; + } + reg(X_EREP) = enq_ | ecs_; + reg(X_ST) |= XST_IP; + } + + // Complete the TRB at ring `dci`'s dequeue pointer: move data into buf (to + // the host) or out of it, post its Transfer event, advance. The TRB has to + // match: on the control ring a Data or Status TRB of this direction, on a + // bulk ring a Normal TRB. + int transfer(int dci, bool to_host, uint8_t *buf, int len) { + if (reg(X_EP_HALT) & (1u << dci)) + return XFER_STALL; + Ring &r = rings_[dci]; + if (!r.valid) + return XFER_NAK; + uint32_t t[4] = {}; + for (int guard = 0; guard < 4; guard++) { + if (!mem_read(r.deq, t, sizeof(t)) || (t[3] & 1) != r.dcs) + return XFER_NAK; + if (((t[3] >> 10) & 0x3F) != TRB_LINK) + break; + if (t[3] & 2) // toggle cycle + r.dcs ^= 1; + r.deq = t[0] & ~0xFu; + } + uint32_t type = (t[3] >> 10) & 0x3F; + bool dir_in = (t[3] >> 16) & 1; + UTRACE("ep %d %s: TRB @%08X type %u dir %u len %u\n", dci, + to_host ? "IN" : "OUT", r.deq, type, dir_in, t[2] & 0x1FFFF); + if (dci == 0 ? !((type == TRB_DATA || type == TRB_STATUS) && dir_in == to_host) + : type != TRB_NORMAL) + return XFER_NAK; + uint32_t size = type == TRB_STATUS ? 0 : t[2] & 0x1FFFF; + uint32_t n = std::min(size, (uint32_t)std::max(len, 0)); + if (n) { + if (to_host) + mem_read(t[0], buf, n); + else + mem_write(t[0], buf, n); + } + uint32_t left = size - n; + post_event(r.deq, 0, left | (left ? COMP_SHORT_PKT : COMP_SUCCESS) << 24, + TRB_TRANSFER_EV << 10 | (uint32_t)dci << 16); + r.deq += 16; + // Keep the context's dequeue pointer current, as the controller does. + uint32_t w2 = r.deq | r.dcs; + mem_write(ctx_addr(dci) + 8, &w2, 4); + return (int)n; + } +}; + +Xusbd g_xusbd; + +} // namespace + +// ---- Bus interface ---------------------------------------------------------- + +// bdk copies SETUP packets out of the queue heads with memcpy() and clears +// them with memset(), so byte and halfword accesses are real: a narrow read +// returns its lanes of the word, and a narrow write to the queue head memory +// merges into it. Registers take a narrow write shifted into place. +uint32_t usb2d_read(EmuState *state, uint64_t addr, unsigned size) { + g_state = state; + g_host.set_controllers(&g_usb2d, &g_xusbd); + g_host.run(); + uint32_t off = (uint32_t)(addr - USB_OTG_BASE); + uint32_t v = g_usb2d.read(off & ~3u); + return size < 4 ? v >> ((off & 3) * 8) : v; +} + +void usb2d_write(EmuState *state, uint64_t addr, unsigned size, uint32_t val) { + g_state = state; + g_host.set_controllers(&g_usb2d, &g_xusbd); + uint32_t off = (uint32_t)(addr - USB_OTG_BASE); + if (size < 4) { + uint32_t shift = (off & 3) * 8; + uint32_t mask = (size == 1 ? 0xFFu : 0xFFFFu) << shift; + val = (val << shift) & mask; + if (off >= 0x1000) + val |= g_usb2d.read(off & ~3u) & ~mask; + } + g_usb2d.write(off & ~3u, val); + g_host.run(); +} + +uint32_t xusbd_read(EmuState *state, uint64_t addr, unsigned size) { + g_state = state; + g_host.set_controllers(&g_usb2d, &g_xusbd); + g_host.run(); + uint32_t off = (uint32_t)(addr - XUSB_DEV_BASE); + uint32_t v = g_xusbd.read(off & ~3u); + return size < 4 ? v >> ((off & 3) * 8) : v; +} + +void xusbd_write(EmuState *state, uint64_t addr, unsigned size, uint32_t val) { + g_state = state; + g_host.set_controllers(&g_usb2d, &g_xusbd); + uint32_t off = (uint32_t)(addr - XUSB_DEV_BASE); + if (size < 4) { + uint32_t shift = (off & 3) * 8; + uint32_t mask = (size == 1 ? 0xFFu : 0xFFFFu) << shift; + val = ((val << shift) & mask) | (g_xusbd.read(off & ~3u) & ~mask); + } + g_xusbd.write(off & ~3u, val); + g_host.run(); +} + +void usb_reset(EmuState *state) { + g_state = state; + g_usb2d.full_reset(); + g_xusbd.reset_all(); + g_host.reset(); +} diff --git a/t210/usb.h b/t210/usb.h new file mode 100644 index 0000000..112a632 --- /dev/null +++ b/t210/usb.h @@ -0,0 +1,18 @@ +#pragma once + +#include + +struct EmuState; + +// USB device mode (see usb.cpp): the Erista USB2 device controller, and the +// PC a --usb-host run plugs into it. +uint32_t usb2d_read(EmuState *state, uint64_t addr, unsigned size); +void usb2d_write(EmuState *state, uint64_t addr, unsigned size, uint32_t val); + +// The Mariko XUSB device controller (XHCI registers, PCI config at +0x8000, +// the device block at +0x9000). +uint32_t xusbd_read(EmuState *state, uint64_t addr, unsigned size); +void xusbd_write(EmuState *state, uint64_t addr, unsigned size, uint32_t val); + +// SoC reset: the controller back to its reset state, the host unplugged. +void usb_reset(EmuState *state); diff --git a/tests/usb/link.ld b/tests/usb/link.ld new file mode 100644 index 0000000..bdc1203 --- /dev/null +++ b/tests/usb/link.ld @@ -0,0 +1,10 @@ +/* Loaded and entered at 0x40010000, like any RCM payload. */ +ENTRY(_start) +SECTIONS { + . = 0x40010000; + .text : { KEEP(*(.text.start)) *(.text*) } + .rodata : { *(.rodata*) } + .data : { *(.data*) } + .bss : { *(.bss*) *(COMMON) } + /DISCARD/ : { *(.comment) *(.note*) *(.ARM.attributes) *(.ARM.exidx*) } +} diff --git a/tests/usb/payload.c b/tests/usb/payload.c new file mode 100644 index 0000000..bb7d42b --- /dev/null +++ b/tests/usb/payload.c @@ -0,0 +1,613 @@ +/* + * USB device mode regression payload. + * + * A freestanding BPMP payload that brings up a small USB mass storage gadget + * - one LUN, a 128-block RAM disk - on one of the two device controllers, + * with the register sequences bdk's drivers use, and serves whatever the + * emulator's --usb-host PC asks. Built once per scenario with -DSCENARIO=n: + * + * 1 the USB2 controller USB1 (bdk usbd.c, Erista): queue heads in the + * controller at +0x1000, transfer descriptors in DRAM + * 2 the XUSB device controller (bdk xusbd.c, Mariko): event ring, + * transfer rings and endpoint contexts in IRAM + * 3 the USB2 controller again, as a HID gadget: after the report + * descriptor and SET_IDLE it sends three interrupt IN reports + * + * Either way the gadget answers the standard requests and GET_MAX_LUN, then + * the Bulk-Only Transport: INQUIRY, TEST UNIT READY, REQUEST SENSE, READ + * CAPACITY, READ(10), PREVENT ALLOW MEDIUM REMOVAL and START STOP UNIT. When + * the host ejects, it stops the controller and powers off. It prints the + * CRC32 of the disk ranges the host reads, which tests/usb/run.sh compares + * with what the host logs. Run without --usb-host, scenario 1 sees no bus + * reset and says so. + */ + +#ifndef SCENARIO +#define SCENARIO 1 +#endif + +typedef unsigned int u32; +typedef unsigned short u16; +typedef unsigned char u8; + +#define REG(a) (*(volatile u32 *)(a)) +#define B(a) (*(volatile u8 *)(a)) + +#define TIMERUS 0x60005010u +#define UARTB_THR 0x70006040u +#define I2C5 0x7000D000u + +#define DISK 0xC0000000u /* 128 blocks of 512 bytes */ +#define DISK_LBAS 128u +#define EP0BUF 0xC0110000u +#define CMDBUF 0xC0111000u /* CBW / CSW / small replies */ + +static void putc_(char c) { REG(UARTB_THR) = (u32)(unsigned char)c; } + +static void puts_(const char *s) { + while (*s) + putc_(*s++); +} + +static void puthex(u32 v) { + for (int i = 28; i >= 0; i -= 4) + putc_("0123456789ABCDEF"[(v >> i) & 0xF]); +} + +static void i2c5_write(u32 dev, u32 reg, u32 val) { + REG(I2C5 + 0x04) = dev << 1; + REG(I2C5 + 0x0C) = reg | (val << 8); + REG(I2C5 + 0x00) = (1u << 1) | (1u << 9); +} + +static __attribute__((noreturn)) void finish(const char *msg) { + puts_(msg); + i2c5_write(0x3C, 0x41, 0x02); /* MAX77620 ONOFFCNFG1: PWR_OFF */ + for (;;) + ; +} + +static void copy(u32 dst, const u8 *src, u32 n) { + for (u32 i = 0; i < n; i++) + B(dst + i) = src[i]; +} + +#if SCENARIO != 3 +static void zero(u32 dst, u32 n) { + for (u32 i = 0; i < n; i += 4) + REG(dst + i) = 0; +} +#endif + +static u32 crc32(u32 addr, u32 n) { + u32 c = 0xFFFFFFFFu; + for (u32 i = 0; i < n; i++) { + c ^= B(addr + i); + for (int k = 0; k < 8; k++) + c = (c >> 1) ^ (0xEDB88320u & (0u - (c & 1))); + } + return ~c; +} + +/* ---- Descriptors --------------------------------------------------------- */ + +static const u8 dev_desc[18] = { + 18, 1, 0x00, 0x02, 0, 0, 0, 64, + 0x09, 0x12, 0x57, 0x7E, /* 1209:7E57 */ + 0x00, 0x01, 1, 2, 3, 1, +}; + +#if SCENARIO == 3 +static const u8 hid_report[21] = { + 0x06, 0x00, 0xFF, 0x09, 0x01, 0xA1, 0x01, /* vendor page, application */ + 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x08, + 0x09, 0x01, 0x81, 0x02, 0xC0, /* 8 bytes of input */ +}; + +static const u8 cfg_desc[34] = { + 9, 2, 34, 0, 1, 1, 0, 0x80, 50, + 9, 4, 0, 0, 1, 0x03, 0x00, 0x00, 0, /* HID */ + 9, 0x21, 0x11, 0x01, 0, 1, 0x22, 21, 0, /* HID descriptor */ + 7, 5, 0x81, 3, 8, 0, 4, /* interrupt IN, 8 bytes */ +}; +#else +static const u8 cfg_desc[32] = { + 9, 2, 32, 0, 1, 1, 0, 0x80, 50, + 9, 4, 0, 0, 2, 0x08, 0x06, 0x50, 0, /* mass storage, SCSI, BOT */ + 7, 5, 0x81, 2, 0x00, 0x02, 0, /* bulk IN, 512 */ + 7, 5, 0x01, 2, 0x00, 0x02, 0, /* bulk OUT, 512 */ +}; +#endif + +static const u8 str_lang[4] = {4, 3, 0x09, 0x04}; +static const char *const strs[3] = {"RCM-Emulator", "USB test disk", "0001"}; + +#if SCENARIO != 3 +static const u8 inquiry[36] = { + 0x00, 0x80, 0x02, 0x02, 31, 0, 0, 0, + 'R', 'C', 'M', 'E', 'M', 'U', ' ', ' ', + 'T', 'e', 's', 't', ' ', 'd', 'i', 's', 'k', ' ', ' ', ' ', ' ', ' ', ' ', ' ', + '1', '.', '0', '0', +}; +#endif + +/* ---- Transport ------------------------------------------------------------ */ +/* + * What the gadget needs from a controller: + * poll_setup(pkt) a SETUP packet, if one came (1) or not (0) + * ep0_in(len) send EP0BUF[0..len), then the status stage + * ep0_status() a no-data request's status stage + * ep0_stall() reject the request + * set_address(a) after its status stage + * configure() bring up the bulk endpoints + * bulk(in, buf, len) one bulk transfer; returns bytes moved + * stop() detach + */ + +#if SCENARIO != 2 +/* ---- USB2 controller USB1 (bdk usbd.c) ---- */ + +#define USB 0x7D000000u +#define U(o) REG(USB + (o)) +#define USBCMD 0x130 +#define USBSTS 0x134 +#define DEVADDR 0x144 +#define EPLIST 0x148 +#define USBMODE 0x1F8 +#define SETUPST 0x208 +#define PRIME 0x20C +#define FLUSH 0x210 +#define STATUS 0x214 +#define COMPL 0x218 +#define EPCTRL(n) (0x21C + 4 * (n)) +#define SUSP 0x400 +#define QHB (USB + 0x1000) +#define QH(i) (QHB + 64 * (i)) +#define DTD 0xC0100000u /* 4 dTDs per queue head, 32 bytes each */ + +static void init(void) { + U(SUSP) |= (1u << 12) | (1u << 11); /* UTMIP_PHY_ENB, UTMIP_RESET */ + U(SUSP) &= ~(1u << 11); + while (!(U(SUSP) & (1u << 7))) /* PHY_CLK_VALID */ + ; + U(USBCMD) |= 1u << 1; /* RESET */ + while (U(USBCMD) & (1u << 1)) + ; + U(USBMODE) = 2; /* device */ + for (u32 i = 0; i < 4; i++) { + for (u32 w = 0; w < 16; w++) + REG(QH(i) + 4 * w) = 0; + REG(QH(i) + 8) = 1; /* no dTD */ + } + REG(QH(0)) = 64u << 16 | 1u << 15; /* EP0 OUT: 64, IOS */ + REG(QH(1)) = 64u << 16; + U(EPLIST) = QHB; + U(USBCMD) |= 1; /* RUN: attach */ +} + +/* One transfer on queue head idx (2 * ep + in), in up to four 16 KiB dTDs as + * bdk builds them. Returns the bytes moved, or -1 if it never completed. */ +static int xfer(u32 idx, u32 buf, u32 len) { + u32 base = DTD + idx * 4 * 32, off = 0, n = 0; + do { + u32 d = base + n * 32, sz = len - off > 16384 ? 16384 : len - off; + REG(d) = 1; + REG(d + 4) = sz << 16 | 0x80; /* bytes, ACTIVE */ + for (u32 p = 0; p < 5; p++) + REG(d + 8 + 4 * p) = buf ? buf + off + 4096 * p : 0; + if (n) + REG(base + (n - 1) * 32) = d; + off += sz; + n++; + } while (off < len && n < 4); + REG(QH(idx) + 8) = base; + REG(QH(idx) + 0xC) = 0; + u32 bit = idx & 1 ? 1u << (16 + idx / 2) : 1u << (idx / 2); + U(PRIME) = bit; + u32 start = REG(TIMERUS); + while ((U(PRIME) | U(STATUS)) & bit) + if (REG(TIMERUS) - start > 5000000) + return -1; + U(COMPL) = bit; + u32 left = 0; + for (u32 i = 0; i < n; i++) + left += (REG(base + i * 32 + 4) >> 16) & 0x7FFF; + return (int)(len - left); +} + +static int poll_setup(u8 *pkt) { + u32 sts = U(USBSTS); + U(USBSTS) = sts; + if (sts & (1u << 6)) { /* bus reset */ + U(DEVADDR) = 0; + U(SETUPST) = U(SETUPST); + U(COMPL) = U(COMPL); + U(FLUSH) = 0xFFFFFFFFu; + } + if (!(U(SETUPST) & 1)) + return 0; + U(SETUPST) = 1; + u32 lo = REG(QH(0) + 0x28), hi = REG(QH(0) + 0x2C); + for (int i = 0; i < 4; i++) { + pkt[i] = lo >> (8 * i); + pkt[4 + i] = hi >> (8 * i); + } + return 1; +} + +static void ep0_in(u32 len) { + xfer(1, EP0BUF, len); + xfer(0, 0, 0); +} + +static void ep0_status(void) { xfer(1, 0, 0); } + +static void ep0_stall(void) { U(EPCTRL(0)) |= 1u | 1u << 16; } + +static void set_address(u32 a) { U(DEVADDR) = a << 25; } + +static void configure(void) { + for (u32 i = 2; i < 4; i++) { + for (u32 w = 0; w < 16; w++) + REG(QH(i) + 4 * w) = 0; + REG(QH(i)) = 512u << 16; + REG(QH(i) + 8) = 1; + } + U(EPCTRL(1)) = 2u << 2 | 1u << 7 | 2u << 18 | 1u << 23; /* bulk RX/TX on */ +} + +static int bulk(int in, u32 buf, u32 len) { return xfer(in ? 3 : 2, buf, len); } + +static void stop(void) { + U(USBCMD) &= ~1u; + (void)U(USBCMD); /* let the host see it go */ +} + +/* Without a host nothing resets the bus: say so after half a second. */ +static int bus_reset_seen(void) { + u32 start = REG(TIMERUS); + while (REG(TIMERUS) - start < 500000) + if (U(USBSTS) & (1u << 6)) + return 1; + return 0; +} + +#else +/* ---- XUSB device controller (bdk xusbd.c) ---- */ + +#define XU 0x700D0000u +#define X(o) REG(XU + (o)) +#define X_DB 0x04 +#define X_ERSTSZ 0x08 +#define X_ERST0 0x10 +#define X_ERST1 0x18 +#define X_ERDP 0x20 +#define X_EREP 0x28 +#define X_CTRL 0x30 +#define X_ST 0x34 +#define X_IMOD 0x38 +#define X_PORTSC 0x3C +#define X_ECP 0x40 +#define X_HALT 0x50 +#define X_RELOAD 0x58 + +#define XMEM 0x40030000u +#define SEG0 (XMEM) +#define SEG1 (XMEM + 0x100) +#define CTX (XMEM + 0x500) /* four 64-byte endpoint contexts */ + +struct ring { u32 base, idx, pcs; }; +static struct ring rings[4]; /* by context index: 0 control, 2 OUT, 3 IN */ +static u32 evt_deq, ccs, seq; + +static void ring_init(u32 dci, u32 base) { + struct ring *r = &rings[dci]; + r->base = base; + r->idx = 0; + r->pcs = 1; + zero(base, 16 * 16); + REG(base + 15 * 16) = base; /* Link TRB back to the start */ + REG(base + 15 * 16 + 12) = 6u << 10 | 2; /* type LINK, toggle cycle */ + u32 ctx = CTX + 64 * dci; + zero(ctx, 64); + REG(ctx) = 1; /* EP_RUNNING */ + REG(ctx + 8) = base | 1; /* dequeue pointer, DCS */ +} + +static void queue(u32 dci, u32 w0, u32 w2, u32 w3) { + struct ring *r = &rings[dci]; + u32 t = r->base + r->idx * 16; + REG(t) = w0; + REG(t + 4) = 0; + REG(t + 8) = w2; + REG(t + 12) = w3 | r->pcs; + if (++r->idx == 15) { + REG(r->base + 15 * 16 + 12) = 6u << 10 | 2 | r->pcs; + r->idx = 0; + r->pcs ^= 1; + } + X(X_DB) = dci << 8 | (dci ? 0 : seq << 16); +} + +static void init(void) { + zero(XMEM, 0x600); + X(X_ERST0) = SEG0; + X(X_ERST1) = SEG1; + X(X_ERSTSZ) = 16u << 16 | 16; + X(X_EREP) = SEG0 | 1; + X(X_ERDP) = SEG0; + evt_deq = SEG0; + ccs = 1; + ring_init(0, XMEM + 0x200); + X(X_CTRL) |= 1u << 4 | 1u << 1; /* IE, LSE */ + X(X_ECP) = CTX; + X(X_IMOD) = 0; + X(X_PORTSC) = (X(X_PORTSC) & ~(0xFu << 5)) | 1u << 16 | 5u << 5; /* RxDetect */ + X(X_CTRL) |= 1u << 31; /* ENABLE */ +} + +/* The next event, if any. Polling ST lets the host run. */ +static int next_event(u32 *ev) { + (void)X(X_ST); + if ((REG(evt_deq + 12) & 1) != ccs) + return 0; + for (int i = 0; i < 4; i++) + ev[i] = REG(evt_deq + 4 * i); + if (evt_deq == SEG0 + 15 * 16) + evt_deq = SEG1; + else if (evt_deq == SEG1 + 15 * 16) { + evt_deq = SEG0; + ccs ^= 1; + } else + evt_deq += 16; + X(X_ERDP) = evt_deq; + X(X_ST) = 1u << 4; /* IP, write 1 to clear */ + return 1; +} + +static void port_change(void) { + u32 ps = X(X_PORTSC); + X(X_PORTSC) = ps; /* write the change bits back */ +} + +/* Wait for the Transfer event of endpoint dci; the bytes it left over. */ +static int wait_xfer(u32 dci) { + u32 ev[4], start = REG(TIMERUS); + for (;;) { + if (REG(TIMERUS) - start > 5000000) + return -1; + if (!next_event(ev)) + continue; + u32 type = ev[3] >> 10 & 0x3F; + if (type == 34) + port_change(); + else if (type == 32 && (ev[3] >> 16 & 0x1F) == dci) + return (int)(ev[2] & 0xFFFFFF); + } +} + +static int poll_setup(u8 *pkt) { + u32 ev[4]; + if (!next_event(ev)) + return 0; + u32 type = ev[3] >> 10 & 0x3F; + if (type == 34) { + port_change(); + return 0; + } + if (type != 63) + return 0; + for (int i = 0; i < 4; i++) { + pkt[i] = ev[0] >> (8 * i); + pkt[4 + i] = ev[1] >> (8 * i); + } + seq = ev[2] & 0xFFFF; + return 1; +} + +static void ep0_in(u32 len) { + queue(0, EP0BUF, len, 3u << 10 | 1u << 16 | 1u << 5); /* Data IN, IOC */ + wait_xfer(0); + queue(0, 0, 0, 4u << 10 | 1u << 5); /* Status OUT */ + wait_xfer(0); +} + +static void ep0_status(void) { + queue(0, 0, 0, 4u << 10 | 1u << 16 | 1u << 5); /* Status IN */ + wait_xfer(0); +} + +static void ep0_stall(void) { X(X_HALT) |= 1; } + +static void set_address(u32 a) { X(X_CTRL) = (X(X_CTRL) & 0x80FFFFFFu) | a << 24; } + +static void configure(void) { + ring_init(2, XMEM + 0x300); + ring_init(3, XMEM + 0x400); + X(X_RELOAD) = 0xC; + while (X(X_RELOAD) & 0xC) + ; + X(X_HALT) &= ~0xCu; + X(X_CTRL) |= 1; /* RUN */ +} + +static int bulk(int in, u32 buf, u32 len) { + u32 dci = in ? 3 : 2; + queue(dci, buf, len, 1u << 10 | 1u << 5 | 1u << 2); /* Normal, IOC, ISP */ + int left = wait_xfer(dci); + return left < 0 ? -1 : (int)(len - left); +} + +static void stop(void) { + X(X_CTRL) = 0; + (void)X(X_CTRL); +} + +static int bus_reset_seen(void) { return 1; } + +#endif + +/* ---- The gadget ----------------------------------------------------------- */ + +static int configured, lun_asked, report_asked, idle_set; + +static void control(const u8 *p) { + u32 bm = p[0], req = p[1], val = p[2] | p[3] << 8, len = p[6] | p[7] << 8; + u32 n = 0; + if (bm == 0x80 && req == 6) { /* GET_DESCRIPTOR */ + u32 type = val >> 8, idx = val & 0xFF; + if (type == 1) { + copy(EP0BUF, dev_desc, n = 18); + } else if (type == 2) { + copy(EP0BUF, cfg_desc, n = sizeof(cfg_desc)); + } else if (type == 3 && idx == 0) { + copy(EP0BUF, str_lang, n = 4); + } else if (type == 3 && idx <= 3) { + const char *s = strs[idx - 1]; + n = 2; + while (*s) { + B(EP0BUF + n) = *s++; + B(EP0BUF + n + 1) = 0; + n += 2; + } + B(EP0BUF) = n; + B(EP0BUF + 1) = 3; + } else { + ep0_stall(); + return; + } + ep0_in(n < len ? n : len); + } else if (bm == 0x00 && req == 5) { /* SET_ADDRESS */ + ep0_status(); + set_address(val & 0x7F); + } else if (bm == 0x00 && req == 9) { /* SET_CONFIGURATION */ + configure(); + ep0_status(); + configured = 1; + puts_("usb test: configured\n"); + } else if (bm == 0xA1 && req == 0xFE) { /* GET_MAX_LUN */ + B(EP0BUF) = 0; + ep0_in(1); + lun_asked = 1; +#if SCENARIO == 3 + } else if (bm == 0x81 && req == 6 && (val >> 8) == 0x22) { /* HID report */ + copy(EP0BUF, hid_report, n = sizeof(hid_report)); + ep0_in(n < len ? n : len); + report_asked = 1; + } else if (bm == 0x21 && req == 0x0A) { /* SET_IDLE */ + ep0_status(); + idle_set = 1; +#endif + } else { + ep0_stall(); + } +} + +#if SCENARIO != 3 +static void put_be32(u32 a, u32 v) { + B(a) = v >> 24; + B(a + 1) = v >> 16; + B(a + 2) = v >> 8; + B(a + 3) = v; +} + +/* Serve Bulk-Only Transport commands until the host ejects the disk. */ +static void bot(void) { + u32 sense = 6, asc = 0x29; /* a unit attention first, like a real disk */ + for (;;) { + int n = bulk(0, CMDBUF, 512); + if (n != 31 || REG(CMDBUF) != 0x43425355u) /* "USBC" */ + finish("usb test: FAIL bad CBW\n"); + u32 tag = REG(CMDBUF + 4), want = REG(CMDBUF + 8); + u8 op = B(CMDBUF + 15); + u32 cdb = CMDBUF + 15, status = 0, sent = 0, eject = 0; + switch (op) { + case 0x12: /* INQUIRY */ + copy(CMDBUF + 0x100, inquiry, 36); + sent = bulk(1, CMDBUF + 0x100, want < 36 ? want : 36); + break; + case 0x00: /* TEST UNIT READY */ + status = sense ? 1 : 0; + break; + case 0x03: /* REQUEST SENSE */ + zero(CMDBUF + 0x100, 20); + B(CMDBUF + 0x100) = 0x70; + B(CMDBUF + 0x102) = sense; + B(CMDBUF + 0x107) = 10; + B(CMDBUF + 0x10C) = asc; + sense = asc = 0; + sent = bulk(1, CMDBUF + 0x100, want < 18 ? want : 18); + break; + case 0x25: /* READ CAPACITY(10) */ + put_be32(CMDBUF + 0x100, DISK_LBAS - 1); + put_be32(CMDBUF + 0x104, 512); + sent = bulk(1, CMDBUF + 0x100, 8); + break; + case 0x28: { /* READ(10) */ + u32 lba = (u32)B(cdb + 2) << 24 | B(cdb + 3) << 16 | B(cdb + 4) << 8 | + B(cdb + 5); + u32 cnt = B(cdb + 7) << 8 | B(cdb + 8); + if (lba + cnt > DISK_LBAS) + status = 1; + else + sent = bulk(1, DISK + lba * 512, cnt * 512); + break; + } + case 0x1E: /* PREVENT ALLOW MEDIUM REMOVAL */ + break; + case 0x1B: /* START STOP UNIT */ + eject = B(cdb + 4) & 2; + break; + default: + status = 1; + break; + } + REG(CMDBUF + 0x200) = 0x53425355u; /* "USBS" */ + REG(CMDBUF + 0x204) = tag; + REG(CMDBUF + 0x208) = want - sent; + B(CMDBUF + 0x20C) = status; + bulk(1, CMDBUF + 0x200, 13); + if (eject) + return; + } +} +#endif + +__attribute__((section(".text.start"), noreturn)) +void _start(void) { + for (u32 i = 0; i < DISK_LBAS * 512; i++) + B(DISK + i) = (u8)((i * 7) ^ (i >> 9)); + puts_("usb test: disk crc32 first "); + puthex(crc32(DISK, 64 * 512)); + puts_(" last "); + puthex(crc32(DISK + (DISK_LBAS - 8) * 512, 8 * 512)); + putc_('\n'); + + init(); + if (!bus_reset_seen()) { + stop(); + finish("usb test: no bus reset, nothing on the cable\n"); + } + u8 pkt[8]; + u32 start = REG(TIMERUS); + while (!(configured && (SCENARIO == 3 ? report_asked && idle_set : lun_asked))) { + if (poll_setup(pkt)) + control(pkt); + if (REG(TIMERUS) - start > 10000000) + finish("usb test: FAIL enumeration timed out\n"); + } +#if SCENARIO == 3 + for (u32 k = 1; k <= 3; k++) { + for (u32 i = 0; i < 8; i++) + B(CMDBUF + i) = (u8)(k * 0x10 + i); + if (bulk(1, CMDBUF, 8) != 8) + finish("usb test: FAIL report not taken\n"); + } + puts_("usb test: hid reports sent\n"); +#else + bot(); + puts_("usb test: ejected\n"); +#endif + stop(); + finish("usb test: done\n"); +} diff --git a/tests/usb/run.sh b/tests/usb/run.sh new file mode 100755 index 0000000..48a1182 --- /dev/null +++ b/tests/usb/run.sh @@ -0,0 +1,72 @@ +#!/bin/sh +# USB device mode regression test: tests/usb/payload.c brings up a mass +# storage gadget on each device controller and the emulator's --usb-host PC +# enumerates it, reads it back and ejects it; without a host the gadget must +# see nothing on the cable. Usage: tests/usb/run.sh [rcm_emu] [payload dir] +EMU=${1:-./rcm_emu} +DIR=${2:-tests/usb} +fail=0 + +run() { + log=$DIR/out_$1.log + shift + SDL_VIDEODRIVER=dummy RCM_EMU_NO_AUDIO=1 timeout 60 "$EMU" "$@" > "$log" 2>&1 + echo $? +} + +expect() { + if grep -q -- "$2" "$1"; then + echo " ok $3" + else + echo " FAIL $3 (missing: $2)" + fail=1 + fi +} + +check_host() { + log=$1 + name=$2 + expect "$log" '\[usb-host\] device attached' "$name: the host sees the device attach" + expect "$log" 'high-speed device 1209:7E57 "RCM-Emulator" "USB test disk" serial "0001", address 1' \ + "$name: enumerated, strings read, address set" + expect "$log" 'configuration 1: mass storage, bulk-only (EP 81 IN, EP 01 OUT, 512-byte packets)' \ + "$name: configuration parsed" + expect "$log" 'LUN 0: "RCMEMU Test disk ", removable' "$name: INQUIRY" + expect "$log" 'TEST UNIT READY: sense key 6, ASC 29/00' "$name: unit attention, then REQUEST SENSE" + expect "$log" '128 blocks of 512 bytes' "$name: READ CAPACITY" + first=$(sed -n 's/.*disk crc32 first \([0-9A-F]*\) last.*/\1/p' "$log") + last=$(sed -n 's/.*disk crc32 first [0-9A-F]* last \([0-9A-F]*\).*/\1/p' "$log") + expect "$log" "read blocks 0-63 (crc32 $first)" "$name: READ(10) of blocks 0-63 returns the disk" + expect "$log" "read blocks 120-127 (crc32 $last)" "$name: READ(10) of the last 8 blocks returns the disk" + expect "$log" 'usb test: ejected' "$name: START STOP UNIT ejects" + expect "$log" '\[usb-host\] device detached' "$name: the host sees the device go" + expect "$log" 'usb test: done' "$name: the payload ran to its end" +} + +echo "usb test:" +st=$(run 1 "$DIR/payload_1.bin" --usb-host) +check_host "$DIR/out_1.log" "USB2 controller" +[ "$st" -eq 0 ] || { echo " FAIL USB2 controller: emulator exit $st"; fail=1; } + +st=$(run 2 "$DIR/payload_2.bin" --usb-host --oem mariko) +check_host "$DIR/out_2.log" "XUSB controller" +[ "$st" -eq 0 ] || { echo " FAIL XUSB controller: emulator exit $st"; fail=1; } + +st=$(run 3 "$DIR/payload_3.bin" --usb-host) +log=$DIR/out_3.log +expect "$log" 'configuration 1: HID (EP 81 IN, interrupt every 4)' "HID gadget: configuration parsed" +expect "$log" 'HID report descriptor: 21 bytes' "HID gadget: report descriptor read" +expect "$log" 'SET_IDLE done; polling EP 81 for reports' "HID gadget: SET_IDLE" +expect "$log" 'HID report 1: 10 11 12 13 14 15 16 17' "HID gadget: first interrupt report" +expect "$log" 'HID report 3: 30 31 32 33 34 35 36 37' "HID gadget: third interrupt report" +expect "$log" '\[usb-host\] device detached' "HID gadget: the host sees the device go" +[ "$st" -eq 0 ] || { echo " FAIL HID gadget: emulator exit $st"; fail=1; } + +st=$(run 0 "$DIR/payload_1.bin") +expect "$DIR/out_0.log" 'usb test: no bus reset, nothing on the cable' "no host: the gadget waits on an empty cable" +if grep -q '\[usb-host\]' "$DIR/out_0.log"; then + echo " FAIL no host: the host logged activity" + fail=1 +fi + +[ $fail -eq 0 ] && echo "usb test: PASS" || { echo "usb test: FAIL (logs: $DIR/out_*.log)"; exit 1; } From 0c7f12a83b938a430aef530c5b4c6c5676126d78 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 26 Sep 2026 10:31:55 +0000 Subject: [PATCH 20/21] Store the last three CRLF headers with LF .gitattributes normalises text to LF, but t210/memory_map.h, mmio.h and tegra_bl.h were committed with CRLF before it was added, so any edit to them either rewrote every line or had to be staged around the filter. Line endings only; no content changes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb --- t210/memory_map.h | 532 +++++++++++++++++++++++----------------------- t210/mmio.h | 176 +++++++-------- t210/tegra_bl.h | 52 ++--- 3 files changed, 380 insertions(+), 380 deletions(-) diff --git a/t210/memory_map.h b/t210/memory_map.h index 927be60..891aac9 100644 --- a/t210/memory_map.h +++ b/t210/memory_map.h @@ -1,266 +1,266 @@ -#ifndef T210_MEMORY_MAP_H -#define T210_MEMORY_MAP_H - -#include - -/* - * Tegra X1 (T210) Memory Map for RCM Payload Emulation - * - * RCM payloads (hekate, etc.) run ARM32 code on the BPMP. - * They primarily use IRAM and access hardware via MMIO registers. - */ - -// ==================== RAM Regions ==================== - -// IRAM (Internal SRAM) - 256KB -constexpr uint64_t IRAM_BASE = 0x40000000; -constexpr uint64_t IRAM_SIZE = (16 * 1024 * 1024); // 16 MB mapped (actual 512 KB, but hekate needs relocation space) - -// DRAM - We allocate a modest amount for framebuffer + heap -constexpr uint64_t DRAM_BASE = 0x80000000; -// Size of the contiguous DRAM window we map. The BPMP is a 32-bit core, so -// everything it can address above DRAM_BASE ends at 0x100000000 - that upper -// bound, not the console's physical 4 GB, is what a BPMP-side payload can -// actually walk. MC_EMEM_CFG still reports the true 4096 MB. -constexpr uint64_t DRAM_WINDOW_SIZE = 0x80000000ULL; // 2 GB -constexpr uint64_t DRAM_SIZE = 0x80000000; // 2GB (Full T210 DRAM space for FatFs buffers) - -// Payload load address within IRAM -constexpr uint64_t IPL_LOAD_ADDR = 0x40010000; - -// Stack addresses used by hekate -constexpr uint64_t IPL_STACK_ADDR = 0x4003FF00; - -// Heap (in DRAM) -constexpr uint64_t IPL_HEAP_START = 0x90000000; -constexpr uint64_t IPL_HEAP_SIZE = 0x02000000; // 32MB - -// ==================== MMIO Regions ==================== -// All MMIO is in the 0x50000000-0x7FFFFFFF range on T210 - -// Clock and Reset Controller -constexpr uint64_t CLK_RST_BASE = 0x60006000; -constexpr uint64_t CLK_RST_SIZE = 0x1000; - -// Timer (TMR) -constexpr uint64_t TMR_BASE = 0x60005000; -constexpr uint64_t TMR_SIZE = 0x1000; - -// GPIO -constexpr uint64_t GPIO_BASE = 0x6000D000; -constexpr uint64_t GPIO_SIZE = 0x1000; - -// PINMUX -constexpr uint64_t PINMUX_BASE = 0x70003000; -constexpr uint64_t PINMUX_SIZE = 0x1000; - -// UART -constexpr uint64_t UART_A_BASE = 0x70006000; -constexpr uint64_t UART_SIZE = 0x1000; - -// I2C controllers -// Note: Tegra X1 base offsets per Hekate bdk/soc/i2c.c _i2c_base_offsets[]: -// I2C1=0x0, I2C2=0x400, I2C3=0x500, I2C4=0x700, I2C5=0x1000, I2C6=0x1100 -// All measured from APB I2C base 0x7000C000. -constexpr uint64_t I2C1_BASE = 0x7000C000; -constexpr uint64_t I2C2_BASE = 0x7000C400; // GEN2_I2C, Rohm BH1730 ALS at slave 0x29 -constexpr uint64_t I2C2_SIZE = 0x100; -constexpr uint64_t I2C3_BASE = 0x7000C500; // GEN3_I2C, used by STMFTS touchscreen at slave 0x49 -constexpr uint64_t I2C5_BASE = 0x7000D000; -constexpr uint64_t I2C_SIZE = 0x1000; // the MMIO page: I2C5, I2C6, SPI2B -constexpr uint64_t I2C_CTRL_SIZE = 0x100; // one controller's registers -constexpr uint64_t I2C4_BASE = 0x7000C700; -constexpr uint64_t I2C6_BASE = 0x7000D100; -constexpr uint64_t I2C3_SIZE = 0x100; - -// PWM -constexpr uint64_t PWM_BASE = 0x7000A000; -constexpr uint64_t PWM_SIZE = 0x1000; - -// RTC -constexpr uint64_t RTC_BASE = 0x7000E000; -// 0x400, NOT 0x1000: the PMC block starts at 0x7000E400, immediately after the -// RTC. A 0x1000-long RTC window swallowed the whole PMC range, and because the -// RTC branch is tested first in the MMIO dispatch, every PMC access (reset -// status, scratch registers, and the MAIN_RST reboot write) silently went to -// the RTC handler instead. -constexpr uint64_t RTC_SIZE = 0x400; - -// PMC (Power Management Controller) -constexpr uint64_t PMC_BASE = 0x7000E400; -constexpr uint64_t PMC_SIZE = 0x0C00; - -// Fuse Controller -constexpr uint64_t FUSE_BASE = 0x7000F800; -constexpr uint64_t FUSE_SIZE = 0x0400; - -// EMC (External Memory Controller). EMC_BASE is the broadcast/control bank; -// EMC0/EMC1 are the per-channel banks used to read mode-register responses -// (sdram_read_mrx splits the 16-bit MRR into low byte = ch0, high byte = ch1). -constexpr uint64_t EMC_BASE = 0x7001B000; -constexpr uint64_t EMC_SIZE = 0x1000; -constexpr uint64_t EMC0_BASE = 0x7001E000; -constexpr uint64_t EMC1_BASE = 0x7001F000; - -// MC (Memory Controller) -constexpr uint64_t MC_BASE = 0x70019000; -constexpr uint64_t MC_SIZE = 0x1000; - -// Display Controller (DC/DSI) -constexpr uint64_t DISPLAY_A_BASE = 0x54200000; -constexpr uint64_t DISPLAY_SIZE = 0x40000; - -// DSI Controller -constexpr uint64_t DSI_BASE = 0x54300000; -constexpr uint64_t DSI_SIZE = 0x1000; - -// SOC_THERM - on-die thermal sensors (tCPU0-3, tMEM0/1, tGPU, tPLLX). -// Distinct from the TMP451 (I2C) board sensor: these are the Tegra's own -// internal sensors, calibrated by fuses, that HOS/HW tests read to spot bad -// factory thermal-cal fuses. -constexpr uint64_t SOC_THERM_BASE = 0x700E2000; -constexpr uint64_t SOC_THERM_SIZE = 0x1000; - -// MIPI CAL -constexpr uint64_t MIPI_CAL_BASE = 0x700E3000; -constexpr uint64_t MIPI_CAL_SIZE = 0x1000; - -// SOR (Serial Output Resource) / HDMI -constexpr uint64_t SOR_BASE = 0x54540000; -constexpr uint64_t SOR_SIZE = 0x1000; - -// SDMMC controllers -constexpr uint64_t SDMMC1_BASE = 0x700B0000; // SD Card -constexpr uint64_t SDMMC4_BASE = 0x700B0600; // eMMC -constexpr uint64_t SDMMC_SIZE = 0x1000; - -// APB Misc -constexpr uint64_t APB_MISC_BASE = 0x70000000; -constexpr uint64_t APB_MISC_SIZE = 0x1000; - -// VIC (Video Image Compositor) -constexpr uint64_t VIC_BASE = 0x54340000; -constexpr uint64_t VIC_SIZE = 0x40000; - -// Host1x (display sync) -constexpr uint64_t HOST1X_BASE = 0x50000000; -constexpr uint64_t HOST1X_SIZE = 0x40000; - -// BPMP Cache -constexpr uint64_t BPMP_CACHE_BASE = 0x50040000; -constexpr uint64_t BPMP_CACHE_SIZE = 0x1000; - -// System Registers (SYSREG). SB (secure boot) sits at +0x200 and holds the -// CCPLEX's AArch64 reset vector (SB_AA64_RESET_LOW/HIGH, +0x230/+0x234). -constexpr uint64_t SYSREG_BASE = 0x6000C000; -constexpr uint64_t SYSREG_SIZE = 0x1000; - -// Flow controller: BPMP/CPU halt events, cluster control, RAM repair. -constexpr uint64_t FLOW_CTLR_BASE = 0x60007000; -constexpr uint64_t FLOW_CTLR_SIZE = 0x1000; - -// Exception vectors, incl. EVP_CPU_RESET_VECTOR (+0x100) for AArch32 boot. -constexpr uint64_t EXCP_VEC_BASE = 0x6000F000; -constexpr uint64_t EXCP_VEC_SIZE = 0x1000; - -// I2S (Audio) -constexpr uint64_t I2S_BASE = 0x702D1000; -constexpr uint64_t I2S_SIZE = 0x1000; - -// APE audio hub: ADMAIF (+0x000) and the AXBAR crossbar (+0x800) share one -// 4 KB page directly below I2S. Modelling it is not optional for hwtest: its -// speaker probe pushes ~224k samples through the ADMAIF PIO FIFO one 32-bit -// write at a time, and every write reaching the write-chain's fall-through -// arm costs a printf + fflush. Unmodelled, the melody alone emits a quarter -// of a million log lines and the run never reaches the Display / Inputs / -// Raw state / Diagnostics pages. -constexpr uint64_t ADMAIF_BASE = 0x702D0000; -constexpr uint64_t ADMAIF_SIZE = 0x1000; - -// ADMA, the audio DMA engine. hwtest resets and enables it but never runs a -// channel (the tone goes in by PIO), so only the soft-reset handshake has to -// be believable. -constexpr uint64_t ADMA_BASE = 0x702E2000; -constexpr uint64_t ADMA_SIZE = 0x1000; - -// SE (Security Engine) -constexpr uint64_t SE_BASE = 0x70012000; -constexpr uint64_t SE_SIZE = 0x2000; - -// MSELECT: the fabric between every master (CCPLEX and BPMP alike) and the -// AXI slaves, PCIe among them. Modelled because leaving it in reset is the -// difference between a register read and a permanently hung console. -constexpr uint64_t MSELECT_BASE = 0x50060000; -constexpr uint64_t MSELECT_SIZE = 0x1000; - -// USB2 controller USB1 ("OTG"): the device controller bdk's usbd.c drives on -// Erista. Registers, the UTMI PHY at +0x400/+0x800, queue heads at +0x1000. -constexpr uint64_t USB_OTG_BASE = 0x7D000000; -constexpr uint64_t USB_OTG_SIZE = 0x4000; - -// XUSB device controller: bdk's xusbd.c on Mariko. XHCI registers, then its -// PCI configuration space at +0x8000 and device registers at +0x9000. -constexpr uint64_t XUSB_DEV_BASE = 0x700D0000; -constexpr uint64_t XUSB_DEV_SIZE = 0xA000; - -// XUSB pad controller. Owns the UPHY SERDES lanes shared by PCIe (pcie-0..4) -// and USB 3.0 SuperSpeed (pcie-5/6 on this board), plus UPHY PLL P0. -constexpr uint64_t XUSB_PADCTL_BASE = 0x7009F000; -constexpr uint64_t XUSB_PADCTL_SIZE = 0x1000; - -// ==================== PCIe ==================== -// -// Unlike every other peripheral here, the PCIe apertures live BELOW the -// 0x50000000 MMIO band - T210 puts the whole root complex in the bottom of -// the address map (tegra210.dtsi pcie@1003000). The BPMP can address it: -// bdk's MMU table defines DRAM and IRAM entries only and leaves the fallback -// entry RWX, so PCIe space is reachable and uncached. -// -// These are MMIO windows (callbacks, no backing memory), so they are mapped -// at their architectural sizes: the whole 256 MiB configuration aperture - -// extended registers sit at AXI[27:24] - and the non-prefetchable memory -// window to the end of PCIE_A2, wherever software places the endpoint's BARs. -// A smaller map left a CPU0 access to, say, config offset 0x100 or BAR0 + -// 0x2000 unmapped: nothing answered and the core wedged, where silicon -// returns data or all-ones. -constexpr uint64_t PCIE_RP0_BASE = 0x01000000; // root port 0 registers -constexpr uint64_t PCIE_RP1_BASE = 0x01001000; // root port 1 registers -constexpr uint64_t PCIE_PADS_BASE = 0x01003000; -constexpr uint64_t PCIE_AFI_BASE = 0x01003800; -constexpr uint64_t PCIE_BLOCK_BASE = 0x01000000; -constexpr uint64_t PCIE_BLOCK_SIZE = 0x4000; -constexpr uint64_t PCIE_CS_BASE = 0x02000000; // type-1 extended config -constexpr uint64_t PCIE_CS_MODEL_SIZE = 0x10000000; // all of it: 256 MiB -constexpr uint64_t PCIE_MEM_BASE = 0x13000000; // non-prefetchable window -constexpr uint64_t PCIE_MEM_MODEL_SIZE = 0x0D000000; // up to the end of A2 - -// TSEC (Falcon control regs are in the 0x1000–0x11FF window within TSEC_BASE) -constexpr uint64_t TSEC_BASE = 0x54500000; -constexpr uint64_t TSEC_SIZE = 0x2000; - -// TZRAM -constexpr uint64_t TZRAM_BASE = 0x7C010000; -constexpr uint64_t TZRAM_SIZE = 0x10000; // 64KB - -// System Registers (SYSCTR0) -constexpr uint64_t SYSCTR0_BASE = 0x700F0000; -constexpr uint64_t SYSCTR0_SIZE = 0x1000; - -// ==================== Framebuffer ==================== - -// hekate uses a display window within DRAM for framebuffer -// The display init code sets up a linear framebuffer at predefined addresses. -// IPL_FB_ADDRESS is 0xF5A00000, NYX is 0xF6200000. -// We allocate a 16MB block covering 0xF5A00000 - 0xF6A00000 -constexpr uint64_t FB_BASE = 0xF5A00000; -constexpr uint64_t FB_SIZE = 0x01000000; // 16MB - -// Display dimensions (hekate: 720 width, 1280 height in portrait) -constexpr int DISPLAY_WIDTH = 720; -constexpr int DISPLAY_HEIGHT = 1280; - -// Landscape dimensions for SDL window -constexpr int WINDOW_WIDTH = 720; -constexpr int WINDOW_HEIGHT = 1280; - -#endif // T210_MEMORY_MAP_H +#ifndef T210_MEMORY_MAP_H +#define T210_MEMORY_MAP_H + +#include + +/* + * Tegra X1 (T210) Memory Map for RCM Payload Emulation + * + * RCM payloads (hekate, etc.) run ARM32 code on the BPMP. + * They primarily use IRAM and access hardware via MMIO registers. + */ + +// ==================== RAM Regions ==================== + +// IRAM (Internal SRAM) - 256KB +constexpr uint64_t IRAM_BASE = 0x40000000; +constexpr uint64_t IRAM_SIZE = (16 * 1024 * 1024); // 16 MB mapped (actual 512 KB, but hekate needs relocation space) + +// DRAM - We allocate a modest amount for framebuffer + heap +constexpr uint64_t DRAM_BASE = 0x80000000; +// Size of the contiguous DRAM window we map. The BPMP is a 32-bit core, so +// everything it can address above DRAM_BASE ends at 0x100000000 - that upper +// bound, not the console's physical 4 GB, is what a BPMP-side payload can +// actually walk. MC_EMEM_CFG still reports the true 4096 MB. +constexpr uint64_t DRAM_WINDOW_SIZE = 0x80000000ULL; // 2 GB +constexpr uint64_t DRAM_SIZE = 0x80000000; // 2GB (Full T210 DRAM space for FatFs buffers) + +// Payload load address within IRAM +constexpr uint64_t IPL_LOAD_ADDR = 0x40010000; + +// Stack addresses used by hekate +constexpr uint64_t IPL_STACK_ADDR = 0x4003FF00; + +// Heap (in DRAM) +constexpr uint64_t IPL_HEAP_START = 0x90000000; +constexpr uint64_t IPL_HEAP_SIZE = 0x02000000; // 32MB + +// ==================== MMIO Regions ==================== +// All MMIO is in the 0x50000000-0x7FFFFFFF range on T210 + +// Clock and Reset Controller +constexpr uint64_t CLK_RST_BASE = 0x60006000; +constexpr uint64_t CLK_RST_SIZE = 0x1000; + +// Timer (TMR) +constexpr uint64_t TMR_BASE = 0x60005000; +constexpr uint64_t TMR_SIZE = 0x1000; + +// GPIO +constexpr uint64_t GPIO_BASE = 0x6000D000; +constexpr uint64_t GPIO_SIZE = 0x1000; + +// PINMUX +constexpr uint64_t PINMUX_BASE = 0x70003000; +constexpr uint64_t PINMUX_SIZE = 0x1000; + +// UART +constexpr uint64_t UART_A_BASE = 0x70006000; +constexpr uint64_t UART_SIZE = 0x1000; + +// I2C controllers +// Note: Tegra X1 base offsets per Hekate bdk/soc/i2c.c _i2c_base_offsets[]: +// I2C1=0x0, I2C2=0x400, I2C3=0x500, I2C4=0x700, I2C5=0x1000, I2C6=0x1100 +// All measured from APB I2C base 0x7000C000. +constexpr uint64_t I2C1_BASE = 0x7000C000; +constexpr uint64_t I2C2_BASE = 0x7000C400; // GEN2_I2C, Rohm BH1730 ALS at slave 0x29 +constexpr uint64_t I2C2_SIZE = 0x100; +constexpr uint64_t I2C3_BASE = 0x7000C500; // GEN3_I2C, used by STMFTS touchscreen at slave 0x49 +constexpr uint64_t I2C5_BASE = 0x7000D000; +constexpr uint64_t I2C_SIZE = 0x1000; // the MMIO page: I2C5, I2C6, SPI2B +constexpr uint64_t I2C_CTRL_SIZE = 0x100; // one controller's registers +constexpr uint64_t I2C4_BASE = 0x7000C700; +constexpr uint64_t I2C6_BASE = 0x7000D100; +constexpr uint64_t I2C3_SIZE = 0x100; + +// PWM +constexpr uint64_t PWM_BASE = 0x7000A000; +constexpr uint64_t PWM_SIZE = 0x1000; + +// RTC +constexpr uint64_t RTC_BASE = 0x7000E000; +// 0x400, NOT 0x1000: the PMC block starts at 0x7000E400, immediately after the +// RTC. A 0x1000-long RTC window swallowed the whole PMC range, and because the +// RTC branch is tested first in the MMIO dispatch, every PMC access (reset +// status, scratch registers, and the MAIN_RST reboot write) silently went to +// the RTC handler instead. +constexpr uint64_t RTC_SIZE = 0x400; + +// PMC (Power Management Controller) +constexpr uint64_t PMC_BASE = 0x7000E400; +constexpr uint64_t PMC_SIZE = 0x0C00; + +// Fuse Controller +constexpr uint64_t FUSE_BASE = 0x7000F800; +constexpr uint64_t FUSE_SIZE = 0x0400; + +// EMC (External Memory Controller). EMC_BASE is the broadcast/control bank; +// EMC0/EMC1 are the per-channel banks used to read mode-register responses +// (sdram_read_mrx splits the 16-bit MRR into low byte = ch0, high byte = ch1). +constexpr uint64_t EMC_BASE = 0x7001B000; +constexpr uint64_t EMC_SIZE = 0x1000; +constexpr uint64_t EMC0_BASE = 0x7001E000; +constexpr uint64_t EMC1_BASE = 0x7001F000; + +// MC (Memory Controller) +constexpr uint64_t MC_BASE = 0x70019000; +constexpr uint64_t MC_SIZE = 0x1000; + +// Display Controller (DC/DSI) +constexpr uint64_t DISPLAY_A_BASE = 0x54200000; +constexpr uint64_t DISPLAY_SIZE = 0x40000; + +// DSI Controller +constexpr uint64_t DSI_BASE = 0x54300000; +constexpr uint64_t DSI_SIZE = 0x1000; + +// SOC_THERM - on-die thermal sensors (tCPU0-3, tMEM0/1, tGPU, tPLLX). +// Distinct from the TMP451 (I2C) board sensor: these are the Tegra's own +// internal sensors, calibrated by fuses, that HOS/HW tests read to spot bad +// factory thermal-cal fuses. +constexpr uint64_t SOC_THERM_BASE = 0x700E2000; +constexpr uint64_t SOC_THERM_SIZE = 0x1000; + +// MIPI CAL +constexpr uint64_t MIPI_CAL_BASE = 0x700E3000; +constexpr uint64_t MIPI_CAL_SIZE = 0x1000; + +// SOR (Serial Output Resource) / HDMI +constexpr uint64_t SOR_BASE = 0x54540000; +constexpr uint64_t SOR_SIZE = 0x1000; + +// SDMMC controllers +constexpr uint64_t SDMMC1_BASE = 0x700B0000; // SD Card +constexpr uint64_t SDMMC4_BASE = 0x700B0600; // eMMC +constexpr uint64_t SDMMC_SIZE = 0x1000; + +// APB Misc +constexpr uint64_t APB_MISC_BASE = 0x70000000; +constexpr uint64_t APB_MISC_SIZE = 0x1000; + +// VIC (Video Image Compositor) +constexpr uint64_t VIC_BASE = 0x54340000; +constexpr uint64_t VIC_SIZE = 0x40000; + +// Host1x (display sync) +constexpr uint64_t HOST1X_BASE = 0x50000000; +constexpr uint64_t HOST1X_SIZE = 0x40000; + +// BPMP Cache +constexpr uint64_t BPMP_CACHE_BASE = 0x50040000; +constexpr uint64_t BPMP_CACHE_SIZE = 0x1000; + +// System Registers (SYSREG). SB (secure boot) sits at +0x200 and holds the +// CCPLEX's AArch64 reset vector (SB_AA64_RESET_LOW/HIGH, +0x230/+0x234). +constexpr uint64_t SYSREG_BASE = 0x6000C000; +constexpr uint64_t SYSREG_SIZE = 0x1000; + +// Flow controller: BPMP/CPU halt events, cluster control, RAM repair. +constexpr uint64_t FLOW_CTLR_BASE = 0x60007000; +constexpr uint64_t FLOW_CTLR_SIZE = 0x1000; + +// Exception vectors, incl. EVP_CPU_RESET_VECTOR (+0x100) for AArch32 boot. +constexpr uint64_t EXCP_VEC_BASE = 0x6000F000; +constexpr uint64_t EXCP_VEC_SIZE = 0x1000; + +// I2S (Audio) +constexpr uint64_t I2S_BASE = 0x702D1000; +constexpr uint64_t I2S_SIZE = 0x1000; + +// APE audio hub: ADMAIF (+0x000) and the AXBAR crossbar (+0x800) share one +// 4 KB page directly below I2S. Modelling it is not optional for hwtest: its +// speaker probe pushes ~224k samples through the ADMAIF PIO FIFO one 32-bit +// write at a time, and every write reaching the write-chain's fall-through +// arm costs a printf + fflush. Unmodelled, the melody alone emits a quarter +// of a million log lines and the run never reaches the Display / Inputs / +// Raw state / Diagnostics pages. +constexpr uint64_t ADMAIF_BASE = 0x702D0000; +constexpr uint64_t ADMAIF_SIZE = 0x1000; + +// ADMA, the audio DMA engine. hwtest resets and enables it but never runs a +// channel (the tone goes in by PIO), so only the soft-reset handshake has to +// be believable. +constexpr uint64_t ADMA_BASE = 0x702E2000; +constexpr uint64_t ADMA_SIZE = 0x1000; + +// SE (Security Engine) +constexpr uint64_t SE_BASE = 0x70012000; +constexpr uint64_t SE_SIZE = 0x2000; + +// MSELECT: the fabric between every master (CCPLEX and BPMP alike) and the +// AXI slaves, PCIe among them. Modelled because leaving it in reset is the +// difference between a register read and a permanently hung console. +constexpr uint64_t MSELECT_BASE = 0x50060000; +constexpr uint64_t MSELECT_SIZE = 0x1000; + +// USB2 controller USB1 ("OTG"): the device controller bdk's usbd.c drives on +// Erista. Registers, the UTMI PHY at +0x400/+0x800, queue heads at +0x1000. +constexpr uint64_t USB_OTG_BASE = 0x7D000000; +constexpr uint64_t USB_OTG_SIZE = 0x4000; + +// XUSB device controller: bdk's xusbd.c on Mariko. XHCI registers, then its +// PCI configuration space at +0x8000 and device registers at +0x9000. +constexpr uint64_t XUSB_DEV_BASE = 0x700D0000; +constexpr uint64_t XUSB_DEV_SIZE = 0xA000; + +// XUSB pad controller. Owns the UPHY SERDES lanes shared by PCIe (pcie-0..4) +// and USB 3.0 SuperSpeed (pcie-5/6 on this board), plus UPHY PLL P0. +constexpr uint64_t XUSB_PADCTL_BASE = 0x7009F000; +constexpr uint64_t XUSB_PADCTL_SIZE = 0x1000; + +// ==================== PCIe ==================== +// +// Unlike every other peripheral here, the PCIe apertures live BELOW the +// 0x50000000 MMIO band - T210 puts the whole root complex in the bottom of +// the address map (tegra210.dtsi pcie@1003000). The BPMP can address it: +// bdk's MMU table defines DRAM and IRAM entries only and leaves the fallback +// entry RWX, so PCIe space is reachable and uncached. +// +// These are MMIO windows (callbacks, no backing memory), so they are mapped +// at their architectural sizes: the whole 256 MiB configuration aperture - +// extended registers sit at AXI[27:24] - and the non-prefetchable memory +// window to the end of PCIE_A2, wherever software places the endpoint's BARs. +// A smaller map left a CPU0 access to, say, config offset 0x100 or BAR0 + +// 0x2000 unmapped: nothing answered and the core wedged, where silicon +// returns data or all-ones. +constexpr uint64_t PCIE_RP0_BASE = 0x01000000; // root port 0 registers +constexpr uint64_t PCIE_RP1_BASE = 0x01001000; // root port 1 registers +constexpr uint64_t PCIE_PADS_BASE = 0x01003000; +constexpr uint64_t PCIE_AFI_BASE = 0x01003800; +constexpr uint64_t PCIE_BLOCK_BASE = 0x01000000; +constexpr uint64_t PCIE_BLOCK_SIZE = 0x4000; +constexpr uint64_t PCIE_CS_BASE = 0x02000000; // type-1 extended config +constexpr uint64_t PCIE_CS_MODEL_SIZE = 0x10000000; // all of it: 256 MiB +constexpr uint64_t PCIE_MEM_BASE = 0x13000000; // non-prefetchable window +constexpr uint64_t PCIE_MEM_MODEL_SIZE = 0x0D000000; // up to the end of A2 + +// TSEC (Falcon control regs are in the 0x1000–0x11FF window within TSEC_BASE) +constexpr uint64_t TSEC_BASE = 0x54500000; +constexpr uint64_t TSEC_SIZE = 0x2000; + +// TZRAM +constexpr uint64_t TZRAM_BASE = 0x7C010000; +constexpr uint64_t TZRAM_SIZE = 0x10000; // 64KB + +// System Registers (SYSCTR0) +constexpr uint64_t SYSCTR0_BASE = 0x700F0000; +constexpr uint64_t SYSCTR0_SIZE = 0x1000; + +// ==================== Framebuffer ==================== + +// hekate uses a display window within DRAM for framebuffer +// The display init code sets up a linear framebuffer at predefined addresses. +// IPL_FB_ADDRESS is 0xF5A00000, NYX is 0xF6200000. +// We allocate a 16MB block covering 0xF5A00000 - 0xF6A00000 +constexpr uint64_t FB_BASE = 0xF5A00000; +constexpr uint64_t FB_SIZE = 0x01000000; // 16MB + +// Display dimensions (hekate: 720 width, 1280 height in portrait) +constexpr int DISPLAY_WIDTH = 720; +constexpr int DISPLAY_HEIGHT = 1280; + +// Landscape dimensions for SDL window +constexpr int WINDOW_WIDTH = 720; +constexpr int WINDOW_HEIGHT = 1280; + +#endif // T210_MEMORY_MAP_H diff --git a/t210/mmio.h b/t210/mmio.h index 8f87af8..44e2cbc 100644 --- a/t210/mmio.h +++ b/t210/mmio.h @@ -1,88 +1,88 @@ -#ifndef T210_MMIO_H -#define T210_MMIO_H - -#include -#include - -/* - * Tegra X1 MMIO Handler - * - * Routes memory-mapped IO reads/writes to peripheral handlers. - * Unknown registers return 0 / ignore writes (permissive stub). - */ - -// Forward declarations for peripheral modules. -struct EmuState; - -// Which processor issued the access being dispatched. Two masters share one -// register model: the BPMP (the ARM7 every RCM payload runs on) and CPU0 of -// the CCPLEX (Cortex-A57), which a payload can boot through bdk's -// ccplex_boot_cpu0(). They do not see the same bus - PCIe and MSELECT answer -// a CPU-complex master only (Tegra X1 TRM ch.16/ch.19) - so the few models -// that care consult this. Both cores run on the emulator's one thread, one -// slice at a time, so a global is exact: whoever is running is the master. -enum BusMaster : uint8_t { - BUS_BPMP = 0, - BUS_CPU0 = 1, -}; -extern BusMaster g_bus_master; - -// Initialize all MMIO hooks on the Unicorn engine. -void mmio_init(uc_engine *uc, EmuState *state); - -// Map the same peripheral windows into another engine (CPU0's), backed by the -// same register models. Everything in the 0x50000000..0x7FFFFFFF band plus -// the PCIe apertures low in the map. -void mmio_map_bus(uc_engine *uc, EmuState *state); -// Forget the windows mapped into `uc`, before that engine is closed. -void mmio_unmap_bus(uc_engine *uc); - -// The shared dispatch both engines' MMIO callbacks funnel into. `size` is the -// access width in bytes (1, 2 or 4). -uint32_t mmio_bus_read(EmuState *state, uint64_t addr, unsigned size); -void mmio_bus_write(EmuState *state, uint64_t addr, unsigned size, - uint64_t value); - -// Reset the per-run peripheral state that a soft reboot must not carry over. -// `power_cycle`: the PMIC reset too (its register files return to their -// seeds); otherwise only the SoC reset (PMC MAIN_RST) and the PMIC keeps -// its rails. -void mmio_soft_reset(EmuState *state, bool power_cycle); - -// PMC power-partition state (APBDEV_PMC_PWRGATE_STATUS bit `part`). -bool pmc_partition_on(int part); - -// APBDEV_PMC_SECURE_SCRATCH`n` (n = 0..7), written by hardware: the SE -// deposits its context-save key there. -void pmc_secure_scratch_write(unsigned n, uint32_t value); - -// True when the CCPLEX CPU rail is up: the MAX77621 on Erista (enabled, and -// its EN pin driven by MAX77620 GPIO5), the MAX77812 M4 phase on Mariko. -bool cpu_rail_on(EmuState *state); - -// Individual peripheral handlers. -uint32_t timer_read(EmuState *state, uint64_t addr); -void timer_write(EmuState *state, uint64_t addr, uint32_t val); - -uint32_t gpio_read(EmuState *state, uint64_t addr); -void gpio_write(EmuState *state, uint64_t addr, uint32_t val); - -uint32_t i2c_read(EmuState *state, uint64_t addr); -void i2c_write(EmuState *state, uint64_t addr, uint32_t val); - -uint32_t display_read(EmuState *state, uint64_t addr); -void display_write(EmuState *state, uint64_t addr, uint32_t val); - -uint32_t pmc_read(EmuState *state, uint64_t addr); -void pmc_write(EmuState *state, uint64_t addr, uint32_t val); - -uint32_t clk_rst_read(EmuState *state, uint64_t addr); -void clk_rst_write(EmuState *state, uint64_t addr, uint32_t val); - -uint32_t fuse_read(EmuState *state, uint64_t addr); -void fuse_write(EmuState *state, uint64_t addr, uint32_t val); - -uint32_t misc_read(EmuState *state, uint64_t addr); -void misc_write(uc_engine *uc, EmuState *state, uint64_t addr, int64_t value, int size); - -#endif // T210_MMIO_H +#ifndef T210_MMIO_H +#define T210_MMIO_H + +#include +#include + +/* + * Tegra X1 MMIO Handler + * + * Routes memory-mapped IO reads/writes to peripheral handlers. + * Unknown registers return 0 / ignore writes (permissive stub). + */ + +// Forward declarations for peripheral modules. +struct EmuState; + +// Which processor issued the access being dispatched. Two masters share one +// register model: the BPMP (the ARM7 every RCM payload runs on) and CPU0 of +// the CCPLEX (Cortex-A57), which a payload can boot through bdk's +// ccplex_boot_cpu0(). They do not see the same bus - PCIe and MSELECT answer +// a CPU-complex master only (Tegra X1 TRM ch.16/ch.19) - so the few models +// that care consult this. Both cores run on the emulator's one thread, one +// slice at a time, so a global is exact: whoever is running is the master. +enum BusMaster : uint8_t { + BUS_BPMP = 0, + BUS_CPU0 = 1, +}; +extern BusMaster g_bus_master; + +// Initialize all MMIO hooks on the Unicorn engine. +void mmio_init(uc_engine *uc, EmuState *state); + +// Map the same peripheral windows into another engine (CPU0's), backed by the +// same register models. Everything in the 0x50000000..0x7FFFFFFF band plus +// the PCIe apertures low in the map. +void mmio_map_bus(uc_engine *uc, EmuState *state); +// Forget the windows mapped into `uc`, before that engine is closed. +void mmio_unmap_bus(uc_engine *uc); + +// The shared dispatch both engines' MMIO callbacks funnel into. `size` is the +// access width in bytes (1, 2 or 4). +uint32_t mmio_bus_read(EmuState *state, uint64_t addr, unsigned size); +void mmio_bus_write(EmuState *state, uint64_t addr, unsigned size, + uint64_t value); + +// Reset the per-run peripheral state that a soft reboot must not carry over. +// `power_cycle`: the PMIC reset too (its register files return to their +// seeds); otherwise only the SoC reset (PMC MAIN_RST) and the PMIC keeps +// its rails. +void mmio_soft_reset(EmuState *state, bool power_cycle); + +// PMC power-partition state (APBDEV_PMC_PWRGATE_STATUS bit `part`). +bool pmc_partition_on(int part); + +// APBDEV_PMC_SECURE_SCRATCH`n` (n = 0..7), written by hardware: the SE +// deposits its context-save key there. +void pmc_secure_scratch_write(unsigned n, uint32_t value); + +// True when the CCPLEX CPU rail is up: the MAX77621 on Erista (enabled, and +// its EN pin driven by MAX77620 GPIO5), the MAX77812 M4 phase on Mariko. +bool cpu_rail_on(EmuState *state); + +// Individual peripheral handlers. +uint32_t timer_read(EmuState *state, uint64_t addr); +void timer_write(EmuState *state, uint64_t addr, uint32_t val); + +uint32_t gpio_read(EmuState *state, uint64_t addr); +void gpio_write(EmuState *state, uint64_t addr, uint32_t val); + +uint32_t i2c_read(EmuState *state, uint64_t addr); +void i2c_write(EmuState *state, uint64_t addr, uint32_t val); + +uint32_t display_read(EmuState *state, uint64_t addr); +void display_write(EmuState *state, uint64_t addr, uint32_t val); + +uint32_t pmc_read(EmuState *state, uint64_t addr); +void pmc_write(EmuState *state, uint64_t addr, uint32_t val); + +uint32_t clk_rst_read(EmuState *state, uint64_t addr); +void clk_rst_write(EmuState *state, uint64_t addr, uint32_t val); + +uint32_t fuse_read(EmuState *state, uint64_t addr); +void fuse_write(EmuState *state, uint64_t addr, uint32_t val); + +uint32_t misc_read(EmuState *state, uint64_t addr); +void misc_write(uc_engine *uc, EmuState *state, uint64_t addr, int64_t value, int size); + +#endif // T210_MMIO_H diff --git a/t210/tegra_bl.h b/t210/tegra_bl.h index e8a2279..100f463 100644 --- a/t210/tegra_bl.h +++ b/t210/tegra_bl.h @@ -1,26 +1,26 @@ -#ifndef T210_TEGRA_BL_H -#define T210_TEGRA_BL_H - -#include - -// Tegra X1-style block-linear byte offset for 32 bpp (RGBA8888 / XRGB in RAM). -// Matches test_img.py "Block Linear / Tegra X1" mode. -inline uint32_t tegra_bl_byte_off_rgba8888(uint32_t sx, uint32_t sy, - uint32_t width_gobs, - uint32_t block_height_gobs) { - uint32_t gob_x = sx / 16u; - uint32_t pixel_x = sx % 16u; - uint32_t gob_y = sy / 8u; - uint32_t line_y = sy % 8u; - uint32_t block_y = gob_y / block_height_gobs; - uint32_t gob_in_block_y = gob_y % block_height_gobs; - - uint32_t idx = - (block_y * width_gobs * block_height_gobs * 128u) + - (gob_x * block_height_gobs * 128u) + (gob_in_block_y * 128u) + - (pixel_x & 3u) + ((line_y & 1u) << 2) + ((pixel_x & 4u) << 1) + - ((line_y & 2u) << 3) + ((pixel_x & 8u) << 2) + ((line_y & 4u) << 4); - return idx * 4u; -} - -#endif +#ifndef T210_TEGRA_BL_H +#define T210_TEGRA_BL_H + +#include + +// Tegra X1-style block-linear byte offset for 32 bpp (RGBA8888 / XRGB in RAM). +// Matches test_img.py "Block Linear / Tegra X1" mode. +inline uint32_t tegra_bl_byte_off_rgba8888(uint32_t sx, uint32_t sy, + uint32_t width_gobs, + uint32_t block_height_gobs) { + uint32_t gob_x = sx / 16u; + uint32_t pixel_x = sx % 16u; + uint32_t gob_y = sy / 8u; + uint32_t line_y = sy % 8u; + uint32_t block_y = gob_y / block_height_gobs; + uint32_t gob_in_block_y = gob_y % block_height_gobs; + + uint32_t idx = + (block_y * width_gobs * block_height_gobs * 128u) + + (gob_x * block_height_gobs * 128u) + (gob_in_block_y * 128u) + + (pixel_x & 3u) + ((line_y & 1u) << 2) + ((pixel_x & 4u) << 1) + + ((line_y & 2u) << 3) + ((pixel_x & 8u) << 2) + ((line_y & 4u) << 4); + return idx * 4u; +} + +#endif From f84caeaacca7194787fe550bb6fddda9d76daac9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 26 Sep 2026 11:09:57 +0000 Subject: [PATCH 21/21] Let the USB host write, and serve a gadget's disk over NBD The emulated PC only ever read a mass storage disk and then ejected it, so the write path through a gadget went untested and the disk could not be used from the machine running the emulator. The default session now asks MODE SENSE(6) for the write-protect bit and, on a writable disk whose read checked out, writes the last 8 sectors back as read (WRITE(10), SYNCHRONIZE CACHE) and reads them again. --usb-host nbd[:port] (or [usb] nbd_port, or the config window) locks the medium and serves the disk on 127.0.0.1 with a small non-blocking NBD server (t210/nbd.cpp: fixed newstyle handshake, READ/WRITE/FLUSH/DISC). Requests become READ(10)/WRITE(10)s of up to 64 KiB, a quiet client gets a TEST UNIT READY every second, a write-protected disk is exported read-only, and when the client disconnects the host ejects the disk. Serving Nyx exposed a controller model bug: a device transfer shorter than the host's request was taken as a short packet, so bdk's 64 KiB READ(10), sent as two 32 KiB transfers, lost the second half. Only a short or zero-length packet (the USB2 controller's own ZLP unless the queue head disables it) now ends the host's transfer. tests/usb grows a write-protected scenario, WRITE(10), MODE SENSE and SYNCHRONIZE CACHE on its RAM disk (reads sent in 32 KiB transfers, as bdk does), and three NBD runs driven by a Python client. Checked with Nyx SD UMS on Erista and Mariko: nbdinfo negotiates, qemu-img convert copies the 256 MiB disk byte for byte, and a qemu-io write lands in the SD image. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb --- .github/workflows/build.yml | 5 +- DESIGN.md | 64 ++++-- Makefile | 3 +- README.md | 44 +++- display/config_window.cpp | 14 +- emu_state.h | 4 + main.cpp | 23 ++- t210/nbd.cpp | 397 ++++++++++++++++++++++++++++++++++++ t210/nbd.h | 67 ++++++ t210/usb.cpp | 299 +++++++++++++++++++++++++-- tests/usb/nbd_check.py | 153 ++++++++++++++ tests/usb/payload.c | 83 ++++++-- tests/usb/run.sh | 94 ++++++++- 13 files changed, 1183 insertions(+), 67 deletions(-) create mode 100644 t210/nbd.cpp create mode 100644 t210/nbd.h create mode 100644 tests/usb/nbd_check.py diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index b49ec72..10392ee 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -51,8 +51,9 @@ jobs: # refused, a powered one must run an AArch64 blob at EL3, and WFE must # park the core. One runs the Security Engine's RSA, SHA-256, AES and # RNG against vectors computed in Python. One brings up USB gadgets on - # both device controllers for the --usb-host PC to enumerate and read - # back. The others drive the display controller and VIC in six + # both device controllers for the --usb-host PC to enumerate, read + # back and write, and serves the disk over NBD (on a localhost port) + # to a Python client. The others drive the display controller and VIC in six # scenarios, and the frame the emulator shows must match the picture # drawn, pixel for pixel. run: make test diff --git a/DESIGN.md b/DESIGN.md index 61fa119..8fe3297 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -570,21 +570,48 @@ class: - *Mass storage (Bulk-Only Transport):* `GET_MAX_LUN`, INQUIRY, TEST UNIT READY (answering the first unit attention with REQUEST SENSE), READ - CAPACITY, READ(10) of the first 64 and the last 8 blocks, each logged with - its CRC32 and checked against the SD image when the disk is its size; then - PREVENT ALLOW MEDIUM REMOVAL, an eject (START STOP UNIT, LoEj) and TEST - UNIT READY every 500 ms until the gadget detaches, as Linux does. It only - reads. + CAPACITY, MODE SENSE(6) for the write-protect bit (asking for just the + 4-byte header: bdk stalls bulk IN on a reply shorter than asked), READ(10) + of the first 64 and the last 8 blocks, each logged with its CRC32 and + checked against the SD image when the disk is its size. Unless the disk is + write-protected or the read was wrong, the last 8 blocks are written back + as read (WRITE(10), SYNCHRONIZE CACHE) and read again. Then PREVENT ALLOW + MEDIUM REMOVAL, an eject (START STOP UNIT, LoEj) and TEST UNIT READY every + 500 ms until the gadget detaches, as Linux does. +- *Mass storage over NBD* (`--usb-host nbd[:port]`, `[usb] nbd_port`): after + MODE SENSE the host sends PREVENT MEDIUM REMOVAL and serves the disk on + 127.0.0.1 with `t210/nbd.cpp`, a one-client NBD server (fixed newstyle + handshake: `EXPORT_NAME`, `LIST`, `INFO` and `GO`, with the export's size, + flags and 512-byte minimum block size; simple replies; READ, WRITE, FLUSH, + DISC). It is non-blocking and polled from the host every 100 us of + emulated time. A READ or WRITE is split into READ(10)s or WRITE(10)s of up + to 64 KiB, a FLUSH is a SYNCHRONIZE CACHE, and misaligned or out-of-range + requests are refused with `EINVAL` (writes to a write-protected disk with + `EPERM`, and the export is read-only). A quiet client gets a TEST UNIT + READY every emulated second, as Windows sends. When the client + disconnects the host allows removal and ejects as above. - *HID:* the report descriptor, `SET_IDLE` with an idle rate of 0 (report on change), then the interrupt IN endpoint is polled. Nyx's gamepad has nothing to report without Joy-Cons. The host advances on every access to either controller - it runs as far as the device and the emulated clock allow - so it needs no thread or main-loop -hook and runs repeat exactly. It logs `[usb-host]` lines; `RCM_USB_TRACE=1` -also logs each transfer descriptor, TRB and doorbell. Nyx's SD card mass -storage reads back identical to the image and reports "Disk ejected" on -both SoCs. +hook and runs repeat exactly (an NBD session aside: its requests come when +the client sends them). It logs `[usb-host]` lines; `RCM_USB_TRACE=1` also +logs each transfer descriptor, TRB and doorbell. + +A device transfer that retires before the host has all it asked for ends the +host's transfer only on a short packet: fewer bytes than a whole number of +max-size packets (the queue head or endpoint context gives the size), or a +zero-length packet, which the USB2 controller appends unless the queue head +disables it (ZLT; bdk disables it on every endpoint) and the XUSB controller +never adds. Otherwise the host carries on with the device's next transfer: +bdk sends a READ(10) under 512 KiB as 32 KiB transfers. + +Nyx's SD card mass storage reads back identical to the image, takes the +write check and reports "Disk ejected" on both SoCs. Over NBD, `nbdinfo` +negotiates, `qemu-img convert` copies the whole 256 MiB disk byte for byte, +and a `qemu-io` write lands in the SD image. ### Other peripherals (mostly stubs) @@ -780,10 +807,14 @@ refusal, the EL3 entry, a core released with its clock stopped, the mailbox, WFE parking and the reset; `tests/se/`, which runs the SE's RSA, SHA-256, AES and RNG against vectors computed in Python (`gen_vectors.py` writes `vectors.h`); `tests/usb/`, a -mass storage gadget over a RAM disk on each device controller and a HID -gadget, which the `--usb-host` PC must enumerate, read back (the CRC32s it -logs match the payload's) and see detach, plus a run with nothing on the -cable; and `tests/display/`, one payload built per scenario that drives the display +mass storage gadget over a RAM disk on each device controller (writable, and +write-protected in scenario 4) and a HID gadget, which the `--usb-host` PC +must enumerate, read back (the CRC32s it logs match the payload's), write +back unchanged unless write-protected and see detach, plus a run with +nothing on the cable and three NBD runs where `nbd_check.py` negotiates, +reads the disk, is refused a misaligned and an out-of-range read, writes +(or is refused on the write-protected disk), pipelines two reads, flushes +and disconnects, and the disk's CRC32 after the eject must be the client's; and `tests/display/`, one payload built per scenario that drives the display controller and VIC the way bdk does (a pitch window; Nyx's VIC turn into pitch and into block-linear surfaces; a block-linear VIC source; the DC's own column scan with an address offset; a mirrored window with window D @@ -811,6 +842,13 @@ don't repeat the diagnosis: register caches, so `USBCMD.RESET` never cleared and bdk's `usb_device_init()` timed out; Nyx's USB tools could not even wait for a cable. Fix: both device controllers are modelled, with a PC to plug in. +- **NBD reads of 64 KiB failed on Nyx.** The host took a device transfer + that moved less than it asked for as a short packet, so when bdk sent a + 64 KiB READ(10) as two 32 KiB transfers the data phase ended after the + first and the CSW read found data. Fix: only a transfer whose last packet + is short (or zero-length, including the USB2 controller's own ZLP when the + queue head allows it) ends the host's transfer; the test payload now sends + reads in 32 KiB transfers too. - **Minerva hung Nyx** (hekate 6.5.3 with the stock `bootloader/` folder never reached its GUI). The emulator planted hekate's "watchdog fired" cookie in IRAM so the IPL would skip Minerva; Nyx then trained the DRAM diff --git a/Makefile b/Makefile index d5bae68..2e9f5a2 100644 --- a/Makefile +++ b/Makefile @@ -102,7 +102,8 @@ tests/se/payload.bin: tests/se/payload.c tests/se/vectors.h tests/se/link.ld $(TEST_CC) $(TEST_CFLAGS) -T tests/se/link.ld -o tests/se/payload.elf $< $(TEST_OBJCOPY) -O binary tests/se/payload.elf $@ -USB_PAYLOADS = tests/usb/payload_1.bin tests/usb/payload_2.bin tests/usb/payload_3.bin +USB_PAYLOADS = tests/usb/payload_1.bin tests/usb/payload_2.bin tests/usb/payload_3.bin \ + tests/usb/payload_4.bin tests/usb/payload_%.bin: tests/usb/payload.c tests/usb/link.ld $(TEST_CC) $(TEST_CFLAGS) -DSCENARIO=$* -T tests/usb/link.ld -o tests/usb/payload_$*.elf $< diff --git a/README.md b/README.md index c5fc673..61168a0 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,9 @@ slow or destructive. - Plug an emulated PC into the USB-C port (`--usb-host`): Nyx's USB mass storage and gamepad gadgets enumerate on both the Erista (USB2) and Mariko (XUSB) device controllers, and the PC reads a mass storage disk back, - checks it against the SD image and ejects it. + checks it against the SD image, writes a few sectors back unchanged and + ejects it. With `--usb-host nbd` the PC serves the disk over NBD instead, + so it can be mounted on the machine running the emulator. - Tweak emulated hardware live (battery, charger, thermal, USB-PD, PMIC, fuses, SD insertion, the USB host) from a side window. See [Live hardware tweaks](#live-hardware-tweaks). - Inspect each Tegra UART port (TX history) and inject keystrokes into the @@ -191,11 +193,39 @@ refusal of an unpowered release, the EL3 entry, the mailbox, a stopped clock, WFE parking and the reset; one checks the Security Engine's RSA, SHA-256, AES and RNG against vectors computed in Python; one brings up a USB mass storage gadget on each device controller (and a HID gadget) for the `--usb-host` PC to -enumerate and read back; one drives the display controller and VIC and +enumerate, read back and write, and serves it over NBD to a Python client; +one drives the display controller and VIC and compares the frame pixel for pixel. The hwtest scripts run hwtest-rcm's whole hardware sweep headless and check that the CPU0-driven Wi-Fi probe enumerates the endpoint. CI runs both. +## Mounting a gadget's disk + +`--usb-host nbd` turns the emulated PC into a bridge: when a mass storage +gadget attaches - Nyx's SD card, eMMC or emuMMC under USB tools - the PC +locks the medium (PREVENT MEDIUM REMOVAL, so Nyx will not unload it from its +side) and serves it with the NBD protocol on 127.0.0.1, port 10809 or the one +given as `nbd:`. Every NBD read, write and flush becomes SCSI +commands to the gadget, so what reaches the SD image goes through bdk's UMS +code as it would from a real PC. A write-protected disk (Nyx's eMMC in its +default read-only mode) is exported read-only. + +```sh +./rcm_emu hekate.bin --sd sd.img --usb-host nbd +# in Nyx: Tools > USB Tools > SD Card, then on the host: +sudo modprobe nbd max_part=8 +sudo nbd-client 127.0.0.1 10809 /dev/nbd0 -b 512 +sudo mount /dev/nbd0p1 /mnt # ... use it ... +sudo umount /mnt && sudo nbd-client -d /dev/nbd0 # the disk is ejected +``` + +Without root, `qemu-img convert nbd://127.0.0.1:10809 copy.img` takes a +copy, `qemu-io nbd://127.0.0.1:10809` reads and writes sectors, and +`nbdfuse` exposes the disk as a file. The session ends when the client +disconnects: the PC allows removal and ejects, and Nyx reports "Disk +ejected". The port only listens while a disk is being served. In the config +window, the USB device mode section has the same switch and port. + ## Live hardware tweaks Press `M` in the main window to open a second window that exposes the values @@ -288,7 +318,7 @@ needed. | `--oem` | `erista` \| `mariko` | Switch SoC generation. Drives `APB_MISC_GP_HIDREV` so Hekate's `h_cfg.t210b01` matches and pkg1 identification skips the right OEM header. Default `erista`. | | `--bt-radio` | `healthy` \| `faulty` \| `absent` | Broadcom CYW4356 behaviour on UART-D. `healthy` powers up on the `BT_REG_ON` edge, holds `BT_HOST_WAKE` high, asserts `RTS_N` and answers HCI; `faulty` reproduces the 2110-1118 console (module fitted, never leaves POR); `absent` additionally leaves `BT_UART_RXD` in a break condition. Overrides `[bluetooth] radio` in the ini. Default `healthy`. | | `--wifi-radio` | `healthy` \| `faulty` \| `absent` | The WLAN half of the same CYW4356: a PCI Express endpoint on root port 1, reachable only from CPU0 (the BPMP reads all ones, as on silicon). `healthy` trains the link, enumerates as `14E4:43EC` and answers a ChipCommon ChipID read with `0x4356`; `faulty` still trains and enumerates but reads all ones on the backplane (live PCIe front-end, dead radio die); `absent` never leaves detect. The model also enforces the datasheet's power-up ordering, so a payload that releases PERST# too early gets a link that stays down and a `[pcie]` line naming the reason. Overrides `[wifi] radio` in the ini. Default `healthy`. | -| `--usb-host` | (none) | A PC on the USB-C port. It enumerates whatever USB gadget the payload brings up; a mass storage disk is read back (checked against the SD image), then ejected, and HID reports are polled. Logged as `[usb-host]`; `RCM_USB_TRACE=1` traces every transfer. Overrides `[usb] host` in the ini. | +| `--usb-host` | `nbd[:port]` (optional) | A PC on the USB-C port. It enumerates whatever USB gadget the payload brings up; a mass storage disk is read back (checked against the SD image), its last 8 sectors are written back unchanged and read again unless it is write-protected, and it is ejected; HID reports are polled. With `nbd` the disk is served over NBD on 127.0.0.1 (port 10809 by default) until the client disconnects, then ejected - see [Mounting a gadget's disk](#mounting-a-gadgets-disk). Logged as `[usb-host]`; `RCM_USB_TRACE=1` traces every transfer. Overrides `[usb] host` and `[usb] nbd_port` in the ini. | | `--input-script` | file or spec | Scripted input keyed to emulated time: ` P\|U\|D [hold_ms]` presses POWER / VOL+ / VOL-, ` TAP [hold_ms]` taps the touchscreen at (x, y) in the 1280x720 picture, `+N` times an event N ms after the previous one. Events are separated by `,`, `;` or newlines. | | `--auto-pin-recovery` | (none) | Drive the Lockpick PIN-recovery menu without user input. | | `--auto-te-script` | (none) | Drive `recover_pin.te` in TegraExplorer without input. | @@ -332,9 +362,11 @@ For implementation details, see [DESIGN.md](DESIGN.md). seed, so runs repeat. - **Single-threaded.** Both cores run in batches on the main thread between SDL event polls. That is also what keeps them deterministic. -- **The USB host is scripted.** `--usb-host` runs a fixed session - enumerate, - read back, eject - rather than bridging the gadget to the machine running - the emulator, so the disk cannot be mounted on it. +- **The USB host drives mass storage and HID only.** A gadget of another + class is enumerated and left configured. Over NBD, one client has the disk + per session: when it disconnects - `nbdinfo` and `qemu-img info` do so as + soon as they have their answer - the disk is ejected, as a PC ejects a + disk it has unmounted. ## Acknowledgements diff --git a/display/config_window.cpp b/display/config_window.cpp index 0b60b06..60a220d 100644 --- a/display/config_window.cpp +++ b/display/config_window.cpp @@ -139,6 +139,7 @@ void reset_to_defaults(EmuState *s) { X(usb_pd_voltage_mv, "usb_pd", "voltage_mv", 0) \ X(usb_pd_amperage_ma, "usb_pd", "amperage_ma", 0) \ X(usb_host, "usb", "host", 0) \ + X(usb_nbd_port, "usb", "nbd_port", 0) \ /* SoC / PMIC */ \ X(pmic_otp, "soc", "pmic_otp", 0) \ X(is_mariko, "soc", "is_mariko", 0) \ @@ -652,7 +653,18 @@ void build_ui(EmuState *state) { if (ImGui::Checkbox("PC on the USB-C port (--usb-host)", &host)) { state->usb_host.store(host); } - ImGui::TextDisabled("Mass storage is read back and ejected; HID is polled."); + // Mass storage served over NBD instead (--usb-host nbd[:port]); + // takes effect when the next disk is attached. + bool nbd = state->usb_nbd_port.load() != 0; + if (ImGui::Checkbox("Serve mass storage over NBD", &nbd)) { + state->usb_nbd_port.store(nbd ? 10809 : 0); + } + if (nbd) { + atomic_slider_int("NBD port", state->usb_nbd_port, 1024, 65535, "%d"); + ImGui::TextDisabled("127.0.0.1 only; the disk is ejected when the client disconnects."); + } else { + ImGui::TextDisabled("Mass storage is read back, written back unchanged and ejected;\nHID is polled."); + } } if (ImGui::CollapsingHeader("Display")) { diff --git a/emu_state.h b/emu_state.h index 9a2c63d..f1a4aa0 100644 --- a/emu_state.h +++ b/emu_state.h @@ -323,6 +323,10 @@ struct EmuState { // A PC on the USB-C port (--usb-host): it enumerates whatever gadget the // payload brings up (t210/usb.cpp). Off, nothing is on the cable. std::atomic usb_host{false}; + // --usb-host nbd[:port]: instead of reading a mass storage disk back and + // ejecting it, the host serves it over NBD on 127.0.0.1:port until the + // client disconnects. 0: off. + std::atomic usb_nbd_port{0}; // SD card identity (returned for SDMMC1 CMD2 ALL_SEND_CID). // Hekate parses these out of the R2 response per bdk/storage/sdmmc.c diff --git a/main.cpp b/main.cpp index 5fa8a7a..072c8d1 100644 --- a/main.cpp +++ b/main.cpp @@ -358,9 +358,28 @@ int main(int argc, char *argv[]) { } } else if (strcmp(argv[i], "--usb-host") == 0) { // A PC on the USB-C port: it enumerates whatever gadget the - // payload brings up and, for mass storage, reads it back. + // payload brings up and, for mass storage, reads it back - or, + // given "nbd[:port]", serves the disk over NBD. state.usb_host = true; - printf("[emu] USB host connected [overrides ini]\n"); + if (i + 1 < argc && strncmp(argv[i + 1], "nbd", 3) == 0 && + (argv[i + 1][3] == 0 || argv[i + 1][3] == ':')) { + const char *arg = argv[++i]; + unsigned long port = 10809; // the NBD port + char *end = nullptr; + if (arg[3] == ':') + port = strtoul(arg + 4, &end, 10); + if (port == 0 || port > 65535 || (end && *end)) { + fprintf(stderr, "[emu] Bad --usb-host value '%s'; expected" + " nbd or nbd:\n", arg); + port = 10809; + } + state.usb_nbd_port = (uint16_t)port; + printf("[emu] USB host connected, serving mass storage over" + " NBD on port %lu [overrides ini]\n", port); + } else { + state.usb_nbd_port = 0; + printf("[emu] USB host connected [overrides ini]\n"); + } } else if (strcmp(argv[i], "--wifi-radio") == 0 && i + 1 < argc) { // WLAN half of the same package, on PCIe. 'faulty' means // something different here from the Bluetooth side: the link diff --git a/t210/nbd.cpp b/t210/nbd.cpp new file mode 100644 index 0000000..1369390 --- /dev/null +++ b/t210/nbd.cpp @@ -0,0 +1,397 @@ +// A one-client NBD server for the emulated USB host (see nbd.h). +// +// The handshake is the fixed newstyle one every current client speaks +// (nbd-client, qemu-nbd, nbdfuse, libnbd): +// +// server "NBDMAGIC" "IHAVEOPT" handshake flags +// client its flags, then options: "IHAVEOPT", option, length, data +// server answers each option; EXPORT_NAME or GO hands over the disk +// +// then requests (magic 0x25609513, flags, type, handle, offset, length, +// and a WRITE's data) each answered by a simple reply (magic 0x67446698, +// error, handle, and a READ's data). The export has one name - any name +// the client asks for - and takes READ, WRITE, FLUSH and DISC; structured +// replies and the other extensions are refused, which clients handle. + +#include "nbd.h" + +#ifdef _WIN32 +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +#include +#include +#include + +namespace { + +constexpr uint64_t NBDMAGIC = 0x4E42444D41474943ull; // "NBDMAGIC" +constexpr uint64_t IHAVEOPT = 0x49484156454F5054ull; // "IHAVEOPT" +constexpr uint64_t REPLY_MAGIC = 0x0003E889045565A9ull; // option replies +constexpr uint32_t REQUEST_MAGIC = 0x25609513; +constexpr uint32_t SIMPLE_REPLY_MAGIC = 0x67446698; + +constexpr uint16_t FLAG_FIXED_NEWSTYLE = 1 << 0, FLAG_NO_ZEROES = 1 << 1; +constexpr uint16_t FLAG_HAS_FLAGS = 1 << 0, FLAG_READ_ONLY = 1 << 1, + FLAG_SEND_FLUSH = 1 << 2; + +constexpr uint32_t OPT_EXPORT_NAME = 1, OPT_ABORT = 2, OPT_LIST = 3, + OPT_INFO = 6, OPT_GO = 7; +constexpr uint32_t REP_ACK = 1, REP_SERVER = 2, REP_INFO = 3, + REP_ERR_UNSUP = 0x80000001, REP_ERR_INVALID = 0x80000003; +constexpr uint16_t INFO_EXPORT = 0, INFO_BLOCK_SIZE = 3; + +#ifdef _WIN32 +using sock_t = SOCKET; +const sock_t BAD_SOCK = INVALID_SOCKET; +bool net_init() { + static bool ok = [] { + WSADATA d; + return WSAStartup(MAKEWORD(2, 2), &d) == 0; + }(); + return ok; +} +void close_sock(sock_t s) { closesocket(s); } +bool would_block() { return WSAGetLastError() == WSAEWOULDBLOCK; } +bool set_nonblocking(sock_t s) { + u_long on = 1; + return ioctlsocket(s, FIONBIO, &on) == 0; +} +const char *sock_error() { + static char buf[32]; + snprintf(buf, sizeof(buf), "winsock error %d", WSAGetLastError()); + return buf; +} +#else +using sock_t = int; +const sock_t BAD_SOCK = -1; +bool net_init() { return true; } +void close_sock(sock_t s) { ::close(s); } +bool would_block() { +#if EWOULDBLOCK != EAGAIN + if (errno == EWOULDBLOCK) + return true; +#endif + return errno == EAGAIN || errno == EINTR; +} +bool set_nonblocking(sock_t s) { + int fl = fcntl(s, F_GETFL, 0); + return fl >= 0 && fcntl(s, F_SETFL, fl | O_NONBLOCK) == 0; +} +const char *sock_error() { return strerror(errno); } +#endif + +#ifdef MSG_NOSIGNAL +constexpr int SEND_FLAGS = MSG_NOSIGNAL; // a gone client is an error, not SIGPIPE +#else +constexpr int SEND_FLAGS = 0; +#endif + +sock_t sock(intptr_t s) { return (sock_t)s; } + +// Wait up to 10 s for room to send. +bool wait_writable(sock_t s) { + fd_set w; + FD_ZERO(&w); + FD_SET(s, &w); + timeval tv = {10, 0}; + return select((int)s + 1, nullptr, &w, nullptr, &tv) > 0; +} + +// Everything on the wire is big-endian. +void put16(uint8_t *p, uint16_t v) { + p[0] = v >> 8; + p[1] = (uint8_t)v; +} +void put32(uint8_t *p, uint32_t v) { + put16(p, v >> 16); + put16(p + 2, (uint16_t)v); +} +void put64(uint8_t *p, uint64_t v) { + put32(p, v >> 32); + put32(p + 4, (uint32_t)v); +} +uint16_t get16(const uint8_t *p) { return (uint16_t)(p[0] << 8 | p[1]); } +uint32_t get32(const uint8_t *p) { + return (uint32_t)get16(p) << 16 | get16(p + 2); +} +uint64_t get64(const uint8_t *p) { + return (uint64_t)get32(p) << 32 | get32(p + 4); +} + +} // namespace + +bool NbdServer::listen(uint16_t port, uint64_t size, bool read_only) { + close(); + if (!net_init()) { + printf("[usb-host] NBD: no sockets (%s)\n", sock_error()); + return false; + } + sock_t s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (s == BAD_SOCK) { + printf("[usb-host] NBD: no socket (%s)\n", sock_error()); + return false; + } +#ifndef _WIN32 + // Windows' SO_REUSEADDR lets another process take a bound port; the + // POSIX one only skips TIME_WAIT, so a restarted run gets its port back. + int one = 1; + setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)); +#endif + sockaddr_in a; + memset(&a, 0, sizeof(a)); + a.sin_family = AF_INET; + a.sin_port = htons(port); + a.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + if (bind(s, (sockaddr *)&a, sizeof(a)) != 0 || ::listen(s, 1) != 0 || + !set_nonblocking(s)) { + printf("[usb-host] NBD: cannot listen on 127.0.0.1:%u (%s)\n", port, + sock_error()); + close_sock(s); + return false; + } + listen_ = (intptr_t)s; + size_ = size; + read_only_ = read_only; + state_ = Listening; + return true; +} + +void NbdServer::close() { + drop_client(); + if (listen_ != -1) + close_sock(sock(listen_)); + listen_ = -1; + state_ = Idle; +} + +void NbdServer::drop_client() { + if (client_ != -1) + close_sock(sock(client_)); + client_ = -1; + in_.clear(); + peer_closed_ = false; + state_ = listen_ != -1 ? Listening : Idle; +} + +uint16_t NbdServer::transmission_flags() const { + return FLAG_HAS_FLAGS | FLAG_SEND_FLUSH | (read_only_ ? FLAG_READ_ONLY : 0); +} + +// Read what the client has sent. False once it has closed its end. +bool NbdServer::fill() { + static uint8_t buf[65536]; + // Room for the largest WRITE; a client pipelining more waits in the socket. + while (in_.size() < NBD_MAX_PAYLOAD + sizeof(buf)) { + int n = recv(sock(client_), (char *)buf, sizeof(buf), 0); + if (n > 0) { + in_.insert(in_.end(), buf, buf + n); + continue; + } + return n < 0 && would_block(); + } + return true; +} + +bool NbdServer::send_all(const void *p, size_t n) { + const char *c = (const char *)p; + while (n) { + int k = send(sock(client_), c, (int)std::min(n, 1u << 20), + SEND_FLAGS); + if (k > 0) { + c += k; + n -= (size_t)k; + } else if (k < 0 && would_block()) { + if (!wait_writable(sock(client_))) + return false; + } else { + return false; + } + } + return true; +} + +bool NbdServer::option_reply(uint32_t opt, uint32_t type, + const std::vector &data) { + uint8_t h[20]; + put64(h, REPLY_MAGIC); + put32(h + 8, opt); + put32(h + 12, type); + put32(h + 16, (uint32_t)data.size()); + return send_all(h, sizeof(h)) && + (data.empty() || send_all(data.data(), data.size())); +} + +// One handshake option. False drops the client. +bool NbdServer::option(uint32_t opt, const std::vector &d) { + switch (opt) { + case OPT_EXPORT_NAME: { + // No reply header: the export's size and flags, then (unless the + // client opted out) 124 zero bytes, and the disk is the client's. + uint8_t r[10 + 124] = {}; + put64(r, size_); + put16(r + 8, transmission_flags()); + if (!send_all(r, no_zeroes_ ? 10 : sizeof(r))) + return false; + state_ = Transmission; + break; + } + case OPT_ABORT: + option_reply(opt, REP_ACK); + return false; + case OPT_LIST: { + if (!d.empty()) + return option_reply(opt, REP_ERR_INVALID); + std::vector unnamed(4, 0); // one export, the default name + return option_reply(opt, REP_SERVER, unnamed) && option_reply(opt, REP_ACK); + } + case OPT_INFO: + case OPT_GO: { + // Export name length, the name, the count of info requests, the + // requests. Whatever the client asks for, it gets the size and flags + // and the block sizes: 512-byte sectors, 4 KiB preferred. + if (d.size() < 6) + return option_reply(opt, REP_ERR_INVALID); + uint32_t name_len = get32(&d[0]); + if (name_len > d.size() - 6 || + d.size() != 6 + name_len + 2 * (size_t)get16(&d[4 + name_len])) + return option_reply(opt, REP_ERR_INVALID); + std::vector e(12), b(14); + put16(&e[0], INFO_EXPORT); + put64(&e[2], size_); + put16(&e[10], transmission_flags()); + put16(&b[0], INFO_BLOCK_SIZE); + put32(&b[2], 512); + put32(&b[6], 4096); + put32(&b[10], NBD_MAX_PAYLOAD); + if (!option_reply(opt, REP_INFO, e) || !option_reply(opt, REP_INFO, b) || + !option_reply(opt, REP_ACK)) + return false; + if (opt == OPT_GO) + state_ = Transmission; + break; + } + default: + return option_reply(opt, REP_ERR_UNSUP); + } + if (state_ == Transmission) + printf("[usb-host] NBD client has the disk\n"); + return true; +} + +NbdEvent NbdServer::poll(NbdRequest *req) { + if (state_ == Idle) + return NbdEvent::None; + if (state_ == Listening) { + sock_t c = accept(sock(listen_), nullptr, nullptr); + if (c == BAD_SOCK) + return NbdEvent::None; + set_nonblocking(c); + int one = 1; + setsockopt(c, IPPROTO_TCP, TCP_NODELAY, (const char *)&one, sizeof(one)); +#ifdef SO_NOSIGPIPE + setsockopt(c, SOL_SOCKET, SO_NOSIGPIPE, &one, sizeof(one)); +#endif + client_ = (intptr_t)c; + in_.clear(); + peer_closed_ = no_zeroes_ = false; + uint8_t hello[18]; + put64(hello, NBDMAGIC); + put64(hello + 8, IHAVEOPT); + put16(hello + 16, FLAG_FIXED_NEWSTYLE | FLAG_NO_ZEROES); + if (!send_all(hello, sizeof(hello))) { + drop_client(); + return NbdEvent::None; + } + state_ = ClientFlags; + } + if (!fill()) + peer_closed_ = true; + + for (;;) { + size_t n = in_.size(); + if (state_ == ClientFlags) { + if (n < 4) + break; + uint32_t f = get32(&in_[0]); + in_.erase(in_.begin(), in_.begin() + 4); + no_zeroes_ = (f & FLAG_FIXED_NEWSTYLE) && (f & FLAG_NO_ZEROES); + state_ = Options; + } else if (state_ == Options) { + if (n < 16) + break; + uint32_t opt = get32(&in_[8]), len = get32(&in_[12]); + if (get64(&in_[0]) != IHAVEOPT || len > 65536) { + printf("[usb-host] NBD: not an NBD client; dropped\n"); + drop_client(); + return NbdEvent::None; + } + if (n < 16 + (size_t)len) + break; + std::vector data(in_.begin() + 16, in_.begin() + 16 + len); + in_.erase(in_.begin(), in_.begin() + 16 + len); + if (!option(opt, data)) { + drop_client(); + return NbdEvent::None; + } + } else { + if (n < 28) + break; + uint16_t type = get16(&in_[6]); + uint32_t len = get32(&in_[24]); + if (get32(&in_[0]) != REQUEST_MAGIC || + (type == NBD_CMD_WRITE && len > NBD_MAX_PAYLOAD)) { + printf("[usb-host] NBD: malformed request; client dropped\n"); + drop_client(); + return NbdEvent::Closed; + } + size_t need = 28 + (type == NBD_CMD_WRITE ? len : 0); + if (n < need) + break; + req->flags = get16(&in_[4]); + req->type = type; + req->handle = get64(&in_[8]); + req->offset = get64(&in_[16]); + req->len = len; + req->data.assign(in_.begin() + 28, in_.begin() + need); + in_.erase(in_.begin(), in_.begin() + need); + if (type == NBD_CMD_DISC) { + printf("[usb-host] NBD client disconnected\n"); + drop_client(); + return NbdEvent::Closed; + } + return NbdEvent::Request; + } + } + + if (peer_closed_) { + bool had_disk = state_ == Transmission; + printf("[usb-host] NBD client %s\n", + had_disk ? "went away without disconnecting" : "left"); + drop_client(); + return had_disk ? NbdEvent::Closed : NbdEvent::None; + } + return NbdEvent::None; +} + +void NbdServer::reply(uint64_t handle, uint32_t error, const uint8_t *data, + size_t len) { + if (state_ != Transmission) + return; + uint8_t h[16]; + put32(h, SIMPLE_REPLY_MAGIC); + put32(h + 4, error); + put64(h + 8, handle); + if (!send_all(h, sizeof(h)) || (!error && len && !send_all(data, len))) + peer_closed_ = true; // the next poll reports it gone +} diff --git a/t210/nbd.h b/t210/nbd.h new file mode 100644 index 0000000..a6142cd --- /dev/null +++ b/t210/nbd.h @@ -0,0 +1,67 @@ +#pragma once + +#include +#include + +// A one-client NBD server - the network block device protocol, fixed +// newstyle handshake - that the emulated USB host (usb.cpp) serves a mass +// storage gadget's disk with, so the disk can be mounted on the machine the +// emulator runs on. It listens on 127.0.0.1 only. Single-threaded and +// non-blocking: poll() does whatever the socket allows and returns. + +struct NbdRequest { + uint16_t type = 0; // NBD_CMD_* + uint16_t flags = 0; + uint64_t handle = 0, offset = 0; + uint32_t len = 0; + std::vector data; // what a WRITE carries +}; + +constexpr uint16_t NBD_CMD_READ = 0, NBD_CMD_WRITE = 1, NBD_CMD_DISC = 2, + NBD_CMD_FLUSH = 3; +constexpr uint32_t NBD_EPERM = 1, NBD_EIO = 5, NBD_EINVAL = 22; + +// The largest READ or WRITE a client may send (the protocol's default). +constexpr uint32_t NBD_MAX_PAYLOAD = 32u << 20; + +enum class NbdEvent { + None, // nothing to do yet + Request, // *req holds the next command + Closed, // the client that was using the disk disconnected +}; + +class NbdServer { +public: + ~NbdServer() { close(); } + + // Listen on 127.0.0.1:port for a client, exporting `size` bytes. False + // (and logged) when the port cannot be had. + bool listen(uint16_t port, uint64_t size, bool read_only); + void close(); + bool active() const { return state_ != Idle; } + + // Accept, run the handshake, read the next request. A client that goes + // away before it has the disk (a listing, a failed negotiation) is not a + // Closed event: the server just waits for the next one. + NbdEvent poll(NbdRequest *req); + + // Answer a request; a READ's data goes with a zero error. + void reply(uint64_t handle, uint32_t error, const uint8_t *data = nullptr, + size_t len = 0); + +private: + enum State { Idle, Listening, ClientFlags, Options, Transmission }; + State state_ = Idle; + intptr_t listen_ = -1, client_ = -1; // sockets + std::vector in_; + bool peer_closed_ = false, no_zeroes_ = false, read_only_ = false; + uint64_t size_ = 0; + + bool fill(); + bool send_all(const void *p, size_t n); + bool option(uint32_t opt, const std::vector &data); + bool option_reply(uint32_t opt, uint32_t type, + const std::vector &data = {}); + void drop_client(); + uint16_t transmission_flags() const; +}; diff --git a/t210/usb.cpp b/t210/usb.cpp index 6a80d47..4754d8c 100644 --- a/t210/usb.cpp +++ b/t210/usb.cpp @@ -13,15 +13,25 @@ // runs the class: // // mass storage GET_MAX_LUN, then over Bulk-Only Transport INQUIRY, TEST -// UNIT READY, READ CAPACITY and two READ(10)s (the first 64 -// sectors and the last 8), checked against the SD image when -// the capacity matches it; then it allows medium removal, -// ejects (START STOP UNIT, LoEj) and polls TEST UNIT READY -// until the gadget lets go, as Linux does +// UNIT READY, READ CAPACITY, MODE SENSE (write protection) +// and two READ(10)s (the first 64 sectors and the last 8), +// checked against the SD image when the capacity matches it. +// Unless the disk is write-protected, the last 8 sectors are +// then written back unchanged (WRITE(10), SYNCHRONIZE CACHE) +// and read again. Then it allows medium removal, ejects +// (START STOP UNIT, LoEj) and polls TEST UNIT READY until +// the gadget lets go, as Linux does // HID the report descriptor, SET_IDLE, then interrupt IN reports // -// Everything is logged as [usb-host]. The host only reads: nothing is ever -// written to the storage a gadget exports. +// With --usb-host nbd[:port] (or [usb] nbd_port) the mass storage session +// instead locks the medium (PREVENT MEDIUM REMOVAL) and serves the disk over +// NBD on 127.0.0.1 (nbd.cpp), so it can be mounted on this machine: each +// request becomes READ(10)s, WRITE(10)s or a SYNCHRONIZE CACHE, and a TEST +// UNIT READY goes out every second the client is quiet, as Windows does. +// When the client disconnects, the host ejects the disk as above. +// +// Everything is logged as [usb-host]. The only data the host writes on its +// own is what it has just read from the same sectors. // // The host advances whenever the payload touches the controller - every // register access runs it as far as the device and the emulated clock allow @@ -41,6 +51,7 @@ #include "../emu_state.h" #include "../platform.h" #include "memory_map.h" +#include "nbd.h" namespace { @@ -106,6 +117,12 @@ constexpr uint64_t kSetAddrUs = 2000; // USB 2.0 9.2.6.3: SET_ADDRESS recover constexpr uint64_t kBindUs = 100000; constexpr uint64_t kTimeoutUs = 5000000; constexpr uint64_t kEjectPollUs = 500000; +// Serving NBD: the socket is polled every 100 us of emulated time rather +// than on every register access, a quiet client gets a TEST UNIT READY every +// second, and requests go to the device 64 KiB at a time. +constexpr uint64_t kNbdPollUs = 100; +constexpr uint64_t kNbdIdleUs = 1000000; +constexpr uint32_t kNbdChunkBlocks = 128; struct Endpoint { uint8_t addr = 0, attr = 0, interval = 0; @@ -139,8 +156,10 @@ enum class Step { Unplugged, WaitAttach, Debounce, WaitReset, Recover, GetDevice8, SetAddress, AddrRecovery, GetDevice, GetConfig9, GetConfig, GetLangs, GetVendor, GetProduct, GetSerial, SetConfig, Bind, - MscMaxLun, MscInquiry, MscTur, MscSense, MscCapacity, MscReadFirst, MscReadLast, - MscAllow, MscEject, MscAfterEject, MscEjectWait, + MscMaxLun, MscInquiry, MscTur, MscSense, MscCapacity, MscModeSense, + MscReadFirst, MscReadLast, MscWrite, MscSync, MscReadBack, + NbdPrevent, NbdRead, NbdWrite, NbdFlush, NbdTur, + MscAllow, MscEject, MscAfterEject, MscEjectWait, NbdServe, HidReport, HidIdle, HidPoll, Idle, Failed, }; @@ -161,6 +180,7 @@ public: if (step_ != Step::Unplugged) { if (dc_) dc_->detach(); + nbd_.close(); step_ = Step::Unplugged; printf("[usb-host] unplugged\n"); } @@ -181,6 +201,7 @@ public: if (step_ != Step::WaitAttach && !dc_->attached()) { printf("[usb-host] device detached\n"); dc_->detach(); + nbd_.close(); step_ = Step::WaitAttach; ctl_.stage = Control::DONE; bot_.phase = Bot::DONE; @@ -199,6 +220,7 @@ public: step_ = Step::Unplugged; ctl_ = Control(); bot_ = Bot(); + nbd_.close(); } private: @@ -222,8 +244,22 @@ private: uint32_t tag_ = 0, blocks_ = 0, block_len_ = 0; int tur_tries_ = 0; uint64_t eject_deadline_ = 0; + bool wp_ = false; // MODE SENSE said write-protected + std::vector last_; // the last 8 sectors, as read int reports_ = 0; + // Serving NBD: the request in hand, how many of its blocks have been + // moved, and what a READ has gathered. + NbdServer nbd_; + NbdRequest req_; + uint32_t req_done_ = 0; + std::vector req_data_; + uint64_t last_cmd_us_ = 0, last_poll_us_ = 0; + uint64_t nbd_reads_ = 0, nbd_writes_ = 0, nbd_read_bytes_ = 0, + nbd_write_bytes_ = 0; + + static uint16_t nbd_port() { return g_state ? g_state->usb_nbd_port.load() : 0; } + void go(Step s) { step_ = s; progressed_ = true; @@ -231,6 +267,7 @@ private: void fail(const char *what) { printf("[usb-host] %s - giving up on this device\n", what); + nbd_.close(); go(Step::Failed); } @@ -465,6 +502,8 @@ private: // ---- Mass storage checks ---- + static constexpr const char *kDiffers = "DIFFERS from the SD image"; + // Compare what was read with the SD image, when the disk is the size of it. const char *compare_sd(uint32_t lba, const std::vector &got) { if (!g_state || g_state->sd_fd < 0) @@ -478,7 +517,7 @@ private: return "SD image unreadable"; return memcmp(want.data(), got.data(), got.size()) == 0 ? "matches the SD image" - : "DIFFERS from the SD image"; + : kDiffers; } static uint32_t crc32(const std::vector &d) { @@ -502,6 +541,28 @@ private: bot(cdb, 10, true, (uint32_t)count * block_len_); } + void write10(uint32_t lba, uint16_t count, const uint8_t *src) { + uint8_t cdb[10] = {0x2A, 0, (uint8_t)(lba >> 24), (uint8_t)(lba >> 16), + (uint8_t)(lba >> 8), (uint8_t)lba, 0, + (uint8_t)(count >> 8), (uint8_t)count, 0}; + bot(cdb, 10, false, (uint32_t)count * block_len_); + memcpy(bot_.data.data(), src, bot_.data.size()); + } + + void synchronize_cache() { + uint8_t cdb[10] = {0x35}; + bot(cdb, 10, false, 0); + } + + bool bot_good() const { return !bot_.stalled && bot_status() == 0; } + + // Done with the disk: allow medium removal, then eject. + void release_disk() { + uint8_t cdb[6] = {0x1E, 0, 0, 0, 0, 0}; // PREVENT ALLOW: allow + bot(cdb, 6, false, 0); + go(Step::MscAllow); + } + // A BOT command finished: false (and the session failed) if it did not end // with a good CSW. bool bot_ok(const char *what) { @@ -585,6 +646,10 @@ private: finish(); // polls the endpoint itself return; + case Step::NbdServe: + serve(); + return; + default: break; } @@ -600,6 +665,72 @@ private: finish(); } + // ---- Serving NBD ---- + + void serve_next() { + last_cmd_us_ = now_us(); + last_poll_us_ = 0; // a pipelined request is next + go(Step::NbdServe); + } + + // The next piece of an NBD READ or WRITE. + void next_chunk() { + uint32_t lba = (uint32_t)(req_.offset / block_len_) + req_done_; + uint16_t count = (uint16_t)std::min( + req_.len / block_len_ - req_done_, kNbdChunkBlocks); + if (req_.type == NBD_CMD_READ) { + read10(lba, count); + return go(Step::NbdRead); + } + write10(lba, count, req_.data.data() + (size_t)req_done_ * block_len_); + go(Step::NbdWrite); + } + + void serve() { + if (now_us() - last_poll_us_ < kNbdPollUs) + return; + last_poll_us_ = now_us(); + switch (nbd_.poll(&req_)) { + case NbdEvent::None: + if (now_us() - last_cmd_us_ >= kNbdIdleUs) { + uint8_t cdb[6] = {0x00, 0, 0, 0, 0, 0}; // TEST UNIT READY + bot(cdb, 6, false, 0); + go(Step::NbdTur); + } + return; + case NbdEvent::Closed: + nbd_.close(); + printf("[usb-host] NBD: %llu reads (%llu KiB), %llu writes (%llu KiB); " + "ejecting the disk\n", + (unsigned long long)nbd_reads_, + (unsigned long long)(nbd_read_bytes_ >> 10), + (unsigned long long)nbd_writes_, + (unsigned long long)(nbd_write_bytes_ >> 10)); + return release_disk(); + case NbdEvent::Request: + break; + } + uint64_t size = ((uint64_t)blocks_ + 1) * block_len_; + bool rw = req_.type == NBD_CMD_READ || req_.type == NBD_CMD_WRITE; + uint32_t err = 0; + if (req_.type == NBD_CMD_FLUSH) { + synchronize_cache(); + return go(Step::NbdFlush); + } + if (!rw || req_.offset % block_len_ || req_.len % block_len_ || + req_.offset > size || req_.len > size - req_.offset) + err = NBD_EINVAL; // whole sectors, on the disk + else if (req_.type == NBD_CMD_WRITE && wp_) + err = NBD_EPERM; + if (err || !req_.len) { + nbd_.reply(req_.handle, err); + return serve_next(); + } + req_done_ = 0; + req_data_.clear(); + next_chunk(); + } + // The class driver binds: its first request. void start_class() { if (iface_class_ == 0x08 && iface_proto_ == 0x50 && bulk_in_.addr && @@ -760,10 +891,32 @@ private: blocks_ = be32(&bot_.data[0]); block_len_ = be32(&bot_.data[4]); uint64_t bytes = ((uint64_t)blocks_ + 1) * block_len_; - printf("[usb-host] %u blocks of %u bytes (%llu MiB)\n", blocks_ + 1, - block_len_, (unsigned long long)(bytes >> 20)); + bool mib = bytes >= (1u << 20); + printf("[usb-host] %u blocks of %u bytes (%llu %s)\n", blocks_ + 1, + block_len_, (unsigned long long)(bytes >> (mib ? 20 : 10)), + mib ? "MiB" : "KiB"); if (block_len_ != 512 || blocks_ < 72) return fail("unexpected capacity"); + // Just the 4-byte header: bdk stalls bulk IN on a reply shorter than + // the host asked for. + uint8_t cdb[6] = {0x1A, 0, 0x3F, 0, 4, 0}; // MODE SENSE(6), all pages + bot(cdb, 6, true, 4); + return go(Step::MscModeSense); + } + + case Step::MscModeSense: { + // Bit 7 of byte 2 of the header: write-protected. A device that + // cannot say is taken to be. + bool ok = bot_good() && bot_.data.size() >= 4; + wp_ = !ok || (bot_.data[2] & 0x80); + printf("[usb-host] %s\n", !ok ? "MODE SENSE failed; taking the disk as " + "write-protected" + : wp_ ? "write-protected" : "writable"); + if (nbd_port()) { + uint8_t cdb[6] = {0x1E, 0, 0, 0, 1, 0}; // PREVENT ALLOW: prevent + bot(cdb, 6, false, 0); + return go(Step::NbdPrevent); + } read10(0, 64); return go(Step::MscReadFirst); } @@ -779,13 +932,97 @@ private: case Step::MscReadLast: { if (!bot_ok("READ(10)")) return; + const char *cmp = compare_sd(blocks_ - 7, bot_.data); printf("[usb-host] read blocks %u-%u (crc32 %08X): %s\n", blocks_ - 7, - blocks_, crc32(bot_.data), compare_sd(blocks_ - 7, bot_.data)); - uint8_t cdb[6] = {0x1E, 0, 0, 0, 0, 0}; // PREVENT ALLOW: allow - bot(cdb, 6, false, 0); - return go(Step::MscAllow); + blocks_, crc32(bot_.data), cmp); + // The write check puts back exactly what was read, so only data that + // is known good - or cannot be checked - is written. + if (wp_ || cmp == kDiffers) { + printf("[usb-host] write check skipped: %s\n", + wp_ ? "the disk is write-protected" : "the read was wrong"); + return release_disk(); + } + last_ = bot_.data; + write10(blocks_ - 7, 8, last_.data()); + return go(Step::MscWrite); } + case Step::MscWrite: + if (!bot_ok("WRITE(10)")) + return; + synchronize_cache(); + return go(Step::MscSync); + + case Step::MscSync: + if (!bot_ok("SYNCHRONIZE CACHE")) + return; + read10(blocks_ - 7, 8); + return go(Step::MscReadBack); + + case Step::MscReadBack: + if (!bot_ok("READ(10)")) + return; + printf("[usb-host] wrote blocks %u-%u back unchanged; read back: %s, " + "%s\n", blocks_ - 7, blocks_, + bot_.data == last_ ? "the same data" : "DIFFERENT data", + compare_sd(blocks_ - 7, bot_.data)); + return release_disk(); + + // ---- Serving NBD ---- + + case Step::NbdPrevent: { + if (!bot_ok("PREVENT ALLOW MEDIUM REMOVAL")) + return; + uint16_t port = nbd_port(); + if (!nbd_.listen(port, ((uint64_t)blocks_ + 1) * block_len_, wp_)) { + printf("[usb-host] not serving the disk\n"); + return release_disk(); + } + printf("[usb-host] serving the disk over NBD at 127.0.0.1:%u%s (e.g. " + "nbd-client 127.0.0.1 %u /dev/nbd0); it is ejected when the " + "client disconnects\n", + port, wp_ ? ", read-only" : "", port); + fflush(stdout); // a script may be waiting on it + nbd_reads_ = nbd_writes_ = nbd_read_bytes_ = nbd_write_bytes_ = 0; + return serve_next(); + } + + case Step::NbdRead: + case Step::NbdWrite: { + bool read = step_ == Step::NbdRead; + uint32_t count = bot_.len / block_len_; + if (!bot_good() || (read && bot_.data.size() != bot_.len)) { + printf("[usb-host] NBD %s of blocks %llu-%llu failed\n", + read ? "read" : "write", + (unsigned long long)(req_.offset / block_len_ + req_done_), + (unsigned long long)(req_.offset / block_len_ + req_done_ + + count - 1)); + nbd_.reply(req_.handle, NBD_EIO); + return serve_next(); + } + if (read) + req_data_.insert(req_data_.end(), bot_.data.begin(), bot_.data.end()); + req_done_ += count; + if (req_done_ < req_.len / block_len_) + return next_chunk(); + if (read) { + nbd_reads_++; + nbd_read_bytes_ += req_.len; + } else { + nbd_writes_++; + nbd_write_bytes_ += req_.len; + } + nbd_.reply(req_.handle, 0, req_data_.data(), read ? req_data_.size() : 0); + return serve_next(); + } + + case Step::NbdFlush: + nbd_.reply(req_.handle, bot_good() ? 0 : NBD_EIO); + return serve_next(); + + case Step::NbdTur: + return serve_next(); // only keeps the gadget company + case Step::MscAllow: { if (!bot_ok("PREVENT ALLOW MEDIUM REMOVAL")) return; @@ -904,6 +1141,7 @@ constexpr uint32_t EPCTRL_RX_STALL = 1u << 0, EPCTRL_RX_RESET = 1u << 6, constexpr uint32_t SUSP_PHY_CLK_VALID = 1u << 7, SUSP_UTMIP_RESET = 1u << 11, SUSP_UTMIP_PHY_ENB = 1u << 12; constexpr uint32_t DTD_ACTIVE = 1u << 7, DTD_IOC = 1u << 15; +constexpr uint32_t QH_MAX_PKT_SHIFT = 16, QH_ZLT_DISABLE = 1u << 29; class Usb2d : public UsbDc { public: @@ -1013,7 +1251,7 @@ public: if (!(reg(R_STATUS) & bit)) return XFER_NAK; int moved = transfer(2 * ep + 1, buf, max, true); - *short_pkt = moved < max; + *short_pkt = moved < max && ends_transfer(2 * ep + 1, moved); return moved; } @@ -1042,6 +1280,18 @@ private: return (s & SUSP_UTMIP_PHY_ENB) && !(s & SUSP_UTMIP_RESET); } + // A device transfer of n bytes that retired before the host had all it + // asked for ends the host's transfer too only if its last packet was + // short, or zero-length - which the controller appends to a whole number + // of packets unless the queue head disables it (ZLT, as bdk does on every + // endpoint). Otherwise the host goes on to the device's next transfer: + // bdk sends a 64 KiB READ(10) as two 32 KiB ones. + bool ends_transfer(int index, int n) { + uint32_t caps = qh_read32(qh_addr(index)); + uint32_t mps = (caps >> QH_MAX_PKT_SHIFT) & 0x7FF; + return n == 0 || !mps || n % mps || !(caps & QH_ZLT_DISABLE); + } + // Queue heads live wherever ENDPOINTLISTADDR points: bdk uses the // controller's own memory, but DRAM works the same way. uint64_t qh_addr(int index) { return (uint64_t)reg(R_EPLISTADDR) + index * 64; } @@ -1296,9 +1546,18 @@ public: bool setup_taken() override { return true; } int in(int ep, uint8_t *buf, int max, bool *short_pkt) override { - int n = transfer(ep ? 3 : 0, true, buf, max); - if (n >= 0) - *short_pkt = n < max; + int dci = ep ? 3 : 0; + int n = transfer(dci, true, buf, max); + if (n >= 0) { + // As on the USB2 controller, a TRB that moved less than the host asked + // for ends its transfer only on a short or zero-length packet; this + // side appends no ZLP of its own. The max packet size is in word 1 of + // the endpoint context. + uint32_t w1 = 0; + mem_read(ctx_addr(dci) + 4, &w1, 4); + uint32_t mps = w1 >> 16; + *short_pkt = n < max && (n == 0 || !mps || n % mps); + } return n; } diff --git a/tests/usb/nbd_check.py b/tests/usb/nbd_check.py new file mode 100644 index 0000000..cbe339d --- /dev/null +++ b/tests/usb/nbd_check.py @@ -0,0 +1,153 @@ +#!/usr/bin/env python3 +"""NBD client for tests/usb/run.sh: talks to the disk the emulator's +--usb-host nbd serves and checks what comes back. + +Usage: nbd_check.py rw|ro + +Waits for the host to say it is serving, negotiates with NBD_OPT_GO, reads +the whole disk (tests/usb/payload.c fills it with a known pattern), checks +that bad requests are refused, then - on a writable disk - writes two +sectors, reads them back and flushes, or - on a write-protected one - checks +that the write is refused. Two reads go out back to back to check that +pipelined requests are answered in turn. Prints the CRC32 the disk should +have once the client is done, then disconnects. +""" + +import socket +import struct +import sys +import time +import zlib + +NBDMAGIC = 0x4E42444D41474943 +IHAVEOPT = 0x49484156454F5054 +REPLY_MAGIC = 0x0003E889045565A9 +OPT_GO, OPT_LIST = 7, 3 +REP_ACK, REP_SERVER, REP_INFO = 1, 2, 3 +CMD_READ, CMD_WRITE, CMD_DISC, CMD_FLUSH = 0, 1, 2, 3 +FLAG_READ_ONLY, FLAG_SEND_FLUSH = 1 << 1, 1 << 2 +EPERM, EINVAL = 1, 22 + +LBAS = 384 +failed = False + + +def check(ok, what): + global failed + print((" ok " if ok else " FAIL ") + what) + if not ok: + failed = True + + +def pattern(): + return bytes(((i * 7) ^ (i >> 9)) & 0xFF for i in range(LBAS * 512)) + + +def recv_all(s, n): + b = b"" + while len(b) < n: + c = s.recv(n - len(b)) + if not c: + raise EOFError("server closed the connection") + b += c + return b + + +def option(s, opt, data=b""): + s.sendall(struct.pack(">QII", IHAVEOPT, opt, len(data)) + data) + replies = [] + while True: + magic, ropt, rtype, rlen = struct.unpack(">QIII", recv_all(s, 20)) + if magic != REPLY_MAGIC or ropt != opt: + raise ValueError("bad option reply") + replies.append((rtype, recv_all(s, rlen))) + if rtype == REP_ACK or rtype & 0x80000000: + return replies + + +def request(s, cmd, handle, offset, length, data=b""): + s.sendall(struct.pack(">IHHQQI", 0x25609513, 0, cmd, handle, offset, + length) + data) + + +def reply(s, want_handle, length=0): + magic, err, handle = struct.unpack(">IIQ", recv_all(s, 16)) + if magic != 0x67446698 or handle != want_handle: + raise ValueError("bad reply (magic %08X, handle %d)" % (magic, handle)) + return err, (recv_all(s, length) if not err and length else b"") + + +def main(): + port, log, mode = int(sys.argv[1]), sys.argv[2], sys.argv[3] + deadline = time.time() + 60 + while "serving the disk over NBD" not in open(log, errors="replace").read(): + if time.time() > deadline: + check(False, "the host serves the disk over NBD") + return 1 + time.sleep(0.1) + + s = socket.create_connection(("127.0.0.1", port), timeout=30) + magic, opt_magic, hflags = struct.unpack(">QQH", recv_all(s, 18)) + check(magic == NBDMAGIC and opt_magic == IHAVEOPT and hflags & 1, + "NBD %s: fixed newstyle greeting" % mode) + s.sendall(struct.pack(">I", 3)) # fixed newstyle, no zeroes + + listing = option(s, OPT_LIST) + check([r[0] for r in listing] == [REP_SERVER, REP_ACK], + "NBD %s: NBD_OPT_LIST names one export" % mode) + + go = option(s, OPT_GO, struct.pack(">IH", 0, 0)) + size = flags = None + for rtype, data in go: + if rtype == REP_INFO and struct.unpack(">H", data[:2])[0] == 0: + size, flags = struct.unpack(">QH", data[2:12]) + check(go[-1][0] == REP_ACK and size == LBAS * 512, + "NBD %s: NBD_OPT_GO, export of %s bytes" % (mode, size)) + check(bool(flags & FLAG_READ_ONLY) == (mode == "ro") and + bool(flags & FLAG_SEND_FLUSH), + "NBD %s: transmission flags %s" % (mode, flags and hex(flags))) + + disk = bytearray(pattern()) + request(s, CMD_READ, 1, 0, len(disk)) + err, data = reply(s, 1, len(disk)) + check(err == 0 and data == disk, + "NBD %s: reading the whole disk returns it" % mode) + + request(s, CMD_READ, 2, 100, 512) + check(reply(s, 2)[0] == EINVAL, "NBD %s: an unaligned read is refused" % mode) + request(s, CMD_READ, 3, len(disk), 512) + check(reply(s, 3)[0] == EINVAL, "NBD %s: a read past the end is refused" % mode) + + new = bytes((i * 13 + 5) & 0xFF for i in range(1024)) + request(s, CMD_WRITE, 4, 10 * 512, len(new), new) + err = reply(s, 4)[0] + if mode == "rw": + check(err == 0, "NBD rw: writing blocks 10-11") + disk[10 * 512:12 * 512] = new + else: + check(err == EPERM, "NBD ro: a write is refused") + + request(s, CMD_READ, 5, 8 * 512, 4 * 512) + request(s, CMD_READ, 6, (LBAS - 1) * 512, 512) + e5, d5 = reply(s, 5, 4 * 512) + e6, d6 = reply(s, 6, 512) + check(e5 == 0 and d5 == disk[8 * 512:12 * 512] and + e6 == 0 and d6 == disk[(LBAS - 1) * 512:], + "NBD %s: two pipelined reads%s" % + (mode, ", the first seeing the write" if mode == "rw" else "")) + + request(s, CMD_FLUSH, 7, 0, 0) + check(reply(s, 7)[0] == 0, "NBD %s: flush" % mode) + + request(s, CMD_DISC, 8, 0, 0) + s.close() + print("nbd check: disk crc32 %08X" % (zlib.crc32(disk) & 0xFFFFFFFF)) + return 1 if failed else 0 + + +if __name__ == "__main__": + try: + sys.exit(main()) + except (OSError, EOFError, ValueError) as e: + print(" FAIL NBD client: %s" % e) + sys.exit(1) diff --git a/tests/usb/payload.c b/tests/usb/payload.c index bb7d42b..22b90d8 100644 --- a/tests/usb/payload.c +++ b/tests/usb/payload.c @@ -2,7 +2,7 @@ * USB device mode regression payload. * * A freestanding BPMP payload that brings up a small USB mass storage gadget - * - one LUN, a 128-block RAM disk - on one of the two device controllers, + * - one LUN, a 384-block RAM disk - on one of the two device controllers, * with the register sequences bdk's drivers use, and serves whatever the * emulator's --usb-host PC asks. Built once per scenario with -DSCENARIO=n: * @@ -12,14 +12,16 @@ * transfer rings and endpoint contexts in IRAM * 3 the USB2 controller again, as a HID gadget: after the report * descriptor and SET_IDLE it sends three interrupt IN reports + * 4 scenario 1 with the disk write-protected * * Either way the gadget answers the standard requests and GET_MAX_LUN, then * the Bulk-Only Transport: INQUIRY, TEST UNIT READY, REQUEST SENSE, READ - * CAPACITY, READ(10), PREVENT ALLOW MEDIUM REMOVAL and START STOP UNIT. When - * the host ejects, it stops the controller and powers off. It prints the - * CRC32 of the disk ranges the host reads, which tests/usb/run.sh compares - * with what the host logs. Run without --usb-host, scenario 1 sees no bus - * reset and says so. + * CAPACITY, MODE SENSE(6), READ(10), WRITE(10), SYNCHRONIZE CACHE, PREVENT + * ALLOW MEDIUM REMOVAL and START STOP UNIT. When the host ejects, it stops + * the controller and powers off. It prints the CRC32 of the disk ranges the + * host reads, and of the whole disk after the eject, which tests/usb/run.sh + * compares with what the host logs and what its NBD client wrote. Run without + * --usb-host, scenario 1 sees no bus reset and says so. */ #ifndef SCENARIO @@ -37,10 +39,12 @@ typedef unsigned char u8; #define UARTB_THR 0x70006040u #define I2C5 0x7000D000u -#define DISK 0xC0000000u /* 128 blocks of 512 bytes */ -#define DISK_LBAS 128u +#define DISK 0xC0000000u /* 384 blocks of 512 bytes */ +#define DISK_LBAS 384u #define EP0BUF 0xC0110000u #define CMDBUF 0xC0111000u /* CBW / CSW / small replies */ +#define SCRATCH 0xC0120000u /* a rejected WRITE's data */ +#define READ_ONLY (SCENARIO == 4) static void putc_(char c) { REG(UARTB_THR) = (u32)(unsigned char)c; } @@ -54,6 +58,19 @@ static void puthex(u32 v) { putc_("0123456789ABCDEF"[(v >> i) & 0xF]); } +#if SCENARIO != 3 +static void putdec(u32 v) { + char b[10]; + int n = 0; + do { + b[n++] = (char)('0' + v % 10); + v /= 10; + } while (v); + while (n) + putc_(b[--n]); +} +#endif + static void i2c5_write(u32 dev, u32 reg, u32 val) { REG(I2C5 + 0x04) = dev << 1; REG(I2C5 + 0x0C) = reg | (val << 8); @@ -250,7 +267,7 @@ static void configure(void) { for (u32 i = 2; i < 4; i++) { for (u32 w = 0; w < 16; w++) REG(QH(i) + 4 * w) = 0; - REG(QH(i)) = 512u << 16; + REG(QH(i)) = 512u << 16 | 1u << 29; /* 512, no ZLP, as bdk */ REG(QH(i) + 8) = 1; } U(EPCTRL(1)) = 2u << 2 | 1u << 7 | 2u << 18 | 1u << 23; /* bulk RX/TX on */ @@ -311,6 +328,7 @@ static void ring_init(u32 dci, u32 base) { u32 ctx = CTX + 64 * dci; zero(ctx, 64); REG(ctx) = 1; /* EP_RUNNING */ + REG(ctx + 4) = (dci ? 512u : 64u) << 16; /* max packet size */ REG(ctx + 8) = base | 1; /* dequeue pointer, DCS */ } @@ -543,16 +561,49 @@ static void bot(void) { put_be32(CMDBUF + 0x104, 512); sent = bulk(1, CMDBUF + 0x100, 8); break; - case 0x28: { /* READ(10) */ + case 0x1A: /* MODE SENSE(6) */ + zero(CMDBUF + 0x100, 4); /* the header, no pages */ + B(CMDBUF + 0x100) = 3; + B(CMDBUF + 0x102) = READ_ONLY ? 0x80 : 0; /* WP */ + sent = bulk(1, CMDBUF + 0x100, want < 4 ? want : 4); + break; + case 0x28: /* READ(10) */ + case 0x2A: { /* WRITE(10) */ u32 lba = (u32)B(cdb + 2) << 24 | B(cdb + 3) << 16 | B(cdb + 4) << 8 | B(cdb + 5); u32 cnt = B(cdb + 7) << 8 | B(cdb + 8); - if (lba + cnt > DISK_LBAS) + int bad = lba + cnt > DISK_LBAS || cnt * 512 != want; + if (op == 0x28) { + /* In 32 KiB transfers, as bdk sends a read: the host has to + * go on to the next one after a full-sized packet. */ + if (bad) + status = 1; + for (u32 off = 0; !bad && off < want; off += 32768) { + u32 n = want - off > 32768 ? 32768 : want - off; + if (bulk(1, DISK + lba * 512 + off, n) != (int)n) + break; + sent += n; + } + break; + } + /* The host sends the data whatever happens to it. */ + if (bad || READ_ONLY) { + sent = bulk(0, SCRATCH, want); status = 1; - else - sent = bulk(1, DISK + lba * 512, cnt * 512); + break; + } + sent = bulk(0, DISK + lba * 512, want); + status = sent != want; + puts_("usb test: WRITE(10) blocks "); + putdec(lba); + putc_('-'); + putdec(lba + cnt - 1); + putc_('\n'); break; } + case 0x35: /* SYNCHRONIZE CACHE(10) */ + puts_("usb test: SYNCHRONIZE CACHE\n"); + break; case 0x1E: /* PREVENT ALLOW MEDIUM REMOVAL */ break; case 0x1B: /* START STOP UNIT */ @@ -581,6 +632,8 @@ void _start(void) { puthex(crc32(DISK, 64 * 512)); puts_(" last "); puthex(crc32(DISK + (DISK_LBAS - 8) * 512, 8 * 512)); + puts_(" all "); + puthex(crc32(DISK, DISK_LBAS * 512)); putc_('\n'); init(); @@ -606,7 +659,9 @@ void _start(void) { puts_("usb test: hid reports sent\n"); #else bot(); - puts_("usb test: ejected\n"); + puts_("usb test: ejected; disk crc32 "); + puthex(crc32(DISK, DISK_LBAS * 512)); + putc_('\n'); #endif stop(); finish("usb test: done\n"); diff --git a/tests/usb/run.sh b/tests/usb/run.sh index 48a1182..95d114f 100755 --- a/tests/usb/run.sh +++ b/tests/usb/run.sh @@ -1,8 +1,11 @@ #!/bin/sh # USB device mode regression test: tests/usb/payload.c brings up a mass # storage gadget on each device controller and the emulator's --usb-host PC -# enumerates it, reads it back and ejects it; without a host the gadget must -# see nothing on the cable. Usage: tests/usb/run.sh [rcm_emu] [payload dir] +# enumerates it, reads it back, writes its last sectors back unchanged and +# ejects it; on a write-protected disk it leaves the write out. With +# --usb-host nbd the disk is served over NBD instead, and nbd_check.py reads +# and writes it. Without a host the gadget must see nothing on the cable. +# Usage: tests/usb/run.sh [rcm_emu] [payload dir] EMU=${1:-./rcm_emu} DIR=${2:-tests/usb} fail=0 @@ -23,7 +26,19 @@ expect() { fi } -check_host() { +expect_not() { + if grep -q -- "$2" "$1"; then + echo " FAIL $3 (found: $2)" + fail=1 + else + echo " ok $3" + fi +} + +crc() { sed -n "s/.*disk crc32 first [0-9A-F]* last [0-9A-F]* all \([0-9A-F]*\).*/\1/p" "$1"; } + +# Enumeration and the reads, the same in every mass storage run. +check_disk() { log=$1 name=$2 expect "$log" '\[usb-host\] device attached' "$name: the host sees the device attach" @@ -33,14 +48,64 @@ check_host() { "$name: configuration parsed" expect "$log" 'LUN 0: "RCMEMU Test disk ", removable' "$name: INQUIRY" expect "$log" 'TEST UNIT READY: sense key 6, ASC 29/00' "$name: unit attention, then REQUEST SENSE" - expect "$log" '128 blocks of 512 bytes' "$name: READ CAPACITY" + expect "$log" '384 blocks of 512 bytes (192 KiB)' "$name: READ CAPACITY" +} + +check_end() { + log=$1 + name=$2 + want=$3 + expect "$log" "usb test: ejected; disk crc32 $want" "$name: START STOP UNIT ejects, the disk as expected" + expect "$log" '\[usb-host\] device detached' "$name: the host sees the device go" + expect "$log" 'usb test: done' "$name: the payload ran to its end" +} + +check_host() { + log=$1 + name=$2 + check_disk "$log" "$name" first=$(sed -n 's/.*disk crc32 first \([0-9A-F]*\) last.*/\1/p' "$log") last=$(sed -n 's/.*disk crc32 first [0-9A-F]* last \([0-9A-F]*\).*/\1/p' "$log") expect "$log" "read blocks 0-63 (crc32 $first)" "$name: READ(10) of blocks 0-63 returns the disk" - expect "$log" "read blocks 120-127 (crc32 $last)" "$name: READ(10) of the last 8 blocks returns the disk" - expect "$log" 'usb test: ejected' "$name: START STOP UNIT ejects" - expect "$log" '\[usb-host\] device detached' "$name: the host sees the device go" - expect "$log" 'usb test: done' "$name: the payload ran to its end" + expect "$log" "read blocks 376-383 (crc32 $last)" "$name: READ(10) of the last 8 blocks returns the disk" + if [ "$3" = ro ]; then + expect "$log" '\[usb-host\] write-protected' "$name: MODE SENSE reports write protection" + expect "$log" 'write check skipped: the disk is write-protected' "$name: no write to a write-protected disk" + expect_not "$log" 'usb test: WRITE(10)' "$name: the gadget sees no WRITE(10)" + else + expect "$log" '\[usb-host\] writable' "$name: MODE SENSE reports a writable disk" + expect "$log" 'usb test: WRITE(10) blocks 376-383' "$name: WRITE(10) of the last 8 blocks" + expect "$log" 'usb test: SYNCHRONIZE CACHE' "$name: SYNCHRONIZE CACHE" + expect "$log" 'wrote blocks 376-383 back unchanged; read back: the same data' \ + "$name: the blocks read back as written" + fi + check_end "$log" "$name" "$(crc "$log")" +} + +# --usb-host nbd: nbd_check.py reads, writes (or is refused) and disconnects. +check_nbd() { + n=$1 + name=$2 + mode=$3 + shift 3 + port=$((PORT_BASE + n)) + log=$DIR/out_nbd$n.log + SDL_VIDEODRIVER=dummy RCM_EMU_NO_AUDIO=1 timeout 60 "$EMU" "$@" --usb-host nbd:$port > "$log" 2>&1 & + emu=$! + python3 "$DIR/nbd_check.py" $port "$log" $mode > "$DIR/out_nbd${n}_client.log" 2>&1 + client=$? + wait $emu + st=$? + cat "$DIR/out_nbd${n}_client.log" + [ $client -eq 0 ] || { echo " FAIL $name: NBD client"; fail=1; } + check_disk "$log" "$name" + expect "$log" "serving the disk over NBD at 127.0.0.1:$port" "$name: serving over NBD" + expect "$log" 'NBD client has the disk' "$name: the client negotiated" + expect "$log" 'NBD client disconnected' "$name: the client disconnected" + expect "$log" 'ejecting the disk' "$name: the disk is ejected on disconnect" + want=$(sed -n 's/^nbd check: disk crc32 \([0-9A-F]*\)$/\1/p' "$DIR/out_nbd${n}_client.log") + check_end "$log" "$name" "${want:-none}" + [ "$st" -eq 0 ] || { echo " FAIL $name: emulator exit $st"; fail=1; } } echo "usb test:" @@ -52,6 +117,10 @@ st=$(run 2 "$DIR/payload_2.bin" --usb-host --oem mariko) check_host "$DIR/out_2.log" "XUSB controller" [ "$st" -eq 0 ] || { echo " FAIL XUSB controller: emulator exit $st"; fail=1; } +st=$(run 4 "$DIR/payload_4.bin" --usb-host) +check_host "$DIR/out_4.log" "write-protected disk" ro +[ "$st" -eq 0 ] || { echo " FAIL write-protected disk: emulator exit $st"; fail=1; } + st=$(run 3 "$DIR/payload_3.bin" --usb-host) log=$DIR/out_3.log expect "$log" 'configuration 1: HID (EP 81 IN, interrupt every 4)' "HID gadget: configuration parsed" @@ -69,4 +138,13 @@ if grep -q '\[usb-host\]' "$DIR/out_0.log"; then fail=1 fi +if command -v python3 > /dev/null; then + PORT_BASE=${USB_TEST_NBD_PORT:-$((20000 + $$ % 20000))} + check_nbd 1 "NBD, USB2 controller" rw "$DIR/payload_1.bin" + check_nbd 2 "NBD, XUSB controller" rw "$DIR/payload_2.bin" --oem mariko + check_nbd 4 "NBD, write-protected disk" ro "$DIR/payload_4.bin" +else + echo " skip NBD: no python3" +fi + [ $fail -eq 0 ] && echo "usb test: PASS" || { echo "usb test: FAIL (logs: $DIR/out_*.log)"; exit 1; }