diff --git a/DESIGN.md b/DESIGN.md index 237bee8..37074ed 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -14,7 +14,7 @@ flowchart TB main -->|ccplex_run| a57["t210/ccplex
2nd Unicorn engine, AArch64
CCPLEX CPU0 (Cortex-A57)"] a57 -->|MMIO callbacks| mmio a57 -.->|shares| uc - main -->|sdl_display_*| sdl["display/sdl_display
block-linear de-swizzle
rotate, blit"] + main -->|sdl_display_*| sdl["display/sdl_display
DC window scan-out
blend, turn, blit"] main -->|config_window_*| cfg["display/config_window
2nd SDL window + ImGui
live hardware tweaks"] main -->|console_window_*| con["display/console_window
3rd SDL window + ImGui
per-port UART TX log + RX inject"] @@ -25,7 +25,8 @@ flowchart TB mmio --> i2c["i2c3
STMFTS / FTS4 touch"] mmio --> i2c1["I2C_1 slaves (inline)
MAX17050, TMP451,
BQ24193, BM92T36"] mmio --> i2c5["I2C_5 slaves (inline)
MAX77620, MAX77621"] - mmio --> stubs["inline stubs
GPIO, PMC, TSEC, KFUSE,
PWM, DC, CLK, TMR, FUSE, UART"] + mmio --> dc["DC + VIC (inline)
window registers A-D
VIC compose, flip/transpose"] + mmio --> stubs["inline stubs
GPIO, PMC, TSEC, KFUSE,
PWM, CLK, TMR, FUSE, UART"] mmio --> pcie["pcie
AFI, root ports, CYW4356
(CPU-complex master only)"] cfg -.->|writes atomics| state["EmuState
(emu_state.h)"] @@ -58,11 +59,13 @@ same peripheral models through one dispatch (see [CCPLEX CPU0](#ccplex-cpu0)). 2. PC is set to `0x40010000`, SP to `IPL_STACK_ADDR`. CPSR enters ARM mode. 3. The IPL (Initial Program Loader) initialises clocks, fuses and the display, then continues straight into the boot menu without loading LP0 or Minerva. -4. Hekate self-relocates into DRAM (`0xC0000000+`) and continues. The display - pipeline resamples its DRAM-side framebuffer parameters. -5. Nyx (the LVGL graphics stack) initialises and draws into a separate FB. The - DC (Display Controller) `WINDOW_HEADER` register tracks the currently - primary surface. The display code follows that pointer. +4. Hekate self-relocates into DRAM (`0xC0000000+`) and continues. It points + DC (Display Controller) window A at its portrait framebuffer and draws its + boot logo and menus there, sideways, for the landscape-mounted panel. +5. Nyx (the LVGL GUI) draws landscape into a second framebuffer and has VIC + turn every frame into the portrait surface that window A scans out. The + display follows the DC's windows, whatever they point at (see Display + pipeline). ## Memory map @@ -326,25 +329,61 @@ do not auto-creep into the build. ### Display pipeline (`display/sdl_display.cpp`) -Hekate and Nyx draw into a block-linear surface. One block-height row covers -16 GOBs (Group Of Bytes, NVIDIA's 64 by 8 pixel tile). The display thread: +The display controller is modelled as the registers of its four windows, +A-D (TRM 24.10-24.11), in `t210/mmio.cpp`. Payloads reach a window through +the indirect window pages (0x700-0x83F), which write every window +`DC_CMD_DISPLAY_WINDOW_HEADER` selects, or through a window's direct range +(A 0xB80, B 0xD80, C 0xF80). Writes land in the window's assembly copy, and +`WIN_x_ACT_REQ` in `DC_CMD_STATE_CONTROL` copies that into the active copy, +so a half-programmed window never shows. Reads return what was written. +`STATE_CONTROL` reads 0 (every request has completed), and `INT_STATUS` +reports a frame end and a vblank, which bdk polls before DSI commands. -1. Reads DC `WINDOW_HEADER` to follow the active surface (Window A, B, C or - D). -2. Looks up the FB pointer, stride and GOB block height latched from - `DC_WIN_x_SURFACE_KIND`. -3. De-swizzles into a linear RGBA buffer using a per-pixel address calc. -4. Optionally rotates 0, 90, 180 or 270 degrees to match the panel orientation - detected from window dimensions, with an `R` or `Shift+R` manual override. -5. Blits to an SDL_Texture at the host window current size. +Each display tick builds the picture the panel would receive, 720x1280 and +portrait, the way the DC builds it: -The de-swizzle is the hottest path. It is inlined and operates on `u32` -units. The surface is read straight from the host memory behind emulated DRAM, -and a frame whose bytes and layout `(addr, w, h, stride, sw, bh, rot)` match -the previous one skips the de-swizzle and the texture upload entirely. No -renderer uses `PRESENTVSYNC`: the CPU runs on the same thread, the loop -already paces redraws to ~60 Hz, and a vsync'd present could stall the -emulated CPU for a whole frame. +1. Every enabled window's surface is fetched at `START_ADDR`. The layout + comes from `SURFACE_KIND`: pitch, 16x16 tiled, or block linear with + 2^`BLOCK_HEIGHT` GOBs (Groups of Bytes, 64x8-byte tiles) per block. The + line pitch is `LINE_STRIDE`, and pixels are decoded per `COLOR_DEPTH`. + Block-linear byte order follows TRM 20.1.2 and Figure 47. +2. `WIN_OPTIONS` turns the surface: H_DIRECTION and V_DIRECTION mirror it, + and SCAN_COLUMN walks its columns (90/270 degrees, TRM Table 122). The + result is scaled from `PRESCALED_SIZE` to `SIZE`, nearest-neighbour, and + placed at `POSITION`. +3. The windows are stacked by layer depth (A under D when equal) and blended + per `BLEND_LAYER_CONTROL` and `BLEND_MATCH_SELECT`. Hekate's log console + (window D, K1 = 200) shows through as it does on the console. + +The panel picture is then turned for the host window. When the surface on +show was turned on its way to the panel, by the DC (SCAN_COLUMN) or by a +VIC compose (Nyx), the turn is undone. A GUI drawn landscape is then shown +landscape. A surface drawn straight into portrait (hekate's logo and TUI, +hwtest) is shown as the panel receives it. `Ctrl+R` / `Ctrl+Shift+R` +override the turn, and `S` forces pitch or block-linear decoding for +diagnosis. Until +the payload first activates a window, the emulator's own framebuffer at +`FB_BASE` stands in as window A. + +A frame whose surfaces' bytes and layout match the previous frame skips the +rebuild and the texture upload. Surfaces are read straight from the host +memory behind emulated DRAM. No renderer uses `PRESENTVSYNC`: the CPU runs +on the same thread, the loop already paces redraws to ~60 Hz, and a vsync'd +present could stall the emulated CPU for a whole frame. + +### VIC (`t210/mmio.cpp`) + +bdk drives VIC through the Falcon private-register window. The model keeps +the config struct's address (`VIC_SC_PRAMBASE`), the slots' source surfaces +(`VIC_SC_SFC0_BASE_LUMA(n)`) and the target (`VIC_BL_TARGET_BASADR`). On +`VIC_FC_COMPOSE` it reads bdk's `vic_config_t` from guest memory and draws +every enabled pitch slot into the target, scaling the source rect onto the +dest rect, clipped to the target rect, with the output flip X, flip Y and +transpose applied. The output size is given before the transpose, so a +transposed target is H x W pixels, which is how the DC then reads it. The +compose also records the target address and the turn applied, which the +display uses to undo it. Nyx's 270-degree rotation is flip X then transpose. +Block-linear VIC surfaces are not modelled, and nothing in bdk uses them. ### UART @@ -585,6 +624,15 @@ don't repeat the diagnosis: Now `fstat`-derived from `rawnand.bin.00`. - **Save header SHA-256** rejected by TE because the SE only modelled AES. Hence the SHA-256 path in `se_engine.cpp`. +- **Display stride and window state.** The DC model took the line stride + from `PRESCALED_SIZE` rather than `LINE_STRIDE`, kept one set of window + parameters shared by all four windows (window D's 656-pixel width leaked + into window A), and the block-linear decoder had two GOB address bits + swapped. The renderer compensated with per-address heuristics (a + "known menu stride" of 2624, forced block-linear decoding of the IPL + carveout, a hard-coded 1280x720 geometry for Nyx's framebuffer). Fix: + per-window register files latched on `WIN_x_ACT_REQ`, a TRM-exact + scan-out, and a VIC that really rotates. The heuristics are gone. - **PINMUX / PWM read-back** silently returned 0, so any probe that read back its own pad-mux setting (e.g. hwtest checking `LCD_BL_PWM` is in PWM0 mode) saw an unconfigured pin even after a successful write. Fix: diff --git a/README.md b/README.md index 44e2b42..6f33435 100644 --- a/README.md +++ b/README.md @@ -296,7 +296,7 @@ flowchart LR t210 --> se["se_engine.{h,cpp}
AES-128, SHA-256"] t210 --> i2c["i2c3.{h,cpp}
STMFTS / FTS4 touch"] - display --> sdl["sdl_display.{h,cpp}
block-linear de-swizzle
+ SDL2"] + display --> sdl["sdl_display.{h,cpp}
DC window scan-out
+ SDL2"] ``` For implementation details, see [DESIGN.md](DESIGN.md). diff --git a/display/sdl_display.cpp b/display/sdl_display.cpp index 5b2bd8d..d52e7da 100644 --- a/display/sdl_display.cpp +++ b/display/sdl_display.cpp @@ -6,6 +6,7 @@ #include #include +#include #include #include @@ -55,141 +56,335 @@ bool sdl_display_init() { return true; } +// ---- Scan-out ------------------------------------------------------------ +// +// The frame is built the way the display controller builds it (TRM 24): +// every enabled window's surface is fetched per its SURFACE_KIND (pitch, +// 16x16 tiled or block linear) and LINE_STRIDE, turned per WIN_OPTIONS +// (H/V direction, SCAN_COLUMN), scaled from PRESCALED_SIZE to SIZE and +// placed at POSITION, the windows stacked by layer depth and blended per +// BLEND_*. The result is the 720x1280 portrait picture the panel receives. +// +// For the host window that picture is then turned: when the surface on show +// was itself turned on its way to the panel - by the DC (SCAN_COLUMN) or by +// a VIC compose, as Nyx does - the turn is undone, so a GUI drawn landscape +// is shown landscape. A surface drawn straight into portrait (hekate's TUI, +// hwtest) is shown as the panel gets it. Ctrl+R / Ctrl+Shift+R override the +// turn. + +namespace { + +constexpr uint32_t kPanelW = 720, kPanelH = 1280; + +// A picture turn as a 2x2 matrix on centred coordinates: out = M * in. +struct Turn { + int a, b, c, d; // [[a b] [c d]] +}; + +Turn turn_of(uint32_t xf) { // dcwin::XF_* (flip, then transpose) + int fx = (xf & dcwin::XF_FLIP_X) ? -1 : 1; + int fy = (xf & dcwin::XF_FLIP_Y) ? -1 : 1; + if (xf & dcwin::XF_TRANSPOSE) + return {0, fy, fx, 0}; + return {fx, 0, 0, fy}; +} + +Turn operator*(const Turn &l, const Turn &r) { + return {l.a * r.a + l.b * r.c, l.a * r.b + l.b * r.d, + l.c * r.a + l.d * r.c, l.c * r.b + l.d * r.d}; +} + +// The view rotation (as the render loop applies it, see rot below) that +// undoes turn t, or 0 when t is a mirror image, which no rotation undoes. +int undo_rot(const Turn &t) { + if (t.a * t.d - t.b * t.c != 1) + return 0; + Turn inv = {t.a, t.c, t.b, t.d}; // a rotation's inverse is its transpose + if (inv.a == 0 && inv.b == -1) + return 1; + if (inv.a == -1) + return 2; + if (inv.a == 0 && inv.b == 1) + return 3; + return 0; +} + +uint32_t depth_bpp(uint32_t depth) { + if (depth <= 3) + return 1; // palettised + if (depth <= 7 || (depth >= 0x1E && depth <= 0x21)) + return 2; + return 4; +} + +// One pixel of a DC_WIN_COLOR_DEPTH format as ARGB8888. +uint32_t depth_argb(const uint8_t *p, uint32_t depth) { + auto x5 = [](uint32_t v) { return (v << 3) | (v >> 2); }; + auto x6 = [](uint32_t v) { return (v << 2) | (v >> 4); }; + switch (depth) { + case 0x4: { // B4G4R4A4 + uint32_t v = p[0] | (p[1] << 8); + return ((v >> 12) * 0x11u) << 24 | ((v >> 8) & 0xF) * 0x11u << 16 | + ((v >> 4) & 0xF) * 0x11u << 8 | (v & 0xF) * 0x11u; + } + case 0x5: { // B5G5R5A + uint32_t v = p[0] | (p[1] << 8); + return ((v & 0x8000) ? 0xFF000000u : 0) | x5((v >> 10) & 0x1F) << 16 | + x5((v >> 5) & 0x1F) << 8 | x5(v & 0x1F); + } + case 0x7: { // AB5G5R5 + uint32_t v = p[0] | (p[1] << 8); + return ((v & 1) ? 0xFF000000u : 0) | x5(v >> 11) << 16 | + x5((v >> 6) & 0x1F) << 8 | x5((v >> 1) & 0x1F); + } + case 0xD: // R8G8B8A8 + case 0xF: + return (uint32_t)p[3] << 24 | (uint32_t)p[0] << 16 | + (uint32_t)p[1] << 8 | p[2]; + default: + break; + } + switch (depth_bpp(depth)) { + case 1: + return 0xFF000000u | p[0] * 0x010101u; + case 2: { // B5G6R5 and anything else 16-bit + uint32_t v = p[0] | (p[1] << 8); + return 0xFF000000u | x5(v >> 11) << 16 | x6((v >> 5) & 0x3F) << 8 | + x5(v & 0x1F); + } + default: // B8G8R8A8 (bytes B, G, R, A) + return (uint32_t)p[3] << 24 | (uint32_t)p[2] << 16 | + (uint32_t)p[1] << 8 | p[0]; + } +} + +struct Win { + int idx = 0; + uint64_t addr = 0; + uint32_t depth = 0, bpp = 4, kind = 0, gob_h = 1, stride = 0, gobs = 0; + uint32_t src_w = 0, src_h = 0; // the surface, before the DC turns it + uint32_t pre_w = 0, pre_h = 0; // PRESCALED_SIZE, in pixels (post-turn) + uint32_t out_w = 0, out_h = 0; // SIZE + int32_t x = 0, y = 0; + uint32_t xf = 0, layer = 0, blend_layer = 0, blend_match = 0; + size_t len = 0; + const uint8_t *mem = nullptr; + std::vector copy; // when the surface is not in the DRAM window +}; + +// Byte offset of surface pixel (sx, sy). +inline size_t fetch_off(const Win &w, uint32_t sx, uint32_t sy) { + uint32_t xb = sx * w.bpp; + switch (w.kind) { + case 1: // 16x16-byte tiles, row-major + return (size_t)(sy / 16) * w.stride * 16 + (xb / 16) * 256 + + (sy % 16) * 16 + (xb % 16); + case 2: { // block linear, TRM 20.1.2 (Figure 47 sector order) + uint32_t gob_y = sy / 8; + size_t gob = ((size_t)(gob_y / w.gob_h) * w.gobs + xb / 64) * w.gob_h + + gob_y % w.gob_h; + uint32_t x = xb % 64, y = sy % 8; + return gob * 512 + (x / 32) * 256 + (y / 2) * 64 + ((x % 32) / 16) * 32 + + (y % 2) * 16 + (x % 16); + } + default: + return (size_t)sy * w.stride + xb; + } +} + +// Build window w from its active register file; false if it shows nothing. +bool load_window(EmuState *state, uc_engine *uc, int idx, const uint32_t *r, + int swizzle_override, Win &w) { + if (!(r[dcwin::OPTIONS] & dcwin::WIN_ENABLE)) + return false; + w.idx = idx; + w.depth = r[dcwin::COLOR_DEPTH] & 0x7F; + w.bpp = depth_bpp(w.depth); + uint32_t sk = r[dcwin::SURFACE_KIND]; + w.kind = sk & 3; + w.gob_h = 1u << ((sk >> 4) & 7); + if (swizzle_override == 0) { + w.kind = 0; + } else if (swizzle_override == 2 && w.kind != 2) { + w.kind = 2; + w.gob_h = 16; + } + w.out_w = r[dcwin::SIZE] & 0x1FFF; + w.out_h = (r[dcwin::SIZE] >> 16) & 0x1FFF; + w.pre_w = (r[dcwin::PRESCALED] & 0x7FFF) / w.bpp; + w.pre_h = (r[dcwin::PRESCALED] >> 16) & 0x1FFF; + if (!w.pre_w || !w.pre_h) { // never programmed: no scaling + w.pre_w = w.out_w; + w.pre_h = w.out_h; + } + if (!w.out_w || !w.out_h) + return false; + uint32_t opt = r[dcwin::OPTIONS]; + w.xf = ((opt & dcwin::H_DIRECTION) ? dcwin::XF_FLIP_X : 0) | + ((opt & dcwin::V_DIRECTION) ? dcwin::XF_FLIP_Y : 0) | + ((opt & dcwin::SCAN_COLUMN) ? dcwin::XF_TRANSPOSE : 0); + // SCAN_COLUMN walks the surface's columns: it is pre_h wide, pre_w tall. + bool column = w.xf & dcwin::XF_TRANSPOSE; + w.src_w = column ? w.pre_h : w.pre_w; + w.src_h = column ? w.pre_w : w.pre_h; + w.x = (int16_t)(r[dcwin::POSITION] & 0xFFFF); + w.y = (int16_t)(r[dcwin::POSITION] >> 16); + w.blend_layer = r[dcwin::BLEND_LAYER]; + w.blend_match = r[dcwin::BLEND_MATCH]; + w.layer = w.blend_layer & 0xFF; + w.stride = r[dcwin::LINE_STRIDE] & 0xFFFF; + if (!w.stride) + w.stride = w.src_w * w.bpp; + w.addr = (uint64_t)r[dcwin::START_ADDR] + (int64_t)state->manual_offset; + switch (w.kind) { + case 2: + w.gobs = (w.stride + 63) / 64; + w.len = (size_t)w.gobs * 512 * w.gob_h * + ((w.src_h + 8 * w.gob_h - 1) / (8 * w.gob_h)); + break; + case 1: + w.len = (size_t)w.stride * ((w.src_h + 15) / 16) * 16; + break; + default: + w.len = (size_t)w.stride * w.src_h; + break; + } + if (w.len == 0 || w.len > 64u * 1024 * 1024) + return false; + if (state->dram_low_ptr && w.addr >= DRAM_BASE && + w.addr + w.len <= DRAM_BASE + DRAM_WINDOW_SIZE) { + w.mem = state->dram_low_ptr + (w.addr - DRAM_BASE); + } else { + w.copy.resize(w.len); + if (uc_mem_read(uc, w.addr, w.copy.data(), w.len) != UC_ERR_OK) + return false; + w.mem = w.copy.data(); + } + return true; +} + +// Blend factor (0..255) per BLEND_MATCH_SELECT (TRM 24.10.13). +uint32_t src_factor(uint32_t sel, uint32_t k1, uint32_t sa) { + switch (sel) { + case 1: return 255; + case 2: case 3: return k1; // K1, K1 x dst alpha (opaque dst) + case 4: return 255 - k1; // 1 - K1 x dst alpha + case 5: return k1 * sa / 255; // K1 x src alpha + default: return 0; + } +} +uint32_t dst_factor(uint32_t sel, uint32_t k1, uint32_t k2, uint32_t sa) { + switch (sel) { + case 1: return 255; + case 2: case 4: return k1; + case 3: return k2; + case 5: case 7: return 255 - k1; + case 6: return 255 - k1 * sa / 255; + default: return 0; + } +} + +// Draw window w onto the panel picture. +void draw_window(const Win &w, std::vector &panel) { + bool blend = !(w.blend_layer & (1u << 24)); + uint32_t k1 = (w.blend_layer >> 8) & 0xFF, k2 = (w.blend_layer >> 16) & 0xFF; + uint32_t ssel = w.blend_match & 7, dsel = (w.blend_match >> 4) & 7; + bool hflip = w.xf & dcwin::XF_FLIP_X, vflip = w.xf & dcwin::XF_FLIP_Y; + bool column = w.xf & dcwin::XF_TRANSPOSE; + // Column scaling map, worked out once per window rather than per pixel. + static std::vector txs; + txs.resize(w.out_w); + for (uint32_t ox = 0; ox < w.out_w; ox++) + txs[ox] = (uint32_t)((uint64_t)ox * w.pre_w / w.out_w); + for (uint32_t oy = 0; oy < w.out_h; oy++) { + int32_t py = w.y + (int32_t)oy; + if (py < 0 || py >= (int32_t)kPanelH) + continue; + uint32_t ty = (uint32_t)((uint64_t)oy * w.pre_h / w.out_h); + for (uint32_t ox = 0; ox < w.out_w; ox++) { + int32_t px = w.x + (int32_t)ox; + if (px < 0 || px >= (int32_t)kPanelW) + continue; + uint32_t tx = txs[ox]; + // (tx, ty) is post-turn; walk it back to the surface. + uint32_t a = column ? ty : tx, b = column ? tx : ty; + uint32_t sx = hflip ? w.src_w - 1 - a : a; + uint32_t sy = vflip ? w.src_h - 1 - b : b; + size_t off = fetch_off(w, sx, sy); + if (off + w.bpp > w.len) + continue; + uint32_t s = depth_argb(w.mem + off, w.depth); + uint32_t &d = panel[(size_t)py * kPanelW + px]; + if (!blend) { + d = s | 0xFF000000u; + continue; + } + uint32_t sa = s >> 24; + uint32_t fs = src_factor(ssel, k1, sa), fd = dst_factor(dsel, k1, k2, sa); + uint32_t o = 0xFF000000u; + for (int sh = 0; sh < 24; sh += 8) { + uint32_t c = (((s >> sh) & 0xFF) * fs + ((d >> sh) & 0xFF) * fd) / 255; + o |= (c > 255 ? 255 : c) << sh; + } + d = o; + } + } +} + +} // namespace + void sdl_display_update(EmuState *state, uc_engine *uc) { if (!renderer) return; - uint32_t width = state->fb_width, height = state->fb_height, - stride = state->fb_stride; - if (width < 16 || height < 16) - return; - - // If the current fb_addr is empty but we have a saved Window A with - // content, prefer the Window A surface. This handles the case where - // Hekate's TUI renders to IPL_FB (0xF5A00000) but the DC was repointed - // to NYX_FB (0xF6200000) by a failed Nyx init sequence. - uint64_t eff_addr = state->fb_addr; - if (state->winA_addr && state->winA_addr != eff_addr) { - // Quick check: sample a few dwords from fb_addr. - uint32_t sample[4] = {0}; - uc_mem_read(uc, eff_addr, sample, sizeof(sample)); - bool empty = (sample[0] == 0 && sample[1] == 0 && - sample[2] == 0 && sample[3] == 0); - if (empty) { - // Check if winA_addr has content. - uc_mem_read(uc, state->winA_addr, sample, sizeof(sample)); - if (sample[0] != 0 || sample[1] != 0 || - sample[2] != 0 || sample[3] != 0) { - eff_addr = state->winA_addr; - width = state->winA_w; - height = state->winA_h; - stride = state->winA_stride; - } - } + // The windows on show, bottom first. Until the payload programs the DC, + // the emulator's own framebuffer stands in as window A. + std::vector wins; + uint32_t boot_win[dcwin::kRegs] = {}; + boot_win[dcwin::OPTIONS] = dcwin::WIN_ENABLE; + boot_win[dcwin::COLOR_DEPTH] = 0xC; // B8G8R8A8 + boot_win[dcwin::SIZE] = kPanelH << 16 | kPanelW; + boot_win[dcwin::LINE_STRIDE] = kPanelW * 4; + boot_win[dcwin::BLEND_LAYER] = dcwin::BLEND_LAYER_RESET; + boot_win[dcwin::START_ADDR] = (uint32_t)FB_BASE; + for (int i = 0; i < 4; i++) { + const uint32_t *r = state->dc_programmed ? state->dc_win_active[i] + : (i == 0 ? boot_win : nullptr); + if (!r) + continue; + Win w; + if (load_window(state, uc, i, r, g_swizzle_override, w)) + wins.push_back(std::move(w)); } + // Deeper layers first; equal depths stack A (bottom) to D (top). + std::stable_sort(wins.begin(), wins.end(), [](const Win &l, const Win &r) { + return l.layer > r.layer; + }); - // Helper: is the address inside the IPL framebuffer carveout? - auto addr_in_ipl_fb = [](uint64_t a) -> bool { - return a >= FB_BASE && a < FB_BASE + FB_SIZE; - }; - - // Auto-detect first; a manual override is applied on top further down. - int rot = -1; - - uint32_t sw = state->fb_swizzle; - uint32_t eff_stride = stride; - uint32_t bpp = 4; - uint32_t bh = state->fb_bh ? state->fb_bh : 16; // Block height in GOBs - - // --- OVERRIDES & AUTO-DETECTS --- - constexpr uint64_t kNyxFbBase = 0xF6200000ULL; - - if (g_swizzle_override != -1) { - sw = (uint32_t)g_swizzle_override; // Manual User Override (S Key) - } else if (eff_addr == kNyxFbBase) { - // Nyx GUI uses VIC to rotate its 1280x720 landscape UI into 720x1280 portrait mode (NYX_FB_ADDRESS). - // Our emulator's mock VIC only memcpys the data, so 0xF6200000 actually holds a 1280x720 landscape image! - // Since the DC is programmed for 720x1280, it will scramble it. - // We override the display geometry here to render the raw 1280x720 memory correctly. - sw = 0; - width = 1280; - height = 720; - eff_stride = 1280 * 4; // 32-bit XRGB - rot = 0; - bh = 4; - } else if (eff_addr == FB_BASE && sw == 0 && width == 720u && - height == 1280u && eff_stride == width * 4u) { - // Hekate TUI or static bootlogo: natively rendered as 720x1280 pitch-linear portrait. - // Do not apply any automatic layout overrides. - sw = 0; - rot = 0; // The UI is drawn sideways in memory to appear upright on a landscape physical Switch screen. - // On PC, we want to view it rotated so it resembles the physical landscape Switch! - } else if (addr_in_ipl_fb(eff_addr) && sw == 0) { - // IPL carveout with Sw=0: Hekate writes block-linear data but the DC - // surface kind says pitch. Detect when the stride/dimensions don't - // match a coherent pitch-linear layout and force block-linear decode. - bool coherent_pitch = - width > 0 && (eff_stride == width * 4u || eff_stride == width * 2u); - bool portrait_stride_mismatch = - height == 1280u && width == 720u && eff_stride != width * 4u; - bool known_menu_stride = (eff_stride == 2624u && !coherent_pitch); - - // crop_portrait only forces BL when stride is incoherent — if stride - // matches width*bpp, the data may already be VIC-de-swizzled pitch. - bool crop_portrait_incoherent = - height == 1280u && width < 720u && width >= 640u && !coherent_pitch; - - if (!coherent_pitch || portrait_stride_mismatch || known_menu_stride || - crop_portrait_incoherent) { - sw = 2; // Force block-linear decode - bh = 4; // Hekate menu uses BH=4 - } + // The largest window decides how the picture is turned for the host. + const Win *primary = nullptr; + for (const Win &w : wins) + if (!primary || (uint64_t)w.out_w * w.out_h > + (uint64_t)primary->out_w * primary->out_h || + ((uint64_t)w.out_w * w.out_h == + (uint64_t)primary->out_w * primary->out_h && + w.idx < primary->idx)) + primary = &w; + int rot = 0; + if (primary) { + Turn t = turn_of(primary->xf); + if (state->vic_out_addr && primary->addr == state->vic_out_addr) + t = t * turn_of(state->vic_out_xform); + rot = undo_rot(t); } - - // Final heuristic: NEVER auto-rotate 720x1280 portrait buffers to landscape! - if (rot == -1) { - if (width == 720 && height == 1280) { - rot = 0; // Hekate already drew it sideways for physical portrait, so rot=0 makes it look like a phone on PC monitor! - // Actually wait: if drawn upright in memory (row-by-row), then rot=0 produces a tall 720x1280 window on PC where it is perfectly upright! - // The user wants the white lines to be horizontal. This means we MUST let the window be 720x1280! - } else { - rot = (height > width) ? 1 : 0; // Legacy heuristic for other stuff - } - } - - // Manual rotation override always wins. The auto-detect branches above set - // rot = 0 for Nyx and Hekate TUI surfaces; if the user pressed R/Shift+R - // they expect the rotation to actually change, regardless of what the - // auto-detect picked. -1 means "use auto-detect", anything else overrides. - state->last_auto_rot.store((uint32_t)(rot & 3)); + state->last_auto_rot.store((uint32_t)rot); if (state->rotation_override != -1) rot = state->rotation_override & 3; - // --- Compute GOB stride for block-linear --- - uint32_t sw_gobs = (width * bpp + 63) / 64; - if (sw == 2) { - // For IPL carveout portrait surfaces, Hekate allocates a full 720px-wide - // BL surface even when the DC window is cropped to 656px. - if (addr_in_ipl_fb(state->fb_addr) && state->fb_addr != kNyxFbBase && - bpp == 4 && height == 1280u && width >= 640u && width <= 720u) { - uint32_t sw_720 = (720u * bpp + 63) / 64u; - if (sw_gobs < sw_720) - sw_gobs = sw_720; - } - // If DC provides a stride that's GOB-aligned, prefer it - if (eff_stride >= 64u && (eff_stride % 64u) == 0u) { - uint32_t stride_gobs = eff_stride / 64u; - if (stride_gobs > sw_gobs) - sw_gobs = stride_gobs; - } - } - - uint32_t out_w = (rot & 1) ? height : width; - uint32_t out_h = (rot & 1) ? width : height; - - // Cache the effective rotation and output dims so the SDL event handler can - // invert the framebuffer→window transform when mapping mouse → panel coords. - state->last_rot.store((uint32_t)((rot < 0) ? 0 : (rot & 3))); + uint32_t out_w = (rot & 1) ? kPanelH : kPanelW; + uint32_t out_h = (rot & 1) ? kPanelW : kPanelH; + // The SDL event handler inverts this view to map mouse -> panel coords. + state->last_rot.store((uint32_t)rot); state->last_out_w.store(out_w); state->last_out_h.store(out_h); @@ -197,8 +392,8 @@ void sdl_display_update(EmuState *state, uc_engine *uc) { if (!texture || out_w != last_w || out_h != last_h) { if (texture) SDL_DestroyTexture(texture); - // Use ARGB8888: natively matches Tegra's BGRA memory layout on Little - // Endian + // ARGB8888 matches the B8G8R8A8 bytes of a Tegra surface on a + // little-endian host. texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, out_w, out_h); last_w = out_w; @@ -206,194 +401,84 @@ void sdl_display_update(EmuState *state, uc_engine *uc) { SDL_SetWindowSize(window, out_w, out_h); } - static uint32_t last_log_p[6] = {0}; // Addr, W, H, Rot, Sw, BH - if (state->fb_addr != last_log_p[0] || width != last_log_p[1] || - height != last_log_p[2] || (uint32_t)rot != last_log_p[3] || - sw != last_log_p[4] || bh != last_log_p[5]) { - printf("[display] LATCH: 0x%X (%dx%d), Rot: %d (Manual: %d), Sw: %d, " - "GOBs: %u, BH: %u, BPP: %u\n", - (uint32_t)state->fb_addr, width, height, rot, - state->rotation_override, sw, sw_gobs, bh, bpp * 8); - last_log_p[0] = state->fb_addr; - last_log_p[1] = width; - last_log_p[2] = height; - last_log_p[3] = rot; - last_log_p[4] = sw; - last_log_p[5] = bh; + // Skip the rebuild and the texture upload when neither the surfaces' bytes + // nor the way they are laid out changed since the last frame - the common + // case for a payload sitting on a menu or waiting on hardware. + std::vector shape = {(uint64_t)rot, wins.size()}, where; + for (const Win &w : wins) { + shape.insert(shape.end(), + {(uint64_t)w.idx, w.addr, w.len, w.depth, w.kind, w.gob_h, + w.stride, (uint64_t)w.pre_w << 32 | w.pre_h, + (uint64_t)w.out_w << 32 | w.out_h, w.xf, w.blend_layer, + w.blend_match}); + where.push_back((uint64_t)(uint32_t)w.x << 32 | (uint32_t)w.y); } + static std::vector last_shape, last_where; + static std::vector last_bytes; + size_t total = 0; + for (const Win &w : wins) + total += w.len; + bool same = shape == last_shape && where == last_where && + last_bytes.size() == total; + for (size_t i = 0, pos = 0; same && i < wins.size(); pos += wins[i++].len) + same = memcmp(last_bytes.data() + pos, wins[i].mem, wins[i].len) == 0; - eff_addr = - (eff_addr ? eff_addr : FB_BASE) + - (uint64_t)(int64_t)state->manual_offset; - - // Compute framebuffer byte size - size_t fb_size = (sw == 2) ? ((size_t)sw_gobs * ((height + 7) / 8) * 512) - : ((size_t)eff_stride * height); - if (fb_size < 1024) - return; - if (sw != 2 && eff_stride < 16) - return; // Pitch-linear sanity check only - if (fb_size > 32 * 1024 * 1024) - fb_size = 32 * 1024 * 1024; - - // The surface is read straight out of the host memory backing emulated - // DRAM when it lives there (it always does for hekate/Nyx), instead of a - // uc_mem_read into a fresh 3.5 MB vector - and the converted frame reuses - // one buffer too. The old code allocated and zero-filled two such vectors - // on every frame, 60 times a second, which showed up in profiles as page- - // fault and munmap churn on the emulation thread. - static std::vector fallback; - const uint8_t *src = nullptr; - if (state->dram_low_ptr && eff_addr >= DRAM_BASE && - eff_addr + fb_size <= DRAM_BASE + DRAM_WINDOW_SIZE) { - src = state->dram_low_ptr + (eff_addr - DRAM_BASE); - } else { - fallback.resize(fb_size); - if (uc_mem_read(uc, eff_addr, fallback.data(), fb_size) == UC_ERR_OK) - src = fallback.data(); - } - - // Skip the de-swizzle and the texture upload when neither the surface - // bytes nor the way they are laid out has changed since the last frame - - // the common case for a payload sitting on a menu or waiting on hardware. - struct Layout { - uint64_t addr = 0; - uint32_t w = 0, h = 0, stride = 0, sw = 0, bh = 0, gobs = 0, out_w = 0, - out_h = 0; - int rot = 0; - bool operator==(const Layout &o) const { - return addr == o.addr && w == o.w && h == o.h && stride == o.stride && - sw == o.sw && bh == o.bh && gobs == o.gobs && out_w == o.out_w && - out_h == o.out_h && rot == o.rot; - } - }; - static Layout last_layout; - static std::vector last_src; - Layout layout; - layout.addr = eff_addr; - layout.w = width; - layout.h = height; - layout.stride = eff_stride; - layout.sw = sw; - layout.bh = bh; - layout.gobs = sw_gobs; - layout.out_w = out_w; - layout.out_h = out_h; - layout.rot = rot; - bool unchanged = src && layout == last_layout && last_src.size() == fb_size && - memcmp(last_src.data(), src, fb_size) == 0; static bool snapshot_pending = true; - - if (src && !unchanged) { - last_layout = layout; - last_src.assign(src, src + fb_size); + if (!same) { + // Log layout changes, but not moves: bdk slides its log window in. + if (shape != last_shape) + printf("[display] scan-out: %zu window(s), view %ux%u, rot %d (auto %u)\n", + wins.size(), out_w, out_h, rot, state->last_auto_rot.load()); + last_shape = shape; + last_where = where; + last_bytes.resize(total); + size_t pos = 0; + for (const Win &w : wins) { + memcpy(last_bytes.data() + pos, w.mem, w.len); + pos += w.len; + } snapshot_pending = true; - const uint8_t *buf_data = src; - std::vector &proc = g_frame; - proc.assign((size_t)out_w * out_h, 0xFF000000); // opaque black - for (uint32_t sy = 0; sy < height; sy++) { - for (uint32_t sx = 0; sx < width; sx++) { - uint32_t off = 0; - if (sw == 2) { - if (bpp == 4) { - // Use tegra_bl_byte_off_rgba8888 formula inline for 32bpp - uint32_t gob_x = sx / 16u; - uint32_t pixel_x = sx % 16u; - uint32_t gob_y = sy / 8u; - uint32_t line_y = sy % 8u; - uint32_t block_y = gob_y / bh; - uint32_t gob_in_block_y = gob_y % bh; + static std::vector panel; + panel.assign((size_t)kPanelW * kPanelH, 0xFF000000u); // black background + for (const Win &w : wins) + draw_window(w, panel); - uint32_t idx = - (block_y * sw_gobs * bh * 128u) + (gob_x * bh * 128u) + - (gob_in_block_y * 128u) + (pixel_x & 3u) + - ((line_y & 1u) << 2) + ((pixel_x & 4u) << 1) + - ((line_y & 2u) << 3) + ((pixel_x & 8u) << 2) + - ((line_y & 4u) << 4); - off = idx; // Already in uint32 units - } else { - // 16bpp block-linear (Nyx RGB565) - uint32_t byte_x = sx * bpp; - uint32_t gx = byte_x / 64; - uint32_t px_in = byte_x % 64; - uint32_t gy = sy / 8; - uint32_t ly = sy % 8; - uint32_t gob_off = ((ly >> 1) << 7) + ((px_in >> 4) << 5) + - ((ly & 1) << 4) + (px_in & 0xF); - uint32_t gob_idx = - (gy / bh) * (sw_gobs * bh) + gx * bh + (gy % bh); - uint32_t byte_off = gob_idx * 512 + gob_off; - // Read 16-bit pixel and expand to 32-bit ARGB - if (byte_off + 2 <= fb_size) { - uint16_t u16 = *(const uint16_t *)&buf_data[byte_off]; - uint32_t p = (((u16 >> 11) & 0x1F) << 19) | - (((u16 >> 5) & 0x3F) << 10) | - ((u16 & 0x1F) << 3) | 0xFF000000; - uint32_t dx = sx, dy = sy; - switch (rot) { - case 1: dx = height - 1 - sy; dy = sx; break; - case 2: dx = width - 1 - sx; dy = height - 1 - sy; break; - case 3: dx = sy; dy = width - 1 - sx; break; - default: break; - } - if (dx < out_w && dy < out_h) - proc[dy * out_w + dx] = p; - } - continue; // Skip the common 32bpp path below - } - } else { - off = (sy * eff_stride + sx * bpp) / 4; - } - - if (off < fb_size / 4) { - uint32_t p = ((const uint32_t *)buf_data)[off]; - uint32_t dx = sx, dy = sy; - - switch (rot) { - case 1: - dx = height - 1 - sy; - dy = sx; - break; - case 2: - dx = width - 1 - sx; - dy = height - 1 - sy; - break; - case 3: - dx = sy; - dy = width - 1 - sx; - break; - default: - break; // 0 - } - if (dx < out_w && dy < out_h) { - // Native BGRA to ARGB8888 conversion mapping (forces A to 0xFF) - proc[dy * out_w + dx] = p | 0xFF000000; - } + // Turn the panel picture for the view: a panel pixel (sx, sy) of the + // W x H picture lands at + // rot 1: (H-1-sy, sx) 2: (W-1-sx, H-1-sy) 3: (sy, W-1-sx) + g_frame.resize((size_t)out_w * out_h); + for (uint32_t sy = 0; sy < kPanelH; sy++) { + const uint32_t *row = &panel[(size_t)sy * kPanelW]; + for (uint32_t sx = 0; sx < kPanelW; sx++) { + uint32_t dx = sx, dy = sy; + switch (rot) { + case 1: dx = kPanelH - 1 - sy; dy = sx; break; + case 2: dx = kPanelW - 1 - sx; dy = kPanelH - 1 - sy; break; + case 3: dx = sy; dy = kPanelW - 1 - sx; break; + default: break; } + g_frame[(size_t)dy * out_w + dx] = row[sx]; } } - SDL_UpdateTexture(texture, nullptr, proc.data(), out_w * 4); + SDL_UpdateTexture(texture, nullptr, g_frame.data(), out_w * 4); } - if (src) { - // Snapshot for PNG conversion — at most once a second (~60 frames), and - // only when the frame has changed since the last one written, so an idle - // payload no longer rewrites a 3.5 MB file every second. - static int snap_counter = 0; - const std::vector &proc = g_frame; - if (++snap_counter >= 60 && snapshot_pending && !proc.empty()) { - snap_counter = 0; - snapshot_pending = false; - FILE *f = fopen("last_fb.rgba", "wb"); - if (f) { - fwrite(proc.data(), 1, proc.size() * 4, f); - fclose(f); - FILE *fm = fopen("last_fb.meta", "w"); - if (fm) { - fprintf(fm, "%u %u\n", out_w, out_h); - fclose(fm); - } + // Snapshot for PNG conversion - at most once a second (~60 frames), and + // only when the frame has changed since the last one written, so an idle + // payload does not rewrite a 3.5 MB file every second. + static int snap_counter = 0; + if (++snap_counter >= 60 && snapshot_pending && !g_frame.empty()) { + snap_counter = 0; + snapshot_pending = false; + FILE *f = fopen("last_fb.rgba", "wb"); + if (f) { + fwrite(g_frame.data(), 1, g_frame.size() * 4, f); + fclose(f); + FILE *fm = fopen("last_fb.meta", "w"); + if (fm) { + fprintf(fm, "%u %u\n", out_w, out_h); + fclose(fm); } } } @@ -426,12 +511,11 @@ static bool window_to_panel(EmuState *state, int mx, int my, if (tx >= out_w) tx = out_w - 1; if (ty >= out_h) ty = out_h - 1; - // With the auto-detected rotation, the rendered SDL view represents the - // physical Switch screen in its intended orientation (post-rotation, post- - // de-swizzle): what the user sees is what they would see looking at a - // Switch held landscape. A manual override (R / Shift+R) turns that view - // by a further quarter-turn or two, so undo exactly that extra turn first: - // the render maps a source pixel (sx, sy) of a W x H image to + // With the auto-detected turn, the view shows the picture the way the + // payload drew it (Nyx: landscape, as on a Switch held landscape). A + // manual override (Ctrl+R / Ctrl+Shift+R) turns that view by a further + // quarter-turn or two, so undo exactly that extra turn first: the render + // maps a source pixel (sx, sy) of a W x H image to // 1: (H-1-sy, sx) 2: (W-1-sx, H-1-sy) 3: (sy, W-1-sx) uint32_t delta = (state->last_rot.load() - state->last_auto_rot.load()) & 3; uint32_t aw = (delta & 1) ? out_h : out_w; // auto-rotated view's size diff --git a/emu_state.h b/emu_state.h index cf18f04..bcda4ed 100644 --- a/emu_state.h +++ b/emu_state.h @@ -91,6 +91,40 @@ inline bool wifi_radio_parse(const char *s, uint8_t *out) { return false; } +// Tegra DC window registers (TRM 24.10-24.11) as slots in a window's +// register file: the indirect window page 0x700-0x7FF is slots 0x000-0x0FF, +// the WINBUF page 0x800-0x83F slots 0x100-0x13F. +namespace dcwin { +constexpr uint32_t kRegs = 0x140; +constexpr uint32_t OPTIONS = 0x000; // DC_WIN_WIN_OPTIONS +constexpr uint32_t COLOR_DEPTH = 0x003; // DC_WIN_COLOR_DEPTH +constexpr uint32_t POSITION = 0x004; // DC_WIN_POSITION +constexpr uint32_t SIZE = 0x005; // DC_WIN_SIZE (post-scaling) +constexpr uint32_t PRESCALED = 0x006; // DC_WIN_PRESCALED_SIZE (bytes x lines) +constexpr uint32_t LINE_STRIDE = 0x00A; // DC_WIN_LINE_STRIDE (bytes) +constexpr uint32_t BLEND_LAYER = 0x016; // DC_WINBUF_BLEND_LAYER_CONTROL +constexpr uint32_t BLEND_MATCH = 0x017; // DC_WINBUF_BLEND_MATCH_SELECT +constexpr uint32_t START_ADDR = 0x100; // DC_WINBUF_START_ADDR +constexpr uint32_t SURFACE_KIND = 0x10B; // DC_WINBUF_SURFACE_KIND + +// WIN_OPTIONS bits. +constexpr uint32_t H_DIRECTION = 1u << 0; +constexpr uint32_t V_DIRECTION = 1u << 2; +constexpr uint32_t SCAN_COLUMN = 1u << 4; +constexpr uint32_t WIN_ENABLE = 1u << 30; + +// BLEND_LAYER_CONTROL resets to BLEND_BYPASS (TRM 24.10.12). +constexpr uint32_t BLEND_LAYER_RESET = 0x01000000; + +// A picture turn, as flip-then-transpose: the source is mirrored left-right +// (XF_FLIP_X) and/or top-bottom (XF_FLIP_Y), then rows become columns +// (XF_TRANSPOSE). DC WIN_OPTIONS (H_DIRECTION, V_DIRECTION, SCAN_COLUMN) and +// VIC's OutputFlipX/FlipY/Transpose both follow this convention. +constexpr uint32_t XF_FLIP_X = 1u << 0; +constexpr uint32_t XF_FLIP_Y = 1u << 1; +constexpr uint32_t XF_TRANSPOSE = 1u << 2; +} // namespace dcwin + struct EmuState { uc_engine *uc = nullptr; // Button state (updated by SDL keyboard events). @@ -139,24 +173,21 @@ struct EmuState { std::atomic last_out_w{1280}; std::atomic last_out_h{720}; - // Display state. - uint64_t fb_addr = 0, pre_addr = 0; - uint32_t fb_width = 720, pre_w = 720; - uint32_t fb_height = 1280, pre_h = 1280; - uint32_t fb_stride = 2880, pre_stride = 2880; - uint32_t fb_swizzle = 0, pre_sw = 0; - uint32_t fb_rotation = 0, pre_rot = 0; - uint32_t pre_bh = 0; // block height in GOBs from DC surface-kind (0 = unset) - uint32_t fb_sw_gobs = 80; - uint32_t fb_bh = 0; // 0 = use display code default until DC surface-kind latches - - // DC window selection: tracks DC_CMD_DISPLAY_WINDOW_HEADER. - // Bit 4 = Window A, Bit 5 = Window B, Bit 6 = Window C, Bit 7 = Window D. - uint32_t dc_window_sel = 0x10; // Default: Window A - // Saved Window A parameters (primary display surface). - uint64_t winA_addr = 0; - uint32_t winA_w = 720, winA_h = 1280, winA_stride = 2880; - uint32_t winA_sw = 0, winA_rot = 0, winA_bh = 0; + // Display controller windows A-D (t210/mmio.cpp, Display). Each window + // has a register file indexed by dcwin:: slot. The CPU writes the + // assembly copy; DC_CMD_STATE_CONTROL's WIN_x_ACT_REQ copies it into the + // active copy, which is what the scan-out (display/sdl_display.cpp) + // decodes. + uint32_t dc_win[4][dcwin::kRegs] = {}; + uint32_t dc_win_active[4][dcwin::kRegs] = {}; + uint32_t dc_window_header = 0; // DC_CMD_DISPLAY_WINDOW_HEADER + // False from reset until the payload first activates a window. Until + // then the scan-out shows the emulator's own framebuffer (FB_BASE). + bool dc_programmed = false; + // Where the last VIC compose wrote, and how it turned the picture on the + // way (dcwin::XF_* bits). The scan-out undoes that turn for display. + uint64_t vic_out_addr = 0; + uint32_t vic_out_xform = 0; std::atomic display_dirty{false}; std::atomic display_initialized{false}; int32_t manual_offset = 0; diff --git a/main.cpp b/main.cpp index 00a6487..1e207ad 100644 --- a/main.cpp +++ b/main.cpp @@ -204,7 +204,6 @@ static uc_engine *setup_emulation(EmuState *state, uint8_t *payload, size_t payl // ---- Map Framebuffer pointer ---- state->fb_ptr = state->dram_low_ptr + (FB_BASE - DRAM_BASE); fill_fb_background(state); - state->fb_addr = FB_BASE; printf("[emu] Defined FB: 0x%08llX - 0x%08llX (%u MB)\n", (unsigned long long)FB_BASE, (unsigned long long)(FB_BASE + FB_SIZE), @@ -532,7 +531,6 @@ int main(int argc, char *argv[]) { uc_reg_write(uc, UC_ARM_REG_CPSR, &reset_cpsr); uc_reg_write(uc, UC_ARM_REG_SP, &reset_sp); uc_reg_write(uc, UC_ARM_REG_PC, &reset_pc); - state.fb_addr = FB_BASE; // re-point display at the FB base state.emu_usec = 0; state.insn_count = 0; state.bpmp_slept_us = 0; diff --git a/t210/mmio.cpp b/t210/mmio.cpp index 1ca7eae..780ec76 100644 --- a/t210/mmio.cpp +++ b/t210/mmio.cpp @@ -1570,112 +1570,132 @@ void i2c_write(EmuState *state, uint64_t addr, uint32_t val) { } // ==================== Display ==================== +// +// The display controller's windows (TRM 24.10-24.11) are modelled as one +// register file per window, A-D. The CPU reaches them either through the +// indirect window pages (0x700-0x7FF, 0x800-0x83F), which write every window +// DC_CMD_DISPLAY_WINDOW_HEADER selects and read back the lowest selected one, +// or through a window's own direct range (A: 0xB80/0xBC0, B: 0xD80/0xDC0, +// C: 0xF80/0xFC0). Writes go to the assembly copy. WIN_x_ACT_REQ in +// DC_CMD_STATE_CONTROL promotes window x to the active copy that the scan-out +// (display/sdl_display.cpp) decodes, so a half-programmed window never shows. +// (The hardware stages this twice, UPDATE then ACT_REQ; every payload writes +// both back to back, so one step is enough.) +// +// The rest of the DC is plain read-back storage, except the two words that +// payloads poll: STATE_CONTROL (requests complete at once) and INT_STATUS +// (a frame has always just ended). + +static constexpr uint32_t kDcCmdIntStatus = 0x037; +static constexpr uint32_t kDcCmdStateControl = 0x041; +static constexpr uint32_t kDcCmdWindowHeader = 0x042; +static constexpr uint32_t kDcIntFrameEndVBlank = (1u << 1) | (1u << 2); + +// Resolve a DC word index to the windows it addresses and the register-file +// slot. False for anything that is not a window register. +static bool dc_window_reg(const EmuState *state, uint32_t index, + uint32_t *mask, uint32_t *slot) { + if (index >= 0x700 && index < 0x800) { + *mask = (state->dc_window_header >> 4) & 0xF; + *slot = index - 0x700; + return true; + } + if (index >= 0x800 && index < 0x840) { + *mask = (state->dc_window_header >> 4) & 0xF; + *slot = 0x100 + (index - 0x800); + return true; + } + static const uint32_t kDirect[3] = {0xB80, 0xD80, 0xF80}; + for (uint32_t w = 0; w < 3; w++) { + uint32_t base = kDirect[w]; + if (index >= base && index < base + 0x80) { + *mask = 1u << w; + *slot = index < base + 0x40 ? index - base : 0x100 + (index - base - 0x40); + return true; + } + } + return false; +} + +static void dc_reset(EmuState *state) { + memset(state->dc_win, 0, sizeof(state->dc_win)); + memset(state->dc_win_active, 0, sizeof(state->dc_win_active)); + for (int w = 0; w < 4; w++) + state->dc_win[w][dcwin::BLEND_LAYER] = + state->dc_win_active[w][dcwin::BLEND_LAYER] = dcwin::BLEND_LAYER_RESET; + state->dc_window_header = 0; + state->dc_programmed = false; + state->vic_out_addr = 0; + state->vic_out_xform = 0; +} + +// One line per window whose picture changed (not for moves: bdk slides its +// log window in 16 pixels at a time). +static void dc_log_window(int w, const uint32_t *r) { + if (!(r[dcwin::OPTIONS] & dcwin::WIN_ENABLE)) { + printf("[display] window %c off\n", 'A' + w); + return; + } + static const char *const kKind[4] = {"pitch", "tiled", "block", "?"}; + uint32_t kind = r[dcwin::SURFACE_KIND]; + printf("[display] window %c: %ux%u @ 0x%08X, %s", 'A' + w, + r[dcwin::SIZE] & 0x1FFF, (r[dcwin::SIZE] >> 16) & 0x1FFF, + r[dcwin::START_ADDR], kKind[kind & 3]); + if ((kind & 3) == 2) + printf(" (%u-GOB blocks)", 1u << ((kind >> 4) & 7)); + printf(", stride %u, depth 0x%X, options 0x%X\n", + r[dcwin::LINE_STRIDE] & 0xFFFF, r[dcwin::COLOR_DEPTH] & 0x7F, + r[dcwin::OPTIONS]); +} uint32_t display_read(EmuState *state, uint64_t addr) { - uint32_t offset = (uint32_t)(addr - DISPLAY_A_BASE); - if (offset == 0x800 * 4 || offset == 0x2000) - return (uint32_t)state->fb_addr; - return 0; + uint32_t index = (uint32_t)(addr - DISPLAY_A_BASE) / 4; + uint32_t mask, slot; + if (dc_window_reg(state, index, &mask, &slot)) { + for (int w = 0; w < 4; w++) + if (mask & (1u << w)) + return state->dc_win[w][slot]; + return 0; + } + switch (index) { + case kDcCmdIntStatus: return kDcIntFrameEndVBlank; + case kDcCmdStateControl: return 0; + case kDcCmdWindowHeader: return state->dc_window_header; + default: return mmio_regs.get(addr); + } } void display_write(EmuState *state, uint64_t addr, uint32_t val) { - if (addr < 0x54200000 || addr >= 0x54240000) + uint32_t index = (uint32_t)(addr - DISPLAY_A_BASE) / 4; + uint32_t mask, slot; + if (dc_window_reg(state, index, &mask, &slot)) { + for (int w = 0; w < 4; w++) + if (mask & (1u << w)) + state->dc_win[w][slot] = val; return; - uint32_t offset = (uint32_t)(addr - 0x54200000); - uint32_t index = offset / 4; - - // DC_CMD_DISPLAY_WINDOW_HEADER (offset 0x042*4 = 0x108). - // Tracks which window's registers are currently selected. - if (offset == 0x108) - state->dc_window_sel = val; - - if (offset >= 0x1C00 && offset < 0x1E00) { - uint32_t win_off = offset - 0x1C00; - if (win_off == 0x00) - state->pre_rot = val; - if (win_off == 0x14) { - state->pre_w = (val & 0x1FFF); - state->pre_h = ((val >> 16) & 0x1FFF); + } + if (index == kDcCmdWindowHeader) { + state->dc_window_header = val; + } else if (index == kDcCmdStateControl) { + uint32_t req = (val >> 1) & 0xF; // WIN_A..D_ACT_REQ + for (int w = 0; w < 4; w++) { + if (!(req & (1u << w))) + continue; + uint32_t *act = state->dc_win_active[w]; + const uint32_t *asm_ = state->dc_win[w]; + static const uint32_t kShown[] = { + dcwin::OPTIONS, dcwin::COLOR_DEPTH, dcwin::SIZE, dcwin::LINE_STRIDE, + dcwin::START_ADDR, dcwin::SURFACE_KIND}; + bool changed = !state->dc_programmed; + for (uint32_t r : kShown) + changed |= act[r] != asm_[r]; + memcpy(act, asm_, sizeof(state->dc_win_active[w])); + if (changed) + dc_log_window(w, act); } - if (win_off == 0x18) - state->pre_stride = val & 0xFFFF; - if (win_off == 0x2C) { - state->pre_sw = ((val & 0x7) == 2) ? 2 : 0; - // Tegra DC surface kind: tile in low bits; bits 4–7 = log2(block height in - // GOBs) for block-linear (values 1..5 → 2,4,8,16,32 GOBs). - unsigned log2bh = (val >> 4) & 0xF; - if (log2bh >= 1 && log2bh <= 5) - state->pre_bh = 1u << log2bh; - else - state->pre_bh = 0; - } - } else if (offset >= 0x2000 && offset < 0x2100) { - uint32_t buf_off = offset - 0x2000; - if (buf_off == 0x00) { - state->pre_addr = val; - if (val == 0xF6200000) { - printf("[display] WARNING: Guest wrote 0xF6200000 to pre_addr!\n"); - // Print the guest PC to see where this comes from - uint32_t pc = 0; - uc_reg_read(state->uc, UC_ARM_REG_PC, &pc); - printf("[display] Guest PC: 0x%X\n", pc); - uint8_t code[16] = {0}; - if (uc_mem_read(state->uc, pc - 8, code, 16) == UC_ERR_OK) { - printf("[display] Code: "); - for (int i=0; i<16; i++) printf("%02X ", code[i]); - printf("\n"); - } - } - } - if (buf_off == 0x2C) { - state->pre_sw = ((val & 0x7) == 2) ? 2 : 0; - unsigned log2bh = (val >> 4) & 0xF; - if (log2bh >= 1 && log2bh <= 5) - state->pre_bh = 1u << log2bh; - else - state->pre_bh = 0; - } - } else if (index == 0x85) { // SIZE legacy - state->pre_w = (val & 0x1FFF); - state->pre_h = ((val >> 16) & 0x1FFF); - } else if (index == 0x41 || offset == 0x104) { // DC_CMD_STATE_CONTROL - // Latch when activation request bits are set (WIN_A_ACT_REQ=bit1, - // GENERAL_ACT_REQ=bit0) - if (val & 0x3) { - bool is_window_a = (state->dc_window_sel & 0x10) != 0; // Bit 4 = Window A - bool is_window_d = (state->dc_window_sel & 0x80) != 0; // Bit 7 = Window D - - if (is_window_a && state->pre_addr) { - // Save Window A parameters as primary display surface. - state->winA_addr = state->pre_addr; - state->winA_w = state->pre_w; - state->winA_h = state->pre_h; - state->winA_stride = state->pre_stride; - state->winA_sw = state->pre_sw; - state->winA_rot = state->pre_rot; - state->winA_bh = state->pre_bh; - } - - // Always latch to fb_* for display — but prefer Window A over Window D - // since Window D is just a transparent overlay in Hekate. - if (is_window_a || !is_window_d) { - state->fb_addr = state->pre_addr; - state->fb_width = state->pre_w; - state->fb_height = state->pre_h; - state->fb_stride = state->pre_stride; - state->fb_swizzle = state->pre_sw; - state->fb_rotation = state->pre_rot; - if (state->pre_bh) - state->fb_bh = state->pre_bh; - } - // If Window D is latched alone, don't override — keep Window A's surface. - + if (req) { + state->dc_programmed = true; state->display_dirty = true; - printf("[display] LATCH (ACT_REQ): 0x%llX (%dx%d), WinSel: 0x%X, Sw: %d, " - "Str: %d\n", - (unsigned long long)state->fb_addr, state->fb_width, - state->fb_height, state->dc_window_sel, state->fb_swizzle, - state->fb_stride); } } } @@ -3481,93 +3501,179 @@ static void se_write(EmuState *state, uint64_t addr, uint32_t val) { // ==================== MMIO Hook Callbacks ==================== -static uint64_t vic_src_addr = 0; -static uint64_t vic_dst_addr = 0; +// ==================== VIC ==================== +// +// bdk (vic.c) drives VIC through the Falcon private-register window: +// VIC(0x1000 + (priv >> 6)) = data. PVIC_FALCON_ADDR supplies the low bits +// for registers that need them; none of the ones modelled here do. The model +// keeps what a compose needs - the config struct's address (PRAMBASE), the +// slots' source surfaces and the target surface - and, on COMPOSE_START, +// reads the config struct from guest memory and draws the enabled pitch +// slots into the target with the output flip/transpose. That is what Nyx +// relies on: its 1280x720 GUI is turned into the panel's 720x1280 portrait +// framebuffer by a 270-degree VIC rotation (flip X, then transpose). +// +// Config struct layout (bdk vic_config_t; all fields little-endian u64 +// bitfields): +// 0x10 OutputConfig u64 0: FlipX b48, FlipY b49, Transpose b50 +// u64 1: TargetRect L b0, R b16, T b32, B b48 +// 0x20 OutputSurfaceConfig u64 0: format b0, BlkKind b11, W-1 b32, H-1 b46 +// 0x90 + n * 0xB0 slot n: u64 0: SlotEnable b0 +// u64 4/5: SourceRect L|R, T|B (16.16, b0/b32) +// u64 6: DestRect L b0, R b16, T b32, B b48 +// + 0x40 SlotSurfaceConfig: as OutputSurfaceConfig +// Rects are inclusive. The output surface size is given pre-transpose, so a +// transposed target is (H x W) pixels, which is how the DC reads it back. + +static constexpr uint32_t kVicPramBase = 0x1500; // VIC_SC_PRAMBASE 0x14000 +static constexpr uint32_t kVicSfcBase0 = 0x150C; // VIC_SC_SFC0_BASE_LUMA 0x14300 + n * 0x100 +static constexpr uint32_t kVicTarget = 0x1880; // VIC_BL_TARGET_BASADR 0x22000 +static constexpr uint32_t kVicCompose = 0x1400; // VIC_FC_COMPOSE 0x10000 + +struct VicRegs { + uint64_t cfg = 0; // config struct address + uint64_t sfc[8] = {}; // slot n luma surface + uint64_t target = 0; // output surface +}; +static VicRegs vic; static uint32_t vic_read(EmuState *state, uint64_t addr) { (void)state; (void)addr; + return 0; // PVIC_FALCON_IDLESTATE: composes finish at once +} + +// Bytes per pixel of a VIC pixel format (bdk vic.h), 0 if not modelled. +static uint32_t vic_bpp(uint32_t fmt) { + if (fmt == 1) + return 1; // L8 + if (fmt >= 21 && fmt <= 24) + return 2; // X1B5G5R5 .. B5G5R5X1 + if (fmt >= 31 && fmt <= 38) + return 4; // A8B8G8R8 .. R8G8B8X8 return 0; } -// VIC registers using Falcon PA translated offsets (1000 + untranslated >> 6) -// VIC registers using Falcon PA translated offsets (1000 + untranslated >> 6) -static uint64_t vic_config_addr = 0; -static uint32_t vic_config_size = 0; -static uint32_t vic_last_falcon_addr = 0; - -struct vic_out_config_struct { - uint32_t raw[2]; -}; - -struct vic_out_sfc_config_struct { - uint32_t raw[2]; -}; - -static void vic_write_internal(EmuState *state, uint32_t translated_off, - uint32_t val); - -static void vic_write(EmuState *state, uint64_t addr, uint32_t val) { - uint32_t offset = (uint32_t)(addr - VIC_BASE); - - if (offset == 0x10AC) { // PVIC_FALCON_ADDR - vic_last_falcon_addr = val; - } else if (offset == 0x10B0) { // PVIC_FALCON_DATA - uint32_t translated_off = (vic_last_falcon_addr >> 6) + 0x1000; - vic_write_internal(state, translated_off, val); - } else { - vic_write_internal(state, offset, val); - } +// A host pointer to [addr, addr + len) of emulated DRAM, or null. +static uint8_t *vic_dram(EmuState *state, uint64_t addr, uint64_t len) { + if (!state->dram_low_ptr || addr < DRAM_BASE || + addr + len > DRAM_BASE + DRAM_WINDOW_SIZE) + return nullptr; + return state->dram_low_ptr + (addr - DRAM_BASE); } -static void vic_write_internal(EmuState *state, uint32_t offset, uint32_t val) { +static void vic_compose(EmuState *state) { + uint64_t c[0x610 / 8]; + if (!vic.cfg || uc_mem_read(state->uc, vic.cfg, c, sizeof(c)) != UC_ERR_OK) + return; + auto bits = [](uint64_t v, unsigned lo, unsigned n) { + return (uint32_t)((v >> lo) & ((1ull << n) - 1)); + }; - if (offset == 0x1500) { // VIC_SC_PRAMBASE - vic_config_addr = (uint64_t)val << 8; - } else if (offset == 0x1504) { // VIC_SC_PRAMSIZE - vic_config_size = val << 6; - } else if (offset == 0x150C) { // VIC_SC_SFC0_BASE_LUMA - vic_src_addr = (uint64_t)val << 8; - } else if (offset == 0x1880) { // VIC_BL_TARGET_BASADR - vic_dst_addr = (uint64_t)val << 8; - } else if ((offset == 0x1400 || offset == 0x1440) && - val == 1) { // VIC_FC_COMPOSE - if (vic_src_addr >= 0x40000000 && vic_dst_addr >= 0x40000000) { - uint32_t sfc[2] = {0}; - uc_mem_read(state->uc, vic_config_addr + 0x18, sfc, 8); + bool flip_x = bits(c[2], 48, 1), flip_y = bits(c[2], 49, 1); + bool transpose = bits(c[2], 50, 1); + uint32_t tl = bits(c[3], 0, 14), tr = bits(c[3], 16, 14); + uint32_t tt = bits(c[3], 32, 14), tb = bits(c[3], 48, 14); + uint32_t ofmt = bits(c[4], 0, 7), okind = bits(c[4], 11, 4); + uint32_t ow = bits(c[4], 32, 14) + 1, oh = bits(c[4], 46, 14) + 1; + uint32_t bpp = vic_bpp(ofmt); - uint32_t dw = (sfc[1] & 0x3FFF), dh = ((sfc[1] >> 14) & 0x3FFF); - bool fb_fb = false; - if (dw < 16 || dh < 16 || dw > 2048 || dh > 2048) { - dw = state->fb_width; - dh = state->fb_height; - fb_fb = true; - if (dw < 16) - dw = 720; - if (dh < 16) - dh = 1280; - } + static uint64_t logged = ~0ull; + auto log_once = [&](const char *what) { + uint64_t key = vic.target ^ ((uint64_t)ofmt << 40) ^ ((uint64_t)okind << 48); + if (logged != key) { + logged = key; + printf("[vic] compose skipped: %s\n", what); + } + }; + if (!bpp || okind != 0) + return log_once("output surface not pitch or format not modelled"); - printf("[vic] Compose: 0x%llX -> 0x%llX (%dx%d) %s\n", - (unsigned long long)vic_src_addr, (unsigned long long)vic_dst_addr, - dw, dh, fb_fb ? "(FALLBACK)" : ""); + uint32_t out_pitch = (transpose ? oh : ow) * bpp; + uint64_t out_len = (uint64_t)out_pitch * (transpose ? ow : oh); + uint8_t *dst = vic_dram(state, vic.target, out_len); + if (!dst) + return log_once("target outside DRAM"); + if (tr >= ow) + tr = ow - 1; + if (tb >= oh) + tb = oh - 1; - // Hekate configures VIC with SlotBlkKind=PITCH, OutBlkKind=PITCH. - // This is a straight pitch-to-pitch copy (possibly with rotation/flip - // handled by the real VIC FCE microcode, but we just copy here). - size_t sz = (size_t)dw * dh * 4; - if (sz > 32 * 1024 * 1024) - return; - std::vector buf(sz); - if (uc_mem_read(state->uc, vic_src_addr, buf.data(), sz) == UC_ERR_OK) { - uc_mem_write(state->uc, vic_dst_addr, buf.data(), sz); - - - state->display_dirty = true; + for (int n = 0; n < 8; n++) { + const uint64_t *sl = &c[(0x90 + n * 0xB0) / 8]; + if (!(sl[0] & 1) || !vic.sfc[n]) + continue; + uint32_t sfmt = bits(sl[8], 0, 7), skind = bits(sl[8], 11, 4); + uint32_t sw = bits(sl[8], 32, 14) + 1, sh = bits(sl[8], 46, 14) + 1; + if (skind != 0 || vic_bpp(sfmt) != bpp) { + log_once("slot surface not pitch or not the output's size of pixel"); + continue; + } + const uint8_t *src = vic_dram(state, vic.sfc[n], (uint64_t)sw * sh * bpp); + if (!src) + continue; + uint32_t sl_l = bits(sl[4], 16, 14), sl_r = bits(sl[4], 48, 14); + uint32_t sl_t = bits(sl[5], 16, 14), sl_b = bits(sl[5], 48, 14); + uint32_t dl = bits(sl[6], 0, 14), dr = bits(sl[6], 16, 14); + uint32_t dt = bits(sl[6], 32, 14), db = bits(sl[6], 48, 14); + if (sl_r < sl_l || sl_b < sl_t || dr < dl || db < dt) + continue; + uint32_t x0 = std::max(dl, tl), x1 = std::min(dr, tr); + uint32_t y0 = std::max(dt, tt), y1 = std::min(db, tb); + if (x0 > x1 || y0 > y1) + continue; + // Nearest-neighbour scaling from the source rect onto the dest rect; + // the column map is worked out once per compose, not per pixel. + static std::vector sxs; + sxs.resize(x1 - x0 + 1); + for (uint32_t tx = x0; tx <= x1; tx++) + sxs[tx - x0] = sl_l + (uint32_t)((uint64_t)(tx - dl) * + (sl_r - sl_l + 1) / (dr - dl + 1)); + uint32_t src_pitch = sw * bpp; + for (uint32_t ty = y0; ty <= y1; ty++) { + uint32_t sy = sl_t + (uint32_t)((uint64_t)(ty - dt) * (sl_b - sl_t + 1) / + (db - dt + 1)); + if (sy >= sh) + continue; + const uint8_t *srow = src + (uint64_t)sy * src_pitch; + uint32_t fy = flip_y ? oh - 1 - ty : ty; + for (uint32_t tx = x0; tx <= x1; tx++) { + uint32_t sx = sxs[tx - x0]; + if (sx >= sw) + continue; + uint32_t fx = flip_x ? ow - 1 - tx : tx; + uint64_t o = transpose ? (uint64_t)fx * out_pitch + (uint64_t)fy * bpp + : (uint64_t)fy * out_pitch + (uint64_t)fx * bpp; + if (bpp == 4) + memcpy(dst + o, srow + (uint64_t)sx * 4, 4); + else + memcpy(dst + o, srow + (uint64_t)sx * bpp, bpp); } } } - printf("[vic] W: 0x%08X = 0x%08X\n", offset, val); + + uint32_t xf = (flip_x ? dcwin::XF_FLIP_X : 0) | + (flip_y ? dcwin::XF_FLIP_Y : 0) | + (transpose ? dcwin::XF_TRANSPOSE : 0); + if (state->vic_out_addr != vic.target || state->vic_out_xform != xf) + printf("[vic] compose: %ux%u -> 0x%08llX%s%s%s\n", ow, oh, + (unsigned long long)vic.target, flip_x ? ", flip X" : "", + flip_y ? ", flip Y" : "", transpose ? ", transpose" : ""); + state->vic_out_addr = vic.target; + state->vic_out_xform = xf; + state->display_dirty = true; +} + +static void vic_write(EmuState *state, uint64_t addr, uint32_t val) { + uint32_t offset = (uint32_t)(addr - VIC_BASE); + if (offset == kVicPramBase) + vic.cfg = (uint64_t)val << 8; + else if (offset >= kVicSfcBase0 && offset < kVicSfcBase0 + 8 * 4) + vic.sfc[(offset - kVicSfcBase0) / 4] = (uint64_t)val << 8; + else if (offset == kVicTarget) + vic.target = (uint64_t)val << 8; + else if (offset == kVicCompose && (val & 1)) + vic_compose(state); } // ==================== APE audio hub: I2S, ADMAIF, ADMA ==================== @@ -4516,6 +4622,7 @@ void mmio_init(uc_engine *uc, EmuState *state) { ccplex_reset(state); sdhci_reset_regs(sdhci_regs[0]); sdhci_reset_regs(sdhci_regs[1]); + dc_reset(state); uc_hook_add(uc, &h_unmapped, UC_HOOK_MEM_READ_UNMAPPED | UC_HOOK_MEM_WRITE_UNMAPPED, @@ -4585,8 +4692,7 @@ void mmio_soft_reset(EmuState *state, bool power_cycle) { g_dsi_pending_dcs_cmd = 0; memset(g_dsi_rx_fifo, 0, sizeof(g_dsi_rx_fifo)); g_dsi_rx_count = g_dsi_rx_pos = 0; - vic_src_addr = vic_dst_addr = vic_config_addr = 0; - vic_config_size = vic_last_falcon_addr = 0; + vic = VicRegs(); for (auto &d : actmon_dev) d = ActmonDev(); actmon_glb_period = 0; @@ -4616,23 +4722,8 @@ void mmio_soft_reset(EmuState *state, bool power_cycle) { else emmc_ext_csd_card_reset(); - // Display controller back to its defaults (emu_state.h). - state->pre_addr = 0; - state->fb_width = state->pre_w = 720; - state->fb_height = state->pre_h = 1280; - state->fb_stride = state->pre_stride = 2880; - state->fb_swizzle = state->pre_sw = 0; - state->fb_rotation = state->pre_rot = 0; - state->pre_bh = 0; - state->fb_sw_gobs = 80; - state->fb_bh = 0; - state->dc_window_sel = 0x10; - state->winA_addr = 0; - state->winA_w = 720; - state->winA_h = 1280; - state->winA_stride = 2880; - state->winA_sw = state->winA_rot = state->winA_bh = 0; - + // Display controller and VIC back to their defaults. + dc_reset(state); state->bpmp_halted = false; }