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

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

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb
2026-09-25 17:45:02 +00:00

476 lines
24 KiB
C++

#ifndef EMU_STATE_H
#define EMU_STATE_H
#include <array>
#include <atomic>
#include <cstdint>
#include <cstring>
#include <deque>
#include <vector>
#include <string>
/*
* Emulator State
*
* Shared state between CPU emulation, MMIO handlers, and display.
*/
#include <unicorn/unicorn.h>
// Bluetooth radio behaviour, selected by `[bluetooth] radio=` in rcm_emu.ini
// or `--bt-radio` on the command line. The Broadcom CYW4356 model in
// t210/mmio.cpp reads this every time the payload can observe the part.
//
// healthy - the module powers up on the BT_REG_ON edge, holds BT_HOST_WAKE
// high, drives its RTS_N low once POR completes and answers HCI.
// faulty - the module is fitted but never comes out of POR: BT_HOST_WAKE
// reads low, RTS_N never asserts and nothing ever reaches the
// wire. This is the console that returns 2110-1118 in HOS.
// absent - no module at all. As faulty, plus nothing drives BT_UART_TXD,
// so the Tegra's own pull-down on RX reads as a line break.
enum BtRadioMode : uint8_t {
BT_RADIO_HEALTHY = 0,
BT_RADIO_FAULTY = 1,
BT_RADIO_ABSENT = 2,
};
inline const char *bt_radio_name(uint8_t mode) {
switch (mode) {
case BT_RADIO_FAULTY: return "faulty";
case BT_RADIO_ABSENT: return "absent";
default: return "healthy";
}
}
// Accepts the three names above and the raw 0/1/2 the enum uses. Returns
// false on anything else so the caller can warn instead of silently
// selecting a mode the user did not ask for -- which is exactly what would
// happen if this key went through the ini's numeric schema, where
// strtoull("faulty") is 0 and 0 is "healthy".
inline bool bt_radio_parse(const char *s, uint8_t *out) {
if (!s || !*s) return false;
if (!strcmp(s, "healthy") || !strcmp(s, "0")) { *out = BT_RADIO_HEALTHY; return true; }
if (!strcmp(s, "faulty") || !strcmp(s, "1")) { *out = BT_RADIO_FAULTY; return true; }
if (!strcmp(s, "absent") || !strcmp(s, "2")) { *out = BT_RADIO_ABSENT; return true; }
return false;
}
// WLAN half of the same CYW4356 package, selected by `[wifi] radio=` in
// rcm_emu.ini or `--wifi-radio` on the command line. It is a PCI Express
// endpoint on root port 1, so the failure modes are different from the
// Bluetooth side's and worth separating:
//
// healthy - the link trains, the endpoint enumerates as 14E4:43EC, and
// its BAR0 backplane window answers with ChipCommon ChipID
// 0x4356. A working radio.
// faulty - the PCIe front-end is alive: the link trains and config space
// reads back correctly, but the WLAN die behind it is not, so
// every backplane read returns all ones. This is the console
// that enumerates and still has no Wi-Fi.
// absent - no module, or one whose PCIe side never comes up: the link
// never leaves detect and no config access is ever answered.
enum WifiRadioMode : uint8_t {
WIFI_RADIO_HEALTHY = 0,
WIFI_RADIO_FAULTY = 1,
WIFI_RADIO_ABSENT = 2,
};
inline const char *wifi_radio_name(uint8_t mode) {
switch (mode) {
case WIFI_RADIO_FAULTY: return "faulty";
case WIFI_RADIO_ABSENT: return "absent";
default: return "healthy";
}
}
inline bool wifi_radio_parse(const char *s, uint8_t *out) {
if (!s || !*s) return false;
if (!strcmp(s, "healthy") || !strcmp(s, "0")) { *out = WIFI_RADIO_HEALTHY; return true; }
if (!strcmp(s, "faulty") || !strcmp(s, "1")) { *out = WIFI_RADIO_FAULTY; return true; }
if (!strcmp(s, "absent") || !strcmp(s, "2")) { *out = WIFI_RADIO_ABSENT; return true; }
return false;
}
struct EmuState {
uc_engine *uc = nullptr;
// Button state (updated by SDL keyboard events).
std::atomic<bool> btn_vol_up{false};
std::atomic<bool> btn_vol_down{false};
std::atomic<bool> btn_power{false};
// Touchscreen state (FTS4/STMFTS stub on I2C3 @ slave 0x49).
// Updated by SDL mouse events; consumed by i2c3_*/STMFTS code on CPU thread.
// Coordinates are in panel-raw space (X long axis 0..1264, Y short 0..704)
// matching what touch.c expects before its rescaling.
//
// Events queue up rather than overwrite each other: a click shorter than
// the payload's poll interval used to reach it as a bare LEAVE, the
// ENTER lost under it. Single producer (SDL), single consumer (I2C3).
struct TouchEvent { uint8_t op; uint16_t x, y; }; // op 3/4/5 = ENTER/LEAVE/MOTION
static constexpr uint32_t TC_QUEUE = 32;
TouchEvent tc_queue[TC_QUEUE] = {};
std::atomic<uint32_t> tc_q_head{0}; // next slot the producer fills
std::atomic<uint32_t> tc_q_tail{0}; // next slot the consumer takes
std::atomic<bool> tc_pressed{false};
uint8_t tc_finger_id = 0; // raw FTS4 ID; bdk reports it + 1
// Queue a touch event. MOTION is dropped when the queue is nearly full,
// so an ENTER or LEAVE always finds room.
void touch_post(uint8_t op, uint16_t x, uint16_t y) {
uint32_t head = tc_q_head.load(), tail = tc_q_tail.load();
uint32_t used = head - tail;
if (used >= TC_QUEUE || (op == 0x05 && used >= TC_QUEUE - 4))
return;
tc_queue[head % TC_QUEUE] = {op, x, y};
tc_q_head.store(head + 1);
}
bool touch_take(TouchEvent *ev) {
uint32_t tail = tc_q_tail.load();
if (tail == tc_q_head.load())
return false;
*ev = tc_queue[tail % TC_QUEUE];
tc_q_tail.store(tail + 1);
return true;
}
// last_rot mirrors the rotation last applied by sdl_display_update.
// Read from the SDL event handler to invert the display→window transform.
std::atomic<uint32_t> last_rot{0};
std::atomic<uint32_t> last_auto_rot{0}; // what auto-detect picked, before any override
std::atomic<uint32_t> last_out_w{1280};
std::atomic<uint32_t> last_out_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;
std::atomic<bool> display_dirty{false};
std::atomic<bool> display_initialized{false};
int32_t manual_offset = 0;
int32_t rotation_override = -1; // -1 = Auto, 0=0, 1=90, 2=180, 3=270
// Emulation control.
std::atomic<bool> running{true};
std::atomic<bool> paused{false};
std::atomic<bool> reboot_requested{false};
// The reboot is a power cycle (PMIC software reset, the UI's Reboot):
// the regulators lose their state too. Otherwise it is a SoC reset
// (PMC MAIN_RST), which the PMIC, and its rails, sit out.
std::atomic<bool> reboot_cold{false};
// The BPMP parked itself for good (bpmp_halt(): WAITEVENT with no timer)
// while CPU0 still runs - the handoff fusee and hekate's L4T launch do.
// Time keeps passing for CPU0; the BPMP executes nothing until reset.
bool bpmp_halted = false;
// Payload kept around for soft reboot (re-write to IRAM and reset PC).
uint8_t *payload_ptr = nullptr;
size_t payload_len = 0;
// Backlight brightness (0-255).
uint32_t backlight = 100;
// Deterministic timer.
uint64_t emu_usec = 0;
uint64_t insn_count = 0;
// Total time the BPMP has spent parked in a FLOW_CTLR timed halt
// (bpmp_usleep / bpmp_msleep). The ACTMON model derives BPMP load from
// this: time not slept during a sample window counts as active.
uint64_t bpmp_slept_us = 0;
// DRAM pointer (host memory backing the emulated DRAM).
// DRAM is one contiguous host allocation covering 0x80000000..0x100000000.
// dram_low_ptr owns it; dram_ptr is a view at the 0xC0000000 offset kept
// for the existing high-DRAM/framebuffer call sites. Free only dram_low_ptr.
uint8_t *dram_ptr = nullptr; // view: high DRAM (0xC0000000+)
uint8_t *dram_low_ptr = nullptr; // owner: base of the whole DRAM window
uint8_t *iram_ptr = nullptr;
uint8_t *fb_ptr = nullptr;
// SDMMC1 State
uint32_t sdmmc_arg = 0;
uint32_t sdmmc_rsp[4] = {0};
uint32_t sdmmc_norintsts = 0;
uint32_t sdmmc_errintsts = 0;
uint32_t sdmmc_sysad = 0;
uint8_t sdmmc_hostctl = 0;
uint16_t sdmmc_blksize = 0;
uint16_t sdmmc_blkcnt = 0;
uint16_t sdmmc_trnmod = 0;
uint64_t sdmmc_adma_addr = 0;
// SDMMC4 State
uint32_t sdmmc4_arg = 0;
uint32_t sdmmc4_rsp[4] = {0};
uint32_t sdmmc4_norintsts = 0;
uint32_t sdmmc4_errintsts = 0;
uint32_t sdmmc4_sysad = 0;
uint8_t sdmmc4_hostctl = 0;
uint16_t sdmmc4_blksize = 0;
uint16_t sdmmc4_blkcnt = 0;
uint16_t sdmmc4_trnmod = 0;
uint64_t sdmmc4_adma_addr = 0;
// File-backed storage
int sd_fd = -1;
int emmc_boot0_fd = -1;
int emmc_boot1_fd = -1;
std::vector<int> emmc_gpp_fds;
uint32_t emmc_partition = 0; // 0=GPP, 1=BOOT0, 2=BOOT1
// Command state tracking
bool last_cmd_was_55 = false;
bool last_cmd4_was_55 = false;
// Touch injection state (STMFTS FTS5 controller, I2C addr 0x49 on I2C1)
// touch_phase: 0=idle, 1=send_down, 2=send_up, 3=done
std::atomic<int> touch_phase{0};
uint16_t touch_x = 360; // Portrait X coordinate (0-719)
uint16_t touch_y = 640; // Portrait Y coordinate (0-1279)
// ==================== Tweakable hardware values (config window) ====================
// Battery fuel gauge (MAX17050, I2C_1 @ 0x36).
// UI-friendly units; the I2C handler converts to MAX17050's raw register
// encoding (cf. Hekate's max17050_get_property formulas).
std::atomic<uint16_t> bat_soc_pct{80}; // RepSOC: percent (0-100)
std::atomic<uint16_t> bat_vcell_mv{3950}; // VCELL: mV
std::atomic<int16_t> bat_temp_c10{250}; // TEMP: °C * 10 (UI unit), e.g. 250 -> 25.0°C
std::atomic<int16_t> bat_current_ma{0}; // Current: signed mA
std::atomic<uint16_t> bat_capacity_mah{3500}; // RepCap: mAh (current charge)
std::atomic<uint16_t> bat_full_cap_mah{4000}; // FullCAP: mAh (learned full capacity)
std::atomic<uint16_t> bat_design_cap_mah{4310}; // DesignCap: mAh (Switch nominal)
std::atomic<uint16_t> bat_ocv_mv{3960}; // OCVInternal: mV (open-circuit)
std::atomic<uint16_t> bat_v_empty_mv{3300}; // V_empty: mV
std::atomic<uint16_t> bat_min_volt_mv{3500}; // MinMaxVolt low byte * 20
std::atomic<uint16_t> bat_max_volt_mv{4200}; // MinMaxVolt high byte * 20
std::atomic<uint8_t> bat_age_pct{100}; // Age: percent (Age MSB)
std::atomic<uint16_t> bat_cycles{0}; // Cycles count
// Main PMIC OEM (MAX77620 CID4): 0x35 = Erista, 0x53 = Mariko, other = Unknown
std::atomic<uint8_t> pmic_otp{0x35};
// Tegra X1 generation (drives APB_MISC_GP_HIDREV major nibble: 1 = T210
// Erista, 2 = T210B01 Mariko). Hekate's h_cfg.t210b01 derives from this,
// which controls the pkg1 OEM-header skip among other things.
std::atomic<bool> is_mariko{false};
// Silicon revisions, as read off a real console (Mariko, HAC-001(-01)):
// CID3 = 0x5B -> payloads print the low nibble, "max77620 v11"
// CID5 = 0x81 -> ES version (DIDM 8 / DIDO 1)
// These are whole bytes, not nibbles: masking CID3 to 4 bits (the old
// behaviour) made a genuine 0x5B read back as 0x0B. CID3/CID5 describe the
// silicon and are expected to be identical on Erista - only CID4 (the OTP
// version) differs by generation - but only Mariko is measured so far.
std::atomic<uint8_t> pmic_silicon_rev{0x5B}; // MAX77620 CID3
std::atomic<uint8_t> pmic_es_rev{0x81}; // MAX77620 CID5
std::atomic<uint8_t> cpu_pmic_version{0x12}; // MAX77621 CHIPID1 (measured, Erista)
// MAX77620 CNFG1_32K (reg 0x03), the LPO that clocks the combo radio.
// 32K_OK (bit 7) and 32K_OUT0_EN (bit 2) are set on every healthy
// console, but the rest of the byte varies per UNIT, not per SoC
// generation: 0xFC and 0xDC are both measured on Erista and on Mariko.
// Exposed so a capture from a specific console can be reproduced exactly.
std::atomic<uint8_t> pmic_cnfg1_32k{0xFC};
// SD card insertion (GPIO Port Z bit 1 = 0 means inserted).
std::atomic<bool> sd_inserted{true};
// SD card identity (returned for SDMMC1 CMD2 ALL_SEND_CID).
// Hekate parses these out of the R2 response per bdk/storage/sdmmc.c
// _sd_storage_parse_cid; the I2C handler builds the 16-byte CID payload
// from these atomics each time CMD2 fires.
std::atomic<uint8_t> sd_cid_manfid{0x03}; // 0x03 = SanDisk
std::atomic<uint16_t> sd_cid_oemid{0x5344}; // "SD"
std::atomic<uint64_t> sd_cid_prod_name{0x3155445355ULL}; // "USDU1" (low byte first)
std::atomic<uint8_t> sd_cid_hwrev{1}; // 0-15
std::atomic<uint8_t> sd_cid_fwrev{0}; // 0-15
std::atomic<uint32_t> sd_cid_serial{0xC0FFEE42};
std::atomic<uint8_t> sd_cid_month{10}; // 1-12
std::atomic<uint16_t> sd_cid_year{2024}; // 2000-2255
// eMMC identity (SDMMC4 CMD2). Layout per _mmc_storage_parse_cid (MMC v4):
// 8-bit manfid, 8-bit oemid, 6-byte prod_name, 8-bit prv (BCD nibble.nibble),
// 32-bit serial, 4-bit month, 4-bit year offset (year base = 2013 when
// ext_csd.rev >= 5, which is what our EXT_CSD reports).
std::atomic<uint8_t> emmc_cid_manfid{0x90}; // 0x90 = SK Hynix
std::atomic<uint8_t> emmc_cid_oemid{0x01};
std::atomic<uint64_t> emmc_cid_prod_name{0x326134474248ULL}; // "HBG4a2" (low byte first)
std::atomic<uint8_t> emmc_cid_prv{0x07}; // displayed as "0.7" (low.high)
std::atomic<uint32_t> emmc_cid_serial{0x12345678};
std::atomic<uint8_t> emmc_cid_month{6}; // 1-12
std::atomic<uint16_t> emmc_cid_year{2017}; // 2013-2025 (Hekate caps at 2025: see config_window.cpp)
// Ambient light sensor (Rohm BH1730, I2C2 @ 0x29). Defaults are what a
// real Mariko reported in a lit room; part id 0x71 is the measured value
// a payload checks to decide the sensor is present at all.
std::atomic<uint8_t> als_part_id{0x71};
std::atomic<uint16_t> als_visible{128}; // DATA0 counts
std::atomic<uint16_t> als_ir{21}; // DATA1 counts
// Bluetooth radio (Broadcom CYW4356, HCI/H4 on UART-D plus five control
// lines on GPIO port H). See BtRadioMode above for what each mode models.
std::atomic<uint8_t> bt_radio{BT_RADIO_HEALTHY};
// WLAN radio (the other half of the same CYW4356, a PCIe endpoint on
// root port 1). See WifiRadioMode above for what each mode models.
std::atomic<uint8_t> wifi_radio{WIFI_RADIO_HEALTHY};
// SoC thermal sensor (TMP451, I2C5 @ 0x4C).
std::atomic<int16_t> soc_temp_c10{420}; // remote channel (SoC die): °C * 10
std::atomic<int16_t> pcb_temp_c10{350}; // local channel (PCB): °C * 10
// Charger (BQ24193, I2C1 @ 0x6B).
std::atomic<uint8_t> chg_vbus_stat{0}; // 0=none, 1=USB-SDP, 2=adapter, 3=OTG
std::atomic<uint8_t> chg_chrg_stat{0}; // 0=not charging, 1=pre, 2=fast, 3=done
std::atomic<bool> chg_power_good{false};
// BQ24193 charger limits (encoded into regs 0x00/0x01/0x02/0x04/0x06).
// mmio.cpp does the reverse-encoding from these decoded values; the user
// sees real units, the chip sees the closest legal register value.
std::atomic<uint16_t> chg_input_current_ma{2000}; // table: 100/150/500/900/1200/1500/2000/3000
std::atomic<uint16_t> chg_input_voltage_mv{4280}; // 3880-5080 mV, 80 mV step
std::atomic<uint16_t> chg_system_min_mv{3500}; // 3000-3700 mV, 100 mV step
std::atomic<uint16_t> chg_fast_current_ma{1856}; // 512-4544 mA, 64 mA step
std::atomic<uint16_t> chg_charge_voltage_mv{4208}; // 3504-4512 mV, 16 mV step
std::atomic<uint8_t> chg_thermal_c{60}; // 60 / 80 / 100 / 120 °C
// USB-PD controller (BM92T36, I2C1 @ 0x18). One synthesized fixed PDO.
std::atomic<bool> usb_pd_inserted{false};
std::atomic<uint16_t> usb_pd_voltage_mv{5000};
std::atomic<uint16_t> usb_pd_amperage_ma{1500};
// Fuse driver (FUSE @ 0x7000F800). One u32 per offset, indexed by
// offset/4. The HW & Fuses Info screen reads several dozen offsets
// (speedos, IDDQ, SBK, public key, lot/wafer, etc.); seeding plausible
// defaults here keeps the screen rendering meaningful values without a
// dedicated atomic per field. Defaults populated by init_fuse_defaults().
static constexpr size_t FUSE_WORDS = 0x100;
std::array<std::atomic<uint32_t>, FUSE_WORDS> fuse_word{};
std::atomic<uint32_t>& fuse_at(uint32_t offset) { return fuse_word[(offset & 0x3FC) / 4]; }
void init_fuse_defaults() {
for (auto &w : fuse_word)
w.store(0);
// Names below mirror Hekate's bdk/soc/fuse.h. Values picked from a
// typical Erista golden-sample dump (any retail Switch is similar).
fuse_at(0x100).store(1); // FUSE_PRODUCTION_MODE
fuse_at(0x110).store(0x83); // FUSE_SKU_INFO (SKU_ODIN)
fuse_at(0x114).store(2289); // FUSE_CPU_SPEEDO_0_CALIB
fuse_at(0x118).store(1786); // FUSE_CPU_IDDQ_CALIB (x4 -> 7144)
fuse_at(0x128).store(0x82); // FUSE_OPT_FT_REV (4.02)
fuse_at(0x12C).store(2330); // FUSE_CPU_SPEEDO_1_CALIB
fuse_at(0x130).store(2342); // FUSE_CPU_SPEEDO_2_CALIB
fuse_at(0x134).store(1801); // FUSE_SOC_SPEEDO_0_CALIB
fuse_at(0x138).store(0x80); // FUSE_SOC_SPEEDO_1_CALIB (BROM rev)
fuse_at(0x13C).store(1817); // FUSE_SOC_SPEEDO_2_CALIB
fuse_at(0x140).store(1500); // FUSE_SOC_IDDQ_CALIB (x4 -> 6000)
fuse_at(0x148).store(0x83000001); // FUSE_FA
// Public key (8 words). Hekate prints them byte-swapped, so storage
// is the byte-reverse of the desired displayed hex string. Two rows
// of "5F1B7A4D8E2C6F09B3A815C7D4E0F26B" / "A91F4C8B7D2E0653F1A8B4C7E0D962F4".
fuse_at(0x164).store(0x4D7A1B5F);
fuse_at(0x168).store(0x096F2C8E);
fuse_at(0x16C).store(0xC715A8B3);
fuse_at(0x170).store(0x6BF2E0D4);
fuse_at(0x174).store(0x8B4C1FA9);
fuse_at(0x178).store(0x53062E7D);
fuse_at(0x17C).store(0xC7B4A8F1);
fuse_at(0x180).store(0xF462D9E0);
fuse_at(0x190).store(0x100); // FUSE_OPT_CP_REV (8.00)
fuse_at(0x1A0).store(0x06); // FUSE_SECURITY_MODE
// SBK + DK placeholders. Same byte-swap convention as the public key.
// SBK displays as "C8E5719FA34D6B208E14F7B965A028D3", DK as "47A1F39E".
// --prod-keys overrides these via the SE keytable at runtime.
fuse_at(0x1A4).store(0x9F71E5C8);
fuse_at(0x1A8).store(0x206B4DA3);
fuse_at(0x1AC).store(0xB9F7148E);
fuse_at(0x1B0).store(0xD328A065);
fuse_at(0x1B4).store(0x9EF3A147);
// RESERVED_SW bit 7 selects USB controller string in Hekate. Off = "USB2".
fuse_at(0x1C0).store(0x00);
fuse_at(0x1D8).store(0x20); // FUSE_RESERVED_ODM4 (DRAM ID 4)
// FUSE_RESERVED_ODM7: burnt anti-downgrade fuses. A payload compares
// the popcount here against the HOS version of the pkg1 in BOOT0 and
// flags a mismatch as "pkg1 too new/old for this console". Left at 0
// it always looked like a downgraded console. 16 bits matches the
// HOS 13.2.1 pkg1 in the bundled BOOT0 dump; change it alongside the
// dump (real consoles measured: 23 burnt on HOS 22.0.0).
fuse_at(0x1E4).store(0x0000FFFF); // FUSE_RESERVED_ODM7 (16 burnt)
fuse_at(0x200).store(0x06); // FUSE_OPT_VENDOR_CODE
fuse_at(0x204).store(0x12); // FUSE_OPT_FAB_CODE ('I' = base36[18])
// LOT_CODE_0 holds five base36 chars in 6-bit fields at bits 29:24,
// 23:18, 17:12, 11:6, 5:0. Each digit must stay <= 35 or Hekate
// indexes past the base36[] table and prints garbage. Encoded "K1SHQ".
fuse_at(0x208).store(0x1405C45A);
fuse_at(0x210).store(1); // FUSE_OPT_WAFER_ID
// Wafer X/Y must land inside the Erista lithography map
// (X in [-9, 15], Y in [0, 24]) or _hw_info_wafer marks "Error".
fuse_at(0x214).store(5); // FUSE_OPT_X_COORDINATE
fuse_at(0x218).store(12); // FUSE_OPT_Y_COORDINATE
fuse_at(0x228).store(1500); // FUSE_GPU_IDDQ_CALIB (x5 -> 7500)
}
// DRAM mode register responses. Hekate reads these via the EMC controller
// (sdram_read_mrx) to populate the "Vendor / Rev / Density" columns on
// the HW & Fuses Info screen. Defaults match a Samsung K4F6E304HB-MGCH
// 4 GB module on both channels.
std::atomic<uint8_t> dram_vendor{1}; // MR5 MAN_ID (1=Samsung, 6=Hynix, 255=Micron)
std::atomic<uint8_t> dram_rev_id1{2}; // MR6 REV_ID1
std::atomic<uint8_t> dram_rev_id2{0}; // MR7 REV_ID2
std::atomic<uint8_t> dram_density{0x18}; // MR8 DENSITY (bits 5:2 = density code)
// Display panel ID (DSI). Hekate reads MIPI_DCS_GET_DISPLAY_ID (0x04) over
// DSI and stores 3 raw bytes; the screen prints them as "ID: b0 b1 b2"
// and decodes them as `((raw >> 8) & 0xFF00) | (raw & 0xFF)`. Default
// 0x099310 -> JDI LAM062M109A rev 0x93 (a common Erista launch panel).
std::atomic<uint32_t> panel_id_raw{0x099310};
// Touch panel + FW info (FTS4 controller, I2C3 @ 0x49). Idx maps to the
// _panels[] table in Hekate's bdk/input/touch.c (0=NISSHA NFT-K12D pairs
// with fw_id 4CD60D/1, etc.). Defaults render as "NISSHA NFT-K12D" with
// ID "32.00.00.01 (Paired)".
std::atomic<uint8_t> touch_panel_idx{0}; // 0..4 -> known panels, 5 -> GiS VA 6.2"
std::atomic<uint32_t> touch_fw_id{0x32000001}; // displayed as 4CD60D/<n>
std::atomic<uint16_t> touch_ftb_ver{0x0123};
std::atomic<uint16_t> touch_fw_rev{0x4567}; // Hekate byte-swaps before printing
// ============================================================
// Per-UART scratch state used by the in-emulator UART console.
// ============================================================
// Tegra X1 has UART_A..UART_E (5 ports). Their register blocks are NOT
// evenly spaced -- bdk soc/uart.c carries the offset table
// { 0, 0x40, 0x200, 0x300, 0x400 } -- so the mmio dispatcher resolves the
// port index against that same table (uart_bases[] in t210/mmio.cpp), not
// by dividing the offset. Index order is therefore A=0..E=4.
//
// - uart_tx_log[idx] mirrors every byte the payload writes to that
// port's TX register, so the console window can render scrolling
// history without having to re-parse stdout. Capped at ~64 KB by a
// simple "drop the front when too big" trim.
// - uart_rx_fifo[idx] is bytes waiting to be consumed by the next UART
// read (RBR via offset 0x00, with bit 0 of LSR at offset 0x14 set when
// non-empty). Filled by the console window, the input script, 16550
// internal loopback, and emulated devices such as the CYW4356 on
// UART_D.
//
// The CPU-emulation hooks and the ImGui console both run on the main
// thread between SDL polls, so no locking is required.
static constexpr size_t N_UARTS = 5;
std::string uart_tx_log[N_UARTS];
std::deque<uint8_t> uart_rx_fifo[N_UARTS];
};
#endif // EMU_STATE_H