diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..97793dd --- /dev/null +++ b/.gitattributes @@ -0,0 +1,10 @@ +# Normalize text files to LF in the repo. Platform-native on checkout. +* text=auto eol=lf + +# Binary file types kept untouched. +*.png binary +*.jpg binary +*.bmp binary +*.bin binary +*.img binary +*.bso binary diff --git a/.gitignore b/.gitignore index 1112031..e236c20 100644 --- a/.gitignore +++ b/.gitignore @@ -20,3 +20,5 @@ emu_run*.log .DS_Store __pycache__/ *.pyc +backup/ +imgui.ini diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..cb1c738 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "third_party/imgui"] + path = third_party/imgui + url = https://github.com/ocornut/imgui.git diff --git a/DESIGN.md b/DESIGN.md index 2d5c7b5..c1fbb9b 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -12,13 +12,20 @@ flowchart TB main -->|uc_emu_start| uc["Unicorn Engine
ARM32, T210
IRAM / DRAM / MMIO"] main -->|sdl_display_*| sdl["display/sdl_display
block-linear de-swizzle
rotate, blit"] + main -->|config_window_*| cfg["display/config_window
2nd SDL window + ImGui
live hardware tweaks"] uc -->|MMIO trap| mmio["t210/mmio.cpp
central read/write dispatch
by address range"] mmio --> sdmmc["sdmmc
SDMMC1 / SDMMC4
CMD0..18, EXT_CSD, ADMA2"] mmio --> se["se_engine
AES-128, SHA-256
BIS keyslot override"] mmio --> i2c["i2c3
STMFTS / FTS4 touch"] + mmio --> i2c1["I2C_1 slaves (inline)
MAX17050, TMP451,
BQ24193, BM92T36"] + mmio --> i2c5["I2C_5 slaves (inline)
MAX77620, MAX77621"] mmio --> stubs["inline stubs
GPIO, PMC, TSEC, KFUSE,
PWM, DC, CLK, TMR, FUSE, UART"] + + cfg -.->|writes atomics| state["EmuState
(emu_state.h)"] + i2c1 -.->|reads atomics| state + i2c5 -.->|reads atomics| state ``` `EmuState` (`emu_state.h`) is the single shared struct. It holds button atomics, @@ -134,6 +141,81 @@ SDL keyboard handler. The MMIO read handlers map them onto: - VOL+ and VOL– map to GPIO X6 and X7 (active-low) on port X. - POWER routes through the MAX77620 PMIC (Power Management IC), reported via `ONOFFSTAT.EN0` over I²C5. +- GPIO Port Z bit 1 reflects `state->sd_inserted` (active-low). Toggle it from + the config window to simulate SD eject mid-boot. + +### I²C-attached chips (battery, charger, thermal, USB-PD, PMIC ID) + +Modelled inline in `t210/mmio.cpp::i2c_read`. The bus is disambiguated by +`bool on_i2c5 = (addr >= I2C5_BASE)`, which lets the same slave address +serve different chips on different buses. The Synaptics RMI4 stub on I²C1 +@ 0x4C was retired once `i2c3.cpp` took over real touch handling, and +TMP451 took the freed address. + +| Chip | Bus / addr | Reg dispatch | +| ---------- | -------------- | --------------------------------------------------- | +| MAX17050 | I²C\_1 @ 0x36 | "Small" path (CMD\_DATA1 read), 13 regs handled | +| TMP451 | I²C\_1 @ 0x4C | Small path; int byte + frac-nibble per channel | +| BQ24193 | I²C\_1 @ 0x6B | Small path; 7 regs reverse-encoded from EmuState | +| BM92T36 | I²C\_1 @ 0x18 | Packet-mode path (TX\_FIFO/RX\_FIFO FSM) | +| MAX77620 | I²C\_5 @ 0x3C | Small path; ONOFFSTAT + CID3/CID4/CID5 | +| MAX77621 | I²C\_5 @ 0x1B | Small path; CHIPID1 | + +Every register handler reverse-encodes the user-facing decoded value +(stored in `EmuState`) to match the chip's raw register format that the +Hekate `bdk/power/*.c` drivers expect. A slider that reads "2000 mA" +maps to the BQ24193 INLIMIT bucket whose decode formula yields back +2000 mA. Round-trip clean. The encoders mirror the `*_get_property()` +formulas in Hekate. If those units change upstream, re-derive ours from +the same source. + +#### Packet-mode I²C (BM92T36) + +Most slaves on the Switch use Hekate's "small" I²C transactions: write a +register byte, read 1–4 bytes back via `CMD_DATA1`. BM92T36 (USB-PD, +USB Power Delivery) uses the Tegra packet mode instead. A 3-word header +is streamed into `TX_FIFO`, then the CPU drains data from `RX_FIFO` +while polling `FIFO_STATUS`. `mmio.cpp` carries a per-bus `PacketState` +FSM (Finite State Machine): + +1. Watch `TX_FIFO` writes. The PROT magic word (`BIT(4)`) starts a new + packet, and subsequent words are `(size-1, header, payload…)`. +2. The header word carries `dev_addr` and a `READ` flag. +3. On a read header, populate a 64-byte `rx_buf` for the slave/register + pair. Currently only BM92T36 needs this (`bm92t36_fill_rx`). +4. `RX_FIFO` reads drain `rx_buf` 4 bytes at a time. + `PACKET_TRANSFER_STATUS` returns `(payload_size - 1) << 4` so the + Hekate wait loop exits immediately. + +Adding a new packet-mode slave is one extra branch in `packet_populate_rx` +plus a `_fill_rx` helper. + +### Live config window (`display/config_window.cpp`) + +A second SDL window (`SDL_WINDOW_HIDDEN` until the user presses `M`) +hosting Dear ImGui sliders, combos and hex inputs. Edits write directly +to the `EmuState` atomics that the I²C, GPIO and fuse handlers read on +each register access. Two cooperative pieces: + +- Window dispatch. `display/sdl_display.cpp::sdl_display_poll_events` + inspects each SDL event's `windowID`. Events targeting the config + window are forwarded to `config_window_handle_event`, which feeds the + ImGui SDL2 backend. Events targeting the main window run through the + existing Switch-button handlers. +- Lifecycle. `main.cpp` calls `config_window_init` once after + `sdl_display_init`, calls `config_window_render` in the same 16 ms + display tick, and calls `config_window_shutdown` before the SDL display + tear-down. + +`SDL_QUIT` only fires when the last window closes. The main poll loop +also catches `SDL_WINDOWEVENT_CLOSE` on the main window ID and treats it +as quit. The config window's close button just hides it (`M` reopens). + +ImGui ships as a git submodule under `third_party/imgui`. A shallow +clone is sufficient. Only the `imgui_*.cpp` core plus the SDL2 and +SDL\_Renderer2 backends are compiled in (not the demo). The Makefile +lists those sources explicitly, so later additions like `imgui_demo.cpp` +do not auto-creep into the build. ### Display pipeline (`display/sdl_display.cpp`) @@ -178,6 +260,12 @@ TegraExplorer tree, not this repo. - **Timer and RTC.** Backed by `EmuState::emu_usec`, incremented per CPU batch by a fixed amount so timing is deterministic across runs. The auto-script feature relies on this. +- **Probe-magic constants.** Several reads return fixed values, not because + they are tweakable but because the chip-detection code expects exact + cookies: `MAX17050.DevName=0x00AC`, `BQ24193.VendorPart=0x2F`, the BM92T36 + `FW_TYPE`/`MAN_ID`/`DEV_ID` triple, `TSEC.STATUS=0xB0B0B0B0`, + `KFUSE.STATE=DONE|CRCPASS`, `PLL_BASE=ENABLE|LOCK`. Changing them breaks + the Hekate init path. They are hardcoded by design. ## Determinism and the auto-script flag diff --git a/Dockerfile b/Dockerfile index d977e8e..1b306df 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,14 +1,18 @@ FROM ubuntu:24.04 -# Build environment for RCM Payload Emulator +# Build environment for RCM Payload Emulator. +# git is needed so the container can bootstrap the Dear ImGui submodule +# (third_party/imgui) from the bind-mounted source tree on first build. RUN apt-get update && apt-get install -y --no-install-recommends \ build-essential \ pkg-config \ + git \ libunicorn-dev \ libsdl2-dev \ && rm -rf /var/lib/apt/lists/* WORKDIR /work -# Build command: docker run --rm -v $(pwd):/work rcm_emu make -CMD ["make"] +# Build command: docker run --rm -v $(pwd):/work rcm_emu +# (init the imgui submodule if it's missing, then build) +CMD ["sh", "-c", "git submodule update --init --recursive && make"] diff --git a/Makefile b/Makefile index 5cf79ec..a72ad45 100644 --- a/Makefile +++ b/Makefile @@ -3,12 +3,25 @@ SRC_DIR = . t210 display SRCS = $(foreach dir,$(SRC_DIR),$(wildcard $(dir)/*.cpp)) + +# Vendored Dear ImGui (see third_party/imgui/). Listed explicitly so we don't +# accidentally pick up imgui_demo.cpp etc. if they're added later. +IMGUI_DIR = third_party/imgui +IMGUI_SRCS = \ + $(IMGUI_DIR)/imgui.cpp \ + $(IMGUI_DIR)/imgui_draw.cpp \ + $(IMGUI_DIR)/imgui_tables.cpp \ + $(IMGUI_DIR)/imgui_widgets.cpp \ + $(IMGUI_DIR)/backends/imgui_impl_sdl2.cpp \ + $(IMGUI_DIR)/backends/imgui_impl_sdlrenderer2.cpp + +SRCS += $(IMGUI_SRCS) OBJS = $(SRCS:.cpp=.o) OUTPUT = rcm_emu CXX = g++ -CXXFLAGS = -Wall -g -O2 -std=c++17 -I. +CXXFLAGS = -Wall -g -O2 -std=c++17 -I. -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends LDFLAGS = LIBS = -lunicorn -lSDL2 -lpthread @@ -29,9 +42,10 @@ $(OUTPUT): $(OBJS) $(CXX) $(LDFLAGS) -o $@ $^ $(LIBS) # Header dependencies -main.o: main.cpp emu_state.h t210/memory_map.h t210/mmio.h display/sdl_display.h +main.o: main.cpp emu_state.h t210/memory_map.h t210/mmio.h display/sdl_display.h display/config_window.h t210/mmio.o: t210/mmio.cpp t210/mmio.h t210/memory_map.h t210/tegra_bl.h emu_state.h -display/sdl_display.o: display/sdl_display.cpp display/sdl_display.h emu_state.h t210/tegra_bl.h +display/sdl_display.o: display/sdl_display.cpp display/sdl_display.h display/config_window.h emu_state.h t210/tegra_bl.h +display/config_window.o: display/config_window.cpp display/config_window.h emu_state.h %.o: %.cpp $(CXX) $(CXXFLAGS) -c -o $@ $< diff --git a/README.md b/README.md index 277d987..ca99df2 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,8 @@ slow or destructive. - Replay deterministic button sequences via `--auto-pin-recovery` or `--auto-te-script`, so a payload flow can be exercised from a CI run or a one-shot script. +- Tweak emulated hardware live (battery, charger, thermal, USB-PD, PMIC, + fuses, SD insertion) from a side window. See [Live hardware tweaks](#live-hardware-tweaks). - Read real eMMC (embedded MMC) dumps (`BOOT0`, multi-part `rawnand.bin.NN`) and decrypt them with XTS-AES-128 (XEX-based Tweaked-codebook with ciphertext stealing) against keys from `prod.keys`. @@ -66,7 +68,7 @@ PIN-recovery script) and bakes it into `sd.img`: ```bash # 1. Pull the latest HATS release from sthetix. HATS_URL=$(curl -s https://api.github.com/repos/sthetix/HATS/releases/latest \ - | grep -oE '"browser_download_url":"[^"]+\.zip"' \ + | grep -oE '"browser_download_url": "[^"]+\.zip"' \ | head -1 | cut -d'"' -f4) curl -L -o hats.zip "$HATS_URL" mkdir -p sd_root @@ -115,6 +117,51 @@ green: ![PIN recovery demo](img/pin_recovery_demo.png) +## Live hardware tweaks + +Press `M` in the main window to open a second window that exposes the values +the payload reads from the emulated chips. Edits apply on the next register +read, with no restart and no recompile. Use it to exercise payload code that +branches on hardware state (low-battery warnings, thermal throttling, charger +detect, SD eject, OEM-specific PMIC forks, and similar) without needing the +state to occur on real hardware. + +![Live hardware-config window](img/config_menu.png) + +What's tweakable, grouped by chip: + +| Chip | Bus / addr | Tweakable | +| ----------------------- | --------------- | ----------------------------------------------------------------------------------------------- | +| **MAX17050** fuel gauge | I2C\_1 @ 0x36 | SOC %, VCELL, OCV, Temp, Current, RepCap, FullCAP, DesignCap, V\_empty, Min/Max volt, Age, Cycles | +| **TMP451** thermal | I2C\_1 @ 0x4C | SoC die temp, PCB temp | +| **BQ24193** charger | I2C\_1 @ 0x6B | VBUS, charge state, power-good, input current/voltage limit, system min, fast-charge current, charge voltage limit, thermal regulation | +| **BM92T36** USB-PD | I2C\_1 @ 0x18 | Cable-inserted, PDO voltage, PDO amperage | +| **MAX77620** main PMIC | I2C\_5 @ 0x3C | OTP (Erista / Mariko), silicon revision | +| **MAX77621** CPU/GPU PMIC | I2C\_5 @ 0x1B | Chip ID | +| **Tegra fuses** | FUSE 0x7000F800 | 5 fuse offsets read by Hekate (SKU info, fuse ID, etc.) | +| **GPIO** | Port Z bit 1 | SD card insert / eject | +| **Display** | EmuState | Backlight, rotation override | +| **Emulation** | EmuState | Pause / resume, button visualization | + +A few example tweaks: + +- Drag SOC % down to 5%. The Hekate "low battery" branch fires. +- Drop SoC temp to 95 °C. The thermal-throttle path triggers. +- Toggle VBUS to None and Power good off. Hekate flips to the "no charger" + state. +- Set Charge voltage limit to 4096 mV. The Battery Info screen reflects it + on the next poll. +- Toggle SD card inserted off mid-boot. The SD-detect path sees no card, + which is useful for testing failure handling. +- Switch PMIC OTP to Mariko (0x53). The OEM-detection branch prints + "Mariko OTP" instead of "Erista OTP". + +The full layout (sliders, combos, hex inputs for fuses) lives in +[display/config_window.cpp](display/config_window.cpp). Encoding logic that +maps each user-facing decoded value back to the chip's raw register format +is in [t210/mmio.cpp](t210/mmio.cpp). Each encoder mirrors a corresponding +`*_get_property()` formula in the Hekate `bdk/power/` tree. + ## Controls | Key | Switch button / action | @@ -122,6 +169,7 @@ green: | `↑` / `↓` | VOL+ / VOL– | | `Enter` | POWER | | Mouse click | Touch (Nyx, TE menus) | +| `M` | Open / close hardware-config window (see [Live hardware tweaks](#live-hardware-tweaks)) | | `R` / `Shift+R`| Cycle display rotation CW / CCW | | `P` | Pause or resume emulation | | `S` | Cycle swizzle override | diff --git a/display/config_window.cpp b/display/config_window.cpp new file mode 100644 index 0000000..6898009 --- /dev/null +++ b/display/config_window.cpp @@ -0,0 +1,351 @@ +// Hardware-tweak configuration window. +// See config_window.h for the public contract. + +#include "config_window.h" +#include "emu_state.h" + +#include "imgui.h" +#include "backends/imgui_impl_sdl2.h" +#include "backends/imgui_impl_sdlrenderer2.h" + +#include +#include + +namespace { + +SDL_Window *g_window = nullptr; +SDL_Renderer *g_renderer = nullptr; +ImGuiContext *g_imgui = nullptr; +bool g_visible = false; +Uint32 g_window_id = 0; + +// Reset every tweakable to its EmuState constructor default. +// Kept as one function so the body and emu_state.h stay obviously in sync. +void reset_to_defaults(EmuState *s) { + s->bat_soc_pct = 80; + s->bat_vcell_mv = 3950; + s->bat_temp_c10 = 250; + s->bat_current_ma = 0; + s->bat_capacity_mah = 3500; + s->bat_full_cap_mah = 4000; + s->bat_design_cap_mah = 4310; + s->bat_ocv_mv = 3960; + s->bat_v_empty_mv = 3300; + s->bat_min_volt_mv = 3500; + s->bat_max_volt_mv = 4200; + s->bat_age_pct = 100; + s->bat_cycles = 0; + s->soc_temp_c10 = 420; + s->pcb_temp_c10 = 350; + s->chg_vbus_stat = 0; + s->chg_chrg_stat = 0; + s->chg_power_good = false; + s->chg_input_current_ma = 2000; + s->chg_input_voltage_mv = 4280; + s->chg_system_min_mv = 3500; + s->chg_fast_current_ma = 1856; + s->chg_charge_voltage_mv = 4208; + s->chg_thermal_c = 60; + s->usb_pd_inserted = false; + s->usb_pd_voltage_mv = 5000; + s->usb_pd_amperage_ma = 1500; + s->pmic_otp = 0x35; + s->pmic_silicon_rev = 0; + s->cpu_pmic_version = 0; + s->sd_inserted = true; + s->fuse_0x100 = 1; + s->fuse_0x110 = 0x83; + s->fuse_0x1A0 = 0x06; + s->fuse_0x148 = 0x83000001; + s->fuse_0x118 = 1785; + s->backlight = 100; + s->rotation_override = -1; +} + +// Helper: int slider that reads/writes an atomic. +template +bool atomic_slider_int(const char *label, std::atomic &a, int lo, int hi, const char *fmt = "%d") { + int v = (int)a.load(); + if (ImGui::SliderInt(label, &v, lo, hi, fmt)) { + a.store((T)v); + return true; + } + return false; +} + +// Helper: float slider for a temperature stored as °C × 10. The atomic +// holds tenths so MAX17050/TMP451 register encodings stay simple, but the +// user sees the actual decimal Celsius value. +template +bool atomic_slider_temp(const char *label, std::atomic &a, float lo_c, float hi_c) { + float v = (float)a.load() / 10.0f; + if (ImGui::SliderFloat(label, &v, lo_c, hi_c, "%.1f \xC2\xB0""C")) { + a.store((T)(v * 10.0f)); + return true; + } + return false; +} + +// Helper: hex input that reads/writes a uint32 atomic. +bool atomic_hex_input(const char *label, std::atomic &a) { + uint32_t v = a.load(); + if (ImGui::InputScalar(label, ImGuiDataType_U32, &v, nullptr, nullptr, "%08X", + ImGuiInputTextFlags_CharsHexadecimal)) { + a.store(v); + return true; + } + return false; +} + +void build_ui(EmuState *state) { + // Fill the OS window with a single ImGui window (no decorations). + int win_w = 0, win_h = 0; + SDL_GetWindowSize(g_window, &win_w, &win_h); + ImGui::SetNextWindowPos(ImVec2(0, 0)); + ImGui::SetNextWindowSize(ImVec2((float)win_w, (float)win_h)); + ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | + ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse | + ImGuiWindowFlags_NoBringToFrontOnFocus; + ImGui::Begin("##cfg", nullptr, flags); + + if (ImGui::CollapsingHeader("Battery (MAX17050)", ImGuiTreeNodeFlags_DefaultOpen)) { + atomic_slider_int("SOC (%)", state->bat_soc_pct, 0, 100, "%d %%"); + atomic_slider_int("Voltage (mV)", state->bat_vcell_mv, 3000, 4400, "%d mV"); + atomic_slider_int("OCV (mV)", state->bat_ocv_mv, 3000, 4400, "%d mV"); + atomic_slider_temp ("Temp", state->bat_temp_c10, -20.0f, 80.0f); + + int cur = (int)state->bat_current_ma.load(); + if (ImGui::SliderInt("Current (mA)", &cur, -3000, 3000, "%d mA")) { + state->bat_current_ma.store((int16_t)cur); + } + atomic_slider_int("RepCap (mAh)", state->bat_capacity_mah, 0, 6000, "%d mAh"); + atomic_slider_int("FullCAP (mAh)", state->bat_full_cap_mah, 0, 6000, "%d mAh"); + atomic_slider_int("DesignCap (mAh)", state->bat_design_cap_mah, 0, 6000, "%d mAh"); + atomic_slider_int("V_empty (mV)", state->bat_v_empty_mv, 2500, 3800, "%d mV"); + atomic_slider_int("Min volt (mV)", state->bat_min_volt_mv, 2500, 4400, "%d mV"); + atomic_slider_int("Max volt (mV)", state->bat_max_volt_mv, 2500, 4400, "%d mV"); + atomic_slider_int ("Age (%)", state->bat_age_pct, 0, 100, "%d %%"); + atomic_slider_int("Cycles", state->bat_cycles, 0, 2000); + } + + if (ImGui::CollapsingHeader("Thermal (TMP451)", ImGuiTreeNodeFlags_DefaultOpen)) { + atomic_slider_temp("SoC temp", state->soc_temp_c10, 0.0f, 110.0f); + atomic_slider_temp("PCB temp", state->pcb_temp_c10, 0.0f, 80.0f); + } + + if (ImGui::CollapsingHeader("PMIC (MAX77620 / MAX77621)", ImGuiTreeNodeFlags_DefaultOpen)) { + const char *otp_items[] = {"Erista (0x35)", "Mariko (0x53)"}; + int idx = (state->pmic_otp.load() == 0x53) ? 1 : 0; + if (ImGui::Combo("OTP", &idx, otp_items, IM_ARRAYSIZE(otp_items))) { + state->pmic_otp.store(idx == 1 ? 0x53 : 0x35); + } + atomic_slider_int("MAX77620 silicon rev", state->pmic_silicon_rev, 0, 15); + atomic_slider_int("MAX77621 chipid", state->cpu_pmic_version, 0, 15); + } + + if (ImGui::CollapsingHeader("Charger (BQ24193)", ImGuiTreeNodeFlags_DefaultOpen)) { + const char *vbus_items[] = {"None", "USB SDP", "Adapter", "OTG"}; + int vbus = (int)state->chg_vbus_stat.load(); + if (ImGui::Combo("VBUS", &vbus, vbus_items, IM_ARRAYSIZE(vbus_items))) { + state->chg_vbus_stat.store((uint8_t)vbus); + } + const char *chrg_items[] = {"Not charging", "Pre-charge", "Fast charge", "Done"}; + int chrg = (int)state->chg_chrg_stat.load(); + if (ImGui::Combo("Charge state", &chrg, chrg_items, IM_ARRAYSIZE(chrg_items))) { + state->chg_chrg_stat.store((uint8_t)chrg); + } + bool pg = state->chg_power_good.load(); + if (ImGui::Checkbox("Power good", &pg)) { + state->chg_power_good.store(pg); + } + + // ---- Charger limits (encoded into BQ24193 regs 0x00/0x01/0x02/0x04/0x06) ---- + // InputCurrentLimit is a quantized 8-value table in the chip; expose it + // as a Combo so the displayed value always matches what Hekate reads back. + const char *iinlim_items[] = {"100 mA","150 mA","500 mA","900 mA","1200 mA","1500 mA","2000 mA","3000 mA"}; + const uint16_t iinlim_vals[] = {100,150,500,900,1200,1500,2000,3000}; + int iidx = 6; + for (int i = 0; i < 8; i++) if (state->chg_input_current_ma.load() == iinlim_vals[i]) { iidx = i; break; } + if (ImGui::Combo("Input current limit", &iidx, iinlim_items, IM_ARRAYSIZE(iinlim_items))) { + state->chg_input_current_ma.store(iinlim_vals[iidx]); + } + // The four remaining limits are linearly quantized; sliders are fine. + atomic_slider_int("Input voltage limit (mV)", state->chg_input_voltage_mv, 3880, 5080, "%d mV"); + atomic_slider_int("System min voltage (mV)", state->chg_system_min_mv, 3000, 3700, "%d mV"); + atomic_slider_int("Fast charge current (mA)", state->chg_fast_current_ma, 512, 4544, "%d mA"); + atomic_slider_int("Charge voltage limit (mV)", state->chg_charge_voltage_mv, 3504, 4512, "%d mV"); + + const char *therm_items[] = {"60 \xC2\xB0""C","80 \xC2\xB0""C","100 \xC2\xB0""C","120 \xC2\xB0""C"}; + const uint8_t therm_vals[] = {60, 80, 100, 120}; + int tidx = 0; + for (int i = 0; i < 4; i++) if (state->chg_thermal_c.load() == therm_vals[i]) { tidx = i; break; } + if (ImGui::Combo("Thermal regulation", &tidx, therm_items, IM_ARRAYSIZE(therm_items))) { + state->chg_thermal_c.store(therm_vals[tidx]); + } + } + + if (ImGui::CollapsingHeader("Storage")) { + bool ins = state->sd_inserted.load(); + if (ImGui::Checkbox("SD card inserted", &ins)) { + state->sd_inserted.store(ins); + } + } + + if (ImGui::CollapsingHeader("USB-PD (BM92T36)", ImGuiTreeNodeFlags_DefaultOpen)) { + bool ins = state->usb_pd_inserted.load(); + if (ImGui::Checkbox("Cable inserted", &ins)) { + state->usb_pd_inserted.store(ins); + } + atomic_slider_int("PDO voltage (mV)", state->usb_pd_voltage_mv, 5000, 20000, "%d mV"); + atomic_slider_int("PDO amperage (mA)", state->usb_pd_amperage_ma, 500, 3000, "%d mA"); + } + + if (ImGui::CollapsingHeader("Display")) { + int bl = (int)state->backlight; + if (ImGui::SliderInt("Backlight", &bl, 0, 255)) { + state->backlight = (uint32_t)bl; + } + const char *rot_items[] = {"Auto", "0\xC2\xB0", "90\xC2\xB0", "180\xC2\xB0", "270\xC2\xB0"}; + int rot_idx = state->rotation_override + 1; // -1..3 -> 0..4 + if (ImGui::Combo("Rotation", &rot_idx, rot_items, IM_ARRAYSIZE(rot_items))) { + state->rotation_override = rot_idx - 1; + } + } + + if (ImGui::CollapsingHeader("Fuses (advanced)")) { + atomic_hex_input("FUSE 0x100", state->fuse_0x100); + atomic_hex_input("FUSE 0x110 (SKU)", state->fuse_0x110); + atomic_hex_input("FUSE 0x118 (ID)", state->fuse_0x118); + atomic_hex_input("FUSE 0x148", state->fuse_0x148); + atomic_hex_input("FUSE 0x1A0", state->fuse_0x1A0); + } + + if (ImGui::CollapsingHeader("Emulation")) { + bool paused = state->paused.load(); + if (ImGui::Checkbox("Paused", &paused)) { + state->paused.store(paused); + } + ImGui::Text("emu_usec: %llu", (unsigned long long)state->emu_usec); + ImGui::Text("insn_count: %llu", (unsigned long long)state->insn_count); + + ImGui::Separator(); + ImGui::TextDisabled("Buttons (visual; SDL keys still work):"); + bool vu = state->btn_vol_up.load(); + bool vd = state->btn_vol_down.load(); + bool pw = state->btn_power.load(); + if (ImGui::Checkbox("VOL+", &vu)) state->btn_vol_up.store(vu); + ImGui::SameLine(); + if (ImGui::Checkbox("VOL-", &vd)) state->btn_vol_down.store(vd); + ImGui::SameLine(); + if (ImGui::Checkbox("POWER", &pw)) state->btn_power.store(pw); + } + + ImGui::Separator(); + if (ImGui::Button("Reset to defaults")) { + reset_to_defaults(state); + } + + ImGui::End(); +} + +} // namespace + +bool config_window_init() { + g_window = SDL_CreateWindow("rcm_emu - Hardware Config", + SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, + 480, 720, + SDL_WINDOW_HIDDEN | SDL_WINDOW_RESIZABLE); + if (!g_window) { + 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); + if (!g_renderer) { + fprintf(stderr, "[config_window] SDL_CreateRenderer failed: %s\n", SDL_GetError()); + SDL_DestroyWindow(g_window); + g_window = nullptr; + return false; + } + + IMGUI_CHECKVERSION(); + g_imgui = ImGui::CreateContext(); + ImGui::StyleColorsDark(); + + if (!ImGui_ImplSDL2_InitForSDLRenderer(g_window, g_renderer)) { + fprintf(stderr, "[config_window] ImGui SDL2 backend init failed\n"); + ImGui::DestroyContext(g_imgui); + g_imgui = nullptr; + return false; + } + if (!ImGui_ImplSDLRenderer2_Init(g_renderer)) { + fprintf(stderr, "[config_window] ImGui SDLRenderer2 backend init failed\n"); + ImGui_ImplSDL2_Shutdown(); + ImGui::DestroyContext(g_imgui); + g_imgui = nullptr; + return false; + } + + g_window_id = SDL_GetWindowID(g_window); + g_visible = false; + return true; +} + +void config_window_shutdown() { + if (g_imgui) { + ImGui_ImplSDLRenderer2_Shutdown(); + ImGui_ImplSDL2_Shutdown(); + ImGui::DestroyContext(g_imgui); + g_imgui = nullptr; + } + if (g_renderer) { SDL_DestroyRenderer(g_renderer); g_renderer = nullptr; } + if (g_window) { SDL_DestroyWindow(g_window); g_window = nullptr; } + g_window_id = 0; + g_visible = false; +} + +bool config_window_handle_event(const SDL_Event &ev) { + if (!g_imgui) return false; + ImGui::SetCurrentContext(g_imgui); + ImGui_ImplSDL2_ProcessEvent(&ev); + + // Hide on close-button click rather than tearing the window down — the M + // key flips it back on. + if (ev.type == SDL_WINDOWEVENT && + ev.window.windowID == g_window_id && + ev.window.event == SDL_WINDOWEVENT_CLOSE) { + SDL_HideWindow(g_window); + g_visible = false; + } + return true; +} + +void config_window_toggle() { + if (!g_window) return; + g_visible = !g_visible; + if (g_visible) { + SDL_ShowWindow(g_window); + SDL_RaiseWindow(g_window); + } else { + SDL_HideWindow(g_window); + } +} + +bool config_window_is_visible() { return g_visible; } +Uint32 config_window_id() { return g_window_id; } + +void config_window_render(EmuState *state) { + if (!g_visible || !g_imgui) return; + + ImGui::SetCurrentContext(g_imgui); + ImGui_ImplSDLRenderer2_NewFrame(); + ImGui_ImplSDL2_NewFrame(); + ImGui::NewFrame(); + + build_ui(state); + + ImGui::Render(); + SDL_SetRenderDrawColor(g_renderer, 30, 30, 30, 255); + SDL_RenderClear(g_renderer); + ImGui_ImplSDLRenderer2_RenderDrawData(ImGui::GetDrawData(), g_renderer); + SDL_RenderPresent(g_renderer); +} diff --git a/display/config_window.h b/display/config_window.h new file mode 100644 index 0000000..60646ab --- /dev/null +++ b/display/config_window.h @@ -0,0 +1,30 @@ +#ifndef CONFIG_WINDOW_H +#define CONFIG_WINDOW_H + +#include + +struct EmuState; + +// Hardware-tweak configuration window. +// Renders in a separate SDL window (toggle with the M key on the main window) +// using Dear ImGui. Edits write directly to atomic fields on EmuState; MMIO +// handlers in t210/mmio.cpp pick them up on the next register read. + +bool config_window_init(); +void config_window_shutdown(); + +// Called from the main SDL event loop. Returns true if the event targeted the +// config window and was consumed (caller should `continue` the loop). +bool config_window_handle_event(const SDL_Event &ev); + +// Show/hide the config window. +void config_window_toggle(); +bool config_window_is_visible(); + +// Build the ImGui frame and present. Cheap when hidden (returns immediately). +void config_window_render(EmuState *state); + +// Returns the SDL_WindowID of the config window (0 if not yet created). +Uint32 config_window_id(); + +#endif // CONFIG_WINDOW_H diff --git a/display/sdl_display.cpp b/display/sdl_display.cpp index c98421e..c4887fd 100644 --- a/display/sdl_display.cpp +++ b/display/sdl_display.cpp @@ -1,4 +1,5 @@ #include "sdl_display.h" +#include "config_window.h" #include "../emu_state.h" #include "../t210/memory_map.h" @@ -7,6 +8,24 @@ #include #include +// Some SDL events are not window-targeted (e.g. SDL_QUIT). Returns true only +// for events that carry a windowID matching the config window. +static bool event_targets_config_window(const SDL_Event &ev) { + Uint32 cfg_id = config_window_id(); + if (cfg_id == 0) return false; + switch (ev.type) { + case SDL_WINDOWEVENT: return ev.window.windowID == cfg_id; + case SDL_KEYDOWN: + case SDL_KEYUP: return ev.key.windowID == cfg_id; + case SDL_TEXTINPUT: return ev.text.windowID == cfg_id; + case SDL_MOUSEBUTTONDOWN: + case SDL_MOUSEBUTTONUP: return ev.button.windowID == cfg_id; + case SDL_MOUSEMOTION: return ev.motion.windowID == cfg_id; + case SDL_MOUSEWHEEL: return ev.wheel.windowID == cfg_id; + default: return false; + } +} + static SDL_Window *window = nullptr; static SDL_Renderer *renderer = nullptr; static SDL_Texture *texture = nullptr; @@ -379,6 +398,23 @@ bool sdl_display_poll_events(EmuState *state, uc_engine *uc) { state->running = false; return false; } + // SDL_QUIT only fires when the *last* window closes; in multi-window + // setups the per-window close button just emits SDL_WINDOWEVENT_CLOSE. + // Treat closing the main window as "quit", and let the config window's + // close be handled by its own handler below (which just hides it). + if (event.type == SDL_WINDOWEVENT && + event.window.event == SDL_WINDOWEVENT_CLOSE && + event.window.windowID != config_window_id()) { + state->running = false; + return false; + } + // Route events targeting the hardware config window to ImGui and skip + // the main-window handlers below (so e.g. typing into a hex input doesn't + // also press POWER). + if (event_targets_config_window(event)) { + config_window_handle_event(event); + continue; + } // ---- Mouse → FTS4 touchscreen events ---- if (event.type == SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_LEFT) { uint16_t px = 0, py = 0; @@ -470,6 +506,11 @@ bool sdl_display_poll_events(EmuState *state, uc_engine *uc) { printf("[diag] Swizzle Override: %d (-1=Auto, 0=Pitch, 2=Block)\n", g_swizzle_override); break; + case SDLK_m: + config_window_toggle(); + printf("[diag] Config window %s\n", + config_window_is_visible() ? "OPEN" : "CLOSED"); + break; case SDLK_ESCAPE: state->running = false; return false; diff --git a/emu_state.h b/emu_state.h index 261a3e8..b1737e9 100644 --- a/emu_state.h +++ b/emu_state.h @@ -116,6 +116,63 @@ struct EmuState { std::atomic 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 bat_soc_pct{80}; // RepSOC: percent (0-100) + std::atomic bat_vcell_mv{3950}; // VCELL: mV + std::atomic bat_temp_c10{250}; // TEMP: °C * 10 (UI unit), e.g. 250 -> 25.0°C + std::atomic bat_current_ma{0}; // Current: signed mA + std::atomic bat_capacity_mah{3500}; // RepCap: mAh (current charge) + std::atomic bat_full_cap_mah{4000}; // FullCAP: mAh (learned full capacity) + std::atomic bat_design_cap_mah{4310}; // DesignCap: mAh (Switch nominal) + std::atomic bat_ocv_mv{3960}; // OCVInternal: mV (open-circuit) + std::atomic bat_v_empty_mv{3300}; // V_empty: mV + std::atomic bat_min_volt_mv{3500}; // MinMaxVolt low byte * 20 + std::atomic bat_max_volt_mv{4200}; // MinMaxVolt high byte * 20 + std::atomic bat_age_pct{100}; // Age: percent (Age MSB) + std::atomic bat_cycles{0}; // Cycles count + + // Main PMIC OEM (MAX77620 CID4): 0x35 = Erista, 0x53 = Mariko, other = Unknown + std::atomic pmic_otp{0x35}; + std::atomic pmic_silicon_rev{0}; // MAX77620 CID3 low nibble: "max77620 v%d" + std::atomic cpu_pmic_version{0}; // MAX77621 CHIPID1: "max77621 v%d" + + // SD card insertion (GPIO Port Z bit 1 = 0 means inserted). + std::atomic sd_inserted{true}; + + // SoC thermal sensor (TMP451, I2C5 @ 0x4C). + std::atomic soc_temp_c10{420}; // remote channel (SoC die): °C * 10 + std::atomic pcb_temp_c10{350}; // local channel (PCB): °C * 10 + + // Charger (BQ24193, I2C1 @ 0x6B). + std::atomic chg_vbus_stat{0}; // 0=none, 1=USB-SDP, 2=adapter, 3=OTG + std::atomic chg_chrg_stat{0}; // 0=not charging, 1=pre, 2=fast, 3=done + std::atomic 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 chg_input_current_ma{2000}; // table: 100/150/500/900/1200/1500/2000/3000 + std::atomic chg_input_voltage_mv{4280}; // 3880-5080 mV, 80 mV step + std::atomic chg_system_min_mv{3500}; // 3000-3700 mV, 100 mV step + std::atomic chg_fast_current_ma{1856}; // 512-4544 mA, 64 mA step + std::atomic chg_charge_voltage_mv{4208}; // 3504-4512 mV, 16 mV step + std::atomic chg_thermal_c{60}; // 60 / 80 / 100 / 120 °C + + // USB-PD controller (BM92T36, I2C1 @ 0x18). One synthesized fixed PDO. + std::atomic usb_pd_inserted{false}; + std::atomic usb_pd_voltage_mv{5000}; + std::atomic usb_pd_amperage_ma{1500}; + + // Fuse driver (FUSE @ 0x7000F800). Names per Hekate's bdk/soc/fuse.h. + std::atomic fuse_0x100{1}; // FUSE_PRODUCTION_MODE (1 = production unit) + std::atomic fuse_0x110{0x83}; // FUSE_SKU_INFO (0x83 = SKU_ODIN, required by Minerva) + std::atomic fuse_0x118{1785}; // FUSE_CPU_IDDQ_CALIB + std::atomic fuse_0x148{0x83000001}; // FUSE_OPT_FT_REV / mixed + std::atomic fuse_0x1A0{0x06}; // FUSE_OPT_VENDOR_CODE }; #endif // EMU_STATE_H diff --git a/img/config_menu.png b/img/config_menu.png new file mode 100644 index 0000000..69ba2ff Binary files /dev/null and b/img/config_menu.png differ diff --git a/main.cpp b/main.cpp index 9f06928..63634c3 100644 --- a/main.cpp +++ b/main.cpp @@ -25,6 +25,7 @@ #include "t210/memory_map.h" #include "t210/mmio.h" #include "display/sdl_display.h" +#include "display/config_window.h" // ==================== Payload Loading ==================== @@ -150,10 +151,12 @@ static uc_engine *setup_emulation(EmuState *state, uint8_t *payload, size_t payl // Pre-set Hekate's "watchdog fired" magic at IRAM 0x4003FF18 (cookie "WDT") // so its early boot does `goto skip_lp0_minerva_config`, skipping both - // libsys_lp0.bso and the Minerva DRAM-training path. EXCP_EN_ADDR - // (0x4003FF1C) stays zeroed so ERR_EXCEPTION is *not* set and no warning - // screen appears. EMC/MC training touches hardware we don't model; this is - // the same path Hekate takes on real silicon after a legitimate WDT reset. + // libsys_lp0.bso and the Minerva DRAM-training path. The matching + // EXCP_EN_ADDR (0x4003FF1C) is intentionally left zeroed so ERR_EXCEPTION + // is *not* set and the user doesn't see a "hang detected" warning screen. + // We can't model EMC/MC well enough for real Minerva training, so this is + // the cleanest opt-out (the same path Hekate uses on hardware after a + // legitimate WDT reset). { uint32_t wdt_magic = 0x544457; // "WDT" uc_mem_write(uc, 0x4003FF18, &wdt_magic, sizeof(wdt_magic)); @@ -347,8 +350,13 @@ int main(int argc, char *argv[]) { return 1; } + // Initialize the hardware-tweak config window (hidden until 'M' is pressed). + if (!config_window_init()) { + fprintf(stderr, "[warn] Config window init failed; M-key menu disabled\n"); + } + printf("\n[emu] Starting emulation...\n"); - printf("[emu] Press Escape to quit\n\n"); + printf("[emu] Press Escape to quit, M to toggle hardware config\n\n"); // ---- Emulation loop ---- // We run emulation in batches, interleaving with SDL event handling @@ -514,6 +522,7 @@ int main(int argc, char *argv[]) { auto elapsed = std::chrono::duration_cast(now - last_display_update); if (elapsed.count() >= DISPLAY_UPDATE_MS) { sdl_display_update(&state, uc); + config_window_render(&state); last_display_update = now; } } @@ -533,6 +542,7 @@ int main(int argc, char *argv[]) { final_insn[4], final_insn[5], final_insn[6], final_insn[7]); } + config_window_shutdown(); sdl_display_shutdown(); uc_close(uc); diff --git a/t210/mmio.cpp b/t210/mmio.cpp index a4cbc5d..96dd2b7 100644 --- a/t210/mmio.cpp +++ b/t210/mmio.cpp @@ -48,8 +48,9 @@ uint32_t gpio_read(EmuState *state, uint64_t addr) { } if (offset == 0x61C) { - printf("[gpio] R: Port Z IN = 0x00 (SD Inserted)\n"); - return 0; // Bit 1 = 0 (Inserted) + // Port Z IN. Bit 1 active-low = SD card detect. + uint32_t val = state->sd_inserted.load() ? 0x00 : (1u << 1); + return val; } printf("[gpio] R: offset 0x%X = 0\n", offset); @@ -84,75 +85,88 @@ void gpio_write(EmuState *state, uint64_t addr, uint32_t val) { static uint8_t i2c_slave_addr = 0; static uint8_t i2c_reg_addr = 0; -// ==================== Synaptics RMI4 touch controller (I2C addr 0x4C on I2C1) ==================== -// Synaptics S7509A capacitive touch IC. hekate polls two registers per cycle: -// 0x01 – F01 interrupt status (bit 2 = F11 touch interrupt) -// 0x10 – F11 finger data (state, X/Y/W/Z in successive registers) -// -// hekate reads DATA1 (bytes 0-3) and optionally DATA2 (bytes 4-7) per -// transaction via auto-increment. The register pointer is set by writing -// the register address as a 1-byte payload to the device. -// -// Coordinate system: portrait 720×1280. -// reg 0x10 = finger_state (0x01 = one finger) -// reg 0x11 = X[11:4] -// reg 0x12 = Y[11:4] -// reg 0x13 = X[3:0]<<4 | Y[3:0] -// reg 0x14 = Wx<<4 | Wy -// reg 0x15 = Z (pressure) - -static uint8_t rmi4_regs[256] = {0}; -static uint8_t rmi4_read_ptr = 0; -static bool rmi4_initialized = false; -static bool rmi4_touch_updated = false; // prevent double-advance per poll - -static void rmi4_init() { - memset(rmi4_regs, 0, sizeof(rmi4_regs)); - rmi4_initialized = true; -} - -static void rmi4_update_touch(EmuState *state) { - int phase = state->touch_phase.load(); - uint16_t x = state->touch_x; - uint16_t y = state->touch_y; - - if (phase == 1) { - rmi4_regs[0x01] = 0x04; // F11 interrupt - rmi4_regs[0x10] = 0x01; // finger 0 present - rmi4_regs[0x11] = (x >> 4) & 0xFF; // X[11:4] - rmi4_regs[0x12] = (y >> 4) & 0xFF; // Y[11:4] - rmi4_regs[0x13] = ((x & 0xF) << 4) | (y & 0xF); - rmi4_regs[0x14] = 0x44; // Wx=4, Wy=4 - rmi4_regs[0x15] = 0x40; // pressure - state->touch_phase = 2; - printf("[touch] RMI4: DOWN at portrait (%d,%d)\n", x, y); - } else if (phase == 2) { - rmi4_regs[0x01] = 0x04; // F11 interrupt (lift) - rmi4_regs[0x10] = 0x00; // no finger - memset(&rmi4_regs[0x11], 0, 5); - state->touch_phase = 3; - printf("[touch] RMI4: UP\n"); - } else { - rmi4_regs[0x01] = 0x00; - rmi4_regs[0x10] = 0x00; - } -} - -// Pack 4 consecutive rmi4_regs bytes into a little-endian uint32_t -static uint32_t rmi4_read4(uint8_t start) { - uint32_t v = 0; - for (int i = 0; i < 4; i++) - v |= (uint32_t)rmi4_regs[(start + i) & 0xFF] << (i * 8); - return v; -} +// (Touch controller is the STMFTS at I2C_3 / slave 0x49, handled separately +// in t210/i2c3.cpp. Nothing else lives at I2C_1 / slave 0x4C besides TMP451.) #define MAX77620_REG_ONOFFSTAT 0x15 #define MAX77620_ONOFFSTAT_EN0 BIT(2) +// ---- Packet-mode I2C (BM92T36 USB-PD on I2C_1 @ 0x18) ---- +// MAX17050/MAX77620/BQ24193 use the simple "normal" path (CMD_DATA1 reads). +// BM92T36 uses Hekate's i2c_xfer_packet, which streams a multi-word header +// through TX_FIFO and reads data back through RX_FIFO. This is a small FSM +// that watches TX_FIFO writes, captures the slave/register/direction, and +// pre-fills an RX buffer when a read header arrives. +struct PacketState { + int hdr_idx = 0; // word index since last PROT magic + uint8_t dev_addr = 0; + uint32_t payload_size = 0; // bytes + bool is_read = false; + uint8_t reg_addr = 0; // captured from prior write phase + uint8_t rx_buf[64] = {0}; + uint32_t rx_size = 0; + uint32_t rx_pos = 0; +}; +static PacketState pkt_i2c1; +static PacketState pkt_i2c5; + +#define I2C_PACKET_PROT_I2C (1u << 4) +#define I2C_HEADER_READ (1u << 19) + +static void bm92t36_fill_rx(EmuState *state, uint8_t reg, uint8_t *buf, uint32_t size) { + // All multi-byte values are little-endian on the wire (Hekate reassembles + // with `(buf[1] << 8) | buf[0]`). FW_TYPE is the exception — Hekate uses + // `(buf[0] << 4) | buf[1]` and expects 0x36, so buf[0]=3, buf[1]=6. + auto put = [&](uint32_t i, uint8_t v) { if (i < size) buf[i] = v; }; + switch (reg) { + case 0x03: // STATUS1: bit 7 = cable inserted + put(0, state->usb_pd_inserted.load() ? 0x80 : 0x00); + break; + case 0x4B: // FW_TYPE_REG -> VER_36 = 0x36 + put(0, 0x03); put(1, 0x06); + break; + case 0x4D: // MAN_ID_REG -> MAN_ROHM = 0x04B5 + put(0, 0xB5); put(1, 0x04); + break; + case 0x4E: // DEV_ID_REG -> DEV_BM92T = 0x03B0 + put(0, 0xB0); put(1, 0x03); + break; + case 0x08: // READ_PDOS_SRC: byte0 = PDO-bytes count, then 4-byte PDOs + case 0x28: { // CURRENT_PDO: same layout, 1 PDO + // Synthesize a single Fixed-type PDO from the EmuState values. + // pd_object_t bitfields (LSB->MSB): amp:10, volt:10, info:10, type:2. + uint32_t amp_lsb = (uint32_t)(state->usb_pd_amperage_ma.load() / 10) & 0x3FF; + uint32_t volt_lsb = (uint32_t)(state->usb_pd_voltage_mv.load() / 50) & 0x3FF; + uint32_t pdo = amp_lsb | (volt_lsb << 10); + put(0, 4); + put(1, (uint8_t)(pdo >> 0)); + put(2, (uint8_t)(pdo >> 8)); + put(3, (uint8_t)(pdo >> 16)); + put(4, (uint8_t)(pdo >> 24)); + break; + } + default: + break; + } +} + +static void packet_populate_rx(EmuState *state, bool on_i2c5, PacketState &p) { + p.rx_pos = 0; + p.rx_size = std::min((uint32_t)sizeof(p.rx_buf), p.payload_size); + memset(p.rx_buf, 0, sizeof(p.rx_buf)); + if (!on_i2c5 && p.dev_addr == 0x18) { + bm92t36_fill_rx(state, p.reg_addr, p.rx_buf, p.rx_size); + } + // Add other packet-mode slaves here as needed. +} + uint32_t i2c_read(EmuState *state, uint64_t addr) { - uint32_t base = (addr >= I2C5_BASE) ? I2C5_BASE : I2C1_BASE; + bool on_i2c5 = (addr >= I2C5_BASE); + uint32_t base = on_i2c5 ? I2C5_BASE : I2C1_BASE; uint32_t offset = (uint32_t)(addr - base); + PacketState &pkt = on_i2c5 ? pkt_i2c5 : pkt_i2c1; + switch (offset) { case 0x1C: // I2C_STATUS return 0; // Transaction complete, no error, not busy @@ -160,43 +174,195 @@ uint32_t i2c_read(EmuState *state, uint64_t addr) { return 0; // MSTR_CONFIG_LOAD (bit 0) cleared = load complete case 0x68: // I2C_INT_STATUS return (1 << 11); // BUS_CLEAR_DONE (bit 11) - case 0x10: { // I2C_CMD_DATA2 (bytes 4-7 of current chunk) - if (i2c_slave_addr == 0x4C) { - if (!rmi4_initialized) rmi4_init(); - return rmi4_read4(rmi4_read_ptr + 4); + case 0x54: { // I2C_RX_FIFO (packet-mode receive) + uint32_t word = 0; + uint32_t n = std::min((uint32_t)4, pkt.rx_size - pkt.rx_pos); + for (uint32_t i = 0; i < n; i++) { + word |= (uint32_t)pkt.rx_buf[pkt.rx_pos++] << (i * 8); + } + return word; + } + case 0x58: // I2C_PACKET_TRANSFER_STATUS + // Hekate waits for ((status >> 4) & 0xFFF) == size-1 after each phase. + // Return the last-captured payload size shifted; phase always completes + // synchronously in our emulator. + return (pkt.payload_size ? (pkt.payload_size - 1) : 0) << 4; + case 0x60: { // I2C_FIFO_STATUS + // Bits[3:0] = RX_FIFO_FULL_CNT (entries available, each entry = 4 bytes). + if (pkt.rx_size > pkt.rx_pos) { + uint32_t words = (pkt.rx_size - pkt.rx_pos + 3) / 4; + return words & 0xF; } return 0; } + case 0x10: // I2C_CMD_DATA2 (bytes 4-7) — no slaves currently need a >4 byte response + return 0; case 0x0C: // I2C_CMD_DATA1 - // Synaptics RMI4 touch controller (slave 0x4C on I2C1) - if (i2c_slave_addr == 0x4C) { - if (!rmi4_initialized) rmi4_init(); - // When hekate reads interrupt status (reg 0x01), update touch state once per poll - if (rmi4_read_ptr == 0x01 && !rmi4_touch_updated) { - rmi4_update_touch(state); - rmi4_touch_updated = true; - } - return rmi4_read4(rmi4_read_ptr); - } - // Return simulated data based on slave and register - if (i2c_slave_addr == 0x36) { // MAX17050_ADDR + // TMP451 SoC/PCB thermal sensor (slave 0x4C on I2C_1). + // Hekate reads (per bdk/thermal/tmp451.c) the integer °C from + // PCB: 0x00, SoC: 0x01 + // and the fractional byte from + // SoC dec: 0x10, PCB dec: 0x15 + // The fractional byte's high nibble is units of 1/16 °C; Hekate decodes + // tenths_of_C = ((dec >> 4) * 625) / 100 + // So encoding from a UI value of °C×10: + // lsb = (c10 * 8) / 5 // total LSBs (1 LSB = 1/16 °C = 0.625 c10) + // int_byte = lsb >> 4 + // dec_byte = (lsb & 0xF) << 4 + if (!on_i2c5 && i2c_slave_addr == 0x4C) { + auto encode_lsb = [](int16_t c10) -> uint16_t { + return (uint16_t)((int32_t)c10 * 8 / 5); + }; + uint16_t soc_lsb = encode_lsb(state->soc_temp_c10.load()); + uint16_t pcb_lsb = encode_lsb(state->pcb_temp_c10.load()); switch (i2c_reg_addr) { - case 0x06: - return 0x5000; // ~80% battery MAX17050_REP_SOC - case 0x09: - return 3950; // 3950 mV MAX17050_VCELL + case 0x00: return (pcb_lsb >> 4) & 0xFF; // PCB int (local) + case 0x01: return (soc_lsb >> 4) & 0xFF; // SoC int (remote) + case 0x10: return (uint8_t)((soc_lsb & 0xF) << 4); // SoC dec + case 0x15: return (uint8_t)((pcb_lsb & 0xF) << 4); // PCB dec + default: return 0; + } + } + // MAX17050 fuel gauge (slave 0x36 on I2C_1). + // All raw encodings here are the inverse of Hekate's max17050_get_property + // formulas in bdk/power/max17050.c. Switch hardware uses Rsense=5mΩ with + // CGAIN=2 → ADJ_RSENSE = 10mΩ, which sets the per-LSB units below. + if (!on_i2c5 && i2c_slave_addr == 0x36) { + switch (i2c_reg_addr) { + case 0x05: { // RepCap — 0.5 mAh/LSB (= mAh * 2) + return (uint16_t)(state->bat_capacity_mah.load() * 2); + } + case 0x06: { // RepSOC — %·256, Hekate displays (raw >> 8) + return (uint16_t)(state->bat_soc_pct.load() << 8); + } + case 0x07: { // Age — %·256, Hekate displays (raw >> 8) + return (uint16_t)((uint16_t)state->bat_age_pct.load() << 8); + } + case 0x08: { // TEMP — °C/256 signed, UI is °C·10 + int32_t scaled = (int32_t)state->bat_temp_c10.load() * 256 / 10; + return (uint16_t)(int16_t)scaled; + } + case 0x09: // VCELL — 0.625 mV/LSB on the upper 13 bits, i.e. (raw >> 3) * 625 / 1000 = mV + case 0x19: // AvgVCELL — same encoding + case 0xFB: { // OCVInternal — same encoding + uint16_t mv = (i2c_reg_addr == 0xFB) ? state->bat_ocv_mv.load() : state->bat_vcell_mv.load(); + return (uint16_t)(((uint32_t)mv * 8000) / 625); + } + case 0x0A: // Current — 156.25 µA/LSB signed, UI is mA + case 0x0B: { // AvgCurrent — same encoding + int32_t raw = (int32_t)state->bat_current_ma.load() * 64 / 10; + return (uint16_t)(int16_t)raw; + } + case 0x10: { // FullCAP — 0.5 mAh/LSB + return (uint16_t)(state->bat_full_cap_mah.load() * 2); + } + case 0x17: { // Cycles + return state->bat_cycles.load(); + } + case 0x18: { // DesignCap — 0.5 mAh/LSB + return (uint16_t)(state->bat_design_cap_mah.load() * 2); + } + case 0x1B: { // MinMaxVolt — packed (max << 8) | min, units of 20 mV + uint16_t lo = (uint16_t)(state->bat_min_volt_mv.load() / 20) & 0xFF; + uint16_t hi = (uint16_t)(state->bat_max_volt_mv.load() / 20) & 0xFF; + return (hi << 8) | lo; + } + case 0x21: // DevName — must be 0x00AC for max17050_get_version() to succeed + return 0x00AC; + case 0x3A: { // V_empty — (raw >> 7) * 10 = mV + return (uint16_t)(((uint32_t)state->bat_v_empty_mv.load() / 10) << 7); + } default: return 0; } } - if (i2c_slave_addr == 0x3C) { // MAX77620_ADDR - if (i2c_reg_addr == 0x15) { // MAX77620_REG_ONOFFSTAT - uint32_t val = 0; - if (state->btn_power) - val |= (1 << 2); // MAX77620_ONOFFSTAT_EN0 - return val; + // MAX77620 PMIC (slave 0x3C on I2C_5). + if (on_i2c5 && i2c_slave_addr == 0x3C) { + switch (i2c_reg_addr) { + case 0x15: { // ONOFFSTAT — EN0 bit reflects power button + return state->btn_power.load() ? (1 << 2) : 0; + } + case 0x5B: return state->pmic_silicon_rev.load() & 0xF; // CID3: low nibble shown as "v%d" + case 0x5C: return state->pmic_otp.load(); // CID4: 0x35 Erista, 0x53 Mariko + case 0x5D: return 0; // CID5: ES version + default: return 0; + } + } + // MAX77621 CPU/GPU regulator (slave 0x1B on I2C_5). Hekate reads CHIPID1 + // (reg 0x04) and prints the byte verbatim as the version number. + if (on_i2c5 && i2c_slave_addr == 0x1B) { + if (i2c_reg_addr == 0x04) return state->cpu_pmic_version.load(); + return 0; + } + // BQ24193 charger (slave 0x6B on I2C_1). + // Each register is reverse-encoded from a decoded EmuState value (mA / mV + // / °C) so the user-facing tweak reads in real units; the formulas mirror + // bq24193_get_property() in bdk/power/bq24193.c. + if (!on_i2c5 && i2c_slave_addr == 0x6B) { + auto encode_input_current = [](uint16_t ma) -> uint8_t { + // Table-quantized: pick nearest legal bucket. + static const uint16_t tbl[8] = {100,150,500,900,1200,1500,2000,3000}; + uint8_t best = 0; int best_d = 0x7FFFFFFF; + for (uint8_t i = 0; i < 8; i++) { + int d = (int)tbl[i] - (int)ma; if (d < 0) d = -d; + if (d < best_d) { best_d = d; best = i; } + } + return best; + }; + auto clamp_div = [](uint16_t v, uint16_t base, uint16_t step, uint8_t maxbits) -> uint8_t { + if (v < base) v = base; + uint16_t units = (v - base) / step; + uint16_t cap = (1u << maxbits) - 1; + if (units > cap) units = cap; + return (uint8_t)units; + }; + switch (i2c_reg_addr) { + case 0x00: { // InputSource: VINDPM[6:3] | INLIMIT[2:0] + uint8_t ilim = encode_input_current(state->chg_input_current_ma.load()); + uint8_t vindpm = clamp_div(state->chg_input_voltage_mv.load(), 3880, 80, 4); + return (uint32_t)((vindpm << 3) | ilim); + } + case 0x01: { // PORConfig: keep CHGCONFIG=charger-en, set SYSMIN[3:1] + uint8_t sysmin = clamp_div(state->chg_system_min_mv.load(), 3000, 100, 3); + return (uint32_t)((1u << 4) | (sysmin << 1)); + } + case 0x02: { // ChrgCurr: ICHG[7:2] + uint8_t ichg = clamp_div(state->chg_fast_current_ma.load(), 512, 64, 6); + return (uint32_t)(ichg << 2); + } + case 0x04: { // ChrgVolt: VREG[7:2] + uint8_t vreg = clamp_div(state->chg_charge_voltage_mv.load(), 3504, 16, 6); + return (uint32_t)(vreg << 2); + } + case 0x06: { // IRCompThermal: THERM[1:0] + uint8_t c = state->chg_thermal_c.load(); + uint8_t therm = (c >= 110) ? 3 : (c >= 90) ? 2 : (c >= 70) ? 1 : 0; + return (uint32_t)therm; + } + case 0x08: { // Status: bits[7:6]=VBUS, [5:4]=CHRG, [2]=PG + uint32_t v = 0; + v |= (uint32_t)(state->chg_vbus_stat.load() & 0x3) << 6; + v |= (uint32_t)(state->chg_chrg_stat.load() & 0x3) << 4; + if (state->chg_power_good.load()) v |= (1 << 2); + return v; + } + case 0x09: { // FaultReg: bits[2:0] = THERM_STAT (charger NTC thermistor). + // Hekate decodes this independently of MAX17050's TEMP, but on real + // hardware both sensors track the battery, so derive it from the + // battery temp slider for consistency. Code map (per gui_info.c): + // 0=Normal, 2=Warm, 3=Cool, 5=Cold, 6=Hot + int16_t t10 = state->bat_temp_c10.load(); + uint8_t therm; + if (t10 < 0) therm = 5; // Cold + else if (t10 < 100) therm = 3; // Cool + else if (t10 < 450) therm = 0; // Normal + else if (t10 < 500) therm = 2; // Warm + else therm = 6; // Hot + return therm; + } + case 0x0A: return 0x2F; // VendorPart — must be 0x2F for bq24193_get_version() + default: return 0; } - return 0x00; // Default PMIC regs } return 0; default: @@ -205,20 +371,50 @@ uint32_t i2c_read(EmuState *state, uint64_t addr) { } void i2c_write(EmuState *state, uint64_t addr, uint32_t val) { - uint32_t base = (addr >= I2C5_BASE) ? I2C5_BASE : I2C1_BASE; + bool on_i2c5 = (addr >= I2C5_BASE); + uint32_t base = on_i2c5 ? I2C5_BASE : I2C1_BASE; uint32_t offset = (uint32_t)(addr - base); + PacketState &pkt = on_i2c5 ? pkt_i2c5 : pkt_i2c1; + switch (offset) { case I2C_CMD_ADDR0: i2c_slave_addr = (val >> 1) & 0x7F; break; case I2C_CMD_DATA1: i2c_reg_addr = val & 0xFF; - // Synaptics RMI4 (slave 0x4C): track register pointer for reads - if (i2c_slave_addr == 0x4C) { - if (!rmi4_initialized) rmi4_init(); - rmi4_read_ptr = val & 0xFF; - rmi4_touch_updated = false; + break; + case 0x50: { // I2C_TX_FIFO (packet-mode dispatch) + // Each packet starts with the PROT magic word; subsequent words follow a + // fixed layout: [size-1, header, payload...]. The header carries dev_addr + // and a READ flag; for write phases the first payload byte is the slave's + // register address that the matching read phase will target. + if (val == I2C_PACKET_PROT_I2C) { + pkt.hdr_idx = 1; // word 0 (PROT) just consumed + return; + } + int idx = pkt.hdr_idx++; + if (idx == 1) { + pkt.payload_size = (val & 0xFFF) + 1; + } else if (idx == 2) { + pkt.dev_addr = (val >> 1) & 0x7F; + pkt.is_read = (val & I2C_HEADER_READ) != 0; + i2c_slave_addr = pkt.dev_addr; // mirror for any cross-path lookups + if (pkt.is_read) { + packet_populate_rx(state, on_i2c5, pkt); + } + } else if (!pkt.is_read && idx == 3) { + // First (and for our slaves, only) payload byte = register address. + pkt.reg_addr = val & 0xFF; + } + break; + } + case 0x5C: // I2C_FIFO_CONTROL — TX/RX flush at the start of each xfer + if (val & 0x3) { + pkt.hdr_idx = 0; + pkt.rx_size = 0; + pkt.rx_pos = 0; + // reg_addr intentionally preserved across the write→read transition } break; } @@ -1019,18 +1215,12 @@ void clk_rst_write(EmuState *state, uint64_t addr, uint32_t val) { uint32_t fuse_read(EmuState *state, uint64_t addr) { uint32_t offset = (uint32_t)(addr - FUSE_BASE); switch (offset) { - case 0x100: - return 0x83; - case 0x110: - return 0x07; - case 0x1A0: - return 0x06; - case 0x148: - return 0x83000001; - case 0x118: - return 1785; - default: - return 0; + case 0x100: return state->fuse_0x100.load(); + case 0x110: return state->fuse_0x110.load(); + case 0x1A0: return state->fuse_0x1A0.load(); + case 0x148: return state->fuse_0x148.load(); + case 0x118: return state->fuse_0x118.load(); + default: return 0; } } diff --git a/third_party/imgui b/third_party/imgui new file mode 160000 index 0000000..691b89b --- /dev/null +++ b/third_party/imgui @@ -0,0 +1 @@ +Subproject commit 691b89baae95d56df42a59b031c9d19685b7ab2f