From f19a52b779cf21a11ac33ae1ec669c53b48aa4a1 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 15:55:48 +0000 Subject: [PATCH] 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