33 Commits
Author SHA1 Message Date
Baptiste MOINE 6e72741878 Add a late HPD dock mode 2026-11-13 13:38:17 +01:00
Baptiste MOINE afc3dfe28a Add dock clone modes 2026-11-13 01:41:31 +01:00
Baptiste MOINE 41245dc22b Add fake Bluetooth controllers and USBSERFILE 2026-11-08 00:16:48 +01:00
Baptiste MOINE e17c315f87 Add a USB serial host 2026-11-06 13:00:50 +01:00
Baptiste MOINE a9b184d0ea Fix the left Joy-Con rail reading as attached 2026-11-06 13:00:49 +01:00
Baptiste MOINE ee96a1b8ca Fix the Windows and CI builds 2026-11-05 23:57:10 +01:00
Baptiste MOINE e2feebf9f7 Ignore run logs and captures 2026-11-05 23:46:09 +01:00
Baptiste MOINE 61e1fb981a Add a dock and TV model 2026-11-05 23:46:09 +01:00
Baptiste MOINE 20949b4242 Boot Linux on CPU0 2026-11-05 23:45:44 +01:00
Baptiste MOINE d5bf5922ed Add SNAP to input scripts 2026-11-05 23:45:43 +01:00
Baptiste MOINE 4177e98dfb Add fault injection for chips and rails 2026-10-31 17:30:05 +01:00
Baptiste MOINE 927e2ecb20 Merge pull request #1 from Creased/claude/focused-noether-5orhms
Run CCPLEX CPU0 so hwtest's PCIe probe completes, and speed up the core
2026-09-26 13:14:52 +02:00
Claude f84caeaacc Let the USB host write, and serve a gadget's disk over NBD
The emulated PC only ever read a mass storage disk and then ejected it, so
the write path through a gadget went untested and the disk could not be
used from the machine running the emulator.

The default session now asks MODE SENSE(6) for the write-protect bit and,
on a writable disk whose read checked out, writes the last 8 sectors back
as read (WRITE(10), SYNCHRONIZE CACHE) and reads them again.

--usb-host nbd[:port] (or [usb] nbd_port, or the config window) locks the
medium and serves the disk on 127.0.0.1 with a small non-blocking NBD
server (t210/nbd.cpp: fixed newstyle handshake, READ/WRITE/FLUSH/DISC).
Requests become READ(10)/WRITE(10)s of up to 64 KiB, a quiet client gets
a TEST UNIT READY every second, a write-protected disk is exported
read-only, and when the client disconnects the host ejects the disk.

Serving Nyx exposed a controller model bug: a device transfer shorter than
the host's request was taken as a short packet, so bdk's 64 KiB READ(10),
sent as two 32 KiB transfers, lost the second half. Only a short or
zero-length packet (the USB2 controller's own ZLP unless the queue head
disables it) now ends the host's transfer.

tests/usb grows a write-protected scenario, WRITE(10), MODE SENSE and
SYNCHRONIZE CACHE on its RAM disk (reads sent in 32 KiB transfers, as bdk
does), and three NBD runs driven by a Python client. Checked with Nyx SD
UMS on Erista and Mariko: nbdinfo negotiates, qemu-img convert copies the
256 MiB disk byte for byte, and a qemu-io write lands in the SD image.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb
2026-09-26 11:09:57 +00:00
Claude 0c7f12a83b Store the last three CRLF headers with LF
.gitattributes normalises text to LF, but t210/memory_map.h, mmio.h and
tegra_bl.h were committed with CRLF before it was added, so any edit to
them either rewrote every line or had to be staged around the filter.
Line endings only; no content changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb
2026-09-26 10:31:55 +00:00
Claude d661f2738c Model USB device mode, with an emulated PC on the cable
Both USB controllers were plain register caches: USBCMD.RESET never
cleared, so bdk's usb_device_init() timed out and none of Nyx's USB
tools could even wait for a cable.

- The Erista USB2 controller (USB1, 0x7D000000, bdk usbd.c): queue
  heads at ENDPOINTLISTADDR (bdk's are in the controller at +0x1000),
  transfer descriptors in DRAM, ENDPTPRIME / ENDPTSTATUS /
  ENDPTCOMPLETE, SETUP packets in queue head 0 with ENDPTSETUPSTAT,
  a self-clearing controller reset and the PHY's clock-valid bit. Byte
  and halfword accesses work, since bdk memcpy()s SETUP packets out.
- The Mariko XUSB device controller (0x700D0000, bdk xusbd.c): endpoint
  contexts and TRB rings with Link TRBs and cycle bits, the doorbell, a
  two-segment event ring with Port Status Change, Setup and Transfer
  events, EP_HALT / EP_STCHG, EP_RELOAD, and PORTSC's write-1-to-clear
  changes and link-state writes.
- The host (--usb-host, [usb] host, or the config window) plays the PC
  on whichever controller attaches: debounce, bus reset at high speed,
  enumeration with SET_ADDRESS recovery, then after 100 ms for its class
  driver to bind - bdk's XUSB driver stalls an early GET_MAX_LUN - the
  class. For mass storage it runs Bulk-Only Transport: GET_MAX_LUN,
  INQUIRY, TEST UNIT READY with REQUEST SENSE for the unit attention,
  READ CAPACITY, READ(10) of the first 64 and last 8 blocks with their
  CRC32s, checked against the SD image when the size matches, then allow
  removal, eject, and poll until the gadget detaches. For HID it reads
  the report descriptor, sets idle 0 and polls the interrupt endpoint.
  It only reads, and it runs on the controllers' register accesses, so
  runs repeat. [usb-host] lines log it; RCM_USB_TRACE=1 logs every
  descriptor, TRB and doorbell.

With hekate 6.5.3, Nyx's SD card mass storage enumerates as 11EC:A7E0,
reads back identical to the SD image and ends at "Disk ejected" on both
Erista and Mariko; the gamepad enumerates and serves its report
descriptor (with no Joy-Cons it has nothing to report). Without a host
Nyx waits and reports a timeout, as with no cable.

tests/usb/ runs a mass storage gadget over a RAM disk on each controller
and a HID gadget on the USB2 one, checks what the host logs - the
enumeration, the SCSI commands, CRC32s equal to the payload's, the eject
and the detach - and a run with nothing on the cable.

The Windows pread/pwrite shim moves from mmio.cpp to platform.h, as the
host reads the SD image too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb
2026-09-26 10:25:29 +00:00
Claude 66600dafc1 Tap the touchscreen from --input-script
The input script pressed POWER and the volume buttons only, so touch-
driven payloads - Nyx above all - could not be driven headless.

`<ms> TAP <x> <y> [hold_ms]` touches the screen at (x, y) in the
1280x720 picture bdk's touch driver reports, inverted through its
15..1264 / 15..704 scaling to the FTS4 panel's raw coordinates, and
lifts after hold_ms. The press and release go through the same event
queue as a mouse click in the window.

This is how Nyx's Tools > USB Tools > SD Card is reached headless:
"12000 TAP 516 531, 15000 TAP 640 32, 17000 TAP 640 423,
19000 TAP 850 420, 22000 TAP 170 202" on hekate 6.5.3. The README now
documents --input-script, which it did not mention before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb
2026-09-26 10:24:10 +00:00
Claude f31175f19a Leave the SD slot empty when there is no SD image
Without --sd (and no sd.img in the working directory) the emulator still
presented a card: a blank one, which SDMMC1 initialised at SDR104 and
FatFs then found no volume on. A console with nothing in the slot shows
the payload no card at all.

Now the slot starts empty when there is no image: card detect (PZ1)
reads no card and every SDMMC1 command times out, which the existing
[sd] inserted = 0 path already modelled. The config window's SD toggle
can still insert a blank card at runtime.

hwtest, which CI runs without --sd, now reports sd_initialize failing
and the SD as not ready instead of an unformatted 32 GiB card; its
verdict goes from 35 to 34 passes with no failures, and every CI
expectation still holds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb
2026-09-26 10:23:58 +00:00
Claude 33d16976fe Model the CPU complex's reset view and per-core clock stop
RST_CPU_CMPLX_SET/CLR (0x340/0x344) and CLK_CPUG_CMPLX_SET/CLR
(0x460/0x464) read back the last value written, like plain registers.

- RST_CPU_CMPLX_SET has RST_CPUG_CMPLX's fields and reset value (TRM
  5.2.113): it is the active cluster's view, and the Switch runs the G
  cluster. It and its CLR partner now act on the same reset state as the
  CPUG pair, releasing and stopping CPU0 alike, and read it back.
- CLK_CPUG_CMPLX (0x378, TRM 5.2.122) and its SET/CLR strobes track
  CPUGn_CLK_STP, and all three read the register. A stopped CPU0 keeps
  its state and executes nothing while emulated time passes; clearing
  the stop resumes it where it was.

The CCPLEX test now releases CPU0 with its clock stopped, checks it does
not run and that the registers read back, then clears the stop. Against
the previous binary those three checks fail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb
2026-09-26 10:23:45 +00:00
Claude 803729580b Report the EMC DLL's code from its calibration start value
EMC_DIG_DLL_STATUS.DLL_OUT (10:0) read 0. TRM 18.11.2.219 gives the
basis the earlier note said was missing: EMC_DLL_CFG_1's
DDLLCAL_CTRL_START_TRIM (10:0, reset 0x20) is the DLL calibration's
start value, which the timing table sets per frequency. With no delay
line to drift, calibration has nothing to move it by, so DLL_OUT now
reports the channel's start trim once the DLL locks. EMC_DLL_CFG_1
reads its reset value until written.

Minerva's _digital_dll_prelock() returns the value and nothing reads it
further; DRAM training and the 800/1600 MHz switching are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb
2026-09-26 10:23:31 +00:00
Claude 6d5ccb5328 Lock PLLC4 and the other PLLs bdk waits on, and the USB PLL
TegraExplorer hung for good the first time it touched the eMMC. Moving
SDMMC4 to HS200 enables PLLC4, and TegraExplorer's bdk waits for
PLLC4_BASE.LOCK with no timeout; the CAR model had no PLLC4, so the
bit never came. On Erista that stopped it at startup, before its key
dump; on both SoCs "Browse EMMC" hung. hekate's newer bdk times the
wait out, which is why nothing else showed it.

- PLLC4 locks once enabled and out of IDDQ (bit 18), setting LOCK and
  FREQLOCK (27, 28); LOCK_OVERRIDE (24) forces them.
- PLLC2, PLLC3, PLLDP and PLLA1 lock on ENABLE like PLLC/A/X/D2 (bit
  27; PLLA1 also 26, PLLDP also 28). The read-only lock bits are no
  longer stored from a payload's read-modify-write.
- UTMIPLL_HW_PWRDN_CFG0.LOCK is set unless software holds the USB PLL
  in IDDQ, its reset state, so clock_enable_utmipll() sees the lock
  instead of timing out.

TegraExplorer now reaches its main menu on both SoCs and lists the
eMMC's partitions under "Browse EMMC". With no BOOT0 image it cannot
read package1, so the Erista key dump falls back to prod.keys.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb
2026-09-25 22:40:33 +00:00
Claude e592ec2d88 Make every CAR reset and clock-enable bank live
Only bank U followed the payload's writes. L, H and X read fixed values,
RST_DEVICES_L read 0, and every SET/CLR strobe read 0 - but TRM 5.2.100
says any of the three registers reads back the bank, and bdk relies on
it: clock_sdmmc_is_active() reads RST_DEV_L_SET and CLK_ENB_L_SET.

The fixed CLK_OUT_ENB_L/H/X values were real-console readings taken
after a payload had brought the display up. So every payload found
DISP1 already clocked at RCM entry, and bdk's display_init() began each
boot by tearing down a panel that was never on.

The banks now follow direct writes and SET/CLR strobes, and all three
read the bank. The rest start at the TRM reset values, unknown bits as
0; bank U keeps its real-console reading. The PCIe and CPU models still
hold reset banks V, W and Y and clock bank V, since their preconditions
depend on them; reads of those banks' strobes go to them.

hwtest's report is unchanged apart from fan-tach phase, and hekate into
Nyx gives the same frame as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb
2026-09-25 22:40:19 +00:00
Claude 1aa0ee9f23 Model the SE's RSA and random number generator
Both ops finished with OP_DONE and produced nothing. se_rng_pseudo()
left its buffer as it was, so Nyx's partition manager wrote whatever
was on the stack into GPT partition GUIDs, and the SD benchmark drew
its random offsets from uninitialised memory. se_rsa_exp_mod() read
back zeros.

- RSA, as Lockpick's bdk drives it: two keyslots of up to 2048 bits
  loaded through SE_RSA_KEYTABLE_ADDR/DATA, KEY_SIZE in 512-bit steps,
  EXP_SIZE in words, the input a little-endian number over DMA and the
  result in SE_RSA_OUTPUT (or memory). Montgomery multiplication on
  32-bit words; an even modulus fails the op.
- RNG into memory or a keyslot quad, LAST_BLOCK + 1 blocks cut to the
  buffer. The bytes come from SplitMix64 with a fixed seed, reset with
  the SE, so runs stay reproducible.

tests/se/ is a new make test payload: RSA-2048 and RSA-1024 in the two
slots, each m^d and s^e checked against Python (gen_vectors.py writes
vectors.h), SHA-256 one-shot and in two parts, AES-128 ECB, and the
RNG filling a zeroed buffer, changing between calls and stopping at
the size asked for. Run against the previous binary it fails the RSA
and RNG checks. The README's "RSA, RNG and chunked SHA are stubs" is
gone; chunked SHA was already modelled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb
2026-09-25 22:40:08 +00:00
Claude fd98939cca Make the SD card a UHS-I card, so bdk runs it at SDR104
The SD card ran at 3.3 V High Speed, 48 MHz. It never offered 1.8 V in
ACMD41, CMD11 was not handled, and CMD6 always reported High Speed as
selected whatever was asked. It also carried the eMMC's CSD, so hwtest
saw an 896128 MiB card without application commands, and its SD status
was never read.

- ACMD41 answers S18A to S18R while the card signals at 3.3 V, and
  CMD11 moves it to 1.8 V. It stays there until its supply GPIO (PE4)
  drops or the SoC resets; a card re-initialised without a power cycle
  answers S18A = 0.
- CMD6 reports and selects functions per group, per SD 4.3.10: bus speed
  (SDR50, SDR104 and DDR50 added at 1.8 V), driver strength and power
  limit. CMD0 resets the functions, not the voltage.
- The CSD is an SD CSD 2.0 sized from the image, with command class 8.
  ACMD13 reports the bus width set and a Class 10, U1, V10 card, and
  the SCR sets SD_SPEC3.

hwtest now reports the SD card at 199.68 MHz after SDR104 tuning, with
the image's real size, and LDO2 at 1.8 V. Nyx boots with it, including
after cold and warm reboots, each of which re-runs the voltage switch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb
2026-09-25 21:21:56 +00:00
Claude fae29019ae Model DC window address offsets and block-linear VIC surfaces, with a test
- DC: a window's fetch starts at ADDR_V_OFFSET * LINE_STRIDE +
  ADDR_H_OFFSET (TRM 24.11.1). That is the window's top-left pixel, or
  top-right with H_DIRECTION, or bottom-left with V_DIRECTION, and the
  fetch walks away from it; before, the offsets were ignored and flips
  mirrored within the window. HOS's column-scan offset (0x13FF) and
  hekate's inverted-pitch offset (1279) both land where they should.
  Layer order is documented: the TRM sorts windows by depth without
  saying which way.
- VIC: slot and output surfaces may be block linear (BlkKind 1, 2^BlkHeight
  GOBs per block) as well as pitch.
- GOB addressing moves to t210/block_linear.h, shared by the scan-out
  and VIC.
- tests/display: one bare-metal payload built per scenario (a pitch
  window, Nyx's VIC turn into pitch and into block-linear surfaces, a
  block-linear VIC source, the DC's own column scan with an address
  offset, a mirrored window with window D blended over). check.py
  compares every pixel of the frame the emulator shows with the picture
  drawn. It runs in make test and in CI.

hwtest's frame is unchanged, and Nyx's differs only in its clock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb
2026-09-25 21:21:44 +00:00
Claude c6b532fdbd Read back CAR and MC registers, and measure the EMC at its modelled clock
Most CAR registers the model does not handle, and every MC register but
two, read 0 even after a write. Payloads saw a CLK_SOURCE divider, a
PLL misc word or an audio clock source they had just programmed come
back as 0.

- CAR: the fallthrough returns what was written. The SET/CLR alias
  registers are write strobes and keep reading 0. No CAR poll in bdk or
  hwtest waits for hardware to clear a bit it wrote, so read-back cannot
  turn a poll into a hang.
- MC: configuration registers read back (no MC register is polled).
- The PTO counter measures the EMC at the clock CAR and the PLLs give
  it, so it follows Minerva to 1600 MHz. At the 204 MHz boot clock it
  keeps the measured 203.991 / 204.001 MHz.

hwtest now reports the AUD_MCLK source, PLLA misc word and a clock
source divider it programs. Its verdict is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb
2026-09-25 21:21:30 +00:00
Claude 7607dd9f69 Note which fuses Minerva needs, since hekate blames a missing file
hekate prints "Missing Minerva lib!" whenever minerva_init fails. That
covers the module refusing to start, which it does unless HIDREV reads
chip 0x21 and FUSE_SKU_INFO reads 0x83 (ODIN). The emulator's defaults
satisfy both, but editing fuse 0x110 in the config window or
rcm_emu.ini brings the screen back with the module present. Say so on
the fuse's label and in the boot-flow notes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb
2026-09-25 20:02:01 +00:00
Claude 306a86dbcb Stop planting hekate's watchdog cookie in IRAM
The emulator wrote hekate's "watchdog fired" magic (0x544457 at
0x4003FF18) before every boot. hekate then took its post-watchdog path
and skipped LP0 and Minerva, because the EMC could not support DRAM
training. It can now, so the cookie only made the boot differ from
hardware, and it never covered Nyx, which trains the DRAM itself when
it finds Minerva uninitialised.

With the cookie gone, hekate's IPL saves the LP0 SDRAM config and
trains 204, 800 and 1600 MHz itself, and Nyx takes over the trained
context. An SD image without bootloader/sys now gets hekate's real
"Missing LP0/Minerva lib" screen, which waits for a key press.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb
2026-09-25 19:29:24 +00:00
Claude 4f42e04f6e Model PLLMB and the EMC so Minerva can train and switch the DRAM clock
hekate 6.5.3 with the stock bootloader folder never reached Nyx. Nyx
trains the DRAM itself with Minerva, and Minerva spun forever on
PLLMB_BASE.LOCK: the CAR model had no PLLMB and read it as 0. Behind
that poll were more. Every EMC register but three read 0, so Minerva
would have spun on the DLL-enable bit it writes to EMC_CFG_DIG_DLL and
on EMC_DIG_DLL_STATUS lock, timed out on the clock-change handshake, and
divided by a zero MR18/MR19 oscillator count.

- CAR: PLLMB_BASE/MISC1 per TRM 5.2.230-231, locking once enabled.
  CLK_SOURCE_EMC, _EMC_DLL and _EMC_SAFE read back what was written,
  from their TRM resets. A written PLLM or PLLU reads back its
  dividers, which were dropped before while ENABLE was clear.
- EMC: a register file with broadcast and per-channel banks, plus:
  - MRW capture and MRR data/MRR_DIVLD per channel.
  - MR4 at normal temperature, and MR18/MR19 computed from MR23's run
    time at the current DRAM clock over 2 x tDQS2DQ.
  - DLL lock.
  - The CAR/EMC clock-change handshake: a new CLK_SOURCE_EMC source or
    divisor replays the CCFIFO and raises CLKCHANGE_COMPLETE.

With the stock folder, Nyx now trains 204, 800 and 1600 MHz and runs
its 800/1600 MHz power-saving loop, on Erista and Mariko. hwtest's
output is unchanged. The WDT cookie that keeps hekate's IPL from
training is kept; its comments no longer claim the EMC can't do it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb
2026-09-25 19:13:08 +00:00
Claude e32052ffd5 Model the DC windows and VIC compose, and scan out what they describe
The display model took each window's line stride from PRESCALED_SIZE
rather than LINE_STRIDE, and kept one set of window parameters for all
four windows, so window D's 656-pixel log window leaked into window A.
Its block-linear decoder also had two GOB address bits swapped. The mock
VIC only memcpy'd, so Nyx's rotated frame never existed. The renderer
papered over all of this with per-address heuristics: a "known menu
stride" of 2624, forced block-linear decoding of the IPL carveout, and a
hard-coded 1280x720 geometry for Nyx's framebuffer.

- DC: a register file per window (A-D), reached through the indirect
  pages per DISPLAY_WINDOW_HEADER or the A/B/C direct ranges. Writes
  land in the assembly copy, and WIN_x_ACT_REQ promotes it to the active
  copy the scan-out reads. Other DC registers read back what was
  written. STATE_CONTROL reads 0, and INT_STATUS reports frame end and
  vblank, which bdk polls before DSI commands.
- VIC: on COMPOSE_START, read bdk's vic_config_t from guest memory and
  draw the enabled pitch slots into the target, with scaling, clipping
  and the output flip/transpose. Nyx's 270-degree rotation now happens.
- Scan-out: fetch each enabled window per SURFACE_KIND (pitch, tiled or
  block linear, per TRM 20.1.2 Figure 47), LINE_STRIDE and COLOR_DEPTH,
  turn it per WIN_OPTIONS (H/V direction, SCAN_COLUMN), scale it from
  PRESCALED_SIZE to SIZE, place it at POSITION, and stack and blend the
  windows by depth and BLEND_*. When the surface on show was turned on
  its way to the panel, by the DC or by VIC, the view undoes the turn,
  so Nyx still shows landscape. All the heuristics are gone.

hwtest's frame and Nyx's home screen are pixel-identical to before.
Nyx's error console (window D over window A) now shows; before, it was
invisible.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb
2026-09-25 18:40:26 +00:00
Claude 39bfad6a0b Model the SDMMC host registers, eMMC HS200 tuning and HS400
The SDHCI power, clock, reset and HOST_CONTROL2 registers and Tegra's
vendor block all read 0, whatever was written. bdk picks the eMMC bus
mode from them: POWER_CONTROL reading "off" made it fall back to HS52,
so the eMMC ran at 51 MHz while its EXT_CSD claimed HS400.

- Keep a register file per controller for 0x28-0x3F and 0x100-0x1FF,
  with the TRM reset values. INTERNAL_CLK_STABLE follows INT_CLK_EN,
  the SW_RESET bits self-clear (RESET_ALL resets the standard registers,
  RESET_CMD/RESET_DATA clear their line's status), and the pad
  auto-calibration and DLL calibration complete at once.
- Model the tuning circuit (TRM 32.9.2.14). EXECUTE_TUNING starts it,
  each CMD19/CMD21 tries one tap against a fixed data eye, and after
  NUM_TUNING_ITERATIONS commands the final tap is set per MUL_M/DIV_N.
  The tuning block's BUFFER_READ_READY waits for the card clock to be
  re-enabled, which is the order bdk waits in.
- Keep EXT_CSD as one array per power cycle. CMD6 SWITCH updates its
  writable bytes, CMD8 reads them back, and CMD0 resets the card
  fields. BOOT0/BOOT1 and RPMB are 4 MiB, as on a Switch.

hwtest now tunes the eMMC in 128 iterations and reports a 199.68 MHz
HS400 card clock. The hwtest check asserts both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb
2026-09-25 18:37:38 +00:00
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
Claude 11ad2e4d9f Test the CCPLEX model and the hwtest sweep in CI, and document both
- tests/ccplex: a self-contained BPMP payload (ARM, arm-none-eabi-gcc; the
  AArch64 side is pre-assembled words) that drives CPU0 through bdk's
  ccplex_boot_cpu0() register sequence. It checks that an unpowered
  release is refused with its reason, that a powered one runs at EL3 from
  the SB vector and writes the mailbox, that CPU0 sees TIMERUS move, that
  WFE parks the core, and that RST_CPUG_CMPLX_SET stops it. `make test`.
- tests/hwtest: build hwtest-rcm from a pinned commit with distro
  toolchains (an empty base_rules stands in for devkitARM, the CPU0 stub
  builds with gcc-aarch64-linux-gnu) and run its whole sweep headless,
  checking the CPU0-driven Wi-Fi probe enumerates the CYW4356.
- CI runs both in the Linux job and keeps their logs on failure.
- Makefile: `test` target; the clean rule's line continuation was a
  literal "\n" that only worked by accident.
- README/DESIGN: CCPLEX CPU0, the uc_mmio_map bus, the block-level clock
  and TIMERUS poll pacing, the new bug-history entries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb
2026-09-25 15:56:00 +00:00
Claude f19a52b779 Run CCPLEX CPU0 so hwtest's PCIe probe completes, and speed up the core
hwtest-rcm's Wi-Fi probe hands PCIe to an AArch64 stub on CPU0, because
PCIe and MSELECT answer a CPU-complex master only. The emulator had no
CCPLEX, so the stub never reported; and the sweep never got that far
anyway, because it hung in the fan test.

CPU0 (t210/ccplex.cpp)
- A second Unicorn engine, AArch64, Cortex-A57, sharing IRAM, DRAM, TZRAM
  and every peripheral model with the BPMP. It starts when
  RST_CPUG_CMPLX_CLR releases CPU0 with every precondition of bdk's
  ccplex_boot_cpu0() met: CPU rail (MAX77621 + MAX77620 GPIO5 on Erista,
  MAX77812 EN_M4 on Mariko), CRAIL/C0NC/CE0, CPUG clock, PLLX, MSELECT,
  RAM repair, an AArch64 vector in SB_AA64_RESET_LOW/HIGH. A release that
  misses one is refused and the reason printed.
- Entered at EL3, MMU off, like silicon. Unicorn builds its ARM64 core at
  EL1 and neither a PSTATE write (stale hflags) nor an exception (never
  delivered) moves it, so a one-instruction ERET trampoline does.
- Its own clock (1 ns/instruction, 250 ns/bus access), run in 250 us
  lockstep slices behind the BPMP; WFE/WFI park it to the slice end.
- PCIe is master-aware: the BPMP still reads all ones, CPU0 is served.
  MSELECT, AFI_PCIE_CONFIG, LNKSTA, the endpoint class/BAR, the PCIE
  partition, PEX_L1 pinmux and PMC_GLB_AMAP_CFG take their measured values.

hwtest now runs its whole sweep and reports "WLAN core enumerated on the
PCIe bus" / "Wireless : pass", matching the healthy-console capture in
its README.

Performance
- No per-instruction hooks. Three UC_HOOK_CODE callbacks (one registered
  twice, one doing a uc_mem_read per instruction) are replaced by a block
  hook that counts each block's instructions once (cached), credited when
  it has run - the same totals, so the clock is unchanged.
- Peripherals are uc_mmio_map() windows instead of memory hooks, which
  had forced every guest load/store onto Unicorn's slow path; the register
  cache is a paged array instead of a std::map.
- The display reads the framebuffer straight from host DRAM, reuses its
  buffers, skips unchanged frames, and no renderer uses PRESENTVSYNC (a
  vsync'd present could stall the emulated CPU for a whole frame).
Reaching hwtest's fan test: 2.7 s -> 0.8 s; whole sweep ~3 s.

Reliability
- TIMERUS poll pacing: bdk's fan_get_speed() waits for TIMERUS to EQUAL a
  deadline (int - u32 is unsigned, so `> 0` is `!= 0`), and the dilated
  clock stepped past it, so the loop spun until TIMERUS wrapped. Polls at
  most 200 instructions apart now advance the clock by at most 1 us.
- MAX77621/MAX77812 are register files: bdk's hw_init() disabling the
  Erista CPU/GPU bucks used to be ignored and read back as enabled.
- Mariko reads FUSE_RESERVED_ODM28_B01 bit 0 set, so bdk addresses the
  retail MAX77812 at 0x33 instead of the NAK'd 0x31.
- Windows: disk images are opened O_BINARY (MinGW defaults to text mode,
  corrupting sectors) and rawnand chunks are sized with _fstati64.
- Soft reboot resets CPU0 and the PCIe root complex; the payload is
  loaded once, size-checked; an empty/unreadable payload is rejected; the
  NOP-slide check no longer trips on a counter that never reset; the M/C
  windows fall back to a software renderer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb
2026-09-25 15:55:48 +00:00
72 changed files with 14998 additions and 1764 deletions

No files matched your search

+35 -1
View File
@@ -27,7 +27,8 @@ jobs:
run: |
sudo apt-get update -qq
sudo apt-get install -y --no-install-recommends \
build-essential pkg-config libunicorn-dev libsdl2-dev
build-essential pkg-config libunicorn-dev libsdl2-dev \
gcc-arm-none-eabi libnewlib-arm-none-eabi gcc-aarch64-linux-gnu
- name: Build
run: make -j"$(nproc)"
@@ -44,6 +45,39 @@ jobs:
grep -q "RCM Payload Emulator" out.txt \
|| { echo "banner missing - binary did not start"; exit 1; }
- name: CCPLEX, SE, USB and display regression tests
# Small self-contained payloads. One boots CPU0 through bdk's
# ccplex_boot_cpu0() register sequence: an unpowered release must be
# refused, a powered one must run an AArch64 blob at EL3, and WFE must
# park the core. One runs the Security Engine's RSA, SHA-256, AES and
# RNG against vectors computed in Python. One brings up USB gadgets on
# both device controllers for the --usb-host PC to enumerate, read
# back and write, and serves the disk over NBD (on a localhost port)
# to a Python client. The others drive the display controller and VIC in six
# scenarios, and the frame the emulator shows must match the picture
# drawn, pixel for pixel.
run: make test
- name: hwtest end to end
# hwtest-rcm's whole hardware sweep, including the Wi-Fi probe that
# hands PCIe to an AArch64 stub on CPU0. Built from a pinned commit
# with distro toolchains; the run must enumerate the CYW4356.
run: |
tests/hwtest/build.sh build-hwtest
tests/hwtest/run.sh ./rcm_emu build-hwtest/hwtest-rcm/build/hwtest.bin
- name: Keep test logs
if: failure()
uses: actions/upload-artifact@v4
with:
name: test-logs
path: |
tests/ccplex/out.log
tests/se/out.log
tests/usb/out_*.log
tests/hwtest/out.log
if-no-files-found: ignore
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
+10
View File
@@ -3,17 +3,26 @@ rcm_emu
rcm_emu.exe
*.o
*.d
*.elf
# Runtime captures
last_fb.rgba
last_fb.meta
last_fb*.png
out.log
out_*.log
out*.txt
emu_run*.log
emu_capture*.txt
win_run.log
last_audio*.wav
*.log
*.rgba
/*.png
# Generated by linux/build.sh, tests/kernelcpu/build.sh and linux/mkdtb.sh
*_blob.h
linux/*.dtb
# User data — never commit dumps or keys
*.img
@@ -26,5 +35,6 @@ last_audio*.wav
__pycache__/
*.pyc
backup/
build-hwtest/
imgui.ini
rcm_emu.ini
+1
View File
@@ -1,3 +1,4 @@
[submodule "third_party/imgui"]
path = third_party/imgui
url = https://github.com/ocornut/imgui.git
ignore = untracked
+642 -67
View File
@@ -10,19 +10,25 @@ them. Read [README.md](README.md) first for usage.
flowchart TB
main["<b>main.cpp</b><br/>arg parsing, payload load, CLI<br/>emulation loop, auto-script state"]
main -->|uc_emu_start| uc["<b>Unicorn Engine</b><br/>ARM32, T210<br/>IRAM / DRAM / MMIO"]
main -->|sdl_display_*| sdl["<b>display/sdl_display</b><br/>block-linear de-swizzle<br/>rotate, blit"]
main -->|bpmp_run| uc["<b>Unicorn Engine</b><br/>ARM32 BPMP<br/>IRAM / DRAM / MMIO"]
main -->|ccplex_run| a57["<b>t210/ccplex</b><br/>2nd Unicorn engine, AArch64<br/>CCPLEX CPU0 (Cortex-A57)"]
a57 -->|MMIO callbacks| mmio
a57 -.->|shares| uc
main -->|sdl_display_*| sdl["<b>display/sdl_display</b><br/>DC window scan-out<br/>blend, turn, blit"]
main -->|config_window_*| cfg["<b>display/config_window</b><br/>2nd SDL window + ImGui<br/>live hardware tweaks"]
main -->|console_window_*| con["<b>display/console_window</b><br/>3rd SDL window + ImGui<br/>per-port UART TX log + RX inject"]
uc -->|MMIO trap| mmio["<b>t210/mmio.cpp</b><br/>central read/write dispatch<br/>by address range"]
uc -->|MMIO callbacks| mmio["<b>t210/mmio.cpp</b><br/>mmio_bus_read / mmio_bus_write<br/>shared by both masters"]
mmio --> sdmmc["<b>sdmmc</b><br/>SDMMC1 / SDMMC4<br/>CMD0..18, EXT_CSD, ADMA2"]
mmio --> se["<b>se_engine</b><br/>AES-128, SHA-256<br/>BIS keyslot override"]
mmio --> sdmmc["<b>sdmmc</b><br/>SDMMC1 / SDMMC4<br/>CMD0..21, EXT_CSD, ADMA2<br/>SD UHS-I, eMMC HS400"]
mmio --> se["<b>se_engine</b><br/>AES-128, SHA-256, RSA, RNG<br/>BIS keyslot override"]
mmio --> i2c["<b>i2c3</b><br/>STMFTS / FTS4 touch"]
mmio --> i2c1["<b>I2C_1 slaves</b> (inline)<br/>MAX17050, TMP451,<br/>BQ24193, BM92T36"]
mmio --> i2c5["<b>I2C_5 slaves</b> (inline)<br/>MAX77620, MAX77621"]
mmio --> stubs["<b>inline stubs</b><br/>GPIO, PMC, TSEC, KFUSE,<br/>PWM, DC, CLK, TMR, FUSE, UART"]
mmio --> dc["<b>DC + VIC</b> (inline)<br/>window registers A-D<br/>VIC compose, flip/transpose"]
mmio --> stubs["<b>inline stubs</b><br/>GPIO, PMC, TSEC, KFUSE,<br/>PWM, CLK, TMR, FUSE, UART"]
mmio --> pcie["<b>pcie</b><br/>AFI, root ports, CYW4356<br/>(CPU-complex master only)"]
mmio --> usb["<b>usb</b><br/>USB2 + XUSB device controllers<br/>and the --usb-host PC"]
cfg -.->|writes atomics| state["<b>EmuState</b><br/>(emu_state.h)"]
con -.->|RX inject / TX log| state
@@ -35,25 +41,39 @@ touchscreen atomics, framebuffer parameters from the display controller, file
descriptors for SD and eMMC images, and a deterministic `emu_usec` counter used
for auto-script timing.
Two processors can execute: the BPMP, which every RCM payload runs on, and -
once a payload boots it - CPU0 of the CCPLEX. Each is its own Unicorn engine;
both map the same host memory for IRAM, DRAM and TZRAM, and both reach the
same peripheral models through one dispatch (see [CCPLEX CPU0](#ccplex-cpu0)).
## Boot flow (Hekate as the example)
1. The payload is loaded into IRAM (Internal RAM) at `0x40010000` via
`uc_mem_write`. We also pre-write the 4-byte cookie `0x544457` ("WDT") at
IRAM offset `0x4003FF18`. Hekate reads that location during early boot.
When the cookie is present, it takes the `goto skip_lp0_minerva_config`
branch and skips loading both `libsys_lp0.bso` and the Minerva
DRAM-training module. Real DRAM training would touch the EMC (External
Memory Controller) and MC (Memory Controller), neither of which the
emulator models. The matching exception-enable cookie at `0x4003FF1C`
stays zero, so the "hang detected" warning is suppressed.
`uc_mem_write`. Nothing else is planted: IRAM holds what it holds after a
cold boot.
2. PC is set to `0x40010000`, SP to `IPL_STACK_ADDR`. CPSR enters ARM mode.
3. The IPL (Initial Program Loader) initialises clocks, fuses 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.
3. The IPL (Initial Program Loader) initialises clocks, fuses, the DRAM
(`sdram_init`, at 204 MHz) and the display, mounts the SD card, loads
`bootloader/sys/libsys_lp0.bso` (it saves the LP0 SDRAM config to PMC
scratch) and trains the DRAM with Minerva
(`bootloader/sys/libsys_minerva.bso`) at 204, 800 and 1600 MHz, all as on
hardware (see [EMC and DRAM clock](#emc-and-dram-clock)). An SD image
without those modules gets hekate's "Missing LP0 (sleep) lib! / Missing
Minerva lib!" screen, which waits for a key press before the menu.
hekate prints "Missing Minerva lib!" for any Minerva failure, not only a
missing file: Minerva also refuses to start unless HIDREV reads chip
0x21 and `FUSE_SKU_INFO` (0x110) reads 0x83 (ODIN). Both hold by
default; a `[fuses]` edit to 0x110 in the config window or
`rcm_emu.ini` brings the screen back.
4. Hekate self-relocates into DRAM (`0xC0000000+`) and continues. It points
DC (Display Controller) window A at its portrait framebuffer and draws its
boot logo and menus there, sideways, for the landscape-mounted panel.
5. Nyx (the LVGL GUI) takes over the trained Minerva context and from then
on alternates the DRAM between 1600 and 800 MHz on every GUI loop to save
power. It draws landscape into a second framebuffer and has VIC
turn every frame into the portrait surface that window A scans out. The
display follows the DC's windows, whatever they point at (see Display
pipeline).
## Memory map
@@ -65,10 +85,27 @@ Mapped explicitly in `setup_emulation()`:
| `0x80000000 – 0x90000000` | 256 MB | DRAM low |
| `0xC0000000 – 0xFFFFFFFF` | 1 GB | DRAM high (covers FB at 0xF5A00000) |
| `0x00000000 – 0x01000000` | 16 MB | low scratch (some null derefs) |
| Various MMIO pages | 4 KB ea | trapped via UC hooks |
| `0x7C010000 – 0x7C020000` | 64 KB | TZRAM (shared with CPU0) |
| Peripheral windows | 4 KB ea | `uc_mmio_map` callbacks |
MMIO (Memory-Mapped I/O) ranges are added as plain mapped pages with read and
write hooks. The actual register modelling lives in `t210/mmio.cpp`.
MMIO (Memory-Mapped I/O) windows are `uc_mmio_map()` regions: Unicorn calls
`mmio_cb_read` / `mmio_cb_write`, which forward to `mmio_bus_read` /
`mmio_bus_write` in `t210/mmio.cpp`, where the register models live. The list
of windows is `kRegions` in the same file; it is flattened to 4 KiB pages and
mapped as contiguous runs, once per engine.
They used to be plain RAM pages with `UC_HOOK_MEM_READ` / `UC_HOOK_MEM_WRITE`
hooks, a read's result written into the page with `uc_mem_write` before the
load completed. Unicorn sends every guest load and store through its slow path
while any memory hook exists, so ordinary IRAM/DRAM traffic paid for MMIO's
hooks, and each MMIO read cost a walk of Unicorn's region list on top. An
unmapped access in the peripheral band now gets an MMIO page of its own on the
fly (`hook_unmapped`), so the generic register cache still sees it.
The "read back what was written" behaviour of simple registers (PINMUX, PWM,
UART LCR, CLK_SOURCE_* ...) comes from `mmio_regs`, a `RegCache`
(`t210/regcache.h`): flat 4 KiB pages with a presence bitmap and a last-page
cache, replacing a `std::map` that was a measurable share of all MMIO time.
## Subsystems
@@ -80,7 +117,8 @@ of the spec is modelled for the Hekate, Lockpick and TE init paths:
- CMD0 GO_IDLE, CMD1 SEND_OP_COND, CMD2 ALL_SEND_CID, CMD3 SEND_RELATIVE_ADDR,
CMD6 SWITCH, CMD7 SELECT_CARD, CMD8 SEND_EXT_CSD (eMMC) or SEND_IF_COND (SD),
CMD9 SEND_CSD, CMD13 SEND_STATUS, CMD16 SET_BLOCKLEN, CMD17 and CMD18
READ_(MULTI_)BLOCK, CMD55 APP_CMD.
READ_(MULTI_)BLOCK, CMD11 VOLTAGE_SWITCH, CMD19 / CMD21 SEND_TUNING_BLOCK,
CMD55 APP_CMD.
- ADMA2 (Advanced DMA 2) with 64-bit descriptors, multi-block reads chunked
into the host file IO via `pread`-style calls.
- `--rawnand` opens the matching `rawnand.bin.NN` chunks and `fstat`s the first
@@ -101,32 +139,150 @@ of the spec is modelled for the Hekate, Lockpick and TE init paths:
sec_cnt) and writes it via the configured ADMA2 descriptor before raising
the IRQ.
#### Host controller registers and HS400
Each controller keeps its SDHCI registers (0x28-0x3F: power, clock, software
reset, HOST_CONTROL2) and Tegra's vendor block (0x100-0x1FF) in a register
file with the TRM's reset values, plus the side effects bdk waits on:
- CLOCK_CONTROL reports INTERNAL_CLK_STABLE once INT_CLK_EN is set.
SOFTWARE_RESET's bits self-clear. RESET_ALL puts the standard registers
back to reset and leaves the vendor block alone.
- AUTO_CAL_CONFIG.START and DLLCAL_CFG.CALIBRATE self-clear, and the status
registers report the calibration done.
- Setting HOST_CONTROL2.EXEC_TUNING starts tuning. Each CMD19/CMD21 tries one
tap: with TAP_VAL_UPDATED_BY_HW the taps step from TUNING_CNTRL0.START_TAP
by TUNING_CNTRL1's step size, otherwise the tap in VENDOR_CLOCK_CNTRL is
used. A tap passes when it falls in the modelled data eye, taps 26..82.
After NUM_TUNING_ITERATIONS commands EXEC_TUNING clears and TUNED_CLK is
set. The pass map lands in TUNING_STATUS0, and the chosen tap, first +
(last - first) x (MUL_M + 1) / 2^DIV_N (TRM 32.9.2.14), lands in
VENDOR_CLOCK_CNTRL. The tuning block's BUFFER_READ_READY is held until the
card clock is re-enabled, the order in which bdk's tuning loop waits.
- EXT_CSD is one 512-byte array that lives for a power cycle. CMD6 SWITCH
(write byte, set bits or clear bits) changes the bytes eMMC 5.1 makes
writable (BUS_WIDTH, HS_TIMING, PARTITION_CONFIG and a few more). CMD8
returns the array and CMD0 puts the card-reset fields back. CARD_TYPE
advertises HS400 at 1.8 V, so bdk goes 8-bit, then HS200 (tuned), then
HS400, and reports a 199.68 MHz card clock. BOOT0, BOOT1 and RPMB are
4 MiB each, as on a Switch.
#### The SD card: UHS-I
The SD card is a UHS-I card (SD Physical Layer 3.01), so bdk runs it at
SDR104 like the real slot:
- ACMD41 with S18R answers S18A while the card still signals at 3.3 V, and
CMD11 moves it to 1.8 V. It stays there until it loses power: bdk's
supply GPIO (PE4) going low, or a reset. A card re-initialised without a
power cycle answers S18A = 0 but keeps offering its UHS speeds.
- CMD6 (SWITCH_FUNC) reports and selects a function per group, per SD
4.3.10: bus speed (SDR12 and SDR25/HS, plus SDR50, SDR104 and DDR50 at
1.8 V), driver strength and power limit. CMD0 puts the functions back to
their defaults, not the voltage.
- CMD19 tunes the SDR104 sampling point through the same tuning circuit as
the eMMC. hwtest reports a 199.68 MHz card clock.
- With no image (`--sd`, or `sd.img` in the working directory) the slot is
empty: card detect (PZ1) reads no card and every SDMMC1 command times
out, as on a console with no card in. The config window can still insert
a blank card.
- The CSD is an SD CSD 2.0 (SD 5.3.3): the image's size (32 GiB for a blank card)
and command classes that include class 8, so bdk reads the SD status.
That (ACMD13) reports the bus width ACMD6 set and a Class 10, U1, V10
card with 4 MB AUs; the SCR sets SD_SPEC3.
### EMC and DRAM clock
The EMC (External Memory Controller, `t210/mmio.cpp`) is a register file -
reads return what was written, as `sdram_init` programmed it from the BCT -
with the controller's own behaviour on top (TRM 18.11). That is what bdk's
mode-register reads and Minerva, hekate's DRAM training and
frequency-switching module, depend on:
- **Banks.** A write to the broadcast bank (`EMC_BASE`) reaches both
channels; `EMC0_BASE` / `EMC1_BASE` address one channel each.
- **Mode registers.** MRWs (`EMC_MRW`, `EMC_MRW2..15`) are remembered. An
MRR latches the answer into the channel's `EMC_MRR` and sets
`EMC_EMC_STATUS.MRR_DIVLD` until it is read. MR4 reports a normal
temperature, MR5-8 the configured DRAM ID, and MR18/MR19 the DQS interval
oscillator count: MR23's run time at the current DRAM clock over twice a
400 ps tDQS2DQ. Minerva divides by that count.
- **Digital DLL.** `EMC_DIG_DLL_STATUS` reports lock as soon as the DLL is
(re)started; `EMC_CFG_DIG_DLL.CFG_DLL_EN` reads back as written, which is
what Minerva spins on around each DLL restart. The DLL's code, `DLL_OUT`
(10:0), is where its calibration starts: the channel's
`EMC_DLL_CFG_1.DDLLCAL_CTRL_START_TRIM` (10:0, reset 0x20, TRM
18.11.2.219), which the timing table programs per frequency. With no
delay line to drift, calibration has nothing to move it by. (Minerva's
`_digital_dll_prelock()` returns it; nothing reads it further.)
- **Clock change.** A new source or divisor in CAR `CLK_SOURCE_EMC` (TRM
5.2.73) is the CAR/EMC handshake: the EMC replays the writes queued in its
clock-change FIFO (`EMC_CCFIFO_DATA` / `_ADDR`) and raises
`CLKCHANGE_COMPLETE` in `EMC_INTSTATUS`. The DRAM clock follows from
`CLK_SOURCE_EMC` and the PLLM / PLLMB dividers; `PLLMB_BASE` (TRM 5.2.230)
locks once enabled, like the other PLLs.
- **Status.** `EMC_EMC_STATUS` otherwise reports timing updates done, the
DRAM active and the state machines idle.
- **Measured clock.** bdk's PTO counter measures the EMC at the modelled
clock (the measured 204 MHz figure at the boot clock).
With the stock `bootloader/` folder, hekate's IPL trains 204, 800 and
1600 MHz, and Nyx then switches between 800 and 1600 MHz on every GUI loop,
each switch a full handshake with a CCFIFO replay.
### Security Engine (`t210/se_engine.cpp`)
Models the SE (Security Engine) register block at `0x70012000`. Supports:
- **AES-128 ECB, CBC, CTR, CMAC.** The compact public-domain TinyAES core
([kokke/tiny-AES-c](https://github.com/kokke/tiny-AES-c)) drives one block
at a time, with chaining state taken from `IV_ORIGINAL` or `IV_UPDATED` per
slot and `xor_pos` from `CRYPTO_CONFIG`.
- **SHA-256.** Implemented because the TE function `save_process_header`
validates the save container hash. Without it, `readsave()` returns
`Error: Save header is invalid!`. Oneshot only: one IN_LL buffer at a time,
written into the `HASH_RESULT` registers as 8 big-endian dwords (the BDK
driver byte-swaps on read).
- **DST_KEYTABLE unwrap path.** When the destination is another keyslot, the
result of a single block is written into the destination `KEYS_0_3` or
`KEYS_4_7` register pair.
- **AES-128 ECB, CBC, OFB, CTR, CMAC.** The compact public-domain TinyAES
core ([kokke/tiny-AES-c](https://github.com/kokke/tiny-AES-c)) drives one
block at a time through the SE's datapath: `INPUT_SEL` picks memory, the
previous AES output (OFB) or the linear counter (CTR); `XOR_POS` puts the
vector RAM before the core (CBC encrypt) or the vector / the memory data
after it (CBC decrypt, OFB, CTR); `VCTRAM_SEL` says what the vector becomes
next. The vector starts from the slot's `IV_ORIGINAL` or `IV_UPDATED`, and
a chaining mode leaves its final value in `IV_UPDATED`, which is how bdk
continues a chain into a trailing partial block and feeds the last block of
a CMAC. Checked against OpenSSL for every mode bdk uses, including
multi-block CMAC and partial blocks.
- **SHA-256**, one-shot and in parts. `SHA_INIT_HASH` starts from the
standard state, `SHA_CONTINUE` from the one the last part left in
`HASH_RESULT` (8 big-endian dwords; the BDK driver byte-swaps on read), and
the part is padded only when `SHA_MSG_LEFT` says it is the last.
Implemented because the TE function `save_process_header` validates the
save container hash.
- **DST_KEYTABLE unwrap path.** The result of a single block is written into
the destination slot's selected word quad.
- **RSA** modular exponentiation, as Lockpick's bdk drives it
(`se_rsa_key_set()` / `se_rsa_exp_mod()`): two keyslots of up to 2048
bits, loaded a word at a time through `SE_RSA_KEYTABLE_ADDR/DATA` (least
significant word first), `KEY_SIZE` in 512-bit steps and `EXP_SIZE` in
words, the input a little-endian number over DMA and the result in
`SE_RSA_OUTPUT` (or memory). Montgomery multiplication on 32-bit words;
an even modulus fails the operation.
- **RNG** into memory or a keyslot quad (`se_rng_pseudo()`, TegraExplorer's
`se_generate_random()`): `LAST_BLOCK + 1` blocks, cut to the buffer size.
The bytes come from a SplitMix64 generator with a fixed seed, reset with
the SE, so runs repeat. Nyx uses them for GPT partition GUIDs and the SD
benchmark's random offsets.
- **Context save** (`SE_OP_CTX_SAVE`), as bdk's `se_aes_ctx_get_keys()` uses
it to read keyslots back: an RNG op seeds a secure random key (fixed, for
reproducibility), each saved keyslot quad is written out encrypted under it
in one CBC chain, and saving the SRK deposits it in PMC `SECURE_SCRATCH4..7`
for the driver to decrypt with.
- **`--prod-keys` BIS override.** When Lockpick writes the last word of a
derived BIS (Boot Image Storage) key into slots 0..5, the value from the
user-supplied key file is substituted. This sidesteps the
TSEC-firmware to `master_kek` to `master_key` derivation chain that is not
fully modelled. For other keyslots, the SE behaves normally.
fully modelled. Clearing a slot and loading the context-save SRK are left
alone. For other keyslots, the SE behaves normally.
The 16 keyslots are stored in a flat `Keyslot ks_table[16]` with
`key[32] / iv_orig[16] / iv_upd[16]`. RSA, RNG, and chunked SHA are stubbed.
They return `OP_DONE` without producing data, which is enough for current
payloads.
`key[32] / iv_orig[16] / iv_upd[16]`. Block counts are bounded by what one
linked-list entry can describe (16 MiB), and an operation whose buffers are
unreachable finishes with `SE_INT_ERR_STAT` instead of computing on zeros.
`tests/se/` checks RSA-2048 and RSA-1024 both ways against Python, SHA-256
one-shot and in parts, AES-ECB and the RNG.
### Touchscreen (`t210/i2c3.cpp`)
@@ -159,11 +315,27 @@ down or reset are caught by `t210/mmio.cpp`:
caught on both the small CMD\_DATA1 path and the packet-mode TX_FIFO path
-- stops emulation and exits cleanly.
- Same register with `SFT_RST` (bit 7) set requests a payload soft-reboot
via `state->reboot_requested`.
via `state->reboot_requested`, as a power cycle (`reboot_cold`).
- `APBDEV_PMC_CNTRL` (`0x00`) bit 4 (MAIN_RST) -- written by Hekate's
`power_set_state(REBOOT_RCM)` -- also requests a soft-reboot, so the user
can iterate on a payload without restarting `rcm_emu`.
Either request stops the BPMP on the spot: `power_set_state()` follows the
write with `bpmp_halt()`, which would otherwise end the run first.
**What a reboot resets** (`mmio_soft_reset`). Everything on the SoC: the
register cache (GPIO, pinmux, clocks), UART modes and receive FIFOs, the I2C
controllers, the PMC's partitions, pad DPD and registers, CAR, the flow
controller, the SE (back to the `--prod-keys` preload), touch, SDMMC (the
eMMC back in its user area), the display controller, ACTMON, VIC, DSI, the
PCIe root complex and CPU0. What survives is what survives on hardware: PMC
SCRATCH0 and RST_STATUS, the RTC (still counting), and - unless the reboot
is a power cycle - the PMIC with its rails and the external regulators. DRAM
comes back as fresh zero pages (not a memset, which made all 2 GB resident),
the BPMP's translations of IRAM, DRAM and low memory are dropped so the old
run's code cannot run in place of the reloaded payload, the CPSR returns to
its power-on SVC mode, scripted input restarts and every button is released.
### I²C-attached chips (battery, charger, thermal, USB-PD, PMIC ID)
Modelled inline in `t210/mmio.cpp::i2c_read`. The bus is disambiguated by
@@ -239,21 +411,69 @@ 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. A blit cache keys on `(addr, w, h, stride, sw, rot, bh)` so identical
frames don't re-touch the surface.
1. Every enabled window's surface is fetched from `START_ADDR`. The layout
comes from `SURFACE_KIND`: pitch, 16x16 tiled, or block linear with
2^`BLOCK_HEIGHT` GOBs (Groups of Bytes, 64x8-byte tiles) per block. The
line pitch is `LINE_STRIDE`, and pixels are decoded per `COLOR_DEPTH`.
Block-linear byte order follows TRM 20.1.2 and Figure 47
(`t210/block_linear.h`, shared with VIC).
2. The fetch starts at `ADDR_V_OFFSET * LINE_STRIDE + ADDR_H_OFFSET` (TRM
24.11.1): the window's top-left pixel, top-right with H_DIRECTION,
bottom-left with V_DIRECTION, in surface terms. It walks away from there
per the direction bits, and SCAN_COLUMN walks columns instead of rows
(90/270 degrees, TRM Table 122). Pixels before `START_ADDR` or past the
surface are black. The result is scaled from `PRESCALED_SIZE` to `SIZE`,
nearest-neighbour, and placed at `POSITION`.
3. The windows are stacked by layer depth and blended per
`BLEND_LAYER_CONTROL` and `BLEND_MATCH_SELECT`. The TRM sorts windows by
depth into its blend stages without saying which way; lower depth is
nearer the top here, as Linux programs later Tegras, and equal depths
stack A under D. Hekate's log console (window D, K1 = 200) shows
through as it does on the console.
The panel picture is then turned for the host window. When the surface on
show was turned on its way to the panel, by the DC (SCAN_COLUMN) or by a
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 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.
Slot and output surfaces are pitch or block linear (BlkKind 1, with
2^BlkHeight GOBs per block).
### UART
@@ -310,8 +530,104 @@ All TX append / RX pop is single-threaded -- both the CPU emulation and ImGui
rendering run on the main thread between SDL polls -- so no locking is
needed. The 64 KB TX log trim happens in-place during the write hook.
### USB device mode (`t210/usb.cpp`)
bdk runs its gadgets - Nyx's USB mass storage for the SD card, eMMC and
emuMMC, and its Joy-Con gamepad - on one of two device controllers, and both
are modelled:
- **Erista: the USB2 controller USB1** (0x7D000000, bdk `usbd.c`), an
EHCI-derived device controller. Each endpoint half has a 64-byte queue
head at `ENDPOINTLISTADDR` (bdk keeps them in the controller's own memory
at +0x1000) and a chain of transfer descriptors in DRAM. `ENDPTPRIME`
loads the first descriptor and sets its bit in `ENDPTSTATUS` until the
transfer retires; each descriptor it reaches is written back with the
bytes it did not move, and the endpoint's bit set in `ENDPTCOMPLETE`. A
SETUP lands in queue head 0 with `ENDPTSETUPSTAT` bit 0. `USBCMD.RESET`
resets the controller and clears itself; `PHY_CLK_VALID` follows the
UTMI PHY's enable and reset. bdk copies SETUP packets out with `memcpy()`,
so byte and halfword accesses are handled.
- **Mariko: the XUSB device controller** (0x700D0000, bdk `xusbd.c`), the
device side of xHCI. Endpoints are device context indexes (0 control, 2
bulk OUT, 3 bulk IN), each with a context (the dequeue pointer and DCS in
word 2) and a ring of TRBs the driver fills and closes with a Link TRB,
ringing the doorbell. The controller posts events on a two-segment event
ring, flipping its cycle bit per pass and raising `ST.IP`: a Port Status
Change on a bus reset, a Setup event with a sequence number per SETUP, a
Transfer event with the residue and SUCCESS or SHORT_PKT per TRB.
`EP_HALT` halts an endpoint (`EP_STCHG` reports it), `EP_RELOAD` reloads a
context, and a `PORTSC` write with LWS and RxDetect arms the port.
**The host.** `--usb-host` (or `[usb] host`, or the config window's USB
device mode box) plugs in a PC; without it nothing is on the cable and a
gadget waits for a connection until it gives up, as with no cable. The host
sees whichever controller attaches, waits out the attach debounce, resets
the bus at high speed and enumerates: device descriptor, `SET_ADDRESS` (with
its 2 ms recovery), configuration, strings, `SET_CONFIGURATION`. It then gives
the class driver 100 ms to bind, as a PC does - bdk's XUSB driver stalls a
`GET_MAX_LUN` that arrives before the gadget asks for it - and runs the
class:
- *Mass storage (Bulk-Only Transport):* `GET_MAX_LUN`, INQUIRY, TEST UNIT
READY (answering the first unit attention with REQUEST SENSE), READ
CAPACITY, MODE SENSE(6) for the write-protect bit (asking for just the
4-byte header: bdk stalls bulk IN on a reply shorter than asked), READ(10)
of the first 64 and the last 8 blocks, each logged with its CRC32 and
checked against the SD image when the disk is its size. Unless the disk is
write-protected or the read was wrong, the last 8 blocks are written back
as read (WRITE(10), SYNCHRONIZE CACHE) and read again. Then PREVENT ALLOW
MEDIUM REMOVAL, an eject (START STOP UNIT, LoEj) and TEST UNIT READY every
500 ms until the gadget detaches, as Linux does.
- *Mass storage over NBD* (`--usb-host nbd[:port]`, `[usb] nbd_port`): after
MODE SENSE the host sends PREVENT MEDIUM REMOVAL and serves the disk on
127.0.0.1 with `t210/nbd.cpp`, a one-client NBD server (fixed newstyle
handshake: `EXPORT_NAME`, `LIST`, `INFO` and `GO`, with the export's size,
flags and 512-byte minimum block size; simple replies; READ, WRITE, FLUSH,
DISC). It is non-blocking and polled from the host every 100 us of
emulated time. A READ or WRITE is split into READ(10)s or WRITE(10)s of up
to 64 KiB, a FLUSH is a SYNCHRONIZE CACHE, and misaligned or out-of-range
requests are refused with `EINVAL` (writes to a write-protected disk with
`EPERM`, and the export is read-only). A quiet client gets a TEST UNIT
READY every emulated second, as Windows sends. When the client
disconnects the host allows removal and ejects as above.
- *HID:* the report descriptor, `SET_IDLE` with an idle rate of 0 (report on
change), then the interrupt IN endpoint is polled. Nyx's gamepad has
nothing to report without Joy-Cons.
The host advances on every access to either controller - it runs as far as
the device and the emulated clock allow - so it needs no thread or main-loop
hook and runs repeat exactly (an NBD session aside: its requests come when
the client sends them). It logs `[usb-host]` lines; `RCM_USB_TRACE=1` also
logs each transfer descriptor, TRB and doorbell.
A device transfer that retires before the host has all it asked for ends the
host's transfer only on a short packet: fewer bytes than a whole number of
max-size packets (the queue head or endpoint context gives the size), or a
zero-length packet, which the USB2 controller appends unless the queue head
disables it (ZLT; bdk disables it on every endpoint) and the XUSB controller
never adds. Otherwise the host carries on with the device's next transfer:
bdk sends a READ(10) under 512 KiB as 32 KiB transfers.
Nyx's SD card mass storage reads back identical to the image, takes the
write check and reports "Disk ejected" on both SoCs. Over NBD, `nbdinfo`
negotiates, `qemu-img convert` copies the whole 256 MiB disk byte for byte,
and a `qemu-io` write lands in the SD image.
### Other peripherals (mostly stubs)
- **CAR and MC.** Registers without behaviour of their own read back what
was written - the `CLK_SOURCE_*` dividers, PLL MISC words, the MC's
arbitration and address-map configuration - instead of 0.
- **CAR reset and clock-enable banks.** `RST_DEVICES_x` and `CLK_OUT_ENB_x`
(L, H, U, V, W, X, Y) follow direct writes and their SET/CLR strobes, and
a read of any of the three returns the bank (TRM 5.2.100) - bdk's
`clock_sdmmc_is_active()` reads `RST_DEV_L_SET` and `CLK_ENB_L_SET`. The
PCIe and CPU models keep reset banks V, W, Y and clock bank V. The rest
start at the TRM reset values (bank U at a real console's reading), so at
RCM entry the display is unclocked and `display_init()` does not begin
with a panel teardown.
- **USB PLL.** `UTMIPLL_HW_PWRDN_CFG0.LOCK` is set unless software holds
the PLL in IDDQ (the reset state), for bdk's `clock_enable_utmipll()`.
- **PINMUX (`APB_MISC` pad config) and PWM controller (`0x7000A000`).**
No active behaviour, but reads return whatever the payload last wrote
via the global `mmio_regs` cache. Hwtest's "Display backlight & PWM"
@@ -319,29 +635,67 @@ needed. The 64 KB TX log trim happens in-place during the write hook.
function nibble after `display_init`. The previous behaviour
(hardcoded `return 0`) silently dropped the muxed function bits and
made any read-back-style probe see all zeros.
- **PLLs.** Reads on `PLL_BASE` registers return `ENABLE | LOCK` for any of
the PLLs Minerva polls during DRAM training.
- **PLLs.** PLLP and PLLD always read as measured on a console in RCM (up
and locked). The other `_BASE` registers read as measured until the
payload programs them (PLLM up but unlocked on Erista, the rest down),
then read back what was written, dividers included, with LOCK set
whenever ENABLE is. That includes PLLMB, which Minerva moves the EMC onto
for a frequency change, and PLLC4, which clocks the eMMC at HS200/HS400
(not while its IDDQ bit is set); PLLC2, PLLC3, PLLDP and PLLA1 lock the
same way.
- **KFUSE.** `STATE` returns `DONE | CRCPASS` immediately so the BDK function
`kfuse_wait_ready` doesn't hang.
- **TSEC.** `DMATRFCMD_IDLE` is reported set, and the keygen status word is
hardcoded to `0xB0B0B0B0` (the success magic from AMS, the Atmosphère
keygen). No firmware is actually executed.
- **Timer and RTC.** Backed by `EmuState::emu_usec`, incremented per CPU
batch by a fixed amount so timing is deterministic across runs. The
auto-script feature relies on this.
- **Timer and RTC.** Backed by `EmuState::emu_usec`, derived from retired
instructions (see [Determinism](#determinism-and-the-auto-script-flag)), so
timing is identical across runs. The auto-script feature relies on this.
RTC SECONDS counts and is writable, and a MILLI_SECONDS read snapshots it
into SHADOW_SECONDS. TMR0..9 record when they were armed, so bdk's
`timer_usleep()` - TMR8 plus `FLOW_MODE_STOP_UNTIL_IRQ` - sleeps to the
timer's expiry.
- **Flow controller.** `HALT_COP_EVENTS` MODE 0/1 do not halt; a timed
WAITEVENT advances the clock; STOP_UNTIL_IRQ wakes on the first armed
timer; an untimed halt ends the run - unless CPU0 is running, in which case
the BPMP stays parked and CPU0 runs on (fusee's and hekate's L4T handoff).
- **Probe-magic constants.** Several reads return fixed values, not because
they are tweakable but because the chip-detection code expects exact
cookies: `MAX17050.DevName=0x00AC`, `BQ24193.VendorPart=0x2F`, the BM92T36
`FW_TYPE`/`MAN_ID`/`DEV_ID` triple, `TSEC.STATUS=0xB0B0B0B0`,
`KFUSE.STATE=DONE|CRCPASS`, `PLL_BASE=ENABLE|LOCK`. Changing them breaks
`KFUSE.STATE=DONE|CRCPASS`, `PLL_BASE.LOCK` once enabled. Changing them breaks
the Hekate init path. They are hardcoded by design.
## Determinism and the auto-script flag
`emu_usec` advances by a constant per Unicorn batch, never by host wall-clock.
`emu_usec` is derived from retired BPMP instructions, never from host
wall-clock: `emu_usec = skipped_us + insn_count / 10`, where `skipped_us` is
whatever a FLOW_CTLR timed halt (`bpmp_usleep` / `bpmp_msleep`) jumped over.
That makes the entire run reproducible: a payload at PC X always sees timer
value Y, regardless of how busy the host machine is.
The count comes from a `UC_HOOK_BLOCK` callback in `t210/bpmp.cpp`, not from
a callback on every instruction (which kept Unicorn off its fast path for all
code). Each translated block's instructions are counted once from its bytes
(Thumb: a halfword with top bits `0b11101`/`0b11110`/`0b11111` opens a 32-bit
instruction, which includes the Thumb-1 BL pair), cached per block, and
credited when the block has run. Totals match per-instruction counting
exactly; inside a block an MMIO read sees the time at the block's start. A
batch ends by stopping the engine from the block hook, which Unicorn honours
*before* running that block, so no instruction is ever counted twice or lost.
**TIMERUS poll pacing.** Ten instructions per microsecond is a deliberate
dilation - real silicon retires a few hundred - and it is what makes busy-waits
cheap. It is harmless for `while (now - start < us)`, but not for a wait that
must *see* a value. bdk's `fan_get_speed()` is one: `int timer = get_tmr_us() +
2000000; while ((timer - get_tmr_us()) > 0)` is unsigned arithmetic, i.e.
`!= 0`, and compiles to `cmp; bne`. Its ~30-instruction body is 0.1 us on
hardware and 3 us here, so the counter stepped past the deadline and the loop
spun until TIMERUS wrapped. So while TIMERUS reads come at most 200
instructions apart (under a microsecond at real speed), the clock advances at
most 1 us between them. Only increments are capped, so time stays monotonic for
every observer and a wait still ends at the emulated time it asked for.
The `--auto-pin-recovery` and `--auto-te-script` flags exploit this. A real
interactive run was captured by logging every keyboard up and down event with
the matching `emu_usec`, then the same schedule was re-applied verbatim in
@@ -361,15 +715,202 @@ while (te_idx < n && state.emu_usec >= te_events[te_idx].at_us) {
Because `emu_usec` is deterministic, the same timestamps land at the same UI
states across runs. Adding a new automated flow is "press the buttons once
with `[input]` logging on, copy the timestamps".
with `[input]` logging on, copy the timestamps". `--input-script` does the
same for any payload without a rebuild (`input_script.cpp`): button presses
and touchscreen taps (`<ms> TAP <x> <y>`, in the 1280x720 picture, inverted
through bdk's touch scaling) keyed to `emu_usec`. That is how Nyx's USB tools
are reached headless.
## CCPLEX CPU0
`t210/ccplex.cpp` models CPU0 of the main CPU cluster, enough for a payload to
hand work to it the way bdk's `ccplex_boot_cpu0()` does. hwtest-rcm's Wi-Fi
probe is the driving case: PCIe answers a CPU-complex master only (TRM ch.16 /
ch.19: MSELECT is CCPLEX hardware, the BPMP-Lite is an AHB master), so it
copies an AArch64 stub to DRAM, boots CPU0 at it, and supervises through a
mailbox while the stub trains the link and enumerates the CYW4356.
**Release.** The model shadows the registers the boot sequence writes.
`RST_CPUG_CMPLX` starts at its TRM reset value, `0x2000feef`, and the core
runs once CPURESET0 (bit 0), CORERESET0 (16), L2RESET (24) and NONCPURESET
(29) are all clear. (bdk also clears PRESETDBG, bit 30, which only resets the
CoreSight debug logic; bits 15:4 are reserved on this SoC.) It must also be
able to run; a release that is refused is looked at again whenever one of
these changes, since silicon starts the moment the last one arrives:
| Precondition | Where it comes from |
| --- | --- |
| CPU rail up | Erista: MAX77621 @ I2C5 0x1B VOUT_EN and its EN pin, MAX77620 GPIO5 driven high. Mariko: MAX77812 EN_CTRL.EN_M4 |
| CRAIL, C0NC, CE0 ungated | PMC PWRGATE_STATUS bits 0, 15, 14 |
| CPUG clock on, PLLX up if CCLK uses it | CLK_ENB_V bit 0, CCLK_BURST_POLICY, PLLX_BASE |
| MSELECT clocked and out of reset | CLK_ENB_V bit 3, RST_DEV_V bit 3 |
| An AArch64 vector in IRAM/DRAM | SB_AA64_RESET_LOW bit 0 + address, SB_AA64_RESET_HIGH |
A release that misses one prints `[ccplex] CPU0 released from reset but
cannot run: <reason>` and the core stays dark, which is what silicon does,
minus the explanation. Asserting a reset bit, gating a partition or dropping
the rail stops a running core.
`RST_CPU_CMPLX_SET` (0x340, TRM 5.2.113) carries `RST_CPUG_CMPLX`'s fields and
reset value: it is the active cluster's view, and the Switch runs the G
cluster, so it and its CLR partner at 0x344 act on the same reset state.
`CLK_CPUG_CMPLX` (0x378, TRM 5.2.122) and its SET/CLR strobes (0x460/0x464)
stop a core's clock with `CPUGn_CLK_STP`; all three read the register back.
CPU0 with its clock stopped keeps its state and executes nothing while
emulated time passes, and carries on where it was once the stop is cleared.
**Entry at EL3.** A real A57 leaves reset at EL3, AArch64, MMU off. Unicorn
builds its ARM64 core at EL1 and cannot be moved: a PSTATE write does not
rebuild the translator's cached `hflags`, and Unicorn never delivers guest
exceptions, so no SMC can carry it up either. ERET can: its helper takes the
current EL from PSTATE and rebuilds `hflags` for the target. So each boot
creates a fresh engine, writes
PSTATE = SPSR_EL3 = EL3h with DAIF masked and ELR_EL3 = ELR_EL1 = the vector,
and starts it on a one-instruction `eret` trampoline in a page at 1 TiB that
only CPU0 maps.
**Bus.** CPU0's engine maps IRAM, DRAM and TZRAM from the same host memory
as the BPMP's and the same MMIO windows. `g_bus_master` says who is issuing an
access; the PCIe model refuses the BPMP (`0xFFFFFFFF`, and one warning
explaining why) and serves CPU0. MSELECT reads its TRM reset value
`0x07FF4020`, AFI_PCIE_CONFIG `0x00103025`, and LNKSTA `0x3011` once the link
is up - the values hwtest's healthy-console capture shows. The whole config
aperture and non-prefetchable window are decoded (extended registers read 0,
unclaimed addresses all-ones, BARs wherever software puts them), and
MSELECT_CONFIG.ENABLE_PCIE_APERTURE gates them. An access CPU0 makes to an
address nothing decodes wedges it, as on silicon; the BPMP's watchdog on the
mailbox heartbeat is what reports it.
**Code the BPMP rewrites.** Stores from one engine never reach the other's
translation cache, so a stub loaded for a new job at the address of the last
one would run the old code. The pages CPU0 executes from are remembered with
a copy of their bytes, and before each slice any that changed have their
translations dropped (`uc_ctl_remove_cache`). A full `UC_CTL_TB_FLUSH` would
be simpler, but on Unicorn 2.0 it memsets the whole 1 GB code buffer.
**Time.** CPU0 keeps its own clock: 1 ns per retired instruction (PLLX runs
the A57 at ~1 GHz) plus 250 ns per bus access (MSELECT, the APC bridge, APB).
While it runs, the main loop cuts the BPMP's batch into 250 us slices and runs
CPU0 up to the BPMP's time after each - lockstep at a finer grain than the
500 us the BPMP polls the mailbox at. During a CPU0 slice `emu_usec` is CPU0's
clock, so every register model timestamps with the right core's time - a
model timing CPU0's PERST#-after-refclk sequence must use the clock CPU0
waits on. CPU0 trails the BPMP by up to a slice, so a model both cores touch
(ACTMON, the Bluetooth chip) compares times rather than subtracting them.
Releasing CPU0 ends the BPMP's batch at the next block, so the first slice
starts at once. WFE / WFI park the core to the end of the slice: the stub's
final `for(;;) wfe;` would otherwise spin through a billion instructions per
emulated second.
`make test` runs `tests/ccplex/`, a self-contained payload that checks the
refusal, the EL3 entry, a core released with its clock stopped, the
mailbox, WFE parking and the reset, then the same payload under the
`vdd_cpu`, `max77621_cpu` and `max77812` faults (see Fault injection);
`tests/se/`, which runs the SE's RSA, SHA-256, AES and RNG against vectors
computed in Python (`gen_vectors.py` writes `vectors.h`); `tests/usb/`, a
mass storage gadget over a RAM disk on each device controller (writable, and
write-protected in scenario 4) and a HID gadget, which the `--usb-host` PC
must enumerate, read back (the CRC32s it logs match the payload's), write
back unchanged unless write-protected and see detach, plus a run with
nothing on the cable and three NBD runs where `nbd_check.py` negotiates,
reads the disk, is refused a misaligned and an out-of-range read, writes
(or is refused on the write-protected disk), pipelines two reads, flushes
and disconnects, and the disk's CRC32 after the eject must be the client's; and `tests/display/`, one payload built per scenario that drives the display
controller and VIC the way bdk does (a pitch window; Nyx's VIC turn into
pitch and into block-linear surfaces; a block-linear VIC source; the DC's
own column scan with an address offset; a mirrored window with window D
blended over it). `check.py` compares every pixel of the frame the emulator
shows with the picture the payload drew. `tests/hwtest/` builds hwtest-rcm
with distro toolchains and runs its whole sweep; CI runs all four.
## Fault injection
A diagnostic payload is only tested once it has seen broken hardware, so
chips and rails can be killed: `--fault NAME` (repeatable, comma lists),
`NAME=dead` under `[faults]` in `rcm_emu.ini`, or the config window's Faults
section, which applies a change at once. The table is `kFaults` in
`emu_state.h`; `--fault list` prints it. A fault is hardware, so a payload
reboot keeps it.
**Coherence is the rule.** A fault has to show up identically in every model
that depends on it, because a payload judges a part by what its neighbours
do. So a part is listed only once all of its modelled consequences are wired,
and a name with none is left out rather than accepted - otherwise a payload
could "pass" against a fault that cannot fail it. The two kinds:
| Kind | What it models | Where it acts |
| --- | --- | --- |
| chip | The part is dead. | `i2c_slave_present()` NAKs its address (normal and packet mode alike, both read `I2C_STATUS`); the regulator write paths commit nothing to a NAKing slave; `cpu_rail_fault()` takes down every rail the chip supplies. |
| rail | The regulator answers and takes its enable, but delivers nothing - an open inductor, a shorted output cap. | Only what the rail feeds. Nothing changes over I2C: that is the case a probe reading regulator registers back cannot see, and the reason it is worth modelling. |
| Fault | Consequences |
| --- | --- |
| `vdd_cpu` | `cpu_rail_on()` is false whatever the registers say. `FLOW_CTLR_RAM_REPAIR` leaves a request pending with STS clear (no rail, no acks from the CPU repair chain - see below), CPU0 refuses release with `CPU rail has no output (fault: vdd_cpu ...)`, and a running CPU0 stops. bdk's `ccplex_boot_cpu0()` spins on that STS with no timeout, so an unguarded payload hangs there - the "frozen while booting the CPU" console. |
| `max77621_cpu` (Erista), `max77812` (Mariko) | The chip fault, plus `vdd_cpu`. This matters on Erista, where the MAX77621's register file is seeded with VOUT_EN set: without the cascade the rail would stay up behind a chip that no longer answers. A fault on the other generation's chip changes nothing. |
| `max77621_gpu`, `bq24193`, `max17050`, `tmp451`, `bm92t36` | NAK only. Nothing else in the emulator consumes them. |
The RAM repair coupling also holds with no fault at all, because it is how
the part works: software powers the CPU rail, then sets `RAM_REPAIR[REQ]`
and polls `[STS]`, which reports the acknowledgments of every segment of the
CPU repair chain, and a request "must remain high for as long as it does not
receive the corresponding ack signal" (TRM 17.1.3.2). So a repair requested
with the rail off stays pending and completes once the rail is up. Every
payload seen so far powers the rail first, as bdk does.
The PMC partitions (CRAIL, C0NC, CE0) still ungate under a dead rail. The PMC
only takes a CPU power-good indication from the PMIC when
`PMC_CNTRL.CPUPWRGOOD_EN` is set; it resets to 0, bdk never sets it, and the
CPUPWRGOOD/CPUPWROFF timers "are used only when the platform supports a CPU
power good indication" (TRM 12.4.5 CPU Rail Partitions, 12.6.1
APBDEV_PMC_CNTRL_0). So the
partition reads powered either way and the step that really needs the rail
is the RAM repair. A payload that did enable CPUPWRGOOD would make the ungate
wait on the PMIC's pin; none does, and that is not modelled.
Deliberately not offered: the MAX77620 itself (nothing would run), the
ALC5639 codec (audio leaves through I2S whether or not it answers, so "dead"
would be half-modelled), and the GPU and DRAM rails (no consumer modelled).
Adding one means wiring every consequence first; `tests/ccplex/run.sh` shows
how a fault scenario is checked.
## Bug history
These are baked into the current source. Listed here so future maintainers
don't repeat the diagnosis:
- **Minerva DRAM training** hangs in a `PLL_BASE.LOCK` poll. Fix: always
report `LOCK | ENABLE`.
- **Minerva DRAM training** hangs in a `PLL_BASE.LOCK` poll. Fix: report
LOCK once the PLL is enabled.
- **TegraExplorer hung on the eMMC.** Switching SDMMC4 to HS200 enables
PLLC4, and TegraExplorer's bdk waits for `PLLC4_BASE.LOCK` with no
timeout; the CAR model had no PLLC4, so Erista hung at the key dump and
both SoCs at "Browse EMMC". (hekate's newer bdk times the wait out, which
hid it.) Fix: PLLC4 locks once enabled, out of IDDQ.
- **Every payload began with a display teardown.** `CLK_OUT_ENB_L` read a
real console's value taken after a payload had brought the display up, so
`display_init()` found DISP1 already clocked at RCM entry. Fix: the bank
starts at the TRM reset value and follows the payload's writes.
- **Every USB gadget failed to start.** The USB controllers were plain
register caches, so `USBCMD.RESET` never cleared and bdk's
`usb_device_init()` timed out; Nyx's USB tools could not even wait for a
cable. Fix: both device controllers are modelled, with a PC to plug in.
- **NBD reads of 64 KiB failed on Nyx.** The host took a device transfer
that moved less than it asked for as a short packet, so when bdk sent a
64 KiB READ(10) as two 32 KiB transfers the data phase ended after the
first and the CSW read found data. Fix: only a transfer whose last packet
is short (or zero-length, including the USB2 controller's own ZLP when the
queue head allows it) ends the host's transfer; the test payload now sends
reads in 32 KiB transfers too.
- **Minerva hung Nyx** (hekate 6.5.3 with the stock `bootloader/` folder
never reached its GUI). The emulator planted hekate's "watchdog fired"
cookie in IRAM so the IPL would skip Minerva; Nyx then trained the DRAM
itself, and Minerva spun on
`PLLMB_BASE.LOCK` (the CAR model had no PLLMB and read it as 0). Behind
that it would have spun on the DLL-enable bit it writes to
`EMC_CFG_DIG_DLL` and on `EMC_DIG_DLL_STATUS` lock, timed out on the
clock-change handshake, and divided by a zero MR18/MR19 oscillator count,
because every EMC register but three read 0. Fix: PLLMB, and the EMC
model described in [EMC and DRAM clock](#emc-and-dram-clock). With
Minerva working, the cookie is gone too, and hekate boots as on hardware.
- **`kfuse_wait_ready`** loops on `STATE.DONE`. Fix: stub `DONE | CRCPASS`.
- **AMS keygen** retries `tsec_query` 15 times until timeout. Fix: stub
`STATUS = 0xB0B0B0B0`.
@@ -384,6 +925,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:
@@ -398,13 +948,38 @@ don't repeat the diagnosis:
`APBDEV_PMC_CNTRL.MAIN_RST`, then exit or flip
`state->reboot_requested`.
- **A hwtest sweep never finished.** It stalled in the fan spin-up test:
bdk's `fan_get_speed()` waits for TIMERUS to *equal* a deadline, and the
dilated clock stepped past it. Fix: TIMERUS poll pacing (see
[Determinism](#determinism-and-the-auto-script-flag)).
- **Per-instruction hooks.** Three `UC_HOOK_CODE` callbacks (one registered
twice), one doing a `uc_mem_read` per instruction for a NOP-slide check
whose counter never reset, plus memory hooks forcing every load and store
onto Unicorn's slow path, and a display path that re-converted and
re-allocated every frame. Reaching hwtest's fan test took 2.7 s; it takes
0.8 s now, and the whole sweep about 3 s. Fix: block-level clock,
`uc_mmio_map` windows, a change-detecting display path.
- **MAX77621 writes were dropped**, so after bdk's `hw_init()` disabled the
Erista CPU/GPU bucks a payload still read them as on. Fix: register files
for MAX77621 and MAX77812.
- **Mariko's MAX77812 was unreachable through bdk.** bdk picks its address
from `FUSE_RESERVED_ODM28_B01` bit 0; left clear it talked to the NAK'd
PHASE31 address 0x31. Fix: a Mariko reads the bit set (retail PHASE211,
0x33).
- **Windows image I/O ran in text mode.** MinGW's `open()` defaults to it,
so `_read()` rewrote CR LF and stopped at 0x1A inside SD/eMMC sectors, and
its 32-bit `st_size` could not size a 4 GiB rawnand chunk. Fix: `O_BINARY`
and `_fstati64` (`platform.h`).
See `git log` for the commit-by-commit diagnosis trail if you want more
detail on any of them.
## Adding a new peripheral
1. Decide on an MMIO range and add a new `else if` branch in `mmio_read` or
`mmio_write` (or a dedicated module like `i2c3.cpp`).
1. Decide on an MMIO range, make sure it is covered by `kRegions`, and add a
branch in `mmio_bus_read` / `mmio_bus_write` (or a dedicated module like
`i2c3.cpp`). Both processors reach it; check `g_bus_master` if the real
block answers only one of them.
2. If the device participates in the boot fence (status registers polled by
the BDK), make sure the read returns the "ready" or "done" state. Silent
`0` returns are the most common cause of hangs.
+4 -1
View File
@@ -15,4 +15,7 @@ WORKDIR /work
# Build command: docker run --rm -v $(pwd):/work rcm_emu
# (init the imgui submodule if it's missing, then build)
CMD ["sh", "-c", "git submodule update --init --recursive && make"]
# The source is bind-mounted and owned by the host user, not root: without
# safe.directory, git refuses to touch it ("dubious ownership") and make never
# runs.
CMD ["sh", "-c", "git config --global --add safe.directory /work && git submodule update --init --recursive && make"]
+64 -2
View File
@@ -28,6 +28,16 @@ CXXFLAGS = -Wall -g -O2 -std=c++17 -MMD -MP -I. -I$(IMGUI_DIR) -I$(IMGUI_DIR)/ba
LDFLAGS =
LIBS = -lunicorn -lSDL2 -lpthread
# UNICORN_DIR=<prefix>: build against a Unicorn installed there (statically)
# instead of the system one. Booting a kernel on CPU0 needs Unicorn 2.1 or
# later: 2.0.x checks guest accesses against its memory map by VIRTUAL
# address once the guest MMU is on, so every access through a kernel's
# TTBR1 mapping looks unmapped. Everything else works on either. Run
# `make clean` when switching, since the objects depend on its headers.
ifneq ($(strip $(UNICORN_DIR)),)
CXXFLAGS += -I$(UNICORN_DIR)/include
endif
# pkg-config for SDL2 if available
SDL2_CFLAGS := $(shell pkg-config --cflags sdl2 2>/dev/null)
SDL2_LIBS := $(shell pkg-config --libs sdl2 2>/dev/null)
@@ -37,6 +47,11 @@ ifneq ($(SDL2_CFLAGS),)
LIBS = -lunicorn $(SDL2_LIBS) -lpthread
endif
# After the SDL2 block above, which sets LIBS again.
ifneq ($(strip $(UNICORN_DIR)),)
LIBS := $(UNICORN_DIR)/lib/libunicorn.a $(if $(SDL2_LIBS),$(SDL2_LIBS),-lSDL2) -lpthread -lm
endif
# ---- Windows cross-build ---------------------------------------------------
#
# `make windows` builds rcm_emu.exe with the MinGW toolchain. Both deps come
@@ -59,7 +74,7 @@ WIN_CXXFLAGS = -Wall -g -O2 -std=c++17 -MMD -MP -I. -I$(IMGUI_DIR)
WIN_LIBS = -lmingw32 -lSDL2main -lSDL2 -lunicorn -lpthread -lwinmm -limm32 -lole32 -loleaut32 -lversion -lsetupapi -lcfgmgr32 -lcomdlg32 -lgdi32 -lrpcrt4 -lws2_32 -luuid -lshell32 -ladvapi32 -luser32
WIN_LDFLAGS = -static -static-libgcc -static-libstdc++
.PHONY: all clean windows
.PHONY: all clean windows test
all: $(OUTPUT)
@@ -84,5 +99,52 @@ $(OUTPUT): $(OBJS)
# (or after `make clean`) since the files don't exist yet.
-include $(OBJS:.o=.d)
# ---- Regression tests --------------------------------------------------------
#
# `make test` boots the emulator headless on small self-contained payloads and
# checks what they report. Needs arm-none-eabi-gcc for the BPMP side (the
# AArch64 side of the CCPLEX test is pre-assembled words in the source).
TEST_CC = arm-none-eabi-gcc
TEST_OBJCOPY = arm-none-eabi-objcopy
TEST_CFLAGS = -marm -march=armv4t -O2 -ffreestanding -nostdlib -fno-builtin \
-Wall -Wextra
tests/ccplex/payload.bin: tests/ccplex/payload.c tests/ccplex/link.ld
$(TEST_CC) $(TEST_CFLAGS) -T tests/ccplex/link.ld -o tests/ccplex/payload.elf $<
$(TEST_OBJCOPY) -O binary tests/ccplex/payload.elf $@
tests/kernelcpu/payload.bin: tests/kernelcpu/payload.c tests/kernelcpu/cpu0.S tests/kernelcpu/link.ld
sh tests/kernelcpu/build.sh
tests/se/payload.bin: tests/se/payload.c tests/se/vectors.h tests/se/link.ld
$(TEST_CC) $(TEST_CFLAGS) -T tests/se/link.ld -o tests/se/payload.elf $<
$(TEST_OBJCOPY) -O binary tests/se/payload.elf $@
USB_PAYLOADS = tests/usb/payload_1.bin tests/usb/payload_2.bin tests/usb/payload_3.bin \
tests/usb/payload_4.bin
tests/usb/payload_%.bin: tests/usb/payload.c tests/usb/link.ld
$(TEST_CC) $(TEST_CFLAGS) -DSCENARIO=$* -T tests/usb/link.ld -o tests/usb/payload_$*.elf $<
$(TEST_OBJCOPY) -O binary tests/usb/payload_$*.elf $@
DISPLAY_SCENARIOS = 1 2 3 4 5 6
DISPLAY_PAYLOADS = $(DISPLAY_SCENARIOS:%=tests/display/payload_%.bin)
tests/display/payload_%.bin: tests/display/payload.c tests/display/link.ld
$(TEST_CC) $(TEST_CFLAGS) -DSCENARIO=$* -T tests/display/link.ld -o tests/display/payload_$*.elf $<
$(TEST_OBJCOPY) -O binary tests/display/payload_$*.elf $@
test: $(OUTPUT) tests/ccplex/payload.bin tests/kernelcpu/payload.bin tests/se/payload.bin $(USB_PAYLOADS) $(DISPLAY_PAYLOADS)
sh tests/ccplex/run.sh ./$(OUTPUT) tests/ccplex/payload.bin
sh tests/kernelcpu/run.sh ./$(OUTPUT) tests/kernelcpu/payload.bin
sh tests/se/run.sh ./$(OUTPUT) tests/se/payload.bin
sh tests/usb/run.sh ./$(OUTPUT) tests/usb
sh tests/display/run.sh ./$(OUTPUT) tests/display
clean:
rm -f $(OUTPUT) $(OBJS) $(OBJS:.o=.d) \n $(WIN_OUT) $(WIN_OBJS) $(WIN_OBJS:.o=.d)
rm -f $(OUTPUT) $(OBJS) $(OBJS:.o=.d) \
tests/ccplex/payload.elf tests/ccplex/payload.bin tests/ccplex/out.log tests/ccplex/out_fault_*.log \
tests/se/payload.elf tests/se/payload.bin tests/se/out.log \
tests/usb/payload_*.elf tests/usb/payload_*.bin tests/usb/out_*.log \
tests/display/payload_*.elf tests/display/payload_*.bin \
$(WIN_OUT) $(WIN_OBJS) $(WIN_OBJS:.o=.d)
+169 -17
View File
@@ -7,9 +7,10 @@ precompiled `.bin` (Hekate, Lockpick_RCM, TegraExplorer, custom payloads) and
executes its ARM32 code on an emulated Tegra X1 (T210) environment, with a
windowed framebuffer and keyboard input mapped to the Switch hardware buttons.
It is **not** a console emulator. Only the BPMP (Boot and Power Management
Processor) bootloader stage is modelled. You will not boot Horizon, run NSPs,
or load games. The intended use is payload development and scripted
It is **not** a console emulator. The BPMP (Boot and Power Management
Processor) bootloader stage is what is modelled, plus CPU0 of the main CPU
cluster for payloads that boot it to run bare-metal AArch64 code. You will not
boot Horizon, run NSPs, or load games. The intended use is payload development and scripted
verification, plus security research where iterating on real hardware would be
slow or destructive.
@@ -21,17 +22,37 @@ slow or destructive.
bypasses the parts of the chain that aren't fully modelled.
- Run **TegraExplorer**, including `.te` script execution from an emulated SD
card.
- Run **hwtest-rcm**'s complete hardware sweep in a few seconds, including its
Wi-Fi probe, which boots **CPU0** (Cortex-A57, AArch64) to bring up PCIe and
enumerate the CYW4356 - PCIe answers a CPU-complex master only. See
[CCPLEX CPU0](#ccplex-cpu0).
- Replay deterministic button sequences via `--auto-pin-recovery` or
`--auto-te-script`, so a payload flow can be exercised from a CI run or a
one-shot script.
one-shot script. `--input-script` scripts buttons and touchscreen taps for
any payload, and can save the screen at a given point of a run.
- Plug an emulated PC into the USB-C port (`--usb-host`): Nyx's USB mass
storage and gamepad gadgets enumerate on both the Erista (USB2) and Mariko
(XUSB) device controllers, and the PC reads a mass storage disk back,
checks it against the SD image, writes a few sectors back unchanged and
ejects it. With `--usb-host nbd` the PC serves the disk over NBD instead,
so it can be mounted on the machine running the emulator.
- Boot a Linux kernel on CPU0 (switchroot's L4T 4.9), with a GIC-400, the
generic timer, PSCI and the clock controller's reset values for it. See
[Booting Linux on CPU0](#booting-linux-on-cpu0).
- Put a dock on the USB-C port (`--dock`): a Nintendo dock, a third-party
USB-C adapter or a Nintendo charger on the BM92T36, the dock's
DisplayPort-to-HDMI converter on DPAUX1, and a TV in a second window that
shows what display head B sends through SOR1. hwtest-rcm's Dock Test runs
its whole handshake and TV link against it.
- Tweak emulated hardware live (battery, charger, thermal, USB-PD, PMIC,
fuses, SD insertion) from a side window. See [Live hardware tweaks](#live-hardware-tweaks).
fuses, SD insertion, the USB host) from a side window. See [Live hardware tweaks](#live-hardware-tweaks).
- Inspect each Tegra UART port (TX history) and inject keystrokes into the
payload's RX FIFO from a separate console window. See [UART console](#uart-console).
- Read real eMMC (embedded MMC) dumps (`BOOT0`, multi-part `rawnand.bin.NN`)
and decrypt them with XTS-AES-128 (XEX-based Tweaked-codebook with ciphertext
stealing) against keys from `prod.keys`.
- Serve a real FAT32 SD image to the payload (`--sd sd.img`).
- Serve a real FAT32 SD image to the payload (`--sd sd.img`). Without one the
SD slot is empty.
## Quick start
@@ -42,6 +63,16 @@ sudo apt-get install -y build-essential libunicorn-dev libsdl2-dev
make
```
Booting a kernel on CPU0 needs Unicorn 2.1 or later: 2.0.x, which some
distributions still ship, checks guest accesses by virtual address once the
guest MMU is on. Build one into a prefix and point the Makefile at it, which
links it statically (`make clean` first when switching):
```bash
make UNICORN_DIR=$HOME/opt/unicorn-2.1
ldd rcm_emu | grep unicorn # prints nothing when the static one is in
```
### Build (Docker)
```bash
@@ -141,6 +172,109 @@ Audio goes to WASAPI on Windows and ALSA/PulseAudio on Linux; SDL picks the
backend, so nothing in the emulator cares which. `RCM_EMU_NO_AUDIO=1` skips
playback entirely, which is what CI uses since a runner has no sound device.
## CCPLEX CPU0
A payload can boot the first Cortex-A57 exactly as bdk's `ccplex_boot_cpu0()`
does - CPU rail, PLLX, CCLK, the CRAIL/C0NC/CE0 partitions, RAM repair, the
AArch64 vector in `SB_AA64_RESET_LOW/HIGH`, then `RST_CPUG_CMPLX_CLR` - and the
emulator runs it: AArch64, entered at EL3 with the MMU off at the vector,
sharing IRAM, DRAM and every peripheral with the BPMP, in lockstep with it on
the emulated clock. Output is prefixed `[ccplex]`:
```
[ccplex] CPU0 released: AArch64 EL3, MMU off, entry 0xA0000000 (boot #1)
[pcie] root port 1: link UP, gen1 x1 (healthy WLAN)
[uartB] CPU0 : ran to completion (hb=613)
[uartB] AFI (CPU) : cfg=00103025 witness=A5A50000 -> APERTURE LIVE
[uartB] RP1 link : UP, DL active (LNKSTA=3011 gen1 x1)
[uartB] EP config : 14E4:43EC Broadcom BCM/CYW4356 WLAN
[uartB] Result : WLAN core enumerated on the PCIe bus
[ccplex] CPU0 stopped (held in reset) after 19402985 instructions, 4846717 bus accesses
```
A release with something missing does not run the core - silicon would not -
and says what was missing, e.g. `[ccplex] CPU0 released from reset but cannot
run: CPU rail off (MAX77621 VOUT_EN / MAX77620 GPIO5 EN pin)`. PCIe and
MSELECT answer CPU0 only; the BPMP reads all ones from them, as measured on
real consoles. Details in [DESIGN.md](DESIGN.md#ccplex-cpu0).
### Booting Linux on CPU0
`linux/` boots an arm64 kernel Image, switchroot's L4T 4.9 for instance, the
way a bootloader would hand over to it:
```bash
linux/build.sh # linux/boot.bin (arm-none-eabi + aarch64 gcc)
linux/mkdtb.sh tegra210-odin.dtb odin-emu.dtb # console on UART-B, one CPU
linux/run.sh Image odin-emu.dtb boot.log 120
```
`--load FILE@ADDR` places the Image at 0x80080000 and the device tree at
0x83000000 before the payload starts; `linux/boot.bin` sets the clocks and
the CPU rail, releases CPU0 into `linux/shim.S`, which drops to EL1 with the
device tree in x0, and halts the BPMP. For the kernel, CPU0 has a GIC-400
(distributor and CPU interface), the generic timer counting emulated time
at 19.2 MHz, interrupts taken at block boundaries, BRK and undefined
instructions taken to its own vectors (WARN and BUG), PSCI on SMC, WFI
sleeping to the next timer, TMR10..13 as clock event timers, and every
unmodelled page of the peripheral band mapped as plain registers on first
access. The clock controller's registers read their TRM reset values until
written ([t210/car_reset.h](t210/car_reset.h)), since the kernel's clock
driver walks hundreds of them. `RCM_EMU_CPU0_PROFILE=1` prints where CPU0 is
once a second of real time, to tell a hung kernel from a slow one. The
console comes out on UART-B; the saved runs reach the kernel's core
initialisation.
## Tests
```bash
make test # CCPLEX, kernel CPU, SE, USB + display regression payloads (arm-none-eabi-gcc, aarch64 gcc, python3)
tests/hwtest/build.sh build-hwtest # build hwtest-rcm (+ gcc-aarch64-linux-gnu)
tests/hwtest/run.sh ./rcm_emu build-hwtest/hwtest-rcm/build/hwtest.bin
```
`make test` runs small self-contained payloads: one boots CPU0 and checks the
refusal of an unpowered release, the EL3 entry, the mailbox, a stopped clock,
WFE parking and the reset, then runs again with a dead CPU rail and dead
bucks (`--fault`) and checks the RAM repair is held and the core stays dark;
one drops CPU0 to EL1 and checks it takes timer interrupts through the GIC,
a BRK into its own vector and a PSCI call over SMC;
one checks the Security Engine's RSA, SHA-256, AES
and RNG against vectors computed in Python; one brings up a USB mass storage
gadget on each device controller (and a HID gadget) for the `--usb-host` PC to
enumerate, read back and write, and serves it over NBD to a Python client;
one drives the display controller and VIC and
compares the frame pixel for pixel. The hwtest scripts run hwtest-rcm's whole
hardware sweep headless and check that the CPU0-driven Wi-Fi probe enumerates
the endpoint. CI runs both.
## Mounting a gadget's disk
`--usb-host nbd` turns the emulated PC into a bridge: when a mass storage
gadget attaches - Nyx's SD card, eMMC or emuMMC under USB tools - the PC
locks the medium (PREVENT MEDIUM REMOVAL, so Nyx will not unload it from its
side) and serves it with the NBD protocol on 127.0.0.1, port 10809 or the one
given as `nbd:<port>`. Every NBD read, write and flush becomes SCSI
commands to the gadget, so what reaches the SD image goes through bdk's UMS
code as it would from a real PC. A write-protected disk (Nyx's eMMC in its
default read-only mode) is exported read-only.
```sh
./rcm_emu hekate.bin --sd sd.img --usb-host nbd
# in Nyx: Tools > USB Tools > SD Card, then on the host:
sudo modprobe nbd max_part=8
sudo nbd-client 127.0.0.1 10809 /dev/nbd0 -b 512
sudo mount /dev/nbd0p1 /mnt # ... use it ...
sudo umount /mnt && sudo nbd-client -d /dev/nbd0 # the disk is ejected
```
Without root, `qemu-img convert nbd://127.0.0.1:10809 copy.img` takes a
copy, `qemu-io nbd://127.0.0.1:10809` reads and writes sectors, and
`nbdfuse` exposes the disk as a file. The session ends when the client
disconnects: the PC allows removal and ejects, and Nyx reports "Disk
ejected". The port only listens while a disk is being served. In the config
window, the USB device mode section has the same switch and port.
## Live hardware tweaks
Press `M` in the main window to open a second window that exposes the values
@@ -226,13 +360,18 @@ needed.
| Flag | Argument | Purpose |
| --------------------- | ------------- | --------------------------------------------------------- |
| `--sd` | `sd.img` | Back the SD card (SDMMC1) with this raw FAT32 image. |
| `--sd` | `sd.img` | Back the SD card (SDMMC1) with this raw FAT32 image. Without it (and with no `sd.img` in the working directory) the slot is empty. |
| `--boot0` | `BOOT0` | eMMC BOOT0 partition file (SDMMC4). |
| `--rawnand` | `rawnand.bin` | eMMC GPP partition prefix (auto-detects `.00`, `.01`, …). |
| `--prod-keys` | `prod.keys` | Override BIS keys from a Lockpick-style key file. |
| `--oem` | `erista` \| `mariko` | Switch SoC generation. Drives `APB_MISC_GP_HIDREV` so Hekate's `h_cfg.t210b01` matches and pkg1 identification skips the right OEM header. Default `erista`. |
| `--bt-radio` | `healthy` \| `faulty` \| `absent` | Broadcom CYW4356 behaviour on UART-D. `healthy` powers up on the `BT_REG_ON` edge, holds `BT_HOST_WAKE` high, asserts `RTS_N` and answers HCI; `faulty` reproduces the 2110-1118 console (module fitted, never leaves POR); `absent` additionally leaves `BT_UART_RXD` in a break condition. Overrides `[bluetooth] radio` in the ini. Default `healthy`. |
| `--wifi-radio` | `healthy` \| `faulty` \| `absent` | The WLAN half of the same CYW4356: a PCI Express endpoint on root port 1. `healthy` trains the link, enumerates as `14E4:43EC` and answers a ChipCommon ChipID read with `0x4356`; `faulty` still trains and enumerates but reads all ones on the backplane (live PCIe front-end, dead radio die); `absent` never leaves detect. The model also enforces the datasheet's power-up ordering, so a payload that releases PERST# too early gets a link that stays down and a `[pcie]` line naming the reason. Overrides `[wifi] radio` in the ini. Default `healthy`. |
| `--wifi-radio` | `healthy` \| `faulty` \| `absent` | The WLAN half of the same CYW4356: a PCI Express endpoint on root port 1, reachable only from CPU0 (the BPMP reads all ones, as on silicon). `healthy` trains the link, enumerates as `14E4:43EC` and answers a ChipCommon ChipID read with `0x4356`; `faulty` still trains and enumerates but reads all ones on the backplane (live PCIe front-end, dead radio die); `absent` never leaves detect. The model also enforces the datasheet's power-up ordering, so a payload that releases PERST# too early gets a link that stays down and a `[pcie]` line naming the reason. Overrides `[wifi] radio` in the ini. Default `healthy`. |
| `--fault` | `NAME[,NAME…]` \| `list` | Break a chip or a rail; repeatable. A **chip** fault (`max77812`, `max77621_cpu`, `max77621_gpu`, `bq24193`, `max17050`, `tmp451`, `bm92t36`) makes the part NAK its I2C address, refuse writes and take every rail it supplies down with it. A **rail** fault (`vdd_cpu`) leaves the regulator answering and reading back as enabled while its output never comes up, so only what the rail feeds notices: the CPU RAM repair never completes and CPU0 cannot run. `list` prints the names and exits. Faults survive a payload reboot, like the hardware they model, and add to `[faults]` in the ini (`NAME=dead`). See [DESIGN.md](DESIGN.md#fault-injection). |
| `--usb-host` | `nbd[:port]` (optional) | A PC on the USB-C port. It enumerates whatever USB gadget the payload brings up; a mass storage disk is read back (checked against the SD image), its last 8 sectors are written back unchanged and read again unless it is write-protected, and it is ejected; HID reports are polled. With `nbd` the disk is served over NBD on 127.0.0.1 (port 10809 by default) until the client disconnects, then ejected - see [Mounting a gadget's disk](#mounting-a-gadgets-disk). Logged as `[usb-host]`; `RCM_USB_TRACE=1` traces every transfer. Overrides `[usb] host` and `[usb] nbd_port` in the ini. |
| `--load` | `FILE@ADDR` | Place a file in DRAM before the payload starts, the way a bootloader leaves a kernel and its device tree; repeatable. See [Booting Linux on CPU0](#booting-linux-on-cpu0). |
| `--dock` | `nintendo` \| `thirdparty` \| `charger` \| `none`, `:notv` | What is on the USB-C port, behind the BM92T36: a Nintendo dock (057E:2003, 15 V, Nintendo's alt mode, DisplayPort on pin D), a third-party adapter (Fresco Logic 1D5C:7102, four power profiles, the DisplayPort SVID) or the Nintendo charger (057E:2004, no video). A dock's DisplayPort-to-HDMI converter answers on DPAUX1 (DPCD 1.2, the TV's EDID over I2C-over-AUX), and SOR1 judges link training lane by lane against the board's wiring; once trained, head B's frames show in a TV window. `:notv` leaves the dock's HDMI empty. `RCM_EMU_TV_SNAP=file` saves the TV picture, `RCM_EMU_DPTRACE=file` traces DPAUX1 and SOR1. Overrides `[dock] kind` and `[dock] tv` in the ini. Default `none`. |
| `--input-script` | file or spec | Scripted input keyed to emulated time: `<ms> P\|U\|D [hold_ms]` presses POWER / VOL+ / VOL-, `<ms> TAP <x> <y> [hold_ms]` taps the touchscreen at (x, y) in the 1280x720 picture, `<ms> SNAP <file>` saves the next displayed frame to `<file>` (raw B, G, R, A like `last_fb.rgba`, size in the matching `.meta`), `+N` times an event N ms after the previous one. Events are separated by `,`, `;` or newlines. |
| `--auto-pin-recovery` | (none) | Drive the Lockpick PIN-recovery menu without user input. |
| `--auto-te-script` | (none) | Drive `recover_pin.te` in TegraExplorer without input. |
@@ -244,21 +383,28 @@ flowchart LR
root --> top["main.cpp<br/>emu_state.h<br/>Makefile<br/>Dockerfile<br/>README.md / DESIGN.md"]
root --> t210["t210/<br/>(SoC peripheral models)"]
root --> display["display/"]
root --> linux["linux/<br/>kernel boot: boot.c, shim.S, run.sh"]
root --> tests["tests/<br/>ccplex/, kernelcpu/, se/, usb/, display/, hwtest/"]
t210 --> mmio["mmio.{h,cpp}<br/>memory_map.h<br/>tegra_bl.h"]
t210 --> sdmmc["sdmmc.{h,cpp}<br/>SDMMC1 / SDMMC4"]
t210 --> se["se_engine.{h,cpp}<br/>AES-128, SHA-256"]
t210 --> mmio["mmio.{h,cpp}<br/>memory_map.h<br/>regcache.h, tegra_bl.h"]
t210 --> cpus["bpmp.{h,cpp} BPMP clock<br/>ccplex.{h,cpp} CPU0 (A57)<br/>gic.{h,cpp} GIC-400"]
t210 --> pcie["pcie.{h,cpp}<br/>root complex + CYW4356"]
t210 --> se["se_engine.{h,cpp}<br/>AES-128, SHA-256, RSA, RNG"]
t210 --> i2c["i2c3.{h,cpp}<br/>STMFTS / FTS4 touch"]
t210 --> usb["usb.{h,cpp}<br/>USB device controllers + host PC"]
t210 --> dock["dock.{h,cpp}<br/>BM92T36, the dock, DPAUX1, SOR1"]
display --> sdl["sdl_display.{h,cpp}<br/>block-linear de-swizzle<br/>+ SDL2"]
display --> sdl["sdl_display.{h,cpp}<br/>DC window scan-out<br/>+ SDL2"]
```
For implementation details, see [DESIGN.md](DESIGN.md).
## Limitations
- **BPMP only.** Horizon and Atmosphère need A57 core emulation. This only
models the ARM7 bootloader environment.
- **BPMP plus one A57.** CPU0 runs bare-metal AArch64 handed to it by a
payload; there is no GIC, no generic timer, no secondary cores and no guest
exception delivery (a fault halts CPU0 and says so). Horizon and Atmosphère
are out of reach.
- **Subset of MMIO (Memory-Mapped I/O).** Peripherals are modelled to the depth
required by the payloads above. New payloads may exercise registers that fall
through to the default catch-all and need handlers added.
@@ -266,9 +412,15 @@ For implementation details, see [DESIGN.md](DESIGN.md).
firmware and the full master-key unwrapping flow are not faithfully emulated.
`--prod-keys` is a pragmatic shortcut: when Lockpick writes a derived BIS
(Boot Image Storage) key into a keyslot, the value from the user-supplied key
file is substituted. RSA, RNG, and chunked SHA are stubs.
- **Single-threaded.** The CPU runs in batches on the main thread between SDL
event polls. Tight host CPU loops will starve the display refresh.
file is substituted. The random number generator starts from a fixed
seed, so runs repeat.
- **Single-threaded.** Both cores run in batches on the main thread between
SDL event polls. That is also what keeps them deterministic.
- **The USB host drives mass storage and HID only.** A gadget of another
class is enumerated and left configured. Over NBD, one client has the disk
per session: when it disconnects - `nbdinfo` and `qemu-img info` do so as
soon as they have their answer - the disk is ejected, as a PC ejects a
disk it has unmounted.
## Acknowledgements
+91 -4
View File
@@ -3,6 +3,7 @@
#include "config_window.h"
#include "emu_state.h"
#include "t210/mmio.h"
#include "imgui.h"
#include "backends/imgui_impl_sdl2.h"
@@ -58,6 +59,7 @@ void reset_to_defaults(EmuState *s) {
s->pmic_cnfg1_32k = 0xFC; // 32K_OK | 32K_OUT0_EN
s->bt_radio = BT_RADIO_HEALTHY;
s->wifi_radio = WIFI_RADIO_HEALTHY;
s->faults = 0;
s->sd_inserted = true;
s->sd_cid_manfid = 0x03;
s->sd_cid_oemid = 0x5344; // "SD"
@@ -138,6 +140,10 @@ void reset_to_defaults(EmuState *s) {
X(usb_pd_inserted, "usb_pd", "inserted", 0) \
X(usb_pd_voltage_mv, "usb_pd", "voltage_mv", 0) \
X(usb_pd_amperage_ma, "usb_pd", "amperage_ma", 0) \
X(dock_kind, "dock", "kind", 0) \
X(dock_tv, "dock", "tv", 0) \
X(usb_host, "usb", "host", 0) \
X(usb_nbd_port, "usb", "nbd_port", 0) \
/* SoC / PMIC */ \
X(pmic_otp, "soc", "pmic_otp", 0) \
X(is_mariko, "soc", "is_mariko", 0) \
@@ -216,12 +222,20 @@ bool config_window_save_ini_impl(const EmuState *s, const char *path) {
write_header("wifi");
fprintf(f, "radio=%s\n", wifi_radio_name(s->wifi_radio.load()));
// Every fault, set or not, so the file itself lists what can be broken.
write_header("faults");
for (const FaultDef &d : kFaults)
fprintf(f, "%s=%s\n", d.name, (s->faults.load() & d.id) ? "dead" : "ok");
// Fuses are dumped wholesale — small enough (256 × 4 bytes) and keeps the
// load path branch-free.
// load path branch-free. Zero words too: loading layers the file over
// init_fuse_defaults(), so a fuse cleared in the UI and left out here
// came back at its default on the next start.
fprintf(f, "\n[fuses]\n");
for (size_t i = 0; i < EmuState::FUSE_WORDS; i++) {
uint32_t v = s->fuse_word[i].load();
if (v) fprintf(f, "0x%03X=0x%08X\n", (unsigned)(i * 4), v);
fprintf(f, "0x%03X=0x%08X\n", (unsigned)(i * 4), v);
}
fclose(f);
@@ -306,6 +320,25 @@ bool config_window_load_ini_impl(EmuState *s, const char *path) {
}
continue;
}
if (strcmp(section, "faults") == 0) {
// One key per fault, value dead or ok. Same string-vs-schema
// reasoning as [bluetooth]: an unknown name or value is reported,
// never quietly read as healthy.
const FaultDef *f = fault_find(key);
bool dead = false;
if (!f) {
fprintf(stderr, "[config] Unknown fault '%s' in [faults];"
" run with --fault list for the names\n", key);
} else if (!fault_value_parse(val, &dead)) {
fprintf(stderr, "[config] [faults] %s='%s': expected dead or ok\n",
key, val);
} else if (dead) {
s->faults |= f->id;
} else {
s->faults &= ~f->id;
}
continue;
}
if (strcmp(section, "fuses") == 0) {
uint32_t off = (uint32_t)strtoul(key, nullptr, 0);
if (off < EmuState::FUSE_WORDS * 4 && (off & 3) == 0) {
@@ -460,6 +493,30 @@ void build_ui(EmuState *state) {
atomic_slider_int<uint8_t>("MAX77620 CNFG1_32K", state->pmic_cnfg1_32k, 0, 255, "0x%02X");
}
if (ImGui::CollapsingHeader("Faults (dead chips and rails)")) {
// Applied at once. A chip fault NAKs from the next transaction; a
// rail fault stops a running CPU0 on the spot, as silicon would.
// Reboot for a clean POR with the fault already in place.
for (const FaultDef &d : kFaults) {
bool dead = (state->faults.load() & d.id) != 0;
char label[48];
snprintf(label, sizeof(label), "%s (%s)", d.name, d.kind);
if (ImGui::Checkbox(label, &dead)) {
if (dead)
state->faults |= d.id;
else
state->faults &= ~d.id;
printf("[fault] %s %s (config window)\n", d.name,
dead ? "set" : "cleared");
fflush(stdout);
faults_changed(state);
}
ImGui::SameLine();
ImGui::TextDisabled("%s", d.what);
}
}
if (ImGui::CollapsingHeader("Bluetooth (CYW4356)")) {
// Selected before the probe runs; press 'a' on the payload's pager to
// re-run the sweep after changing it, or Reboot for a clean POR.
@@ -643,6 +700,26 @@ void build_ui(EmuState *state) {
atomic_slider_int<uint16_t>("PDO amperage (mA)", state->usb_pd_amperage_ma, 500, 3000, "%d mA");
}
if (ImGui::CollapsingHeader("USB device mode")) {
// The PC in t210/usb.cpp: it enumerates a gadget the payload brings up.
bool host = state->usb_host.load();
if (ImGui::Checkbox("PC on the USB-C port (--usb-host)", &host)) {
state->usb_host.store(host);
}
// Mass storage served over NBD instead (--usb-host nbd[:port]);
// takes effect when the next disk is attached.
bool nbd = state->usb_nbd_port.load() != 0;
if (ImGui::Checkbox("Serve mass storage over NBD", &nbd)) {
state->usb_nbd_port.store(nbd ? 10809 : 0);
}
if (nbd) {
atomic_slider_int<uint16_t>("NBD port", state->usb_nbd_port, 1024, 65535, "%d");
ImGui::TextDisabled("127.0.0.1 only; the disk is ejected when the client disconnects.");
} else {
ImGui::TextDisabled("Mass storage is read back, written back unchanged and ejected;\nHID is polled.");
}
}
if (ImGui::CollapsingHeader("Display")) {
int bl = (int)state->backlight;
if (ImGui::SliderInt("Backlight", &bl, 0, 255)) {
@@ -757,7 +834,7 @@ void build_ui(EmuState *state) {
// Each row corresponds to a FUSE_BASE offset in Hekate's
// bdk/soc/fuse.h. Defaults match a typical Erista golden sample.
atomic_hex_input("0x100 PRODUCTION_MODE", state->fuse_at(0x100));
atomic_hex_input("0x110 SKU_INFO", state->fuse_at(0x110));
atomic_hex_input("0x110 SKU_INFO (0x83 ODIN; Minerva needs it)", state->fuse_at(0x110));
atomic_hex_input("0x114 CPU_SPEEDO_0", state->fuse_at(0x114));
atomic_hex_input("0x118 CPU_IDDQ", state->fuse_at(0x118));
atomic_hex_input("0x128 OPT_FT_REV", state->fuse_at(0x128));
@@ -889,6 +966,7 @@ void build_ui(EmuState *state) {
}
ImGui::SameLine();
if (ImGui::Button("Reboot")) {
state->reboot_cold = true; // the user's reset is a power cycle
state->reboot_requested.store(true);
}
ImGui::Text("emu_usec: %llu", (unsigned long long)state->emu_usec);
@@ -909,6 +987,9 @@ void build_ui(EmuState *state) {
ImGui::Separator();
if (ImGui::Button("Reset to defaults")) {
reset_to_defaults(state);
// Defaults clear every fault (and pick a SoC generation), so a CPU0
// release a fault was holding back must be looked at again.
faults_changed(state);
}
ImGui::SameLine();
static double g_save_msg_until = 0.0;
@@ -944,7 +1025,13 @@ bool config_window_init() {
fprintf(stderr, "[config_window] SDL_CreateWindow failed: %s\n", SDL_GetError());
return false;
}
g_renderer = SDL_CreateRenderer(g_window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
// No PRESENTVSYNC: this window renders on the emulation thread, and
// vsync would stall the emulated CPU for up to a frame per present.
g_renderer = SDL_CreateRenderer(g_window, -1, SDL_RENDERER_ACCELERATED);
// Same fallback as the main window: no GPU renderer (a headless run, a
// VM without GL) should not cost the window altogether.
if (!g_renderer)
g_renderer = SDL_CreateRenderer(g_window, -1, SDL_RENDERER_SOFTWARE);
if (!g_renderer) {
fprintf(stderr, "[config_window] SDL_CreateRenderer failed: %s\n", SDL_GetError());
SDL_DestroyWindow(g_window);
+7 -1
View File
@@ -165,7 +165,13 @@ bool console_window_init()
fprintf(stderr, "[console_window] SDL_CreateWindow failed: %s\n", SDL_GetError());
return false;
}
g_renderer = SDL_CreateRenderer(g_window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
// No PRESENTVSYNC: this window renders on the emulation thread, and
// vsync would stall the emulated CPU for up to a frame per present.
g_renderer = SDL_CreateRenderer(g_window, -1, SDL_RENDERER_ACCELERATED);
// Same fallback as the main window: no GPU renderer (a headless run, a
// VM without GL) should not cost the window altogether.
if (!g_renderer)
g_renderer = SDL_CreateRenderer(g_window, -1, SDL_RENDERER_SOFTWARE);
if (!g_renderer) {
fprintf(stderr, "[console_window] SDL_CreateRenderer failed: %s\n", SDL_GetError());
SDL_DestroyWindow(g_window);
+563 -279
View File
@@ -1,11 +1,16 @@
#include "sdl_display.h"
#include "../t210/dock.h"
#include "../t210/mmio.h"
#include <string>
#include "config_window.h"
#include "console_window.h"
#include "../emu_state.h"
#include "../t210/block_linear.h"
#include "../t210/memory_map.h"
#include <SDL2/SDL.h>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
@@ -30,6 +35,8 @@ static bool event_targets_window(const SDL_Event &ev, Uint32 wid) {
static SDL_Window *window = nullptr;
static SDL_Renderer *renderer = nullptr;
static SDL_Texture *texture = nullptr;
// The last converted frame (ARGB8888, out_w x out_h), reused across updates.
static std::vector<uint32_t> g_frame;
static int g_swizzle_override =
-1; // -1 = Auto, 0 = Pitch Linear, 2 = Block Linear
@@ -41,8 +48,10 @@ bool sdl_display_init() {
SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);
if (!window)
return false;
renderer = SDL_CreateRenderer(
window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
// No PRESENTVSYNC. The CPU runs on this same thread and the main loop
// already paces redraws to ~60 Hz by wall clock; with vsync on, each
// SDL_RenderPresent could block the emulated CPU for up to a whole frame.
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
if (!renderer)
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_SOFTWARE);
if (!renderer)
@@ -51,139 +60,435 @@ 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 fetch, before the DC turns it
uint32_t x0 = 0, y0 = 0; // first pixel fetched (ADDR_H/V_OFFSET)
uint32_t cols = 0, rows = 0; // surface extent from START_ADDR
uint32_t pre_w = 0, pre_h = 0; // PRESCALED_SIZE, in pixels (post-turn)
uint32_t out_w = 0, out_h = 0; // SIZE
int32_t x = 0, y = 0;
uint32_t xf = 0, layer = 0, blend_layer = 0, blend_match = 0;
size_t len = 0;
const uint8_t *mem = nullptr;
std::vector<uint8_t> 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
return bl_offset(xb, sy, w.gobs, w.gob_h);
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;
// The fetch starts at START_ADDR + ADDR_V_OFFSET * LINE_STRIDE +
// ADDR_H_OFFSET (TRM 24.11.1): the window's top-left pixel, or top-right
// with H_DIRECTION, bottom-left with V_DIRECTION - in surface terms,
// before SCAN_COLUMN turns it - and walks away from it.
uint64_t start = (uint64_t)r[dcwin::ADDR_V_OFF] * w.stride +
r[dcwin::ADDR_H_OFF];
w.y0 = (uint32_t)std::min<uint64_t>(start / w.stride, 0xFFFF);
w.x0 = (uint32_t)(start % w.stride) / w.bpp;
w.cols = w.stride / w.bpp;
w.rows = (w.xf & dcwin::XF_FLIP_Y) ? w.y0 + 1 : w.y0 + w.src_h;
switch (w.kind) {
case 2:
w.gobs = (w.stride + 63) / 64;
w.len = bl_size(w.gobs, w.gob_h, w.rows);
break;
case 1:
w.len = (size_t)w.stride * ((w.rows + 15) / 16) * 16;
break;
default:
w.len = (size_t)w.stride * w.rows;
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 (pw x ph, row-major).
void draw_window(const Win &w, std::vector<uint32_t> &panel, uint32_t pw = kPanelW,
uint32_t ph = kPanelH) {
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<uint32_t> 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)ph)
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)pw)
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;
int64_t sx = hflip ? (int64_t)w.x0 - a : (int64_t)w.x0 + a;
int64_t sy = vflip ? (int64_t)w.y0 - b : (int64_t)w.y0 + b;
if (sx < 0 || sy < 0 || sx >= w.cols || sy >= w.rows)
continue; // before START_ADDR or past the surface
size_t off = fetch_off(w, (uint32_t)sx, (uint32_t)sy);
if (off + w.bpp > w.len)
continue;
uint32_t s = depth_argb(w.mem + off, w.depth);
uint32_t &d = panel[(size_t)py * pw + 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;
}
}
}
// ---- The TV on the dock ------------------------------------------------------
//
// A second window, shown while a dock with video is configured: head B's
// windows composed at the head's active size, as SOR1 sends them, when the
// dock model says frames reach the TV; otherwise a dark screen, and the
// window title says why there is no picture.
SDL_Window *tv_window = nullptr;
SDL_Renderer *tv_renderer = nullptr;
SDL_Texture *tv_texture = nullptr;
uint32_t tv_tex_w = 0, tv_tex_h = 0;
std::string tv_title;
void tv_update(EmuState *state, uc_engine *uc) {
uint8_t k = state->dock_kind.load();
bool want = (k == 1 || k == 2) && state->dock_tv.load();
if (!want) {
if (tv_window)
SDL_HideWindow(tv_window);
return;
}
if (!tv_window) {
tv_window = SDL_CreateWindow("TV (dock HDMI)", SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED, 960, 540,
SDL_WINDOW_RESIZABLE);
if (!tv_window)
return;
tv_renderer = SDL_CreateRenderer(tv_window, -1, SDL_RENDERER_ACCELERATED);
if (!tv_renderer)
tv_renderer = SDL_CreateRenderer(tv_window, -1, SDL_RENDERER_SOFTWARE);
}
SDL_ShowWindow(tv_window);
TvState t;
dock_tv_state(state, &t);
uint32_t act = mmio_bus_read(state, 0x54240000 + 0x409 * 4, 4);
uint32_t w = act & 0x1FFF, h = (act >> 16) & 0x1FFF;
char title[256];
if (t.video && w && h)
snprintf(title, sizeof(title), "TV (dock HDMI) - %ux%u, %s", w, h, t.status);
else
snprintf(title, sizeof(title), "TV (dock HDMI) - no signal: %s", t.status);
if (tv_title != title) {
tv_title = title;
SDL_SetWindowTitle(tv_window, title);
printf("[tv] %s\n", title + 16);
fflush(stdout);
}
SDL_SetRenderDrawColor(tv_renderer, 8, 8, 24, 255);
SDL_RenderClear(tv_renderer);
if (t.video && w && h && w <= 4096 && h <= 4096) {
std::vector<uint32_t> pic((size_t)w * h, 0xFF000000u);
std::vector<Win> wins;
for (int i = 0; i < 4; i++) {
Win wn;
if (load_window(state, uc, i, state->dcb_win_active[i], -1, wn))
wins.push_back(std::move(wn));
}
std::stable_sort(wins.begin(), wins.end(),
[](const Win &a, const Win &b) { return a.layer > b.layer; });
for (const Win &wn : wins)
draw_window(wn, pic, w, h);
if (!tv_texture || tv_tex_w != w || tv_tex_h != h) {
if (tv_texture)
SDL_DestroyTexture(tv_texture);
tv_texture = SDL_CreateTexture(tv_renderer, SDL_PIXELFORMAT_ARGB8888,
SDL_TEXTUREACCESS_STREAMING, (int)w, (int)h);
tv_tex_w = w;
tv_tex_h = h;
}
if (tv_texture) {
SDL_UpdateTexture(tv_texture, nullptr, pic.data(), (int)(w * 4));
SDL_RenderCopy(tv_renderer, tv_texture, nullptr, nullptr);
}
if (const char *snap = getenv("RCM_EMU_TV_SNAP")) {
static uint64_t last = 0;
if (state->emu_usec - last > 500000) {
last = state->emu_usec;
if (FILE *f = fopen(snap, "wb")) {
fwrite(&w, 4, 1, f);
fwrite(&h, 4, 1, f);
fwrite(pic.data(), 4, pic.size(), f);
fclose(f);
}
}
}
}
SDL_RenderPresent(tv_renderer);
}
} // namespace
void sdl_display_update(EmuState *state, uc_engine *uc) {
tv_update(state, 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<Win> 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));
}
// The TRM sorts windows by depth into the blend stages (24.3.12) without
// saying which way; lower depth nearer the top, as Linux programs later
// Tegras (depth = 255 - zpos). Equal depths stack A (bottom) to D (top),
// which puts hekate's log window D over A, as its blending expects.
std::stable_sort(wins.begin(), wins.end(), [](const Win &l, const Win &r) {
return l.layer > r.layer;
});
// 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);
}
}
// 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;
};
int rot = state->rotation_override;
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
}
}
// 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);
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);
@@ -191,8 +496,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;
@@ -200,132 +505,98 @@ 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<uint64_t> 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, (uint64_t)w.x0 << 32 | w.y0});
where.push_back((uint64_t)(uint32_t)w.x << 32 | (uint32_t)w.y);
}
static std::vector<uint64_t> last_shape, last_where;
static std::vector<uint8_t> 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;
static bool snapshot_pending = true;
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;
// 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;
static std::vector<uint32_t> panel;
panel.assign((size_t)kPanelW * kPanelH, 0xFF000000u); // black background
for (const Win &w : wins)
draw_window(w, panel);
std::vector<uint8_t> buf(fb_size);
if (uc_mem_read(uc, eff_addr, buf.data(), fb_size) == UC_ERR_OK) {
std::vector<uint32_t> proc(out_w * out_h,
0xFF000000); // Initialize 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;
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 = *(uint16_t *)&buf[byte_off];
uint32_t p = (((u16 >> 11) & 0x1F) << 19) |
(((u16 >> 5) & 0x3F) << 10) |
((u16 & 0x1F) << 3) | 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 = 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;
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;
}
if (dx < out_w && dy < out_h)
proc[dy * out_w + dx] = p;
g_frame[(size_t)dy * out_w + dx] = row[sx];
}
continue; // Skip the common 32bpp path below
}
} else {
off = (sy * eff_stride + sx * bpp) / 4;
SDL_UpdateTexture(texture, nullptr, g_frame.data(), out_w * 4);
}
if (off < fb_size / 4) {
uint32_t p = ((uint32_t *)buf.data())[off];
uint32_t dx = sx, dy = sy;
// Snapshots the input script asked for, from this frame.
std::string snap;
while (!g_frame.empty() && state->snap_take(&snap)) {
if (FILE *f = fopen(snap.c_str(), "wb")) {
fwrite(g_frame.data(), 1, g_frame.size() * 4, f);
fclose(f);
std::string meta = snap;
if (meta.size() > 5 && meta.compare(meta.size() - 5, 5, ".rgba") == 0)
meta.resize(meta.size() - 5);
meta += ".meta";
if (FILE *fm = fopen(meta.c_str(), "w")) {
fprintf(fm, "%u %u\n", out_w, out_h);
fclose(fm);
}
printf("[snap] %s (%ux%u)\n", snap.c_str(), out_w, out_h);
fflush(stdout);
}
}
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;
}
}
}
}
SDL_UpdateTexture(texture, nullptr, proc.data(), out_w * 4);
// Snapshot for PNG conversion — save periodically (~1s) so the last
// written file always reflects the most recent frame content.
// 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) { // ~1 second at 60 FPS
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(proc.data(), 1, proc.size() * 4, f);
fwrite(g_frame.data(), 1, g_frame.size() * 4, f);
fclose(f);
FILE *fm = fopen("last_fb.meta", "w");
if (fm) {
@@ -334,7 +605,6 @@ void sdl_display_update(EmuState *state, uc_engine *uc) {
}
}
}
}
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, nullptr, nullptr);
@@ -364,30 +634,44 @@ static bool window_to_panel(EmuState *state, int mx, int my,
if (tx >= out_w) tx = out_w - 1;
if (ty >= out_h) ty = out_h - 1;
// The rendered SDL view always represents the physical Switch screen in its
// intended orientation (post-rotation, post-de-swizzle). Whatever the
// framebuffer's in-memory layout, what the user sees is what they would see
// looking at a Switch held landscape (long axis horizontal). The FTS4 panel
// sits behind that physical screen with its long axis (panel_x) along the
// long dimension and its short axis (panel_y) along the short.
//
// So we map the texture coord to panel coords by aspect: whichever of (tx,
// ty) lives on the longer rendered axis is the long-axis sample.
bool landscape = (out_w >= out_h);
uint32_t long_pix = landscape ? tx : ty;
uint32_t long_max = landscape ? out_w : out_h;
uint32_t short_pix = landscape ? ty : tx;
uint32_t short_max = landscape ? out_h : out_w;
// With the auto-detected 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
uint32_t ah = (delta & 1) ? out_w : out_h;
uint32_t ax = tx, ay = ty;
switch (delta) {
case 1: ax = ty; ay = ah - 1 - tx; break;
case 2: ax = aw - 1 - tx; ay = ah - 1 - ty; break;
case 3: ax = aw - 1 - ty; ay = tx; break;
}
// The FTS4 panel sits behind that physical screen with its long axis
// (panel_x) along the long dimension and its short axis (panel_y) along
// the short, so whichever of (ax, ay) lives on the longer axis is the
// long-axis sample.
bool landscape = (aw >= ah);
uint32_t long_pix = landscape ? ax : ay;
uint32_t long_max = landscape ? aw : ah;
uint32_t short_pix = landscape ? ay : ax;
uint32_t short_max = landscape ? ah : aw;
if (long_max == 0) long_max = 1;
if (short_max == 0) short_max = 1;
uint32_t px = (long_pix * 1264u) / long_max; // FTS4 X_REAL_MAX = 1264
uint32_t py = (short_pix * 704u) / short_max; // FTS4 Y_REAL_MAX = 704
if (px > 1264) px = 1264;
if (py > 704) py = 704;
// bdk's touch.c clamps raw samples to EDGE_OFFSET..REAL_MAX (15..1264 and
// 15..704) and stretches that span over the 1280x720 screen, so the inverse
// starts at the edge offset, not at 0.
constexpr uint32_t kEdge = 15, kXMax = 1264, kYMax = 704;
uint32_t px = kEdge + (long_pix * (kXMax - kEdge)) / long_max;
uint32_t py = kEdge + (short_pix * (kYMax - kEdge)) / short_max;
if (px > kXMax) px = kXMax;
if (py > kYMax) py = kYMax;
*panel_x = (uint16_t)px;
*panel_y = (uint16_t)py;
(void)state; // last_rot still cached for future use; current mapping is rotation-agnostic
return true;
}
@@ -425,11 +709,8 @@ bool sdl_display_poll_events(EmuState *state, uc_engine *uc) {
if (event.type == SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_LEFT) {
uint16_t px = 0, py = 0;
if (window_to_panel(state, event.button.x, event.button.y, &px, &py)) {
state->tc_x.store(px);
state->tc_y.store(py);
state->tc_pressed.store(true);
state->tc_event_op.store(0x03); // FTS4_EV_MULTI_TOUCH_ENTER
state->tc_event_pending.store(true);
state->touch_post(0x03, px, py); // FTS4_EV_MULTI_TOUCH_ENTER
printf("[touch] DOWN win=(%d,%d) panel=(%u,%u)\n",
event.button.x, event.button.y, px, py);
}
@@ -437,11 +718,8 @@ bool sdl_display_poll_events(EmuState *state, uc_engine *uc) {
if (event.type == SDL_MOUSEBUTTONUP && event.button.button == SDL_BUTTON_LEFT) {
uint16_t px = 0, py = 0;
if (window_to_panel(state, event.button.x, event.button.y, &px, &py)) {
state->tc_x.store(px);
state->tc_y.store(py);
state->tc_pressed.store(false);
state->tc_event_op.store(0x04); // FTS4_EV_MULTI_TOUCH_LEAVE
state->tc_event_pending.store(true);
state->touch_post(0x04, px, py); // FTS4_EV_MULTI_TOUCH_LEAVE
printf("[touch] UP win=(%d,%d) panel=(%u,%u)\n",
event.button.x, event.button.y, px, py);
}
@@ -449,10 +727,15 @@ bool sdl_display_poll_events(EmuState *state, uc_engine *uc) {
if (event.type == SDL_MOUSEMOTION && state->tc_pressed.load()) {
uint16_t px = 0, py = 0;
if (window_to_panel(state, event.motion.x, event.motion.y, &px, &py)) {
state->tc_x.store(px);
state->tc_y.store(py);
state->tc_event_op.store(0x05); // FTS4_EV_MULTI_TOUCH_MOTION
state->tc_event_pending.store(true);
// A release outside the window never reaches it when mouse capture
// is off (the ImGui backend turns SDL's auto-capture off process-
// wide), so a motion with the button up ends the touch instead.
if (!(event.motion.state & SDL_BUTTON_LMASK)) {
state->tc_pressed.store(false);
state->touch_post(0x04, px, py); // FTS4_EV_MULTI_TOUCH_LEAVE
} else {
state->touch_post(0x05, px, py); // FTS4_EV_MULTI_TOUCH_MOTION
}
}
}
if (event.type == SDL_KEYDOWN) {
@@ -461,14 +744,20 @@ bool sdl_display_poll_events(EmuState *state, uc_engine *uc) {
uint32_t step = shift ? 4096 : 128;
switch (event.key.keysym.sym) {
case SDLK_UP:
if (!state->btn_vol_up)
// One press of 150 ms guest time per keydown (the host's
// auto-repeat makes more while the key is held).
if (!state->btn_vol_up) {
printf("[input] DOWN VOL_UP @emu_usec=%llu\n", (unsigned long long)state->emu_usec);
state->kbd_vol_up_until = state->emu_usec + 150000;
state->btn_vol_up = true;
}
break;
case SDLK_DOWN:
if (!state->btn_vol_down)
if (!state->btn_vol_down) {
printf("[input] DOWN VOL_DOWN @emu_usec=%llu\n", (unsigned long long)state->emu_usec);
state->kbd_vol_down_until = state->emu_usec + 150000;
state->btn_vol_down = true;
}
break;
case SDLK_RETURN:
if (!state->btn_power)
@@ -482,7 +771,8 @@ bool sdl_display_poll_events(EmuState *state, uc_engine *uc) {
case SDLK_r: {
if (!ctrl) {
// Plain R: soft reboot. Same path as the config window's "Reboot"
// button — re-prime IRAM payload + WDT cookie, wipe DRAM, reset PC.
// button — reload the payload into IRAM, wipe DRAM, reset PC.
state->reboot_cold = true; // the user's reset is a power cycle
state->reboot_requested = true;
printf("[diag] Reboot requested (R)\n");
} else {
@@ -535,14 +825,8 @@ bool sdl_display_poll_events(EmuState *state, uc_engine *uc) {
if (event.type == SDL_KEYUP) {
switch (event.key.keysym.sym) {
case SDLK_UP:
if (state->btn_vol_up)
printf("[input] UP VOL_UP @emu_usec=%llu\n", (unsigned long long)state->emu_usec);
state->btn_vol_up = false;
break;
case SDLK_DOWN:
if (state->btn_vol_down)
printf("[input] UP VOL_DOWN @emu_usec=%llu\n", (unsigned long long)state->emu_usec);
state->btn_vol_down = false;
// The press ends on its own, 150 ms of guest time after it began.
break;
case SDLK_RETURN:
if (state->btn_power)
+233 -23
View File
@@ -91,47 +91,221 @@ inline bool wifi_radio_parse(const char *s, uint8_t *out) {
return false;
}
// ---- Fault injection ------------------------------------------------------
//
// Named hardware faults, set by `[faults]` in rcm_emu.ini, `--fault NAME` on
// the command line or the config window's Faults section. They are hardware,
// so a payload reboot keeps them. Two kinds:
//
// chip The part is dead. It NAKs its I2C address, takes no writes, and
// every rail it supplies goes down with it.
// rail The regulator answers, takes its enable and reads back as on, but
// its output never comes up: an open inductor, a shorted output cap.
// Nothing visible over I2C; only what the rail feeds notices. This is
// the hard case, and the one a probe that only reads regulator
// registers back cannot catch.
//
// Coherence is the rule: a part is listed only once everything it feeds that
// the emulator models reacts to it. A name with no modelled consequence would
// let a payload "pass" against a fault that cannot fail it, so it is left out
// rather than accepted. DESIGN.md "Fault injection" has what each one does.
//
// Deliberately absent:
// MAX77620 the main PMIC: with it dead nothing would run to test.
// ALC5639 the codec: audio leaves the emulator through I2S whether or not
// the codec answers, so "dead" would be half-modelled.
// GPU / DRAM rails (MAX77621 0x1C output, MAX77812 M1/M3): no consumer is
// modelled. The chips' own death is offered, since all it does
// is NAK.
enum FaultId : uint32_t {
FAULT_MAX77621_CPU = 1u << 0, // Erista CPU buck, I2C5 0x1B; feeds vdd_cpu
FAULT_MAX77621_GPU = 1u << 1, // Erista GPU buck, I2C5 0x1C
FAULT_MAX77812 = 1u << 2, // Mariko CPU/GPU/DRAM buck, I2C5 0x33; feeds vdd_cpu
FAULT_BQ24193 = 1u << 3, // charger, I2C1 0x6B
FAULT_MAX17050 = 1u << 4, // fuel gauge, I2C1 0x36
FAULT_TMP451 = 1u << 5, // thermal sensor, I2C1 0x4C
FAULT_BM92T36 = 1u << 6, // USB-PD controller, I2C1 0x18
FAULT_VDD_CPU = 1u << 7, // the CPU rail's output, whichever buck drives it
};
struct FaultDef {
uint32_t id;
const char *name; // ini key and --fault value
const char *kind; // "chip" or "rail"
const char *what; // one line, for --fault list and the config window
};
inline const FaultDef kFaults[] = {
{FAULT_MAX77621_CPU, "max77621_cpu", "chip",
"Erista CPU buck (I2C5 0x1B): NAKs; vdd_cpu dead with it"},
{FAULT_MAX77621_GPU, "max77621_gpu", "chip",
"Erista GPU buck (I2C5 0x1C): NAKs"},
{FAULT_MAX77812, "max77812", "chip",
"Mariko CPU/GPU/DRAM buck (I2C5 0x33): NAKs; vdd_cpu dead with it"},
{FAULT_BQ24193, "bq24193", "chip", "charger (I2C1 0x6B): NAKs"},
{FAULT_MAX17050, "max17050", "chip", "fuel gauge (I2C1 0x36): NAKs"},
{FAULT_TMP451, "tmp451", "chip", "thermal sensor (I2C1 0x4C): NAKs"},
{FAULT_BM92T36, "bm92t36", "chip", "USB-PD (I2C1 0x18): NAKs"},
{FAULT_VDD_CPU, "vdd_cpu", "rail",
"CPU rail output dead, buck still answers: CPU RAM repair never "
"completes, CPU0 cannot run"},
};
inline const FaultDef *fault_find(const char *name) {
if (!name) return nullptr;
for (const FaultDef &f : kFaults)
if (!strcmp(name, f.name)) return &f;
return nullptr;
}
inline const char *fault_name(uint32_t id) {
for (const FaultDef &f : kFaults)
if (f.id == id) return f.name;
return "?";
}
// Fault value in the ini: dead/1 sets it, ok/0 clears it. Anything else is
// refused so a typo cannot silently mean "healthy".
inline bool fault_value_parse(const char *s, bool *dead) {
if (!s) return false;
if (!strcmp(s, "dead") || !strcmp(s, "1")) { *dead = true; return true; }
if (!strcmp(s, "ok") || !strcmp(s, "0")) { *dead = false; return true; }
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 ADDR_H_OFF = 0x106; // DC_WINBUF_ADDR_H_OFFSET (bytes)
constexpr uint32_t ADDR_V_OFF = 0x108; // DC_WINBUF_ADDR_V_OFFSET (lines)
constexpr uint32_t SURFACE_KIND = 0x10B; // DC_WINBUF_SURFACE_KIND
// WIN_OPTIONS bits.
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).
std::atomic<bool> btn_vol_up{false};
std::atomic<bool> btn_vol_down{false};
std::atomic<bool> btn_power{false};
// A keyboard VOL press ends at this guest time (0: none running). The
// arrow keys press for a fixed guest duration: guest time outruns the
// wall clock while the guest sleeps, so a held key's wall time means
// little to the guest.
std::atomic<uint64_t> kbd_vol_up_until{0};
std::atomic<uint64_t> kbd_vol_down_until{0};
// 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.
std::atomic<uint16_t> tc_x{0};
std::atomic<uint16_t> tc_y{0};
//
// Events queue up rather than overwrite each other: a click shorter than
// the payload's poll interval used to reach it as a bare LEAVE, the
// ENTER lost under it. Single producer (SDL), single consumer (I2C3).
struct TouchEvent { uint8_t op; uint16_t x, y; }; // op 3/4/5 = ENTER/LEAVE/MOTION
static constexpr uint32_t TC_QUEUE = 32;
TouchEvent tc_queue[TC_QUEUE] = {};
std::atomic<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};
std::atomic<bool> tc_event_pending{false};
std::atomic<uint8_t> tc_event_op{0}; // 0x03=ENTER, 0x04=LEAVE, 0x05=MOTION
uint8_t tc_finger_id = 1; // FTS4 finger IDs are 1-indexed
uint8_t tc_finger_id = 0; // raw FTS4 ID; bdk reports it + 1
// Queue a touch event. MOTION is dropped when the queue is nearly full,
// so an ENTER or LEAVE always finds room.
void touch_post(uint8_t op, uint16_t x, uint16_t y) {
uint32_t head = tc_q_head.load(), tail = tc_q_tail.load();
uint32_t used = head - tail;
if (used >= TC_QUEUE || (op == 0x05 && used >= TC_QUEUE - 4))
return;
tc_queue[head % TC_QUEUE] = {op, x, y};
tc_q_head.store(head + 1);
}
bool touch_take(TouchEvent *ev) {
uint32_t tail = tc_q_tail.load();
if (tail == tc_q_head.load())
return false;
*ev = tc_queue[tail % TC_QUEUE];
tc_q_tail.store(tail + 1);
return true;
}
// Framebuffer snapshots asked for by the input script (SNAP), written by
// the display thread from the next frame it shows. CPU thread produces,
// display thread consumes. A spin lock, not std::mutex: the Windows
// build's MinGW uses the win32 thread model, which has none.
std::atomic<bool> snap_busy{false};
std::vector<std::string> snap_paths;
void snap_request(const std::string &path) {
while (snap_busy.exchange(true, std::memory_order_acquire)) {}
snap_paths.push_back(path);
snap_busy.store(false, std::memory_order_release);
}
bool snap_take(std::string *path) {
while (snap_busy.exchange(true, std::memory_order_acquire)) {}
bool got = !snap_paths.empty();
if (got) {
*path = snap_paths.front();
snap_paths.erase(snap_paths.begin());
}
snap_busy.store(false, std::memory_order_release);
return got;
}
// 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;
// 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
// Display head B (DC1, 0x54240000): the head that feeds SOR1 and the
// dock. Same window model as head A, scanned out to the TV window.
uint32_t dcb_win[4][dcwin::kRegs] = {};
uint32_t dcb_win_active[4][dcwin::kRegs] = {};
uint32_t dcb_window_header = 0;
bool dcb_programmed = false;
// 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<bool> display_dirty{false};
std::atomic<bool> display_initialized{false};
int32_t manual_offset = 0;
@@ -141,6 +315,14 @@ struct EmuState {
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;
@@ -254,6 +436,14 @@ struct EmuState {
// SD card insertion (GPIO Port Z bit 1 = 0 means inserted).
std::atomic<bool> sd_inserted{true};
// A PC on the USB-C port (--usb-host): it enumerates whatever gadget the
// payload brings up (t210/usb.cpp). Off, nothing is on the cable.
std::atomic<bool> usb_host{false};
// --usb-host nbd[:port]: instead of reading a mass storage disk back and
// ejecting it, the host serves it over NBD on 127.0.0.1:port until the
// client disconnects. 0: off.
std::atomic<uint16_t> usb_nbd_port{0};
// SD card identity (returned for SDMMC1 CMD2 ALL_SEND_CID).
// Hekate parses these out of the R2 response per bdk/storage/sdmmc.c
// _sd_storage_parse_cid; the I2C handler builds the 16-byte CID payload
@@ -294,6 +484,9 @@ struct EmuState {
// root port 1). See WifiRadioMode above for what each mode models.
std::atomic<uint8_t> wifi_radio{WIFI_RADIO_HEALTHY};
// Dead chips and rails, a FaultId bitmask. See FaultId above.
std::atomic<uint32_t> faults{0};
// 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
@@ -315,6 +508,19 @@ struct EmuState {
// USB-PD controller (BM92T36, I2C1 @ 0x18). One synthesized fixed PDO.
std::atomic<bool> usb_pd_inserted{false};
// The dock on the USB-C port (t210/dock.h DockKind) and whether a TV is
// on its HDMI output. [dock] kind=0 none, 1 Nintendo dock, 2 third-party
// adapter, 3 Nintendo charger; tv=0/1. --dock overrides.
std::atomic<uint8_t> dock_kind{0};
std::atomic<bool> dock_tv{true};
// A clone of the Nintendo dock: 1 (--dock nintendo:clone) answers the
// reads HOS docks with (state 0x16, 0x0B, 0x18) but not the LED or hub
// messages; 2 (nintendo:mute) answers none of the dock's own messages.
std::atomic<uint8_t> dock_clone{0};
// --dock ...:latehpd: the TV's HPD comes 25 s after the DisplayPort
// configuration instead of 150 ms (a VIA Labs adapter, 2109:0103,
// raised it after hwtest's 1.5 s wait; 25 s outlasts any wait).
std::atomic<bool> dock_late_hpd{false};
std::atomic<uint16_t> usb_pd_voltage_mv{5000};
std::atomic<uint16_t> usb_pd_amperage_ma{1500};
@@ -328,6 +534,8 @@ struct EmuState {
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
@@ -435,6 +643,8 @@ struct EmuState {
static constexpr size_t N_UARTS = 5;
std::string uart_tx_log[N_UARTS];
std::deque<uint8_t> uart_rx_fifo[N_UARTS];
// Bytes the emulated PC sends to a USB serial port (USBSER events).
std::deque<uint8_t> usb_serial_rx;
};
#endif // EMU_STATE_H
+139 -5
View File
@@ -12,6 +12,27 @@
// VOL_UP | VOLUP | UP | U
// hold_ms how long to hold the button, default 200 ms.
//
// <when> TAP <x> <y> [hold_ms]
//
// touches the screen at (x, y) in the 1280x720 landscape picture bdk's
// touch driver reports (Nyx's coordinates), and lifts after hold_ms.
//
// <when> USBSER <text>
//
// types text into the USB serial port the PC has open (escapes as UART).
//
// <when> USBSERFILE <file>
//
// sends a file's raw contents through that port, as UARTFILE does on
// UART-B.
//
// <when> SNAP <file>
//
// writes the next frame the display shows to <file>, raw like last_fb.rgba
// (B, G, R, A bytes) with its size in the matching .meta. For screenshots
// at a known point of a run: guest time runs faster than the wall clock,
// so the once-a-second last_fb.rgba cannot be timed from outside.
//
// '#' starts a comment. Example - walk 6 entries down a menu and select:
//
// rcm_emu payload.bin --input-script "3000 D, + D, + D, + D, + D, + D, + P"
@@ -27,6 +48,7 @@
#include "input_script.h"
#include "emu_state.h"
#include <algorithm>
#include <cctype>
#include <cstdio>
#include <cstdlib>
@@ -36,7 +58,7 @@
namespace {
enum class Key { Power, VolUp, VolDown, Uart, UartFile };
enum class Key { Power, VolUp, VolDown, Uart, UartFile, UsbSer, UsbSerFile, Tap, Snap };
struct Event {
uint64_t at_us = 0; // press time
@@ -44,7 +66,8 @@ struct Event {
Key key = Key::Power;
bool pressed = false;
bool released = false;
std::string data; // UART / UARTFILE payload
std::string data; // UART / UARTFILE payload, SNAP file
uint16_t x = 0, y = 0; // TAP: panel-raw coordinates
};
std::vector<Event> g_events;
@@ -60,6 +83,10 @@ const char *key_name(Key k) {
case Key::VolUp: return "VOL+";
case Key::Uart: return "UART";
case Key::UartFile: return "UARTFILE";
case Key::UsbSer: return "USBSER";
case Key::UsbSerFile: return "USBSERFILE";
case Key::Tap: return "TAP";
case Key::Snap: return "SNAP";
default: return "VOL-";
}
}
@@ -80,6 +107,10 @@ bool parse_key(const std::string &tok, Key *out) {
// UARTFILE pushes a file's raw contents, for binary protocol work.
if (s == "UART") { *out = Key::Uart; return true; }
if (s == "UARTFILE") { *out = Key::UartFile; return true; }
if (s == "USBSER") { *out = Key::UsbSer; return true; }
if (s == "USBSERFILE") { *out = Key::UsbSerFile; return true; }
if (s == "TAP" || s == "T") { *out = Key::Tap; return true; }
if (s == "SNAP") { *out = Key::Snap; return true; }
return false;
}
@@ -166,7 +197,8 @@ bool parse_text(const std::string &text) {
return false;
}
if (ev.key == Key::Uart || ev.key == Key::UartFile) {
if (ev.key == Key::Uart || ev.key == Key::UartFile || ev.key == Key::UsbSer ||
ev.key == Key::UsbSerFile || ev.key == Key::Snap) {
// Everything after the keyword is the payload; keep interior spacing.
size_t kpos = raw.find(tok[1]);
std::string rest = (kpos == std::string::npos)
@@ -177,14 +209,30 @@ bool parse_text(const std::string &text) {
while (!rest.empty() && (rest.back() == ' ' || rest.back() == '\t' ||
rest.back() == '\r'))
rest.pop_back();
ev.data = (ev.key == Key::Uart) ? unescape(rest) : rest;
ev.data = (ev.key == Key::Uart || ev.key == Key::UsbSer) ? unescape(rest) : rest;
ev.until_us = ev.at_us; // instantaneous, nothing to release
prev_release_us = ev.at_us;
g_events.push_back(ev);
continue;
}
uint64_t hold_ms = (tok.size() >= 3) ? strtoull(tok[2].c_str(), nullptr, 10)
size_t hold_tok = 2;
if (ev.key == Key::Tap) {
if (tok.size() < 4) {
fprintf(stderr, "[input-script] entry %d: expected '<when> TAP <x> <y> [hold_ms]'\n",
lineno);
return false;
}
// bdk's touch.c clamps raw samples to 15..1264 and 15..704 and
// stretches that span over 1280x720; invert it.
uint32_t x = std::min<uint32_t>(strtoul(tok[2].c_str(), nullptr, 10), 1279);
uint32_t y = std::min<uint32_t>(strtoul(tok[3].c_str(), nullptr, 10), 719);
ev.x = (uint16_t)(15 + (x * (1264 - 15) + 1279) / 1280);
ev.y = (uint16_t)(15 + (y * (704 - 15) + 719) / 720);
hold_tok = 4;
}
uint64_t hold_ms = (tok.size() > hold_tok)
? strtoull(tok[hold_tok].c_str(), nullptr, 10)
: kDefaultHoldMs;
if (hold_ms == 0) hold_ms = kDefaultHoldMs;
ev.until_us = ev.at_us + hold_ms * 1000ULL;
@@ -236,9 +284,58 @@ void input_script_tick(EmuState &state) {
// Events are ordered by press time; stop at the first future one.
if (!ev.pressed && now < ev.at_us) break;
// SNAP is one-shot too: hand the file name to the display thread.
if (ev.key == Key::Snap) {
if (now < ev.at_us)
break;
state.snap_request(ev.data);
ev.pressed = ev.released = true;
printf("[input-script] SNAP %s @%llu us (%zu/%zu)\n", ev.data.c_str(),
(unsigned long long)now, i + 1, g_events.size());
fflush(stdout);
if (i == g_done) {
g_done++;
if (g_done == g_events.size())
printf("[input-script] sequence complete\n");
}
continue;
}
// UART events are one-shot: push the bytes into UART_B's receive FIFO
// (index 1 = UART_B, the port payloads use for their debug console) and
// retire the event immediately.
if (ev.key == Key::UsbSer || ev.key == Key::UsbSerFile) {
if (now >= ev.at_us && !ev.pressed) {
std::string bytes = ev.data;
if (ev.key == Key::UsbSerFile) {
// A file's raw contents, for sending a file to the payload.
bytes.clear();
if (FILE *f = fopen(ev.data.c_str(), "rb")) {
char buf[4096];
size_t n;
while ((n = fread(buf, 1, sizeof(buf), f)) > 0)
bytes.append(buf, n);
fclose(f);
} else {
fprintf(stderr, "[input-script] cannot open USBSERFILE '%s'\n",
ev.data.c_str());
}
}
for (unsigned char ch : bytes)
state.usb_serial_rx.push_back(ch);
ev.pressed = ev.released = true;
printf("[input-script] USB serial <- %zu byte(s) @%llu us (%zu/%zu)\n",
bytes.size(), (unsigned long long)now, i + 1, g_events.size());
fflush(stdout);
if (i == g_done) {
g_done++;
if (g_done == g_events.size())
printf("[input-script] sequence complete\n");
}
continue;
}
break;
}
if (ev.key == Key::Uart || ev.key == Key::UartFile) {
if (now >= ev.at_us && !ev.pressed) {
std::string bytes = ev.data;
@@ -271,6 +368,30 @@ void input_script_tick(EmuState &state) {
break;
}
if (ev.key == Key::Tap) {
if (!ev.pressed && now >= ev.at_us) {
state.tc_pressed.store(true);
state.touch_post(0x03, ev.x, ev.y); // FTS4 ENTER
ev.pressed = true;
printf("[input-script] TAP down panel=(%u,%u) @%llu us (%zu/%zu)\n",
ev.x, ev.y, (unsigned long long)now, i + 1, g_events.size());
fflush(stdout);
break;
}
if (ev.pressed && !ev.released && now >= ev.until_us) {
state.tc_pressed.store(false);
state.touch_post(0x04, ev.x, ev.y); // FTS4 LEAVE
ev.released = true;
if (i == g_done) {
g_done++;
if (g_done == g_events.size())
printf("[input-script] sequence complete\n");
}
}
if (!ev.released) break;
continue;
}
std::atomic<bool> *btn = (ev.key == Key::Power) ? &state.btn_power
: (ev.key == Key::VolUp) ? &state.btn_vol_up
: &state.btn_vol_down;
@@ -280,6 +401,10 @@ void input_script_tick(EmuState &state) {
printf("[input-script] %s down @%llu us (%zu/%zu)\n", key_name(ev.key),
(unsigned long long)now, i + 1, g_events.size());
fflush(stdout);
// Even if the release is already due - a FLOW_CTLR sleep can jump the
// clock past it within one batch - the payload has to run with the
// button down at least once, or it never sees the press.
break;
}
if (ev.pressed && !ev.released && now >= ev.until_us) {
btn->store(false);
@@ -293,3 +418,12 @@ void input_script_tick(EmuState &state) {
if (!ev.released) break; // keep this event current until it's let go
}
}
void input_script_restart(EmuState &state) {
for (Event &ev : g_events)
ev.pressed = ev.released = false;
g_done = 0;
state.btn_power = false;
state.btn_vol_up = false;
state.btn_vol_down = false;
}
+4
View File
@@ -23,3 +23,7 @@ bool input_script_active();
// Apply any events that are due at the current state.emu_usec. Call once per
// emulator loop iteration; cheap no-op when no script is loaded.
void input_script_tick(EmuState &state);
// Soft reboot: the emulated clock starts again from 0, so every event is
// re-armed and any button the script was holding is let go.
void input_script_restart(EmuState &state);
+122
View File
@@ -0,0 +1,122 @@
/*
* BPMP side of booting a Linux kernel on the emulator's CPU0.
*
* run.sh has the emulator place the kernel Image at 0x80080000 and the
* device tree at 0x83000000 (--load), as a bootloader would have. This
* payload powers CPU0 the way bdk's ccplex_boot_cpu0() does (Erista rail),
* releases it at shim.S - which drops to EL1 and enters the kernel - and
* then halts the BPMP for good, so every emulated cycle goes to CPU0.
*/
typedef unsigned int u32;
#define REG(a) (*(volatile u32 *)(a))
#define TIMERUS 0x60005010u
#define CAR 0x60006000u
#define FLOW 0x60007000u
#define SB 0x6000C200u
#define UARTB_THR 0x70006040u
#define PMC 0x7000E400u
#define I2C5 0x7000D000u
#define CPU_ENTRY 0xA0000000u
#define KERNEL 0x80080000u
static void putc_(char c) { REG(UARTB_THR) = (u32)(unsigned char)c; }
static void puts_(const char *s) {
while (*s)
putc_(*s++);
}
static void puthex(u32 v) {
for (int i = 28; i >= 0; i -= 4)
putc_("0123456789ABCDEF"[(v >> i) & 0xF]);
}
static void udelay(u32 us) {
u32 start = REG(TIMERUS);
while (REG(TIMERUS) - start < us)
;
}
/* bdk-style normal-mode I2C write: [reg, val] in CMD_DATA1, 2 bytes, GO. */
static void i2c5_write(u32 dev, u32 reg, u32 val) {
REG(I2C5 + 0x04) = dev << 1; /* CMD_ADDR0 */
REG(I2C5 + 0x0C) = reg | (val << 8); /* CMD_DATA1 */
REG(I2C5 + 0x00) = (1u << 1) | (1u << 9); /* CNFG: 2 bytes, write, GO */
}
static void pwrgate_on(u32 part) {
if (!(REG(PMC + 0x38) & (1u << part))) /* PWRGATE_STATUS */
REG(PMC + 0x30) = part | (1u << 8); /* PWRGATE_TOGGLE */
}
#define RST_CPU0 ((1u << 30) | (1u << 24) | (1u << 16) | (1u << 0))
#define RST_NONCPU (1u << 29)
static void release_cpu0(void) {
REG(SB + 0x30) = CPU_ENTRY | 1u; /* SB_AA64_RESET_LOW */
REG(SB + 0x34) = 0; /* SB_AA64_RESET_HIGH */
REG(CAR + 0x454) = RST_NONCPU; /* RST_CPUG_CMPLX_CLR */
REG(CAR + 0x454) = RST_CPU0;
}
static void hold_cpu0(void) {
REG(CAR + 0x450) = RST_CPU0; /* RST_CPUG_CMPLX_SET */
REG(CAR + 0x450) = RST_NONCPU;
}
#include "shim_blob.h"
__attribute__((section(".text.start"), noreturn))
void _start(void) {
puts_("linux boot: kernel header ");
puthex(((volatile u32 *)KERNEL)[14]); /* 'ARM\x64' at offset 0x38 */
putc_('\n');
for (u32 i = 0; i < sizeof(shim_blob) / sizeof(shim_blob[0]); i++)
((volatile u32 *)CPU_ENTRY)[i] = shim_blob[i];
/* The clocks a bootloader has set before any OS runs: bdk hw_init()'s
* _config_oscillators(), as hekate leaves them for switchroot's chain.
* The kernel's super-clock code BUG()s on a burst policy still in
* STANDBY, which is what these registers hold until someone writes
* them. */
REG(CAR + 0x55C) = (REG(CAR + 0x55C) & 0xFFFFFFF3) | 4; /* CLK_M divisor 2 */
REG(0x700F0000 + 0x20) = 19200000; /* SYSCTR0_CNTFID0 */
REG(0x60005014) = 0x45F; /* TIMERUS_USEC_CFG, 19.2 MHz */
REG(CAR + 0x050) = 0x50000071; /* OSC_CTRL: 38.4 MHz */
REG(CAR + 0x030) = 0x10; /* CLK_SYSTEM_RATE */
REG(CAR + 0x400) = 0; /* CLK_SOURCE_SYS */
REG(CAR + 0x028) = 0x20004444; /* SCLK_BURST_POLICY: run, PLLP_OUT2 */
REG(CAR + 0x02C) = 0x80000000; /* SUPER_SCLK_DIVIDER */
REG(CAR + 0x030) = 2; /* HCLK /1, PCLK /3 */
REG(CAR + 0x370) = 0x20000000; /* CCLKLP_BURST_POLICY: run, clk_m */
i2c5_write(0x3C, 0x40, 0x1C); /* MAX77620 AME_GPIO: GPIO5 plain */
i2c5_write(0x3C, 0x3B, 0x09); /* GPIO5: push-pull, out high */
i2c5_write(0x1B, 0x00, 0x80 | 55); /* MAX77621 VOUT: on, 0.950 V */
REG(CAR + 0x0E0) = (1u << 30) | (2u << 20) | (156u << 8) | 2u; /* PLLX */
REG(CAR + 0x3B4) = 4u << 1; /* CLK_SOURCE_MSELECT */
REG(CAR + 0x440) = 1u << 3; /* CLK_ENB_V_SET: MSELECT */
REG(CAR + 0x020) = 0x20008888; /* CCLK_BURST: PLLX_OUT0_LJ */
REG(CAR + 0x024) = 1u << 31; /* SUPER_CCLK_DIVIDER */
REG(CAR + 0x440) = 1u << 0; /* CLK_ENB_V_SET: CPUG */
pwrgate_on(0); /* CRAIL */
pwrgate_on(15); /* C0NC */
pwrgate_on(14); /* CE0 */
REG(FLOW + 0x40) = 1; /* RAM_REPAIR_REQ */
while (!(REG(FLOW + 0x40) & 2))
;
REG(CAR + 0x434) = 1u << 3; /* RST_DEV_V_CLR: MSELECT */
release_cpu0();
puts_("linux boot: CPU0 released, BPMP halting\n");
/* bdk's bpmp_halt(): WAITEVENT | JTAG, no wake source. */
REG(FLOW + 0x04) = (2u << 29) | (1u << 28);
for (;;)
;
}
Executable
+33
View File
@@ -0,0 +1,33 @@
#!/bin/sh
# Builds linux/boot.bin: shim.S (an AArch64 assembler) embedded in the BPMP payload.
set -e
D=$(dirname "$0")
# devkitPro when it is installed, else the distribution's cross compilers
# (gcc-aarch64-linux-gnu, gcc-arm-none-eabi), as on CI.
DKP=${DEVKITPRO:-/opt/devkitpro}
if [ -z "$A64" ]; then
A64=aarch64-linux-gnu-
if [ -x "$DKP/devkitA64/bin/aarch64-none-elf-gcc" ]; then A64=$DKP/devkitA64/bin/aarch64-none-elf-; fi
fi
if [ -z "$ARM" ]; then
ARM=arm-none-eabi-
if [ -x "$DKP/devkitARM/bin/arm-none-eabi-gcc" ]; then ARM=$DKP/devkitARM/bin/arm-none-eabi-; fi
fi
${A64}gcc -c -o "$D/shim.o" "$D/shim.S"
${A64}ld -Ttext=0xA0000000 -o "$D/shim.elf" "$D/shim.o"
${A64}objcopy -O binary "$D/shim.elf" "$D/shim.bin"
python3 - "$D/shim.bin" "$D/shim_blob.h" <<'PY'
import sys, struct
b = open(sys.argv[1], "rb").read()
b += b"\0" * (-len(b) % 4)
w = struct.unpack("<%dI" % (len(b) // 4), b)
with open(sys.argv[2], "w") as f:
f.write("/* Generated by build.sh from shim.S. */\nstatic const u32 shim_blob[] = {\n")
for i in range(0, len(w), 6):
f.write(" " + ", ".join("0x%08x" % x for x in w[i:i + 6]) + ",\n")
f.write("};\n")
PY
${ARM}gcc -march=armv4t -marm -Os -ffreestanding -nostdlib -fno-builtin -I"$D" \
-T "$D/link.ld" -o "$D/boot.elf" "$D/boot.c"
${ARM}objcopy -O binary "$D/boot.elf" "$D/boot.bin"
echo "built $D/boot.bin"
+10
View File
@@ -0,0 +1,10 @@
/* Loaded and entered at 0x40010000, like any RCM payload. */
ENTRY(_start)
SECTIONS {
. = 0x40010000;
.text : { KEEP(*(.text.start)) *(.text*) }
.rodata : { *(.rodata*) }
.data : { *(.data*) }
.bss : { *(.bss*) *(COMMON) }
/DISCARD/ : { *(.comment) *(.note*) *(.ARM.attributes) *(.ARM.exidx*) }
}
Executable
+23
View File
@@ -0,0 +1,23 @@
#!/bin/sh
# linux/mkdtb.sh IN.dtb OUT.dtb - the switchroot device tree with what the
# emulator boot needs: a console on UART-B (the port the emulator prints),
# kept past init, one CPU, verbose logging. The bootloader normally edits
# bootargs the same way; nothing else changes.
set -e
DTC=${DTC:-$HOME/l4t/kernel/kernel-4.9/scripts/dtc/dtc}
IN=$1; OUT=$2
T=$(mktemp -d)
"$DTC" -I dtb -O dts -q -o "$T/in.dts" "$IN"
ARGS=${BOOTARGS:-"earlycon=uart8250,mmio32,0x70006040 keep_bootcon console=tty0 maxcpus=1 nosmp loglevel=8 ignore_loglevel clk_ignore_unused printk.time=1"}
python3 - "$T/in.dts" "$T/out.dts" "$ARGS" <<'PY'
import re, sys
s = open(sys.argv[1]).read()
args = sys.argv[3]
s, n = re.subn(r'(\n\tchosen \{[^}]*?bootargs = )"[^"]*";', lambda m: m.group(1) + '"' + args + '";', s, count=1)
if n != 1:
raise SystemExit("no /chosen bootargs found")
open(sys.argv[2], "w").write(s)
PY
"$DTC" -I dts -O dtb -q -o "$OUT" "$T/out.dts"
rm -rf "$T"
echo "built $OUT"
Executable
+22
View File
@@ -0,0 +1,22 @@
#!/bin/sh
# linux/run.sh IMAGE DTB [LOG] [SECS] [extra rcm_emu args...]
#
# Boots a Linux kernel (an arm64 Image, e.g. switchroot's L4T 4.9) on the
# emulator's CPU0: the emulator places the Image at 0x80080000 and the
# device tree at 0x83000000, linux/boot.bin powers CPU0 and hands over at
# EL1 through linux/shim.S. Run linux/mkdtb.sh on the device tree first so
# it carries an earlycon on UART-B, which the emulator prints.
#
# Needs an emulator built against Unicorn 2.1 or later (make UNICORN_DIR=...).
set -e
D=$(cd "$(dirname "$0")" && pwd)
E=$(cd "$D/.." && pwd)
IMAGE=$1; DTB=$2; LOG=${3:-$D/boot.log}; SECS=${4:-600}
shift 4 2>/dev/null || shift $#
export PATH=/opt/devkitpro/devkitARM/bin:/opt/devkitpro/devkitA64/bin:$PATH
[ -f "$D/boot.bin" ] || sh "$D/build.sh"
cd "$E"
SDL_VIDEODRIVER=${SDL_VIDEODRIVER:-dummy} RCM_EMU_NO_AUDIO=1 timeout "$SECS" \
./rcm_emu "$D/boot.bin" --oem erista \
--load "$IMAGE@0x80080000" --load "$DTB@0x83000000" "$@" > "$LOG" 2>&1 || true
echo "log: $LOG ($(grep -a -c '\[uartB\]' "$LOG") kernel lines)"
+38
View File
@@ -0,0 +1,38 @@
/*
* The hand-over a kernel expects from its bootloader, as switchroot's chain
* (hekate, ATF, U-Boot) leaves it: AArch64 EL1h, non-secure, MMU and caches
* off, x0 = the device tree, x1..x3 = 0 (Documentation/arm64/booting.txt).
*
* CPU0 enters here at EL3. EL2 is configured so EL1 runs AArch64 with the
* timers and FP/SIMD untrapped, then one ERET lands in the kernel at EL1.
* PSCI calls the kernel makes over SMC are answered by the emulator, which
* plays the secure monitor.
*/
.equ KERNEL, 0x80080000
.equ DTB, 0x83000000
.text
.global _start
_start:
mov x0, #0x431 /* SCR_EL3: RW, RES1, NS */
msr scr_el3, x0
msr cptr_el3, xzr /* FP/SIMD not trapped to EL3 */
mov x0, #0x33FF
msr cptr_el2, x0 /* RES1 bits, nothing trapped to EL2 */
mov x0, #(1 << 31) /* HCR_EL2.RW: EL1 is AArch64 */
msr hcr_el2, x0
mov x0, #3 /* EL1 may use the physical timer */
msr cnthctl_el2, x0
msr cntvoff_el2, xzr
ldr x0, =0x30C50830 /* SCTLR_EL1: RES1, MMU and caches off */
msr sctlr_el1, x0
mov x0, #0x3C5 /* EL1h, DAIF masked */
msr spsr_el3, x0
ldr x0, =KERNEL
msr elr_el3, x0
ldr x0, =DTB
mov x1, xzr
mov x2, xzr
mov x3, xzr
eret
.ltorg
+322 -120
View File
@@ -22,9 +22,12 @@
#include <unicorn/unicorn.h>
#include "emu_state.h"
#include <string>
#include "platform.h"
#include "payload_picker.h"
#include "trace.h"
#include "t210/bpmp.h"
#include "t210/ccplex.h"
#include "t210/dock.h"
#include "t210/memory_map.h"
#include "t210/mmio.h"
#include "display/sdl_display.h"
@@ -32,18 +35,48 @@
#include "display/console_window.h"
#include "input_script.h"
// Low 16 MB of the map (NULL-pointer writes land there); freed at exit.
static uint8_t *g_low_ptr = nullptr;
// Scripted-navigation progress (--auto-pin-recovery, --auto-te-script). A
// soft reboot restarts both, as it restarts the emulated clock they run on.
struct AutoScripts {
int pin_stage = 0;
uint64_t pin_t = 0;
int pin_logged_stage = -1;
size_t te_idx = 0;
};
static AutoScripts g_auto;
// The IPL framebuffer starts out in hekate's background colour (0x1B1B1B),
// at power-on and again after a reboot has handed DRAM back zeroed.
static void fill_fb_background(EmuState *state) {
for (size_t i = 0; i < FB_SIZE; i += 4) {
state->fb_ptr[i + 0] = 0x1B; // B
state->fb_ptr[i + 1] = 0x1B; // G
state->fb_ptr[i + 2] = 0x1B; // R
state->fb_ptr[i + 3] = 0xFF; // A
}
}
// ==================== Payload Loading ====================
static uint8_t *load_payload(const char *path, size_t *out_size) {
FILE *f = fopen(path, "rb");
FILE *f = platform_fopen(path, "rb");
if (!f) {
fprintf(stderr, "[error] Cannot open payload: %s\n", path);
return nullptr;
}
fseek(f, 0, SEEK_END);
size_t size = ftell(f);
fseek(f, 0, SEEK_SET);
long len = -1;
if (fseek(f, 0, SEEK_END) == 0)
len = ftell(f);
if (len <= 0 || fseek(f, 0, SEEK_SET) != 0) {
fclose(f);
fprintf(stderr, "[error] Payload is empty or unreadable: %s\n", path);
return nullptr;
}
size_t size = (size_t)len;
uint8_t *buf = (uint8_t *)malloc(size);
if (!buf) {
@@ -83,42 +116,6 @@ static uint8_t *load_payload(const char *path, size_t *out_size) {
// ==================== Emulation Setup ====================
// Global for instruction tracing
static uint32_t pc_trace[2000];
static size_t pc_trace_idx = 0;
static uint32_t last_valid_block = 0;
static uc_hook trace_h, block_h;
static void trace_callback(uc_engine *uc, uint64_t address, uint32_t size, void *user_data) {
static uint32_t last_pc = 0;
if (address == last_pc) return;
last_pc = (uint32_t)address;
pc_trace[pc_trace_idx] = (uint32_t)address;
pc_trace_idx = (pc_trace_idx + 1) % 2000;
// NOP-slide detection
if (address >= 0x40030000 && address < 0x41000000) {
uint16_t insn = 0;
if (uc_mem_read(uc, address, &insn, 2) == UC_ERR_OK && insn == 0) {
static int nop_count = 0;
if (++nop_count > 10) {
printf("\n[emu] NOP-slide detected at 0x%08llX! Last valid block: 0x%08X\n",
(unsigned long long)address, last_valid_block);
uc_emu_stop(uc);
}
} else {
// nop_count = 0; // would need a persistent counter
}
}
}
static void block_callback(uc_engine *uc, uint64_t address, uint32_t size, void *user_data) {
if (address >= 0x40000000 && address < 0x40030000) {
last_valid_block = (uint32_t)address;
}
}
static uc_engine *setup_emulation(EmuState *state, uint8_t *payload, size_t payload_size) {
uc_engine *uc;
uc_err err;
@@ -131,9 +128,12 @@ static uc_engine *setup_emulation(EmuState *state, uint8_t *payload, size_t payl
}
state->uc = uc;
// Setup hooks
uc_hook_add(uc, &trace_h, UC_HOOK_CODE, (void*)trace_callback, nullptr, 1, 0);
uc_hook_add(uc, &block_h, UC_HOOK_BLOCK, (void*)block_callback, nullptr, 1, 0);
// No UC_HOOK_CODE anywhere: a per-instruction callback keeps Unicorn off
// its fast path for every block it covers. This used to register three
// of them (one of them twice) - an instruction-trace ring buffer nothing
// read, a NOP-slide check that did a uc_mem_read per instruction, and
// the clock. The clock and the NOP-slide check now run once per block
// (t210/bpmp.cpp).
// Enable VFP/NEON
uint32_t cpacr = 0x00F00000;
@@ -152,24 +152,6 @@ static uc_engine *setup_emulation(EmuState *state, uint8_t *payload, size_t payl
(unsigned long long)(IRAM_BASE + IRAM_SIZE),
(unsigned)(IRAM_SIZE / 1024));
uc_mem_write(uc, IPL_LOAD_ADDR, payload, payload_size);
// Pre-set Hekate's "watchdog fired" magic at IRAM 0x4003FF18 (cookie "WDT")
// so its early boot does `goto skip_lp0_minerva_config`, skipping both
// libsys_lp0.bso and the Minerva DRAM-training path. The matching
// 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));
}
// Setup instruction tracing
uc_hook_add(uc, &trace_h, UC_HOOK_CODE, (void*)trace_callback, nullptr, 1, 0);
// ---- Map DRAM as one contiguous region ----
// 0x80000000 .. 0x100000000, i.e. the whole 32-bit-addressable DRAM window
// the BPMP can reach. This used to be two islands (256 MB at 0x80000000
@@ -179,18 +161,19 @@ static uc_engine *setup_emulation(EmuState *state, uint8_t *payload, size_t payl
// through. One contiguous block removes the hole and matches what real
// hardware presents.
//
// Allocated host-side (calloc, so pages are lazily committed - the full
// 2 GB is only ever resident if a payload actually touches all of it) and
// kept as a host pointer so soft reboot can memset() it: Nyx loads here
// and its file-static SD/eMMC caches would otherwise survive a reboot.
err = uc_mem_map_ptr(uc, DRAM_BASE, DRAM_WINDOW_SIZE, UC_PROT_ALL,
(state->dram_low_ptr = (uint8_t *)calloc(1, DRAM_WINDOW_SIZE)));
// Allocated host-side as demand-zero pages (zeroed_alloc), so the full
// 2 GB is only ever resident if a payload actually touches all of it, and
// kept as a host pointer so a soft reboot can hand it back zeroed: Nyx
// loads here and its file-static SD/eMMC caches would otherwise survive.
state->dram_low_ptr = zeroed_alloc(DRAM_WINDOW_SIZE);
if (!state->dram_low_ptr) {
fprintf(stderr, "[error] Failed to allocate %zu MB DRAM host buffer\n",
(size_t)(DRAM_WINDOW_SIZE / (1024 * 1024)));
uc_close(uc);
return nullptr;
}
err = uc_mem_map_ptr(uc, DRAM_BASE, DRAM_WINDOW_SIZE, UC_PROT_ALL,
state->dram_low_ptr);
if (err != UC_ERR_OK) {
fprintf(stderr, "[error] Failed to map DRAM: %s\n", uc_strerror(err));
uc_close(uc);
@@ -208,14 +191,7 @@ static uc_engine *setup_emulation(EmuState *state, uint8_t *payload, size_t payl
// ---- Map Framebuffer pointer ----
state->fb_ptr = state->dram_low_ptr + (FB_BASE - DRAM_BASE);
// Fill with hekate background color (0x1B1B1B)
for (size_t i = 0; i < FB_SIZE; i += 4) {
state->fb_ptr[i + 0] = 0x1B; // B
state->fb_ptr[i + 1] = 0x1B; // G
state->fb_ptr[i + 2] = 0x1B; // R
state->fb_ptr[i + 3] = 0xFF; // A
}
state->fb_addr = FB_BASE;
fill_fb_background(state);
printf("[emu] Defined FB: 0x%08llX - 0x%08llX (%u MB)\n",
(unsigned long long)FB_BASE,
(unsigned long long)(FB_BASE + FB_SIZE),
@@ -223,28 +199,34 @@ static uc_engine *setup_emulation(EmuState *state, uint8_t *payload, size_t payl
// ---- Map low memory (16MB @ 0x0) ----
// hekate seems to do a memset(0, ...) for clear screen if some ptr is NULL.
uint8_t *low_ptr = (uint8_t *)calloc(1, 0x01000000);
uc_mem_map_ptr(uc, 0, 0x01000000, UC_PROT_ALL, low_ptr);
// This covers the iROM range (0x100000, 96 KB) too, as zero-filled RAM:
// there are no BootROM contents to show, and Hekate's "Bootrom Info" /
// "Dump Bootrom" read it without faulting. (A read-only iROM map on top
// of this used to be attempted as well; it overlapped, so it always
// failed, unnoticed - and a read-only iROM would fault the NULL-pointer
// clear above.)
g_low_ptr = (uint8_t *)calloc(1, 0x01000000);
err = g_low_ptr ? uc_mem_map_ptr(uc, 0, 0x01000000, UC_PROT_ALL, g_low_ptr)
: UC_ERR_NOMEM;
if (err != UC_ERR_OK) {
fprintf(stderr, "[error] Failed to map low memory: %s\n", uc_strerror(err));
uc_close(uc);
return nullptr;
}
// ---- Nyx Storage (16MB @ 0xED000000) ----
// Already mapped as part of 2GB DRAM chunk
// ---- Map Peripherals (PWM, SDMMC, etc.) ----
// Map individual pages to allow MMIO hooks
// The mappings previously declared manually were moved here:
// Some are mapped earlier in setup_emulation properly using FB_BASE e.g.
uc_mem_map(uc, 0x7000A000, 0x1000, UC_PROT_ALL); // PWM
uc_mem_map(uc, 0x700B0000, 0x1000, UC_PROT_ALL); // SDMMC1
uc_mem_map(uc, 0x7000E000, 0x1000, UC_PROT_ALL); // RTC/PMC
uc_mem_map(uc, 0x6000C000, 0x2000, UC_PROT_ALL); // SYSREG/APB_SEMAPH
// Peripherals are all mapped by mmio_init() below as MMIO windows. PWM,
// SDMMC1, RTC/PMC and SYSREG used to be mapped here first as plain RAM,
// which only worked because MMIO was a pair of address-range hooks over
// whatever happened to be mapped.
// BootROM (iROM) at 0x100000, 96 KB. We don't have the real BootROM
// contents, but mapping the region as zero-filled lets Hekate's "Bootrom
// Info" / "Dump Bootrom" features read it without faulting. The IPATCH
// CAM at 0x6001DC00 is also zero-mapped so the ipatches table renders
// empty (which matches an unpatched SoC).
uc_mem_map(uc, 0x00100000, 0x18000, UC_PROT_READ | UC_PROT_EXEC); // iROM
uc_mem_map(uc, 0x6001D000, 0x1000, UC_PROT_ALL); // IPATCH CAM page
// The IPATCH CAM at 0x6001DC00 is zero-mapped so the ipatches table
// renders empty (which matches an unpatched SoC).
err = uc_mem_map(uc, 0x6001D000, 0x1000, UC_PROT_ALL);
if (err != UC_ERR_OK)
fprintf(stderr, "[warn] IPATCH page not mapped: %s\n", uc_strerror(err));
// ---- heap region (32MB @ 0x90000000) ----
// Already mapped as part of 2GB DRAM chunk
@@ -267,9 +249,10 @@ static uc_engine *setup_emulation(EmuState *state, uint8_t *payload, size_t payl
printf("[emu] Initial PC=0x%08X SP=0x%08X\n", pc, sp);
// ---- Setup MMIO hooks ----
// ---- Peripherals and the deterministic clock ----
mmio_init(uc, state);
printf("[emu] MMIO hooks registered\n");
bpmp_attach(uc, state);
printf("[emu] MMIO windows mapped\n");
return uc;
}
@@ -286,6 +269,16 @@ int main(int argc, char *argv[]) {
if (strcmp(argv[i], "--trace") == 0)
emu_trace_enabled = true;
// "--fault list" names the faults and exits. Scanned here, like --trace,
// so it works without a payload: it is how you find the names to use.
for (int i = 1; i + 1 < argc; i++)
if (strcmp(argv[i], "--fault") == 0 && strcmp(argv[i + 1], "list") == 0) {
printf("Faults (--fault NAME, or NAME=dead under [faults] in rcm_emu.ini):\n");
for (const FaultDef &f : kFaults)
printf(" %-13s %-4s %s\n", f.name, f.kind, f.what);
return 0;
}
// Started with no payload - usually a double-click, where a usage line
// on stderr goes to a console nobody is looking at. Offer the picker
// instead: drop a file on its window, or press O for the system dialog.
@@ -295,7 +288,7 @@ int main(int argc, char *argv[]) {
if (argc < 2) {
picked = payload_picker_run();
if (picked.empty()) {
fprintf(stderr, "Usage: %s <payload.bin> [--sd <sd.img>] [--boot0 <boot0.bin>] [--rawnand <rawnand_prefix>] [--prod-keys <prod.keys>] [--oem erista|mariko] [--bt-radio healthy|faulty|absent] [--wifi-radio healthy|faulty|absent]\n", argv[0]);
fprintf(stderr, "Usage: %s <payload.bin> [--sd <sd.img>] [--boot0 <boot0.bin>] [--rawnand <rawnand_prefix>] [--prod-keys <prod.keys>] [--oem erista|mariko] [--bt-radio healthy|faulty|absent] [--wifi-radio healthy|faulty|absent] [--fault NAME[,NAME]|list]\n", argv[0]);
fprintf(stderr, "\nControls:\n");
fprintf(stderr, " Arrow Up/Down = VOL+/VOL- buttons\n");
fprintf(stderr, " Enter = POWER button\n");
@@ -348,6 +341,29 @@ int main(int argc, char *argv[]) {
rawnand_prefix = argv[++i];
} else if (strcmp(argv[i], "--prod-keys") == 0 && i + 1 < argc) {
prod_keys_path = argv[++i];
} else if (strcmp(argv[i], "--dock") == 0 && i + 1 < argc) {
// What is on the USB-C port. Same contract as --oem: overrides
// the ini. "nintendo", "thirdparty" (Ugreen-style), "charger",
// "none"; append ":notv" for a dock with nothing on its HDMI,
// ":clone" for one that answers the reads HOS docks with but
// not the LED or hub messages, ":mute" for one that answers
// none of the Nintendo dock's own messages, ":latehpd" for a
// TV whose HPD comes 25 s after DisplayPort is configured.
const char *d = argv[++i];
uint8_t k = 0xFF;
if (!strncmp(d, "nintendo", 8)) k = 1;
else if (!strncmp(d, "thirdparty", 10) || !strncmp(d, "ugreen", 6)) k = 2;
else if (!strncmp(d, "charger", 7)) k = 3;
else if (!strncmp(d, "none", 4)) k = 0;
if (k == 0xFF) {
fprintf(stderr, "[emu] Unknown --dock '%s'; expected nintendo, thirdparty, charger or none\n", d);
return 1;
}
state.dock_kind = k;
state.dock_tv = strstr(d, ":notv") == nullptr;
state.dock_clone = strstr(d, ":mute") ? 2 : strstr(d, ":clone") ? 1 : 0;
state.dock_late_hpd = strstr(d, ":latehpd") != nullptr;
printf("[emu] Dock: %s%s [overrides ini]\n", d, "");
} else if (strcmp(argv[i], "--oem") == 0 && i + 1 < argc) {
const char *oem = argv[++i];
if (strcmp(oem, "mariko") == 0 || strcmp(oem, "t210b01") == 0) {
@@ -374,6 +390,49 @@ int main(int argc, char *argv[]) {
fprintf(stderr, "[emu] Unknown --bt-radio value '%s'; expected"
" 'healthy', 'faulty' or 'absent'\n", mode);
}
} else if (strcmp(argv[i], "--usb-host") == 0) {
// A PC on the USB-C port: it enumerates whatever gadget the
// payload brings up and, for mass storage, reads it back - or,
// given "nbd[:port]", serves the disk over NBD.
state.usb_host = true;
if (i + 1 < argc && strncmp(argv[i + 1], "nbd", 3) == 0 &&
(argv[i + 1][3] == 0 || argv[i + 1][3] == ':')) {
const char *arg = argv[++i];
unsigned long port = 10809; // the NBD port
char *end = nullptr;
if (arg[3] == ':')
port = strtoul(arg + 4, &end, 10);
if (port == 0 || port > 65535 || (end && *end)) {
fprintf(stderr, "[emu] Bad --usb-host value '%s'; expected"
" nbd or nbd:<port>\n", arg);
port = 10809;
}
state.usb_nbd_port = (uint16_t)port;
printf("[emu] USB host connected, serving mass storage over"
" NBD on port %lu [overrides ini]\n", port);
} else {
state.usb_nbd_port = 0;
printf("[emu] USB host connected [overrides ini]\n");
}
} else if (strcmp(argv[i], "--fault") == 0 && i + 1 < argc) {
// Kill a chip or a rail. Repeatable, and comma lists work too.
// Adds to whatever the ini set: a fault is a one-shot override
// the same way --oem is, so the same payload+ini can be re-run
// against broken hardware. ("--fault list" is handled at the top
// of main, before a payload is needed.)
const char *arg = argv[++i];
char buf[256];
snprintf(buf, sizeof(buf), "%s", arg);
for (char *tok = strtok(buf, ","); tok; tok = strtok(nullptr, ",")) {
if (const FaultDef *f = fault_find(tok)) {
state.faults |= f->id;
} else {
fprintf(stderr, "[emu] Unknown --fault '%s'; expected one of:", tok);
for (const FaultDef &d : kFaults)
fprintf(stderr, " %s", d.name);
fprintf(stderr, " (or 'list')\n");
}
}
} else if (strcmp(argv[i], "--wifi-radio") == 0 && i + 1 < argc) {
// WLAN half of the same package, on PCIe. 'faulty' means
// something different here from the Bluetooth side: the link
@@ -392,6 +451,12 @@ int main(int argc, char *argv[]) {
}
}
// Say which hardware is broken before anything runs, so a capture can
// never be mistaken for one from a healthy console.
for (const FaultDef &f : kFaults)
if (state.faults.load() & f.id)
printf("[fault] %s (%s): %s\n", f.name, f.kind, f.what);
if (prod_keys_path) {
extern int se_engine_load_prod_keys(const char *);
se_engine_load_prod_keys(prod_keys_path);
@@ -407,8 +472,14 @@ int main(int argc, char *argv[]) {
else if (strcmp(argv[i], "--auto-te-script") == 0) auto_te_script = true;
// Generic scripted button input, for menu-driven payloads that can't
// be driven any other way from a headless / CI run.
else if (strcmp(argv[i], "--input-script") == 0 && i + 1 < argc)
input_script_load(argv[++i]);
else if (strcmp(argv[i], "--input-script") == 0 && i + 1 < argc) {
// A script that does not parse would leave a CI run idling until
// its timeout with nothing pressed; stop here instead.
if (!input_script_load(argv[++i])) {
fprintf(stderr, "[error] --input-script could not be loaded\n");
return 1;
}
}
}
// Default to sd.img in the working directory when --sd is not given, so the
@@ -420,12 +491,20 @@ int main(int argc, char *argv[]) {
}
if (sd_path) {
state.sd_fd = open(sd_path, O_RDWR);
state.sd_fd = open(sd_path, O_RDWR | O_BINARY);
if (state.sd_fd < 0) perror("[emu] Failed to open SD image");
else printf("[emu] SD image opened: %s\n", sd_path);
}
// No image, no card: the slot starts empty, so card detect (PZ1) reads
// empty and SDMMC1 commands time out, as on a console with no card in.
// This used to present a blank card that FatFs then found no volume on.
// The config window's SD toggle can still insert a blank card.
if (state.sd_fd < 0 && state.sd_inserted.load()) {
state.sd_inserted = false;
printf("[emu] No SD image: the SD slot is empty\n");
}
if (boot0_path) {
state.emmc_boot0_fd = open(boot0_path, O_RDWR);
state.emmc_boot0_fd = open(boot0_path, O_RDWR | O_BINARY);
if (state.emmc_boot0_fd < 0) perror("[emu] Failed to open BOOT0 image");
else printf("[emu] BOOT0 image opened: %s\n", boot0_path);
}
@@ -433,7 +512,7 @@ int main(int argc, char *argv[]) {
for (int i = 0; i < 16; i++) {
char path[512];
snprintf(path, sizeof(path), "%s.%02d", rawnand_prefix, i);
int fd = open(path, O_RDWR);
int fd = open(path, O_RDWR | O_BINARY);
if (fd >= 0) {
state.emmc_gpp_fds.push_back(fd);
// printf("[emu] rawnand part %02d opened: %s\n", i, path);
@@ -455,6 +534,40 @@ int main(int argc, char *argv[]) {
state.payload_len = payload_size;
if (!uc) { free(payload); return 1; }
// --load FILE@ADDR (repeatable): place a file in DRAM before the payload
// starts, the way a bootloader would have left a kernel and its device
// tree there. The payload decides what to do with it.
for (int i = 2; i + 1 < argc; i++) {
if (strcmp(argv[i], "--load") != 0)
continue;
const char *spec = argv[++i];
const char *at = strrchr(spec, '@');
if (!at) {
fprintf(stderr, "[error] --load expects FILE@ADDR, got '%s'\n", spec);
return 1;
}
std::string path(spec, at - spec);
uint64_t addr = strtoull(at + 1, nullptr, 0);
FILE *f = fopen(path.c_str(), "rb");
if (!f) {
fprintf(stderr, "[error] --load cannot open '%s'\n", path.c_str());
return 1;
}
fseek(f, 0, SEEK_END);
long len = ftell(f);
fseek(f, 0, SEEK_SET);
if (len < 0 || addr < DRAM_BASE || addr + (uint64_t)len > DRAM_BASE + DRAM_WINDOW_SIZE) {
fprintf(stderr, "[error] --load '%s' (%ld bytes) does not fit in DRAM at 0x%llX\n",
path.c_str(), len, (unsigned long long)addr);
fclose(f);
return 1;
}
size_t got = fread(state.dram_low_ptr + (addr - DRAM_BASE), 1, (size_t)len, f);
fclose(f);
printf("[loader] --load %s: %zu bytes at 0x%08llX\n", path.c_str(), got,
(unsigned long long)addr);
}
// Initialize SDL2 display
if (!sdl_display_init()) {
fprintf(stderr, "[error] Failed to initialize display\n");
@@ -480,6 +593,11 @@ int main(int argc, char *argv[]) {
const uint64_t BATCH_INSTRUCTIONS = 100000; // Instructions per batch
const int DISPLAY_UPDATE_MS = 16; // ~60 FPS
// While CPU0 is running the two cores advance in lockstep slices of this
// many BPMP instructions (250 us of emulated time). The BPMP polls CPU0's
// mailbox every 500 us, so neither side ever waits on a stale view of the
// other for longer than one of its own poll intervals.
const uint64_t CPU0_QUANTUM_INSTRUCTIONS = 2500;
auto last_display_update = std::chrono::steady_clock::now();
@@ -488,27 +606,52 @@ int main(int argc, char *argv[]) {
if (!sdl_display_poll_events(&state, uc)) break;
// Soft reboot: re-write the payload to IRAM, wipe DRAM (so Nyx and
// the bootloader's file-static caches reset), reset PC/SP/clock and
// re-prime the WDT cookie so Hekate's early boot skips Minerva again.
// the bootloader's file-static caches reset) and reset PC/SP/clock.
if (state.reboot_requested.exchange(false)) {
uc_emu_stop(uc);
// One contiguous block now; dram_ptr is a view into it.
memset(state.dram_low_ptr, 0, DRAM_WINDOW_SIZE);
uc_mem_write(uc, IPL_LOAD_ADDR, state.payload_ptr, state.payload_len);
uint32_t wdt_magic = 0x544457;
uc_mem_write(uc, 0x4003FF18, &wdt_magic, sizeof(wdt_magic));
bool cold = state.reboot_cold.exchange(false);
// The SoC resets as a whole: CPU0 back into reset, the PCIe root
// complex and every other block back to power-on, the clock's
// half-counted block gone. A power cycle resets the PMIC too.
mmio_soft_reset(&state, cold);
bpmp_clock_reset();
// Fresh zero pages rather than a memset, which made all 2 GB
// resident.
zeroed_reset(state.dram_low_ptr, DRAM_WINDOW_SIZE);
fill_fb_background(&state);
size_t reload = state.payload_len;
if (reload > IRAM_SIZE - (IPL_LOAD_ADDR - IRAM_BASE))
reload = IRAM_SIZE - (IPL_LOAD_ADDR - IRAM_BASE);
uc_mem_write(uc, IPL_LOAD_ADDR, state.payload_ptr, reload);
// Neither the zeroed DRAM nor uc_mem_write() reaches the engine's
// code cache, so what the last run translated - a payload it
// chainloaded over this one's load address, Nyx in DRAM - would
// run again in place of the fresh bytes. Drop those translations.
// (Not UC_CTL_TB_FLUSH: on Unicorn 2.0 that memsets the whole
// 1 GB code buffer, seconds and a gigabyte of RSS per reboot.)
uc_ctl_remove_cache(uc, 0, 0x01000000);
uc_ctl_remove_cache(uc, IRAM_BASE, IRAM_BASE + IRAM_SIZE);
uc_ctl_remove_cache(uc, DRAM_BASE, DRAM_BASE + DRAM_WINDOW_SIZE);
// Mode first, as at power-on: SVC, ARM state, IRQ/FIQ/async
// aborts masked. SP is banked, so it is written in that mode.
uint32_t reset_cpsr = 0x1D3;
uint32_t reset_pc = IPL_LOAD_ADDR;
uint32_t reset_sp = IPL_STACK_ADDR;
uint32_t reset_cpsr = 0; // ARM mode, all flags clear
uc_reg_write(uc, UC_ARM_REG_PC, &reset_pc);
uc_reg_write(uc, UC_ARM_REG_SP, &reset_sp);
uc_reg_write(uc, UC_ARM_REG_CPSR, &reset_cpsr);
state.fb_addr = FB_BASE; // re-point display at the FB base
uc_reg_write(uc, UC_ARM_REG_SP, &reset_sp);
uc_reg_write(uc, UC_ARM_REG_PC, &reset_pc);
state.emu_usec = 0;
state.insn_count = 0;
state.bpmp_slept_us = 0;
state.touch_phase = 0;
state.paused = false;
printf("[emu] Soft reboot complete (DRAM wiped)\n");
state.btn_power = false;
state.btn_vol_up = false;
state.btn_vol_down = false;
g_auto = AutoScripts();
input_script_restart(state);
printf("[emu] Soft reboot complete (%s, DRAM wiped)\n",
cold ? "power cycle" : "SoC reset");
}
if (!state.paused) {
@@ -528,8 +671,8 @@ int main(int argc, char *argv[]) {
// idle so recover_pin's final btn_wait blocks on us — keeps the
// result text visible in the framebuffer when the run times out.
if (auto_pin_recovery) {
static int pin_stage = 0;
static uint64_t pin_t = 0;
int &pin_stage = g_auto.pin_stage;
uint64_t &pin_t = g_auto.pin_t;
auto press_release = [&](std::atomic<bool> *btn,
uint64_t hold_us,
uint64_t cooldown_us) {
@@ -548,7 +691,7 @@ int main(int argc, char *argv[]) {
printf("[emu] Auto PIN recovery armed at emu_usec=%llu\n",
(unsigned long long)state.emu_usec);
}
static int last_logged_stage = -1;
int &last_logged_stage = g_auto.pin_logged_stage;
if (pin_stage != last_logged_stage) {
printf("[emu] Auto PIN stage %d at emu_usec=%llu\n", pin_stage,
(unsigned long long)state.emu_usec);
@@ -610,7 +753,7 @@ int main(int argc, char *argv[]) {
{22850000, 'P', true}, {23020000, 'P', false},
};
static const size_t te_n = sizeof(te_events)/sizeof(te_events[0]);
static size_t te_idx = 0;
size_t &te_idx = g_auto.te_idx;
while (te_idx < te_n && state.emu_usec >= te_events[te_idx].at_us) {
const InputEv &ev = te_events[te_idx];
std::atomic<bool> *btn = (ev.btn == 'P') ? &state.btn_power
@@ -625,11 +768,27 @@ int main(int argc, char *argv[]) {
te_idx++;
if (te_idx == te_n)
printf("[auto-te] sequence complete; idling for output\n");
// A time jump (FLOW_CTLR sleep) can make the release due
// in the same tick; the payload must see the press first.
if (ev.down)
break;
}
}
// Scripted button input (--input-script).
input_script_tick(state);
// Keyboard VOL presses end after their fixed guest duration.
for (int k = 0; k < 2; k++) {
std::atomic<uint64_t> &until = k ? state.kbd_vol_down_until : state.kbd_vol_up_until;
std::atomic<bool> &btn = k ? state.btn_vol_down : state.btn_vol_up;
uint64_t u = until.load();
if (u && state.emu_usec >= u) {
until = 0;
btn = false;
printf("[input] UP %s @emu_usec=%llu\n", k ? "VOL_DOWN" : "VOL_UP ",
(unsigned long long)state.emu_usec);
}
}
// Touch injection for the Nyx GUI popup (eMMC Issues Warning).
// Nyx initializes after the IPL stage; we inject a tap once enough
@@ -644,11 +803,45 @@ int main(int argc, char *argv[]) {
state.touch_x, state.touch_y);
}
// Run a batch of ARM instructions
// Run a batch of ARM instructions. With CPU0 up, the batch is cut
// into lockstep slices: the BPMP runs a quantum, then CPU0 runs up
// to the same emulated time. Scripted input and the display are
// still serviced once per full batch, as before.
uint64_t batch_end = state.insn_count + BATCH_INSTRUCTIONS;
uint64_t parked_left = BATCH_INSTRUCTIONS;
while (state.running && !state.paused &&
state.insn_count < batch_end) {
if (state.bpmp_halted) {
// The BPMP parked itself for good after handing off to
// CPU0. It retires nothing; time runs on for CPU0 at the
// rate the BPMP's clock would have advanced it.
if (!ccplex_cpu0_running()) {
printf("[emu] BPMP halted and CPU0 stopped, shutting down emulator\n");
state.running = false;
break;
}
if (parked_left < CPU0_QUANTUM_INSTRUCTIONS)
break;
parked_left -= CPU0_QUANTUM_INSTRUCTIONS;
state.emu_usec += CPU0_QUANTUM_INSTRUCTIONS / 10;
state.bpmp_slept_us += CPU0_QUANTUM_INSTRUCTIONS / 10;
ccplex_run(&state, state.emu_usec);
dock_tick(&state);
display_tick(&state);
if (state.reboot_requested.load())
break;
continue;
}
uint64_t budget = batch_end - state.insn_count;
if (ccplex_cpu0_running() && budget > CPU0_QUANTUM_INSTRUCTIONS)
budget = CPU0_QUANTUM_INSTRUCTIONS;
uc_reg_read(uc, UC_ARM_REG_PC, &pc);
uc_reg_read(uc, UC_ARM_REG_CPSR, &cpsr);
uint32_t start_addr = pc;
if (cpsr & (1 << 5)) start_addr |= 1;
uc_err err = uc_emu_start(uc, start_addr, 0, 0, BATCH_INSTRUCTIONS);
uc_err err = bpmp_run(uc, &state, start_addr, budget);
if (err != UC_ERR_OK) {
uint32_t error_pc;
uc_reg_read(uc, UC_ARM_REG_PC, &error_pc);
@@ -656,6 +849,13 @@ int main(int argc, char *argv[]) {
state.running = false;
break;
}
// CPU0 catches up to the BPMP's clock.
ccplex_run(&state, state.emu_usec);
dock_tick(&state);
display_tick(&state);
if (state.reboot_requested.load())
break;
}
} else {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
@@ -689,11 +889,13 @@ int main(int argc, char *argv[]) {
console_window_shutdown();
config_window_shutdown();
sdl_display_shutdown();
ccplex_reset(&state); // closes CPU0's engine, if one is up
uc_close(uc);
free(state.iram_ptr);
free(g_low_ptr);
// dram_ptr is a view into dram_low_ptr's block; only free the base once.
free(state.dram_low_ptr);
zeroed_free(state.dram_low_ptr, DRAM_WINDOW_SIZE);
free(state.payload_ptr);
// fb_ptr points inside dram_ptr; do not free separately.
+17 -4
View File
@@ -13,6 +13,7 @@ Usage:
"""
import argparse
import os
import shlex
import subprocess
import sys
@@ -21,6 +22,9 @@ def build_sd_image(src_dir: str, out_img: str, size_mb: int) -> int:
if not os.path.isdir(src_dir):
print(f"[error] source folder not found: {src_dir}")
return 1
if size_mb < 64:
print("[error] --size-mb must be at least 64: FAT32 needs 65525 clusters")
return 1
src_dir_abs = os.path.abspath(src_dir)
out_img_abs = os.path.abspath(out_img)
@@ -45,6 +49,13 @@ def build_sd_image(src_dir: str, out_img: str, size_mb: int) -> int:
print(f"[*] formatting + populating via Docker (alpine)")
fdisk_script = f"o\\nn\\np\\n1\\n2048\\n\\nt\\nc\\nw\\n"
# FatFs (and every FAT driver) decides FAT12/16/32 by cluster count, and
# FAT32 needs at least 65525 clusters: 4 KiB clusters only get there from
# ~260 MB up. Below that, format with 512-byte clusters, or the payload's
# f_mount rejects the volume (FR_NO_FILESYSTEM).
spc = 8 if size_mb >= 512 else 1
# File names go into a shell command line: quote them.
q_fat, q_img = shlex.quote(fat_name), shlex.quote(img_name)
docker_cmd = [
"docker", "run", "--rm",
"-v", f"{work_dir}:/work",
@@ -53,10 +64,12 @@ def build_sd_image(src_dir: str, out_img: str, size_mb: int) -> int:
"alpine",
"sh", "-c",
"apk add --no-cache dosfstools mtools util-linux >/dev/null && "
f"mkfs.fat -F 32 -s 8 {fat_name} && "
f"mcopy -i {fat_name} -s /src/* :: && "
f"printf '{fdisk_script}' | fdisk {img_name} && "
f"dd if={fat_name} of={img_name} bs=1M seek=1 conv=notrunc status=none"
f"mkfs.fat -F 32 -s {spc} {q_fat} && "
# Every top-level entry, dotfiles included; an empty source is fine.
f"(cd /src && find . -mindepth 1 -maxdepth 1 "
f"-exec mcopy -i /work/{q_fat} -s {{}} :: \\;) && "
f"printf '{fdisk_script}' | fdisk {q_img} && "
f"dd if={q_fat} of={q_img} bs=1M seek=1 conv=notrunc status=none"
]
try:
subprocess.run(docker_cmd, check=True)
+81
View File
@@ -0,0 +1,81 @@
#include "platform.h"
#include <cstdio>
#include <cstring>
#include <string>
#ifdef _WIN32
#include <windows.h>
#else
#include <sys/mman.h>
#endif
// ---- Zero-filled memory, committed only where touched --------------------
//
// The emulated DRAM window is 2 GiB. calloc gets it from the OS as demand-
// zero pages, so only what a payload touches becomes resident - but a soft
// reboot used to memset() the whole block back to zero, which touched every
// page and left the process 2 GiB resident from the first reboot on. These
// allocate the same demand-zero memory directly, and hand back fresh zero
// pages on reset, at the same address (the engines hold host pointers into
// it), without touching any.
uint8_t *zeroed_alloc(size_t size) {
#ifdef _WIN32
return (uint8_t *)VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT,
PAGE_READWRITE);
#else
void *p = mmap(nullptr, size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
return p == MAP_FAILED ? nullptr : (uint8_t *)p;
#endif
}
void zeroed_reset(uint8_t *p, size_t size) {
#ifdef _WIN32
// Decommitted pages come back zero-filled when committed again.
if (!VirtualFree(p, size, MEM_DECOMMIT) ||
!VirtualAlloc(p, size, MEM_COMMIT, PAGE_READWRITE))
memset(p, 0, size);
#else
// A fresh anonymous mapping over the old one: zero pages, same address.
if (mmap(p, size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE | MAP_FIXED, -1,
0) == MAP_FAILED)
memset(p, 0, size);
#endif
}
void zeroed_free(uint8_t *p, size_t size) {
if (!p)
return;
#ifdef _WIN32
(void)size;
VirtualFree(p, 0, MEM_RELEASE);
#else
munmap(p, size);
#endif
}
// ---- Opening files by name -------------------------------------------------
FILE *platform_fopen(const char *path, const char *mode) {
FILE *f = fopen(path, mode);
#ifdef _WIN32
// Command-line paths arrive in the ANSI code page, which fopen expects;
// SDL hands dropped files over as UTF-8, which it does not. Try the name
// as UTF-8 before giving up.
if (!f) {
int n = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, path, -1,
nullptr, 0);
int m = MultiByteToWideChar(CP_UTF8, 0, mode, -1, nullptr, 0);
if (n > 0 && m > 0) {
std::wstring wpath(n, L'\0'), wmode(m, L'\0');
MultiByteToWideChar(CP_UTF8, 0, path, -1, &wpath[0], n);
MultiByteToWideChar(CP_UTF8, 0, mode, -1, &wmode[0], m);
f = _wfopen(wpath.c_str(), wmode.c_str());
}
}
#endif
return f;
}
+69
View File
@@ -0,0 +1,69 @@
#ifndef RCM_PLATFORM_H
#define RCM_PLATFORM_H
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
// Small portability helpers for the disk-image code, which is the one place
// the emulator does raw POSIX file I/O.
// MinGW's open() defaults to TEXT mode: _read() turns every CR LF into LF
// and stops at the first 0x1A byte. On an SD card or eMMC image that is
// silent sector corruption, so every image fd must be opened O_BINARY.
// POSIX has no such flag (and no such mode), so it is a no-op there.
#ifndef O_BINARY
#define O_BINARY 0
#endif
// Size of an open file, in 64 bits. MinGW's plain struct stat carries a
// 32-bit st_size, which cannot describe the 4 GiB chunks Hekate splits a
// rawnand dump into; _fstati64 can.
static inline int64_t file_size64(int fd) {
#ifdef _WIN32
struct _stati64 st;
if (_fstati64(fd, &st) != 0)
return -1;
return (int64_t)st.st_size;
#else
struct stat st;
if (fstat(fd, &st) != 0)
return -1;
return (int64_t)st.st_size;
#endif
}
// pread/pwrite are POSIX and MinGW does not have them. Seek-then-read is
// equivalent here: the emulated storage is touched only from the CPU thread,
// so the atomicity real pread() buys against a shared file offset is not in
// play.
#ifdef _WIN32
#include <io.h>
static inline ssize_t pread(int fd, void *buf, size_t n, long long off) {
if (_lseeki64(fd, off, SEEK_SET) < 0)
return -1;
return _read(fd, buf, (unsigned int)n);
}
static inline ssize_t pwrite(int fd, const void *buf, size_t n, long long off) {
if (_lseeki64(fd, off, SEEK_SET) < 0)
return -1;
return _write(fd, buf, (unsigned int)n);
}
#else
#include <unistd.h>
#endif
// Large zero-filled memory that only becomes resident where it is touched
// (platform.cpp). zeroed_reset() makes all of it zero again, at the same
// address, without touching it.
uint8_t *zeroed_alloc(size_t size);
void zeroed_reset(uint8_t *p, size_t size);
void zeroed_free(uint8_t *p, size_t size);
// fopen() that also accepts a UTF-8 name on Windows (a dropped file).
FILE *platform_fopen(const char *path, const char *mode);
#endif // RCM_PLATFORM_H
+27
View File
@@ -0,0 +1,27 @@
#pragma once
#include <cstddef>
#include <cstdint>
// Tegra X1 block-linear surfaces (TRM 20.1.2), as the display controller and
// VIC read and write them. A GOB is 64 bytes x 8 lines (512 bytes) of 16Bx2
// sectors; GOBs stack gob_h high into a block, and blocks run left to right,
// then down, gobs_per_row GOBs to a row.
// Byte offset of byte column xb (pixel x * bytes per pixel) on line y.
inline size_t bl_offset(uint32_t xb, uint32_t y, uint32_t gobs_per_row,
uint32_t gob_h) {
uint32_t gob_y = y / 8;
size_t gob = ((size_t)(gob_y / gob_h) * gobs_per_row + xb / 64) * gob_h +
gob_y % gob_h;
// Within the GOB, TRM Figure 47's sector order.
uint32_t x = xb % 64, l = y % 8;
return gob * 512 + (x / 32) * 256 + (l / 2) * 64 + ((x % 32) / 16) * 32 +
(l % 2) * 16 + (x % 16);
}
// Bytes a surface h lines tall occupies (whole blocks).
inline size_t bl_size(uint32_t gobs_per_row, uint32_t gob_h, uint32_t h) {
return (size_t)gobs_per_row * 512 * gob_h *
((h + 8 * gob_h - 1) / (8 * gob_h));
}
+262
View File
@@ -0,0 +1,262 @@
#include "bpmp.h"
#include <cstdio>
#include <cstring>
#include "../emu_state.h"
#include "memory_map.h"
namespace {
// ---- TIMERUS pacing --------------------------------------------------------
//
// Real silicon retires a few hundred BPMP instructions per microsecond; this
// clock credits ten. That dilation is what makes busy-waits cheap to emulate,
// and it is harmless for the usual `while (now - start < us)` wait. It is not
// harmless for a wait that needs to SEE a particular counter value. bdk's own
// fan_get_speed() is one:
//
// int timer = get_tmr_us() + 2000000;
// while ((timer - get_tmr_us()) > 0) // int - u32: unsigned, so "!= 0"
//
// GCC compiles that to `cmp; bne`: the loop ends only on the exact deadline.
// Its body is ~30 instructions - a tenth of a microsecond on hardware, three
// microseconds here - so the emulated counter stepped past the deadline and
// the loop spun until TIMERUS wrapped, about 72 emulated minutes later. That
// is where a hwtest sweep used to stall, in the fan spin-up test.
//
// So polls are paced the way hardware paces them: while TIMERUS reads come
// at most POLL_WINDOW instructions apart - under a microsecond at real speed -
// the clock advances by at most 1 us from one read to the next. Time stays
// monotonic for every observer (only increments are capped), a wait still
// ends at the emulated time it asked for, and a loop that polls less often
// than that runs on the plain instruction clock.
constexpr uint64_t POLL_WINDOW = 200;
struct Clock {
uint64_t limit = 0; // insn_count at which the current batch ends
uint32_t pending = 0; // instructions of the block now executing
// TIMERUS pacing (see above).
bool polling = false;
uint64_t poll_insn = 0; // insn_count at the last TIMERUS read
uint64_t poll_usec = 0; // value it returned
// Diagnostics.
uint64_t loop_addr = 0;
uint64_t loop_insns = 0;
bool stall_logged = false;
bool nop_slide_reported = false;
};
Clock clk;
uc_hook h_block;
// Credit `n` retired instructions. emu_usec ticks once per ten, exactly as
// the per-instruction counter used to tick it, and anything a FLOW_CTLR
// timed halt added to emu_usec directly is preserved.
inline void commit(EmuState *s, uint32_t n) {
uint64_t before = s->insn_count;
s->insn_count += n;
uint64_t delta = s->insn_count / 10 - before / 10;
if (clk.polling && delta) {
if (s->insn_count - clk.poll_insn <= POLL_WINDOW) {
uint64_t cap = clk.poll_usec + 1;
uint64_t room = cap > s->emu_usec ? cap - s->emu_usec : 0;
if (delta > room)
delta = room;
} else {
clk.polling = false;
}
}
s->emu_usec += delta;
}
inline const uint8_t *code_ptr(const EmuState *s, uint64_t a, uint32_t len) {
if (a >= IRAM_BASE && a + len <= IRAM_BASE + IRAM_SIZE)
return s->iram_ptr + (a - IRAM_BASE);
if (a >= DRAM_BASE && a + len <= DRAM_BASE + DRAM_WINDOW_SIZE)
return s->dram_low_ptr + (a - DRAM_BASE);
return nullptr;
}
// Instructions in a translated block, counted the way Unicorn's per-
// instruction hook saw them. ARM: all four bytes. Thumb: a halfword whose top
// five bits are 0b11101, 0b11110 or 0b11111 opens a 32-bit instruction - on
// this core (Unicorn's Cortex-A15) that includes the Thumb-1 BL/BLX prefix
// and suffix pair, which decodes as one instruction.
uint32_t decode_insns(uc_engine *uc, const EmuState *s, uint64_t addr,
uint32_t size) {
uint32_t cpsr = 0;
uc_reg_read(uc, UC_ARM_REG_CPSR, &cpsr);
if (!(cpsr & (1u << 5)))
return size >= 4 ? size / 4 : 1;
static uint8_t scratch[8192];
const uint8_t *p = code_ptr(s, addr, size);
if (!p) {
// Code outside IRAM/DRAM (the zero-filled iROM, low scratch): rare.
uint32_t n = size < sizeof(scratch) ? size : (uint32_t)sizeof(scratch);
if (uc_mem_read(uc, addr, scratch, n) != UC_ERR_OK)
return size >= 2 ? size / 2 : 1;
p = scratch;
size = n;
}
uint32_t n = 0;
for (uint32_t i = 0; i + 1 < size; n++) {
uint16_t hw = (uint16_t)(p[i] | (p[i + 1] << 8));
i += ((hw & 0xF800) >= 0xE800) ? 4 : 2;
}
return n ? n : 1;
}
// Decoding a hot block on every execution was most of this hook's cost, so
// counts are cached per block. A block is identified by address and size,
// and fingerprinted by its first and last words: code rewritten in place
// (a relocation, a chainloaded payload) almost always changes one of those,
// and when it does not, the translator's own retranslation still gives the
// same instruction boundaries unless the 16/32-bit mix inside changed too.
struct CountCacheEntry {
uint32_t addr;
uint32_t head;
uint32_t tail;
uint16_t size;
uint16_t count;
};
constexpr size_t kCountCacheSize = 1u << 16;
CountCacheEntry count_cache[kCountCacheSize];
inline uint32_t load32(const uint8_t *p) {
uint32_t v;
memcpy(&v, p, 4);
return v;
}
uint32_t count_insns(uc_engine *uc, const EmuState *s, uint64_t addr,
uint32_t size) {
const uint8_t *p = (size >= 4 && size < 0x10000) ? code_ptr(s, addr, size)
: nullptr;
if (!p)
return decode_insns(uc, s, addr, size);
uint32_t head = load32(p), tail = load32(p + size - 4);
CountCacheEntry &e = count_cache[(addr >> 1) & (kCountCacheSize - 1)];
if (e.addr == (uint32_t)addr && e.size == size && e.head == head &&
e.tail == tail && e.count)
return e.count;
uint32_t n = decode_insns(uc, s, addr, size);
e.addr = (uint32_t)addr;
e.size = (uint16_t)size;
e.head = head;
e.tail = tail;
e.count = (uint16_t)n;
return n;
}
// A payload that jumps into zeroed memory executes `movs r0, r0` (Thumb
// 0x0000) or `andeq r0, r0, r0` (ARM) until it hits something. No compiler
// emits sixteen zero bytes at the start of a block, so that is the signal.
// The low 16 MB (a null function pointer lands there; the iROM has no
// contents) is zero-filled RAM too, read through the engine as it is not
// one of the host views.
bool nop_slide(uc_engine *uc, const EmuState *s, uint64_t addr) {
static const uint8_t zero[16] = {0};
if (addr < 0x01000000) {
uint8_t buf[16];
return uc_mem_read(uc, addr, buf, sizeof(buf)) == UC_ERR_OK &&
memcmp(buf, zero, sizeof(zero)) == 0;
}
bool in_range = (addr >= 0x40030000 && addr < IRAM_BASE + IRAM_SIZE) ||
(addr >= DRAM_BASE && addr < DRAM_BASE + DRAM_WINDOW_SIZE);
if (!in_range)
return false;
const uint8_t *p = code_ptr(s, addr, 16);
if (!p)
return false;
return memcmp(p, zero, sizeof(zero)) == 0;
}
// Once per translated block, before it runs. Credits the previous block,
// which has now fully executed. When the batch budget is spent it stops the
// engine here, and Unicorn does not run this block at all - PC stays on its
// first instruction and the next batch starts there - so it is not counted.
void hook_block(uc_engine *uc, uint64_t address, uint32_t size, void *ud) {
EmuState *s = (EmuState *)ud;
commit(s, clk.pending);
clk.pending = 0;
if (s->insn_count >= clk.limit) {
uc_emu_stop(uc);
return;
}
if (nop_slide(uc, s, address)) {
if (!clk.nop_slide_reported) {
clk.nop_slide_reported = true;
printf("\n[emu] NOP-slide detected at 0x%08llX (zeroed memory being "
"executed) - emulation paused\n", (unsigned long long)address);
fflush(stdout);
}
s->paused = true;
uc_emu_stop(uc);
return;
}
clk.pending = count_insns(uc, s, address, size);
// A single-instruction self-loop (`b .`) spinning for a long time is a
// payload that has given up; say so once when it finally leaves it.
if (size <= 4 && address == clk.loop_addr) {
clk.loop_insns += clk.pending;
} else {
if (clk.loop_insns > 100000 && !clk.stall_logged) {
printf("[trace] STALL at PC=0x%08llX (looped %llu times)\n",
(unsigned long long)clk.loop_addr,
(unsigned long long)clk.loop_insns);
clk.stall_logged = true;
} else if (clk.loop_insns == 0) {
clk.stall_logged = false;
}
clk.loop_addr = address;
clk.loop_insns = 0;
}
}
} // namespace
void bpmp_attach(uc_engine *uc, EmuState *state) {
uc_hook_add(uc, &h_block, UC_HOOK_BLOCK, (void *)hook_block, state, 1, 0);
}
uc_err bpmp_run(uc_engine *uc, EmuState *state, uint64_t begin,
uint64_t max_insns) {
clk.limit = state->insn_count + (max_insns ? max_insns : 1);
clk.pending = 0;
// `until` must be an address the core can never reach. 0 is not one: a
// null function pointer took the BPMP there, and from then on every start
// returned at once without running anything - the main loop spun forever
// waiting for instructions to retire. The PC is 32 bits wide.
uc_err err = uc_emu_start(uc, begin, 1ULL << 32, 0, 0);
// If something other than the budget ended the run (an MMIO handler
// calling uc_emu_stop, a fault), the block in flight has still run to its
// end - Unicorn only checks for a stop between blocks - so credit it.
commit(state, clk.pending);
clk.pending = 0;
return err;
}
void bpmp_clock_reset() {
clk = Clock();
memset(count_cache, 0, sizeof(count_cache));
}
uint32_t bpmp_timerus_read(EmuState *state) {
clk.polling = true;
clk.poll_insn = state->insn_count;
clk.poll_usec = state->emu_usec;
return (uint32_t)state->emu_usec;
}
void bpmp_clock_jumped() {
clk.polling = false;
}
void bpmp_yield() {
clk.limit = 0;
}
+54
View File
@@ -0,0 +1,54 @@
#ifndef T210_BPMP_H
#define T210_BPMP_H
#include <cstdint>
#include <unicorn/unicorn.h>
struct EmuState;
/*
* BPMP execution and its deterministic clock.
*
* Emulated time is derived from retired instructions, never from the host:
* emu_usec = skipped_us + insn_count / 10, where skipped_us is whatever a
* FLOW_CTLR timed halt jumped over. That makes a run reproducible - the same
* payload sees the same TIMERUS value at the same instruction every time -
* which scripted input (--input-script, --auto-te-script) depends on.
*
* The instruction count used to come from a UC_HOOK_CODE callback on every
* single instruction, which kept Unicorn from running any translated block
* at native speed. It now comes from a block hook: the block's instructions
* are counted once, from its bytes, and credited when the block has run. The
* totals are exactly what per-instruction counting gave. What changed is
* resolution inside a block: an MMIO read there sees the time at the start
* of its block, not at its own instruction - a fraction of a microsecond at
* 10 instructions per microsecond.
*/
// Install the clock's block hook on the BPMP engine.
void bpmp_attach(uc_engine *uc, EmuState *state);
// Run from `begin` (bit 0 = Thumb) until at least `max_insns` more
// instructions have retired, or something stops the engine. Batches end on
// a block boundary.
uc_err bpmp_run(uc_engine *uc, EmuState *state, uint64_t begin,
uint64_t max_insns);
// Forget any half-accounted block (soft reboot).
void bpmp_clock_reset();
// TIMERUS_CNTR_1US as the BPMP reads it. See the pacing note in bpmp.cpp:
// polls issued close together never see the counter skip a value.
uint32_t bpmp_timerus_read(EmuState *state);
// Time jumped forward outside instruction accounting (a FLOW_CTLR timed
// halt): whatever poll loop was being paced is over.
void bpmp_clock_jumped();
// End the current batch at the next block boundary - a clean stop, unlike
// uc_emu_stop() from an MMIO callback, which abandons the block in flight
// with the PC back at its start. Used when CPU0 is released, so its first
// slice starts now rather than a whole batch later.
void bpmp_yield();
#endif // T210_BPMP_H
+527
View File
@@ -0,0 +1,527 @@
// Fake Bluetooth controllers for the CYW4356 model. See btpeer.h.
#include "btpeer.h"
#include "../emu_state.h"
#include <cmath>
#include <cstdio>
#include <cstring>
#include <vector>
namespace {
constexpr int UART_D = 3;
struct Peer {
const char *name;
uint8_t addr[6]; // little-endian, as HCI carries it
uint8_t type; // the controller's own: 1 left Joy-Con, 2 right, 3 Pro
bool needs_security; // answers "security block" until encrypted
bool needs_bonding; // refuses Simple Pairing without bonding
int8_t rssi;
};
// Nintendo OUIs (98:B6:E9 and DC:68:EB), last three bytes made up.
const Peer kPeers[] = {
{"Pro Controller", {0x21, 0x43, 0x65, 0xE9, 0xB6, 0x98}, 3, true, true, -47},
{"Joy-Con (R)", {0x9A, 0xBC, 0xDE, 0xEB, 0x68, 0xDC}, 2, false, false, -61},
};
constexpr int kNPeers = sizeof(kPeers) / sizeof(kPeers[0]);
const uint8_t kRadioAddr[6] = {0x10, 0x32, 0x54, 0xEB, 0x68, 0xDC};
// Bits of the 24-bit button field each controller cycles through.
const uint8_t kBitsPro[] = {3, 2, 1, 0, 17, 16, 19, 18, 22, 6, 23, 7, 8, 9, 12, 13, 11, 10};
const uint8_t kBitsR[] = {3, 2, 1, 0, 6, 7, 9, 12, 10, 5, 4};
constexpr uint16_t kHandle = 0x0040;
constexpr uint64_t kReportUs = 15000; // a report every 15 ms
constexpr uint64_t kPressUs = 600000; // each button: 300 ms down, 300 up
constexpr size_t kHostBacklog = 600; // the radio holds reports past this
struct Pending {
uint64_t due;
int tag; // 1: inquiry traffic, cancelled with it
std::vector<uint8_t> bytes;
};
struct Chan {
uint16_t host_cid = 0;
uint16_t peer_cid = 0;
bool open = false, host_cfg = false, peer_cfg = false;
};
struct State {
std::vector<Pending> q;
int conn = -1; // index into kPeers
bool encrypted = false;
bool info_asked = false;
Chan ch[2]; // HID control 0x11, interrupt 0x13
bool streaming = false, full = false;
uint64_t stream_at = 0, next_report = 0;
uint8_t timer = 0;
uint8_t sig_id = 0x40;
uint8_t last_auth_req = 0;
} st;
uint64_t now_us(EmuState *s) { return s->emu_usec; }
void later(EmuState *s, uint64_t us, std::vector<uint8_t> b, int tag = 0) {
st.q.push_back({now_us(s) + us, tag, std::move(b)});
}
std::vector<uint8_t> event(uint8_t code, std::vector<uint8_t> p) {
std::vector<uint8_t> b = {0x04, code, (uint8_t)p.size()};
b.insert(b.end(), p.begin(), p.end());
return b;
}
void put_addr(std::vector<uint8_t> &v, const uint8_t *a) { v.insert(v.end(), a, a + 6); }
std::vector<uint8_t> cmd_complete(uint16_t op, std::vector<uint8_t> ret) {
std::vector<uint8_t> p = {0x01, (uint8_t)op, (uint8_t)(op >> 8)};
p.insert(p.end(), ret.begin(), ret.end());
return event(0x0E, p);
}
std::vector<uint8_t> cmd_status(uint16_t op, uint8_t status) {
return event(0x0F, {status, 0x01, (uint8_t)op, (uint8_t)(op >> 8)});
}
int peer_of(const uint8_t *addr) {
for (int i = 0; i < kNPeers; i++)
if (!memcmp(kPeers[i].addr, addr, 6))
return i;
return -1;
}
// An L2CAP frame to the host, in one ACL packet.
std::vector<uint8_t> acl(uint16_t cid, const std::vector<uint8_t> &d) {
uint16_t hf = kHandle | 0x2000;
uint16_t l2 = (uint16_t)d.size(), len = l2 + 4;
std::vector<uint8_t> b = {0x02, (uint8_t)hf, (uint8_t)(hf >> 8), (uint8_t)len,
(uint8_t)(len >> 8), (uint8_t)l2, (uint8_t)(l2 >> 8),
(uint8_t)cid, (uint8_t)(cid >> 8)};
b.insert(b.end(), d.begin(), d.end());
return b;
}
std::vector<uint8_t> sig(uint8_t code, uint8_t id, std::vector<uint8_t> d) {
std::vector<uint8_t> b = {code, id, (uint8_t)d.size(), (uint8_t)(d.size() >> 8)};
b.insert(b.end(), d.begin(), d.end());
return acl(0x0001, b);
}
void drop_link() {
st.conn = -1;
st.encrypted = st.info_asked = false;
st.ch[0] = Chan{};
st.ch[1] = Chan{};
st.streaming = st.full = false;
}
// The buttons and sticks at time t into the stream.
void input_now(uint64_t t, uint8_t *btn3, uint8_t *sticks6) {
const Peer &p = kPeers[st.conn];
const uint8_t *bits = p.type == 3 ? kBitsPro : kBitsR;
size_t nbits = p.type == 3 ? sizeof(kBitsPro) : sizeof(kBitsR);
uint32_t b = 0;
uint64_t step = t / kPressUs;
if (t % kPressUs < kPressUs / 2)
b = 1u << bits[step % nbits];
btn3[0] = (uint8_t)b;
btn3[1] = (uint8_t)(b >> 8);
btn3[2] = (uint8_t)(b >> 16);
double a = (double)(t % 2000000) / 2000000.0 * 6.2831853;
auto pack = [](uint8_t *o, double ang, bool on) {
uint16_t x = on ? (uint16_t)(0x800 + 0x500 * cos(ang)) : 0x800;
uint16_t y = on ? (uint16_t)(0x800 + 0x500 * sin(ang)) : 0x800;
o[0] = (uint8_t)x;
o[1] = (uint8_t)((x >> 8) | (y << 4));
o[2] = (uint8_t)(y >> 4);
};
pack(sticks6, a, p.type != 2); // left stick: Pro and left Joy-Con
pack(sticks6 + 3, -a, p.type != 1); // right stick: Pro and right Joy-Con
}
// Input report 0x21 (a subcommand's answer) or 0x30, on the input channel.
std::vector<uint8_t> report(uint8_t id, uint64_t t, const std::vector<uint8_t> &reply) {
std::vector<uint8_t> r(1 + 49, 0);
r[0] = 0xA1; // HID DATA, input
r[1] = id;
r[2] = st.timer++;
r[3] = 0x8E; // battery full, powered by battery
input_now(t, &r[4], &r[7]);
r[13] = 0x00; // vibration
for (size_t i = 0; i < reply.size() && 14 + i < r.size(); i++)
r[14 + i] = reply[i];
return acl(st.ch[1].host_cid, r);
}
void hid_output(EmuState *s, const uint8_t *d, uint32_t n) {
if (n < 12 || d[0] != 0xA2 || d[1] != 0x01)
return;
uint8_t sub = d[11];
uint64_t t = st.streaming ? now_us(s) - st.stream_at : 0;
std::vector<uint8_t> reply;
switch (sub) {
case 0x02: { // device info
const Peer &p = kPeers[st.conn];
reply = {0x82, 0x02, 0x04, 0x21, p.type, 0x02};
for (int i = 5; i >= 0; i--)
reply.push_back(p.addr[i]);
reply.push_back(0x01);
reply.push_back(0x01);
break;
}
case 0x03:
if (n > 12 && d[12] == 0x30) {
st.full = true;
printf("[btpeer] %s: full reports from now on\n", kPeers[st.conn].name);
}
reply = {0x80, 0x03};
break;
default:
reply = {0x80, sub};
break;
}
later(s, 8000, report(0x21, t, reply));
}
void signal_in(EmuState *s, const uint8_t *d, uint32_t n) {
while (n >= 4) {
uint8_t code = d[0], id = d[1];
uint32_t len = d[2] | d[3] << 8;
const uint8_t *p = d + 4;
if (len > n - 4)
return;
switch (code) {
case 0x02: { // Connection Request
uint16_t psm = p[0] | p[1] << 8, scid = p[2] | p[3] << 8;
int i = psm == 0x11 ? 0 : psm == 0x13 ? 1 : -1;
if (i < 0) {
later(s, 2000, sig(0x03, id, {0, 0, (uint8_t)scid, (uint8_t)(scid >> 8), 2, 0, 0, 0}));
break;
}
if (kPeers[st.conn].needs_security && !st.encrypted) {
printf("[btpeer] %s: PSM %02X before encryption, security block\n",
kPeers[st.conn].name, psm);
later(s, 2000, sig(0x03, id, {0, 0, (uint8_t)scid, (uint8_t)(scid >> 8), 3, 0, 0, 0}));
break;
}
Chan &c = st.ch[i];
c = Chan{};
c.host_cid = scid;
c.peer_cid = 0x0060 + i;
c.open = true;
later(s, 2000, sig(0x03, id, {(uint8_t)c.peer_cid, (uint8_t)(c.peer_cid >> 8),
(uint8_t)scid, (uint8_t)(scid >> 8), 0, 0, 0, 0}));
// Its own settings, MTU 672, as a controller sends them.
later(s, 4000, sig(0x04, st.sig_id++, {(uint8_t)scid, (uint8_t)(scid >> 8), 0, 0,
0x01, 0x02, 0xA0, 0x02}));
if (!st.info_asked) {
st.info_asked = true;
later(s, 3000, sig(0x0A, st.sig_id++, {0x02, 0x00}));
}
break;
}
case 0x04: { // the host's Configuration Request
uint16_t dcid = p[0] | p[1] << 8;
for (Chan &c : st.ch)
if (c.open && c.peer_cid == dcid) {
c.host_cfg = true;
later(s, 2000, sig(0x05, id, {(uint8_t)c.host_cid, (uint8_t)(c.host_cid >> 8),
0, 0, 0, 0}));
}
break;
}
case 0x05: { // the host's answer to ours
uint16_t scid = p[0] | p[1] << 8, res = p[4] | p[5] << 8;
for (Chan &c : st.ch)
if (c.open && c.peer_cid == scid && res == 0)
c.peer_cfg = true;
break;
}
case 0x0B: // Information Response
printf("[btpeer] the host answered the information request (result %d)\n",
len >= 4 ? p[2] | p[3] << 8 : -1);
break;
case 0x06: { // Disconnection Request
later(s, 2000, sig(0x07, id, {p[0], p[1], p[2], p[3]}));
break;
}
default:
break;
}
d += 4 + len;
n -= 4 + len;
}
Chan &intr = st.ch[1];
if (!st.streaming && st.ch[0].host_cfg && st.ch[0].peer_cfg && intr.host_cfg &&
intr.peer_cfg) {
st.streaming = true;
st.stream_at = now_us(s);
st.next_report = now_us(s) + kReportUs;
printf("[btpeer] %s: both HID channels open\n", kPeers[st.conn].name);
}
}
} // namespace
void btpeer_reset(EmuState *state) {
(void)state;
st.q.clear();
drop_link();
}
bool btpeer_command(EmuState *s, uint16_t op, const uint8_t *p, uint32_t n) {
switch (op) {
case 0x1009: { // Read_BD_ADDR
std::vector<uint8_t> r = {0x00};
put_addr(r, kRadioAddr);
later(s, 500, cmd_complete(op, r));
return true;
}
case 0x1003: // Read_Local_Supported_Features
// Byte 6 bit 3: Secure Simple Pairing, as the CYW4356 has it.
later(s, 500, cmd_complete(op, {0x00, 0xBF, 0xFE, 0x8F, 0xFE, 0xDB, 0xFF, 0x7B, 0x87}));
return true;
case 0x040D: { // PIN_Code_Request_Reply
std::vector<uint8_t> r = {0x00};
put_addr(r, p);
later(s, 500, cmd_complete(op, r));
return true;
}
case 0x1005: // Read_Buffer_Size: 1021 x 8 ACL
later(s, 500, cmd_complete(op, {0x00, 0xFD, 0x03, 0x40, 0x08, 0x00, 0x08, 0x00}));
return true;
case 0x0C01: case 0x0C56: case 0x0C45: case 0x0C13: case 0x0C24: case 0x0C1A:
case 0x080F: // Write_Default_Link_Policy_Settings
later(s, 500, cmd_complete(op, {0x00}));
return true;
case 0x0401: { // Inquiry
later(s, 500, cmd_status(op, 0x00));
uint64_t len_us = (n >= 4 ? p[3] : 8) * 1280000ull;
for (int i = 0; i < kNPeers; i++) {
const Peer &pr = kPeers[i];
std::vector<uint8_t> e = {0x01};
put_addr(e, pr.addr);
e.insert(e.end(), {0x01, 0x00, 0x08, 0x25, 0x00, 0x34, 0x12, (uint8_t)pr.rssi});
later(s, 1500000ull + i * 1200000ull, event(0x22, e), 1);
}
later(s, len_us, event(0x01, {0x00}), 1);
printf("[btpeer] inquiry started\n");
return true;
}
case 0x0402: { // Inquiry_Cancel
std::vector<Pending> keep;
for (Pending &q : st.q)
if (q.tag != 1)
keep.push_back(std::move(q));
st.q.swap(keep);
later(s, 500, cmd_complete(op, {0x00}));
printf("[btpeer] inquiry cancelled\n");
return true;
}
case 0x0419: { // Remote_Name_Request
later(s, 500, cmd_status(op, 0x00));
int i = n >= 6 ? peer_of(p) : -1;
std::vector<uint8_t> e = {(uint8_t)(i < 0 ? 0x04 : 0x00)};
put_addr(e, p);
std::vector<uint8_t> name(248, 0);
if (i >= 0)
memcpy(name.data(), kPeers[i].name, strlen(kPeers[i].name));
e.insert(e.end(), name.begin(), name.end());
later(s, i < 0 ? 5120000 : 300000, event(0x07, e));
return true;
}
case 0x0405: { // Create_Connection
later(s, 500, cmd_status(op, 0x00));
int i = n >= 6 ? peer_of(p) : -1;
std::vector<uint8_t> e = {(uint8_t)(i < 0 ? 0x04 : 0x00), (uint8_t)kHandle,
(uint8_t)(kHandle >> 8)};
put_addr(e, p);
e.push_back(0x01);
e.push_back(0x00);
if (i >= 0) {
drop_link();
st.conn = i;
printf("[btpeer] %s: connected\n", kPeers[i].name);
}
later(s, i < 0 ? 5120000 : 600000, event(0x03, e));
return true;
}
case 0x0408: { // Create_Connection_Cancel
std::vector<uint8_t> r = {0x00};
put_addr(r, p);
later(s, 500, cmd_complete(op, r));
return true;
}
case 0x0406: { // Disconnect
later(s, 500, cmd_status(op, 0x00));
later(s, 50000, event(0x05, {0x00, (uint8_t)kHandle, (uint8_t)(kHandle >> 8), 0x16}));
if (st.conn >= 0)
printf("[btpeer] %s: the host disconnected\n", kPeers[st.conn].name);
drop_link();
return true;
}
case 0x0411: // Authentication_Requested
later(s, 500, cmd_status(op, 0x00));
if (st.conn >= 0) {
std::vector<uint8_t> e;
put_addr(e, kPeers[st.conn].addr);
later(s, 20000, event(0x17, e)); // Link Key Request
}
return true;
case 0x040C: case 0x040B: { // Link key: none, or one
std::vector<uint8_t> r = {0x00};
put_addr(r, p);
later(s, 500, cmd_complete(op, r));
if (st.conn < 0)
return true;
std::vector<uint8_t> e;
put_addr(e, kPeers[st.conn].addr);
if (op == 0x040B)
later(s, 30000, event(0x06, {0x00, (uint8_t)kHandle, (uint8_t)(kHandle >> 8)}));
else
later(s, 20000, event(0x31, e)); // IO Capability Request
return true;
}
case 0x042B: { // IO_Capability_Request_Reply
std::vector<uint8_t> r = {0x00};
put_addr(r, p);
later(s, 500, cmd_complete(op, r));
if (st.conn < 0)
return true;
const Peer &pr = kPeers[st.conn];
st.last_auth_req = n >= 9 ? p[8] : 0;
std::vector<uint8_t> e;
put_addr(e, pr.addr);
std::vector<uint8_t> resp = e;
resp.insert(resp.end(), {0x03, 0x00, (uint8_t)(pr.needs_bonding ? 0x04 : 0x00)});
later(s, 10000, event(0x32, resp)); // IO Capability Response
if (pr.needs_bonding && !(st.last_auth_req & 0x06)) {
printf("[btpeer] %s: refuses pairing without bonding\n", pr.name);
std::vector<uint8_t> spc = {0x05};
put_addr(spc, pr.addr);
later(s, 30000, event(0x36, spc));
later(s, 35000, event(0x06, {0x05, (uint8_t)kHandle, (uint8_t)(kHandle >> 8)}));
return true;
}
std::vector<uint8_t> conf = e;
conf.insert(conf.end(), {0x40, 0xE2, 0x01, 0x00});
later(s, 20000, event(0x33, conf)); // User Confirmation Request
return true;
}
case 0x042C: { // User_Confirmation_Request_Reply
std::vector<uint8_t> r = {0x00};
put_addr(r, p);
later(s, 500, cmd_complete(op, r));
if (st.conn < 0)
return true;
const Peer &pr = kPeers[st.conn];
std::vector<uint8_t> spc = {0x00};
put_addr(spc, pr.addr);
// The Pro Controller fails its first pairing of a run, as a real one
// can, so a host's second try is exercised too.
static int pro_pairings;
if (pr.type == 3 && pro_pairings++ == 0) {
printf("[btpeer] %s: first pairing fails (authentication failure)\n", pr.name);
spc[0] = 0x05;
later(s, 30000, event(0x36, spc));
later(s, 35000, event(0x06, {0x05, (uint8_t)kHandle, (uint8_t)(kHandle >> 8)}));
return true;
}
later(s, 30000, event(0x36, spc)); // Simple Pairing Complete
std::vector<uint8_t> lk;
put_addr(lk, pr.addr);
for (int i = 0; i < 16; i++)
lk.push_back((uint8_t)(0xA0 + i));
lk.push_back(0x04); // unauthenticated combination key
if (st.last_auth_req & 0x06)
later(s, 35000, event(0x18, lk)); // only kept when bonding
later(s, 40000, event(0x06, {0x00, (uint8_t)kHandle, (uint8_t)(kHandle >> 8)}));
printf("[btpeer] %s: paired (%s)\n", pr.name,
(st.last_auth_req & 0x06) ? "bonding" : "no bonding");
return true;
}
case 0x0413: // Set_Connection_Encryption
later(s, 500, cmd_status(op, 0x00));
if (st.conn >= 0) {
st.encrypted = n >= 3 && p[2];
later(s, 20000, event(0x08, {0x00, (uint8_t)kHandle, (uint8_t)(kHandle >> 8),
(uint8_t)(st.encrypted ? 1 : 0)}));
}
return true;
case 0x040A: // Reject_Connection_Request
later(s, 500, cmd_status(op, 0x00));
return true;
case 0x040E: case 0x042F: { // PIN / passkey negative replies
std::vector<uint8_t> r = {0x00};
put_addr(r, p);
later(s, 500, cmd_complete(op, r));
return true;
}
default:
return false;
}
}
void btpeer_acl(EmuState *s, const uint8_t *pkt, uint32_t n) {
if (n < 8 || st.conn < 0)
return;
uint16_t hf = pkt[0] | pkt[1] << 8;
if ((hf & 0x0FFF) != kHandle)
return;
// Every packet the host sends is acknowledged, as the radio does.
later(s, 1000, event(0x13, {0x01, (uint8_t)kHandle, (uint8_t)(kHandle >> 8), 0x01, 0x00}));
uint16_t l2 = pkt[4] | pkt[5] << 8, cid = pkt[6] | pkt[7] << 8;
if (8u + l2 > n)
return;
const uint8_t *d = pkt + 8;
if (cid == 0x0001)
signal_in(s, d, l2);
else if (cid == st.ch[1].peer_cid && st.ch[1].open)
hid_output(s, d, l2);
}
void btpeer_tick(EmuState *s) {
uint64_t now = now_us(s);
auto &fifo = s->uart_rx_fifo[UART_D];
// What is due, oldest first.
for (;;) {
size_t best = st.q.size();
for (size_t i = 0; i < st.q.size(); i++)
if (st.q[i].due <= now && (best == st.q.size() || st.q[i].due < st.q[best].due))
best = i;
if (best == st.q.size())
break;
for (uint8_t b : st.q[best].bytes)
fifo.push_back(b);
st.q.erase(st.q.begin() + best);
}
if (!st.streaming || st.conn < 0)
return;
// Reports. A host that does not read holds the radio up: past a backlog
// the reports wait instead of piling up, as with flow control.
while (st.next_report <= now) {
if (fifo.size() > kHostBacklog) {
st.next_report = now + kReportUs;
break;
}
uint64_t t = st.next_report - st.stream_at;
std::vector<uint8_t> b;
if (st.full) {
b = report(0x30, t, {});
} else {
// Before it is asked for full reports: the simple 0x3F one.
std::vector<uint8_t> r(1 + 12, 0);
r[0] = 0xA1;
r[1] = 0x3F;
r[4] = 0x08; // hat centred
b = acl(st.ch[1].host_cid, r);
}
for (uint8_t x : b)
fifo.push_back(x);
st.next_report += kReportUs;
}
}
+26
View File
@@ -0,0 +1,26 @@
// Fake Bluetooth controllers for the CYW4356 model (mmio.cpp): what a
// payload acting as an HCI host finds and talks to once the radio is up.
//
// Two peers in pairing mode: a Pro Controller that insists on Secure Simple
// Pairing with bonding before it opens its HID channels, and a right Joy-Con
// that needs no security at all, so both paths of a host are exercised.
// Once a host has both HID channels open, the connected one streams input
// reports in guest time, pressing each of its buttons in turn and sweeping
// its sticks, so a screenshot shows the host's view moving.
//
// This proves a host against this model's reading of the protocol, not
// against a real controller.
#pragma once
#include <cstdint>
struct EmuState;
// The radio went through a power-on reset: forget every connection.
void btpeer_reset(EmuState *state);
// An HCI command the reset model does not answer itself. True when handled.
bool btpeer_command(EmuState *state, uint16_t opcode, const uint8_t *p,
uint32_t n);
// One ACL packet from the host: handle/flags (2), length (2), then data.
void btpeer_acl(EmuState *state, const uint8_t *pkt, uint32_t n);
// Deliver what is due by now. Called on every UART-D register access.
void btpeer_tick(EmuState *state);
+297
View File
@@ -0,0 +1,297 @@
// Generated from the Tegra X1 TRM (DP-07225-001 v1.3p), chapter 5.2:
// CLK_RST_CONTROLLER register reset values, unknown bits as 0.
// Regenerate with trm_car_resets.py; do not edit by hand.
#ifndef T210_CAR_RESET_H
#define T210_CAR_RESET_H
#include <cstdint>
struct CarReset { uint16_t off; uint32_t val; const char *name; };
static const CarReset kCarReset[] = {
{0x000, 0x00000000, "RST_SOURCE"},
{0x004, 0x1CD3D000, "RST_DEVICES_L"},
{0x008, 0x87D1F320, "RST_DEVICES_H"},
{0x00C, 0x828EC5FA, "RST_DEVICES_U"},
{0x010, 0x80000130, "CLK_OUT_ENB_L"},
{0x014, 0x00000080, "CLK_OUT_ENB_H"},
{0x018, 0x01F00200, "CLK_OUT_ENB_U"},
{0x024, 0x00000000, "SUPER_CCLK_DIVIDER"},
{0x028, 0x10000000, "SCLK_BURST_POLICY"},
{0x02C, 0x00000000, "SUPER_SCLK_DIVIDER"},
{0x030, 0x00000000, "CLK_SYSTEM_RATE"},
{0x044, 0x00000000, "CLK_MASK_ARM"},
{0x048, 0x00000000, "MISC_CLK_ENB"},
{0x050, 0x500003F1, "OSC_CTRL"},
{0x05C, 0x00000000, "OSC_FREQ_DET_STATUS"},
{0x068, 0x00005C00, "PLLE_SS_CNTL"},
{0x06C, 0x00000010, "PLLE_MISC1"},
{0x080, 0x00108002, "PLLC_BASE"},
{0x084, 0x00000002, "PLLC_OUT"},
{0x088, 0x40000000, "PLLC_MISC"},
{0x08C, 0x08000000, "PLLC_MISC_1"},
{0x090, 0x00002A02, "PLLM_BASE"},
{0x098, 0x00000000, "PLLM_MISC1"},
{0x09C, 0x00000010, "PLLM_MISC2"},
{0x0A0, 0x00115408, "PLLP_BASE"},
{0x0A4, 0x00000002, "PLLP_OUTA"},
{0x0A8, 0x00020002, "PLLP_OUTB"},
{0x0AC, 0x00040000, "PLLP_MISC"},
{0x0B0, 0x00803003, "PLLA_BASE"},
{0x0B4, 0x00000002, "PLLA_OUT"},
{0x0B8, 0x00000000, "PLLA_MISC1"},
{0x0BC, 0x12000000, "PLLA_MISC"},
{0x0C0, 0x00011902, "PLLU_BASE"},
{0x0C4, 0x00020002, "PLLU_OUTA"},
{0x0C8, 0x00000000, "PLLU_MISC1"},
{0x0CC, 0x00000000, "PLLU_MISC"},
{0x0D0, 0x00211001, "PLLD_BASE"},
{0x0D8, 0x00000000, "PLLD_MISC1"},
{0x0DC, 0x00000000, "PLLD_MISC"},
{0x0E0, 0x00002401, "PLLX_BASE"},
{0x0E4, 0x00000000, "PLLX_MISC"},
{0x0E8, 0x0E007D02, "PLLE_BASE"},
{0x0EC, 0x00000000, "PLLE_MISC"},
{0x0F0, 0x00000000, "PLLE_SS_CNTL1"},
{0x0F4, 0x00000000, "PLLE_SS_CNTL2"},
{0x0F8, 0x00000000, "LVL2_CLK_GATE_OVRA"},
{0x0FC, 0x00000000, "LVL2_CLK_GATE_OVRB"},
{0x100, 0xD0000000, "CLK_SOURCE_I2S2"},
{0x104, 0xD0000000, "CLK_SOURCE_I2S3"},
{0x108, 0xC0000000, "CLK_SOURCE_SPDIF_OUT"},
{0x10C, 0x00000000, "CLK_SOURCE_SPDIF_IN"},
{0x110, 0xC0000000, "CLK_SOURCE_PWM"},
{0x118, 0xC0000000, "CLK_SOURCE_SPI2"},
{0x11C, 0xC0000000, "CLK_SOURCE_SPI3"},
{0x124, 0xC0000000, "CLK_SOURCE_I2C1"},
{0x134, 0xC0000000, "CLK_SOURCE_SPI1"},
{0x138, 0xC0000000, "CLK_SOURCE_DISP1"},
{0x13C, 0xC0000000, "CLK_SOURCE_DISP2"},
{0x144, 0xC0000000, "CLK_SOURCE_ISP"},
{0x148, 0x80000000, "CLK_SOURCE_VI"},
{0x150, 0xC0000000, "CLK_SOURCE_SDMMC1"},
{0x154, 0xC0000000, "CLK_SOURCE_SDMMC2"},
{0x164, 0xC0000000, "CLK_SOURCE_SDMMC4"},
{0x178, 0xC0000002, "CLK_SOURCE_UARTA"},
{0x17C, 0xC0000002, "CLK_SOURCE_UARTB"},
{0x180, 0x80000000, "CLK_SOURCE_HOST1X"},
{0x198, 0xC0000000, "CLK_SOURCE_I2C2"},
{0x1A0, 0xC0000002, "CLK_SOURCE_UARTC"},
{0x1A8, 0x80000000, "CLK_SOURCE_VI_SENSOR"},
{0x1B4, 0xC0000000, "CLK_SOURCE_SPI4"},
{0x1B8, 0xC0000000, "CLK_SOURCE_I2C3"},
{0x1BC, 0xC0000000, "CLK_SOURCE_SDMMC3"},
{0x1C0, 0xC0000002, "CLK_SOURCE_UARTD"},
{0x1CC, 0xC0000000, "CLK_SOURCE_OWR"},
{0x1D4, 0xC0000000, "CLK_SOURCE_CSITE"},
{0x1D8, 0xD0000000, "CLK_SOURCE_I2S1"},
{0x1DC, 0x00000000, "CLK_SOURCE_DTV"},
{0x1F4, 0xC0000000, "CLK_SOURCE_TSEC"},
{0x1F8, 0xC0000000, "CLK_SOURCE_LA"},
{0x1FC, 0x00000000, "CLK_SPARE2"},
{0x280, 0x23000780, "CLK_OUT_ENB_X"},
{0x284, 0x23000780, "CLK_ENB_X_SET"},
{0x288, 0x23000780, "CLK_ENB_X_CLR"},
{0x28C, 0x01E42049, "RST_DEVICES_X"},
{0x290, 0x01E42049, "RST_DEV_X_SET"},
{0x294, 0x01E42049, "RST_DEV_X_CLR"},
{0x298, 0x00000300, "CLK_OUT_ENB_Y"},
{0x29C, 0x00000300, "CLK_ENB_Y_SET"},
{0x2A0, 0x00000300, "CLK_ENB_Y_CLR"},
{0x2A4, 0x0FE9F0DD, "RST_DEVICES_Y"},
{0x2A8, 0x0FE9F0DD, "RST_DEV_Y_SET"},
{0x2AC, 0x0FE9F0DD, "RST_DEV_Y_CLR"},
{0x2F4, 0x00000001, "DFLL_BASE"},
{0x304, 0x1CD3D000, "RST_DEV_L_CLR"},
{0x308, 0x87D1F320, "RST_DEV_H_SET"},
{0x30C, 0x87D1F327, "RST_DEV_H_CLR"},
{0x310, 0x828EC5FA, "RST_DEV_U_SET"},
{0x314, 0x828EC5FA, "RST_DEV_U_CLR"},
{0x320, 0x80000130, "CLK_ENB_L_SET"},
{0x324, 0x80000130, "CLK_ENB_L_CLR"},
{0x328, 0x00000080, "CLK_ENB_H_SET"},
{0x32C, 0x00000080, "CLK_ENB_H_CLR"},
{0x330, 0x01F80200, "CLK_ENB_U_SET"},
{0x334, 0x01F00200, "CLK_ENB_U_CLR"},
{0x33C, 0x00000000, "CCPLEX_PG_SM_OVRD"},
{0x340, 0x2000FEEF, "RST_CPU_CMPLX_SET"},
{0x358, 0xFF818080, "RST_DEVICES_V"},
{0x35C, 0x190077FF, "RST_DEVICES_W"},
{0x360, 0x00400008, "CLK_OUT_ENB_V"},
{0x364, 0x402000FC, "CLK_OUT_ENB_W"},
{0x368, 0x10000000, "CCLKG_BURST_POLICY"},
{0x36C, 0x00000000, "SUPER_CCLKG_DIVIDER"},
{0x374, 0x00000000, "SUPER_CCLKLP_DIVIDER"},
{0x380, 0x00000010, "CPU_SOFTRST_CTRL"},
{0x384, 0x00040004, "CPU_SOFTRST_CTRL1"},
{0x388, 0x07000200, "CPU_SOFTRST_CTRL2"},
{0x3A0, 0x00000000, "LVL2_CLK_GATE_OVRC"},
{0x3A4, 0x00000000, "LVL2_CLK_GATE_OVRD"},
{0x3B4, 0xC0000000, "CLK_SOURCE_MSELECT"},
{0x3B8, 0xC0000000, "CLK_SOURCE_TSENSOR"},
{0x3BC, 0xD0000000, "CLK_SOURCE_I2S4"},
{0x3C0, 0xD0000000, "CLK_SOURCE_I2S5"},
{0x3C4, 0xC0000000, "CLK_SOURCE_I2C4"},
{0x3D0, 0xD0000000, "CLK_SOURCE_AHUB"},
{0x3E4, 0xC0000000, "CLK_SOURCE_HDA2CODEC_2X"},
{0x3E8, 0xC0000000, "CLK_SOURCE_ACTMON"},
{0x3EC, 0x60000000, "CLK_SOURCE_EXTPERIPH1"},
{0x3F0, 0x60000000, "CLK_SOURCE_EXTPERIPH2"},
{0x3F4, 0x60000000, "CLK_SOURCE_EXTPERIPH3"},
{0x3FC, 0xC0000000, "CLK_SOURCE_I2C_SLOW"},
{0x410, 0xC0000000, "CLK_SOURCE_SOR1"},
{0x414, 0x00000000, "CLK_SOURCE_SOR0"},
{0x420, 0xC0000000, "CLK_SOURCE_SATA_OOB"},
{0x424, 0xC1000000, "CLK_SOURCE_SATA"},
{0x428, 0xC0000000, "CLK_SOURCE_HDA"},
{0x430, 0xFF818080, "RST_DEV_V_SET"},
{0x434, 0xFF818080, "RST_DEV_V_CLR"},
{0x438, 0x190077FF, "RST_DEV_W_SET"},
{0x43C, 0x190077FF, "RST_DEV_W_CLR"},
{0x440, 0x00400008, "CLK_ENB_V_SET"},
{0x444, 0x00400008, "CLK_ENB_V_CLR"},
{0x448, 0x402000FC, "CLK_ENB_W_SET"},
{0x44C, 0x402000FC, "CLK_ENB_W_CLR"},
{0x450, 0x2000FEEF, "RST_CPUG_CMPLX_SET"},
{0x454, 0x2000FEEF, "RST_CPUG_CMPLX_CLR"},
{0x460, 0x00000000, "CLK_CPUG_CMPLX_SET"},
{0x464, 0x00000000, "CLK_CPUG_CMPLX_CLR"},
{0x470, 0x00000000, "CPU_CMPLX_STATUS"},
{0x47C, 0x00000000, "INTMASK"},
{0x488, 0x00318015, "UTMIP_PLL_CFG2"},
{0x48C, 0x00002070, "PLLE_AUX"},
{0x494, 0x00011400, "SATA_PLL_CFG1"},
{0x4A0, 0x00000000, "AUDIO_SYNC_CLK_I2S1"},
{0x4A4, 0x00000000, "AUDIO_SYNC_CLK_I2S2"},
{0x4A8, 0x00000000, "AUDIO_SYNC_CLK_I2S3"},
{0x4AC, 0x00000000, "AUDIO_SYNC_CLK_I2S4"},
{0x4B0, 0x00000000, "AUDIO_SYNC_CLK_I2S5"},
{0x4B4, 0x00000000, "AUDIO_SYNC_CLK_SPDIF"},
{0x4B8, 0x00041401, "PLLD2_BASE"},
{0x4BC, 0x40000000, "PLLD2_MISC"},
{0x4C0, 0x00000000, "UTMIP_PLL_CFG3"},
{0x4C4, 0x00004104, "PLLREFE_BASE"},
{0x4C8, 0x00000000, "PLLREFE_MISC"},
{0x4CC, 0x00020002, "PLLREFE_OUT"},
{0x4D0, 0x00000000, "CPU_FINETRIM_BYP"},
{0x4D4, 0x00000000, "CPU_FINETRIM_SELECT"},
{0x4D8, 0x00000000, "CPU_FINETRIM_DR"},
{0x4DC, 0x00000000, "CPU_FINETRIM_DF"},
{0x4E0, 0x00000000, "CPU_FINETRIM_F"},
{0x4E4, 0x00000000, "CPU_FINETRIM_R"},
{0x4E8, 0x00108002, "PLLC2_BASE"},
{0x4EC, 0x40000000, "PLLC2_MISC"},
{0x4F0, 0x08000000, "PLLC2_MISC_1"},
{0x4F4, 0x1F720005, "PLLC2_MISC_2"},
{0x4F8, 0x000000C4, "PLLC2_MISC_3"},
{0x4FC, 0x00108002, "PLLC3_BASE"},
{0x500, 0x40000000, "PLLC3_MISC"},
{0x504, 0x08000000, "PLLC3_MISC_1"},
{0x508, 0x1F720005, "PLLC3_MISC_2"},
{0x50C, 0x000000C4, "PLLC3_MISC_3"},
{0x510, 0x00000000, "PLLX_MISC_1"},
{0x514, 0x00000000, "PLLX_MISC_2"},
{0x518, 0x00000008, "PLLX_MISC_3"},
{0x520, 0x00000014, "XUSBIO_PLL_CFG1"},
{0x524, 0x00000105, "PLLE_AUX1"},
{0x528, 0x00000053, "PLLP_RESHIFT"},
{0x52C, 0x0000000F, "UTMIPLL_HW_PWRDN_CFG0"},
{0x530, 0x0000008D, "PLLU_HW_PWRDN_CFG0"},
{0x534, 0x8002A80F, "XUSB_PLL_CFG0"},
{0x53C, 0x00000002, "CLK_CPU_MISC"},
{0x540, 0x00000002, "CLK_CPUG_MISC"},
{0x548, 0x00000001, "PLLX_HW_CTRL_CFG"},
{0x54C, 0x00000000, "PLLX_SW_RAMP_CFG"},
{0x550, 0x00000000, "PLLX_HW_CTRL_STATUS"},
{0x554, 0x00000000, "LVL2_CLK_GATE_OVRE"},
{0x55C, 0x00000000, "SPARE_REG0"},
{0x560, 0x00000000, "AUDIO_SYNC_CLK_DMIC1"},
{0x564, 0x00000000, "AUDIO_SYNC_CLK_DMIC2"},
{0x570, 0x10000000, "PLLD2_SS_CFG"},
{0x574, 0x00000000, "PLLD2_SS_CTRL1"},
{0x578, 0x00000000, "PLLD2_SS_CTRL2"},
{0x594, 0x40000000, "PLLDP_MISC"},
{0x598, 0x10000000, "PLLDP_SS_CFG"},
{0x59C, 0x00000000, "PLLDP_SS_CTRL1"},
{0x5A0, 0x00000000, "PLLDP_SS_CTRL2"},
{0x5A4, 0x000C2302, "PLLC4_BASE"},
{0x5A8, 0x40000000, "PLLC4_MISC"},
{0x5C4, 0x00000000, "CLK_SPARE0"},
{0x5C8, 0x00000000, "CLK_SPARE1"},
{0x5CC, 0x00000000, "GPU_ISOB_CTRL"},
{0x5D0, 0x1F720005, "PLLC_MISC_2"},
{0x5D4, 0x000000C4, "PLLC_MISC_3"},
{0x5D8, 0x00000000, "PLLA_MISC2"},
{0x5E4, 0x00000002, "PLLC4_OUT"},
{0x5E8, 0x00002A02, "PLLMB_BASE"},
{0x5EC, 0x00010000, "PLLMB_MISC1"},
{0x5F0, 0x00000000, "PLLX_MISC_4"},
{0x5F4, 0x00000000, "PLLX_MISC_5"},
{0x600, 0x00000000, "CLK_SOURCE_XUSB_CORE_HOST"},
{0x604, 0x00000000, "CLK_SOURCE_XUSB_FALCON"},
{0x608, 0x00000000, "CLK_SOURCE_XUSB_FS"},
{0x60C, 0x00000000, "CLK_SOURCE_XUSB_CORE_DEV"},
{0x610, 0x04000000, "CLK_SOURCE_XUSB_SS"},
{0x614, 0xC0000000, "CLK_SOURCE_CILAB"},
{0x618, 0xC0000000, "CLK_SOURCE_CILCD"},
{0x61C, 0xC0000000, "CLK_SOURCE_CILEF"},
{0x620, 0xC0000000, "CLK_SOURCE_DSIA_LP"},
{0x624, 0xC0000000, "CLK_SOURCE_DSIB_LP"},
{0x628, 0x40000000, "CLK_SOURCE_ENTROPY"},
{0x62C, 0xD0000000, "CLK_SOURCE_DVFS_REF"},
{0x630, 0xD0000000, "CLK_SOURCE_DVFS_SOC"},
{0x640, 0x60000000, "CLK_SOURCE_EMC_LATENCY"},
{0x644, 0x40000000, "CLK_SOURCE_SOC_THERM"},
{0x64C, 0x00000000, "CLK_SOURCE_DMIC1"},
{0x650, 0x00000000, "CLK_SOURCE_DMIC2"},
{0x658, 0x80000000, "CLK_SOURCE_VI_SENSOR2"},
{0x65C, 0xC0000000, "CLK_SOURCE_I2C6"},
{0x660, 0xC0000000, "CLK_SOURCE_MIPIBIF"},
{0x664, 0x60000000, "CLK_SOURCE_EMC_DLL"},
{0x66C, 0x00000000, "CLK_SOURCE_UART_FST_MIPI_CAL"},
{0x678, 0xC0000000, "CLK_SOURCE_VIC"},
{0x67C, 0x00030000, "PLLP_OUTC"},
{0x680, 0x30000000, "PLLP_MISC1"},
{0x694, 0x00000000, "CLK_SOURCE_SDMMC_LEGACY_TM"},
{0x698, 0xE0000000, "CLK_SOURCE_NVDEC"},
{0x69C, 0xE0000000, "CLK_SOURCE_NVJPG"},
{0x6A0, 0x80000000, "CLK_SOURCE_NVENC"},
{0x6A4, 0x00108002, "PLLA1_BASE"},
{0x6A8, 0x40000000, "PLLA1_MISC"},
{0x6AC, 0x08000000, "PLLA1_MISC_1"},
{0x6B0, 0x1F720005, "PLLA1_MISC_2"},
{0x6B4, 0x000000C4, "PLLA1_MISC_3"},
{0x6B8, 0x00000000, "AUDIO_SYNC_CLK_DMIC3"},
{0x6BC, 0x00000000, "CLK_SOURCE_DMIC3"},
{0x6C0, 0xC0000000, "CLK_SOURCE_APE"},
{0x6C4, 0xC0000000, "CLK_SOURCE_QSPI"},
{0x6C8, 0xC0000000, "CLK_SOURCE_VI_I2C"},
{0x6CC, 0x00000000, "CLK_SOURCE_USB2_HSIC_TRK"},
{0x6D0, 0x00000000, "CLK_SOURCE_PEX_SATA_USB_RX_BYP"},
{0x6D4, 0x40000000, "CLK_SOURCE_MAUD"},
{0x6D8, 0xC0000000, "CLK_SOURCE_TSECB"},
{0x6DC, 0x00000002, "CLK_CPUG_MISC1"},
{0x6E0, 0x10006666, "ACLK_BURST_POLICY"},
{0x6E4, 0x00000000, "SUPER_ACLK_DIVIDER"},
{0x6E8, 0x80000000, "NVENC_SUPER_CLK_DIVIDER"},
{0x6EC, 0x80000000, "VI_SUPER_CLK_DIVIDER"},
{0x6F0, 0x80000000, "VIC_SUPER_CLK_DIVIDER"},
{0x6F4, 0x80000000, "NVDEC_SUPER_CLK_DIVIDER"},
{0x6F8, 0x80000000, "ISP_SUPER_CLK_DIVIDER"},
{0x6FC, 0x80000000, "ISPB_SUPER_CLK_DIVIDER"},
{0x700, 0x80000000, "NVJPG_SUPER_CLK_DIVIDER"},
{0x704, 0x80000000, "SE_SUPER_CLK_DIVIDER"},
{0x708, 0x80000000, "TSEC_SUPER_CLK_DIVIDER"},
{0x70C, 0x80000000, "TSECB_SUPER_CLK_DIVIDER"},
{0x710, 0xC0000002, "CLK_SOURCE_UARTAPE"},
{0x714, 0x00000000, "CLK_CPUG_MISC2"},
{0x718, 0xC0000000, "CLK_SOURCE_DBGAPB"},
{0x71C, 0x001FFFFF, "CLK_CCPLEX_CC4_RET_CLK_ENB"},
{0x720, 0x00000400, "ACTMON_CPU_CLK"},
{0x724, 0x60000000, "CLK_SOURCE_EMC_SAFE"},
{0x728, 0x00000C00, "SDMMC2_PLLC4_OUT0_SHAPER_CTRL"},
{0x72C, 0x00000C00, "SDMMC2_PLLC4_OUT1_SHAPER_CTRL"},
{0x730, 0x00000C00, "SDMMC2_PLLC4_OUT2_SHAPER_CTRL"},
{0x734, 0x00000C00, "SDMMC2_DIV_CLK_SHAPER_CTRL"},
};
#endif
+1096
View File
File diff suppressed because it is too large. Load diff
+69
View File
@@ -0,0 +1,69 @@
#ifndef T210_CCPLEX_H
#define T210_CCPLEX_H
#include <cstdint>
struct EmuState;
/*
* CCPLEX CPU0 - the first Cortex-A57 of the Tegra X1's main CPU cluster.
*
* An RCM payload runs on the BPMP, but it can boot CPU0 itself with bdk's
* ccplex_boot_cpu0(): rail on, PLLX, CCLK, the CRAIL/C0NC/CE0 partitions,
* RAM repair, the AArch64 reset vector in SB_AA64_RESET_LOW/HIGH, then
* RST_CPUG_CMPLX_CLR. hwtest does exactly that for its PCIe probe, because
* PCIe answers a CPU-complex master only.
*
* This model watches those registers and, when the core is released with
* every precondition met, runs it: a second Unicorn engine in AArch64 mode,
* entered at EL3 with the MMU off at the programmed vector, sharing IRAM,
* DRAM, TZRAM and every peripheral model with the BPMP. A release that is
* missing something does not start the core, and says which precondition
* was missing - on silicon the core would simply never run.
*
* Time: CPU0 keeps its own clock, advanced by the instructions it retires
* and by the latency of each bus access it makes, and the main loop runs it
* in short slices up to the BPMP's current time. WFE/WFI park it until the
* end of the slice. Everything is a pure function of the instruction stream,
* so runs stay deterministic.
*/
// Power-on state: CPU0 in reset, no vector, clocks off.
void ccplex_reset(EmuState *state);
// CAR (clock and reset controller) forwarding.
void ccplex_car_write(EmuState *state, uint32_t offset, uint32_t val);
bool ccplex_car_read(uint32_t offset, uint32_t *out);
// SB block (SYSREG + 0x200): SB_CSR and the AArch64 reset vector.
uint32_t ccplex_sb_read(uint32_t offset);
void ccplex_sb_write(EmuState *state, uint32_t offset, uint32_t val);
// A PMC power partition toggled / the CPU rail regulator changed. Losing any
// of them under a running core stops it.
void ccplex_partition_changed(EmuState *state, int part, bool on);
void ccplex_rail_changed(EmuState *state);
// Something CPU0 needs in order to run changed (MSELECT reset released, ...):
// a core already out of reset but refused starts if nothing is missing now.
void ccplex_preconditions_changed(EmuState *state);
// CPU0's own clock, in emulated microseconds: what TIMERUS reads from CPU0.
uint64_t ccplex_now_us();
// Called by the MMIO front-end for every access CPU0 makes: charges the bus
// latency to CPU0's clock before the access is dispatched.
void ccplex_bus_tick(EmuState *state);
// True while CPU0 is out of reset and executing (not parked on a hung bus).
bool ccplex_cpu0_running();
// TMR10..TMR13 (TMR base + 0x90..0xAF): the timers Tegra210 kernels use as
// per-CPU clock event devices. Their interrupts go to GIC SPI 176..179 on
// CPU0's clock.
void ccplex_tmr_write(uint32_t off, uint32_t val);
// Run CPU0 until its clock reaches `until_us` - the BPMP's current time.
void ccplex_run(EmuState *state, uint64_t until_us);
#endif // T210_CCPLEX_H
+1228
View File
File diff suppressed because it is too large. Load diff
+72
View File
@@ -0,0 +1,72 @@
#ifndef T210_DOCK_H
#define T210_DOCK_H
#include <cstdint>
struct EmuState;
/*
* The USB-C port, the dock on it and the TV behind the dock.
*
* BM92T36 (I2C1 0x18): the PD controller's registers and commands as
* switchroot's bm92txx.c and HOS's usb sysmodule drive them, with a partner
* on the cable that answers the way the measured docks did: a Nintendo dock
* (057E:2003, 5 V 0.5 A + 15 V 3 A, Nintendo alt mode, DP pin D), a third-
* party adapter (Fresco Logic 1D5C:7102, four PDOs, DisplayPort SVID) or
* the Nintendo charger (057E:2004, no video). Its interrupt is GPIO PK4,
* active low; its reset is PV5.
*
* DPAUX1 (0x54040000): the AUX channel to the dock's DisplayPort-to-HDMI
* converter (Realtek OUI 00-E0-4C, DPCD 1.2), its DPCD, and the TV's EDID
* over I2C-over-AUX. HPD reaches DPAUX1 only while the hdmi_int_dp_hpd pad
* is in SFIO mode, as measured.
*
* SOR1 (0x54580000): link training is judged lane by lane against what the
* board does - DP lane 0 leaves the SoC on pad 0 and lane 1 on pad 1, so the
* crossbar has to route them there (L4T's nvidia,xbar-ctrl <2 1 0 3 4>), and
* a lane only trains with its pad powered, the macro PLL up, PLLDP locked
* and SOR1 clocked from the brick at the rate the sink was told.
*/
enum DockKind : uint8_t {
DOCK_NONE = 0,
DOCK_NINTENDO = 1,
DOCK_THIRD_PARTY = 2, // Ugreen-style adapter: Fresco Logic 1D5C:7102
DOCK_CHARGER = 3, // Nintendo charger, no DisplayPort
};
void dock_reset(EmuState *state);
// Advance the dock's timers to state->emu_usec. Cheap; called often.
void dock_tick(EmuState *state);
// BM92T36. A write carries its register first; a read returns n bytes from
// `reg` on (block registers lead with their length byte, as on the chip).
bool bm92_present(EmuState *state);
void bm92_write(EmuState *state, const uint8_t *buf, uint32_t n);
void bm92_read(EmuState *state, uint8_t reg, uint8_t *out, uint32_t n);
// PK4 as the SoC sees it: false while an enabled alert is pending.
bool bm92_alert_line(EmuState *state);
// PV5 driven by the SoC: high holds the chip in reset.
void bm92_reset_line(EmuState *state, bool high);
// HPD from the dock's DisplayPort sink.
bool dock_hpd(EmuState *state);
// DPAUX1 and SOR1 register windows (byte offsets).
uint32_t dpaux1_read(EmuState *state, uint32_t off);
void dpaux1_write(EmuState *state, uint32_t off, uint32_t val);
uint32_t sor1_read(EmuState *state, uint32_t off);
void sor1_write(EmuState *state, uint32_t off, uint32_t val);
// What the TV shows, for its window.
struct TvState {
bool connected; // a dock with a TV behind it is on the cable
bool hpd; // the converter raised HPD to the SoC
bool link_trained; // every configured lane has CR, EQ, symbol lock
bool video; // SOR1 attached to a running head: frames flow
uint32_t lanes, rate_code;
char status[160]; // one line for the "no signal" screen
};
void dock_tv_state(EmuState *state, TvState *out);
#endif // T210_DOCK_H
+307
View File
@@ -0,0 +1,307 @@
#include "gic.h"
#include <cstdio>
#include <cstring>
/*
* GIC-400 model. See gic.h. Register offsets and reset values: ARM IHI 0048B
* (GICv2 architecture) ch.4, GIC-400 TRM (DDI 0471B) table 3-1 / 3-6.
*/
namespace {
struct Gic {
uint32_t dctlr = 0;
uint32_t cctlr = 0;
uint32_t pmr = 0;
uint32_t bpr = 2;
uint32_t group[GIC_NR_IRQS / 32] = {};
bool enabled[GIC_NR_IRQS] = {};
bool latched[GIC_NR_IRQS] = {}; // edge, SGI or software-set pending
bool line[GIC_NR_IRQS] = {}; // level input
bool active[GIC_NR_IRQS] = {};
uint8_t prio[GIC_NR_IRQS] = {};
uint8_t target[GIC_NR_IRQS] = {};
uint8_t cfg[GIC_NR_IRQS] = {}; // 2 bits each, bit 1 set = edge
// Active priorities, most recent last: the running priority is the
// highest (numerically lowest) of them.
int stack[GIC_NR_IRQS] = {};
int depth = 0;
};
Gic g;
// CPU0 asks "is an interrupt pending?" before every translated block, so the
// answer is cached and recomputed only after something changed.
bool g_dirty = true;
int g_best = 1023;
bool g_line_up = false;
bool is_edge(int id) { return id < 16 || (g.cfg[id] & 2); }
bool pending(int id) {
if (g.latched[id])
return true;
return !is_edge(id) && g.line[id];
}
int running_prio() {
int p = 0x100;
for (int i = 0; i < g.depth; i++)
if (g.prio[g.stack[i]] < p)
p = g.prio[g.stack[i]];
return p;
}
int best_scan() {
int bestid = 1023, bestp = 0x100;
for (int id = 0; id < GIC_NR_IRQS; id++) {
if (!g.enabled[id] || g.active[id] || !pending(id))
continue;
if (g.prio[id] < bestp) {
bestp = g.prio[id];
bestid = id;
}
}
return bestid;
}
int best() {
if (g_dirty) {
g_best = best_scan();
g_line_up = false;
if ((g.dctlr & 3) && (g.cctlr & 3) && g_best != 1023)
g_line_up = g.prio[g_best] < g.pmr && g.prio[g_best] < running_prio();
g_dirty = false;
}
return g_best;
}
uint32_t bits_read(const bool *v, uint32_t word) {
uint32_t r = 0;
for (int b = 0; b < 32; b++)
if (v[word * 32 + b])
r |= 1u << b;
return r;
}
uint32_t pend_read(uint32_t word) {
uint32_t r = 0;
for (int b = 0; b < 32; b++)
if (pending(word * 32 + b))
r |= 1u << b;
return r;
}
// Byte-array registers (priority, targets) accessed by byte or by word.
uint32_t bytes_read(const uint8_t *a, uint32_t off, unsigned size) {
uint32_t r = 0;
for (unsigned i = 0; i < size && off + i < GIC_NR_IRQS; i++)
r |= (uint32_t)a[off + i] << (8 * i);
return r;
}
void bytes_write(uint8_t *a, uint32_t off, unsigned size, uint32_t v,
uint8_t mask) {
for (unsigned i = 0; i < size && off + i < GIC_NR_IRQS; i++)
a[off + i] = (uint8_t)((v >> (8 * i)) & mask);
}
} // namespace
void gic_reset() {
g = Gic();
g_dirty = true;
for (int id = 0; id < 32; id++)
g.target[id] = 0x01; // banked: reads this CPU's own bit
for (int id = 0; id < 16; id++)
g.enabled[id] = true; // SGIs are always enabled on GIC-400
for (int id = 16; id < 32; id++)
g.cfg[id] = 0; // PPIs level
}
uint32_t gic_dist_read(uint32_t off, unsigned size) {
if (off >= 0x400 && off < 0x400 + GIC_NR_IRQS)
return bytes_read(g.prio, off - 0x400, size);
if (off >= 0x800 && off < 0x800 + GIC_NR_IRQS) {
uint32_t i = off - 0x800;
if (i < 32)
return bytes_read(g.target, i, size);
return bytes_read(g.target, i, size);
}
uint32_t w = (off & 0x7F) >> 2;
switch (off & ~0x7Fu) {
case 0x080: return w < GIC_NR_IRQS / 32 ? g.group[w] : 0;
case 0x100: case 0x180: return w < GIC_NR_IRQS / 32 ? bits_read(g.enabled, w) : 0;
case 0x200: case 0x280: return w < GIC_NR_IRQS / 32 ? pend_read(w) : 0;
case 0x300: case 0x380: return w < GIC_NR_IRQS / 32 ? bits_read(g.active, w) : 0;
default: break;
}
if (off >= 0xC00 && off < 0xC00 + GIC_NR_IRQS / 4) {
uint32_t base = (off - 0xC00) * 4, r = 0;
for (int i = 0; i < 16; i++)
r |= (uint32_t)(g.cfg[base + i] & 3) << (2 * i);
return r;
}
switch (off) {
case 0x000: return g.dctlr;
case 0x004: return (1u << 10) | (3u << 5) | (GIC_NR_IRQS / 32 - 1); // SecExt, 4 CPUs
case 0x008: return 0x0200143B; // GIC-400, implementer ARM
case 0xFE8: return 0x2B; // PIDR2: GICv2
case 0xFD0: return 0x04;
case 0xFE0: return 0x90;
case 0xFE4: return 0xB4;
case 0xFEC: return 0x00;
case 0xFF0: return 0x0D;
case 0xFF4: return 0xF0;
case 0xFF8: return 0x05;
case 0xFFC: return 0xB1;
default: return 0;
}
}
void gic_dist_write(uint32_t off, unsigned size, uint32_t val) {
g_dirty = true;
if (off >= 0x400 && off < 0x400 + GIC_NR_IRQS) {
bytes_write(g.prio, off - 0x400, size, val, 0xF8); // 5 priority bits
return;
}
if (off >= 0x800 && off < 0x800 + GIC_NR_IRQS) {
uint32_t i = off - 0x800;
if (i >= 32)
bytes_write(g.target, i, size, val, 0xFF);
return;
}
if (off >= 0xC00 && off < 0xC00 + GIC_NR_IRQS / 4) {
uint32_t base = (off - 0xC00) * 4;
for (int i = 0; i < 16; i++)
if (base + i >= 16) // SGI configuration is read-only
g.cfg[base + i] = (uint8_t)((val >> (2 * i)) & 3);
return;
}
uint32_t w = (off & 0x7F) >> 2;
bool inrange = w < GIC_NR_IRQS / 32;
switch (off & ~0x7Fu) {
case 0x080: if (inrange) g.group[w] = val; return;
case 0x100:
if (inrange) for (int b = 0; b < 32; b++) if (val & (1u << b)) g.enabled[w * 32 + b] = true;
return;
case 0x180:
if (inrange) for (int b = 0; b < 32; b++)
if ((val & (1u << b)) && w * 32 + b >= 16) g.enabled[w * 32 + b] = false;
return;
case 0x200:
if (inrange) for (int b = 0; b < 32; b++) if (val & (1u << b)) g.latched[w * 32 + b] = true;
return;
case 0x280:
if (inrange) for (int b = 0; b < 32; b++) if (val & (1u << b)) g.latched[w * 32 + b] = false;
return;
case 0x300:
if (inrange) for (int b = 0; b < 32; b++) if (val & (1u << b)) g.active[w * 32 + b] = true;
return;
case 0x380:
if (inrange) for (int b = 0; b < 32; b++) if (val & (1u << b)) g.active[w * 32 + b] = false;
return;
default: break;
}
switch (off) {
case 0x000: g.dctlr = val & 3; return;
case 0xF00: { // GICD_SGIR
int id = val & 0xF;
uint32_t filter = (val >> 24) & 3, targets = (val >> 16) & 0xFF;
bool to_me = filter == 2 || (filter == 0 && (targets & 1));
if (to_me)
g.latched[id] = true;
return;
}
default: return;
}
}
uint32_t gic_cpu_read(uint32_t off, unsigned size) {
(void)size;
if (off == 0x0C || off == 0x20)
g_dirty = true;
switch (off) {
case 0x00: return g.cctlr;
case 0x04: return g.pmr;
case 0x08: return g.bpr;
case 0x0C: case 0x20: { // IAR / AIAR: acknowledge
if (!(g.dctlr & 3) || !(g.cctlr & 3))
return 1023;
int id = best();
if (id == 1023 || g.prio[id] >= g.pmr || g.prio[id] >= running_prio())
return 1023;
g.active[id] = true;
g.latched[id] = false;
if (g.depth < GIC_NR_IRQS)
g.stack[g.depth++] = id;
return (uint32_t)id; // SGI source CPU field: CPU0, i.e. 0
}
case 0x14: return (uint32_t)(running_prio() & 0xFF);
case 0x18: case 0x28: return (uint32_t)best();
case 0x1C: return g.bpr;
case 0xFC: return 0x0202143B; // GICC_IIDR, GIC-400
default: return 0;
}
}
void gic_cpu_write(uint32_t off, unsigned size, uint32_t val) {
(void)size;
g_dirty = true;
switch (off) {
case 0x00: g.cctlr = val & 0x3FF; return;
case 0x04: g.pmr = val & 0xF8; return;
case 0x08: case 0x1C: g.bpr = val & 7; return;
case 0x10: case 0x24: case 0x1000: { // EOIR / AEOIR / DIR
int id = (int)(val & 0x3FF);
if (id >= GIC_NR_IRQS)
return;
g.active[id] = false;
for (int i = g.depth - 1; i >= 0; i--)
if (g.stack[i] == id) {
memmove(&g.stack[i], &g.stack[i + 1], (g.depth - i - 1) * sizeof(int));
g.depth--;
break;
}
return;
}
default: return;
}
}
void gic_set_spi(int spi, bool level) {
int id = 32 + spi;
if (spi < 0 || id >= GIC_NR_IRQS)
return;
if (g.line[id] == level)
return;
if (level && is_edge(id))
g.latched[id] = true; // rising edge of an edge-configured line
g.line[id] = level;
g_dirty = true;
}
void gic_set_ppi(int id, bool level) {
if (id < 16 || id >= 32 || g.line[id] == level)
return;
g.line[id] = level;
g_dirty = true;
}
bool gic_irq_pending() {
best();
return g_line_up;
}
int gic_highest_pending() { return best(); }
void gic_describe(int id, char *buf, unsigned n) {
if (id < 0 || id >= GIC_NR_IRQS) {
snprintf(buf, n, "?");
return;
}
snprintf(buf, n, "dctlr %u cctlr %u pmr %02X id%d en %d line %d latch %d act %d prio %02X depth %d",
g.dctlr, g.cctlr, g.pmr, id, g.enabled[id], g.line[id], g.latched[id],
g.active[id], g.prio[id], g.depth);
}
+48
View File
@@ -0,0 +1,48 @@
#ifndef T210_GIC_H
#define T210_GIC_H
#include <cstdint>
/*
* GIC-400 - the interrupt controller in front of the CCPLEX (Tegra X1 TRM
* ch.3; ARM IHI 0048B, GICv2). Distributor at 0x50041000, CPU interface at
* 0x50042000 (8 KiB: GICC_DIR is at +0x1000).
*
* One CPU interface is modelled: CPU0 is the only core the emulator runs.
* Security is not: both groups behave as one, which is all a kernel booted
* non-secure ever sees. Peripherals drive level lines (gic_set_spi); SGIs
* and edge-configured interrupts latch.
*/
constexpr uint64_t GICD_BASE = 0x50041000;
constexpr uint64_t GICD_SIZE = 0x1000;
constexpr uint64_t GICC_BASE = 0x50042000;
constexpr uint64_t GICC_SIZE = 0x2000;
constexpr int GIC_NR_IRQS = 256; // 32 private + 224 SPIs (ITLinesNumber 7)
constexpr int GIC_PPI_VTIMER = 27; // EL1 virtual timer
constexpr int GIC_PPI_PTIMER = 30; // EL1 physical (non-secure) timer
void gic_reset();
uint32_t gic_dist_read(uint32_t off, unsigned size);
void gic_dist_write(uint32_t off, unsigned size, uint32_t val);
uint32_t gic_cpu_read(uint32_t off, unsigned size);
void gic_cpu_write(uint32_t off, unsigned size, uint32_t val);
// A peripheral's interrupt line. `spi` is the SPI number as device trees
// write it (<GIC_SPI n ...>); the interrupt ID is 32 + n.
void gic_set_spi(int spi, bool level);
// A private peripheral interrupt line (ID 16..31) of CPU0.
void gic_set_ppi(int id, bool level);
// CPU0's nIRQ: something enabled, pending, not active and above the
// priority mask and the running priority.
bool gic_irq_pending();
// For the log: the interrupt ID that IRQ would deliver, or 1023.
int gic_highest_pending();
// One line of the distributor and CPU interface state for interrupt `id`.
void gic_describe(int id, char *buf, unsigned n);
#endif // T210_GIC_H
+26 -10
View File
@@ -132,17 +132,15 @@ void push_controller_ready() {
if (ev_stack.size() < 32) ev_stack.push_back(ev);
}
// If SDL has flagged a pending touch event, pack it into the FTS4 stack.
// Move whatever SDL has queued into the FTS4 event stack, oldest first.
void try_emit_pending_touch(EmuState *state) {
bool was_pending = state->tc_event_pending.exchange(false);
if (!was_pending) return;
uint8_t op = state->tc_event_op.load();
uint16_t x = state->tc_x.load();
uint16_t y = state->tc_y.load();
// pressure: a small non-zero value keeps z below the 500-palm-reject threshold
// in touch.c (z = (pressure_lo|pressure_hi<<8) << 6 / (mod+0x40)).
uint16_t pressure = (op == FTS4_EV_MULTI_TOUCH_LEAVE) ? 0 : 0x10;
push_event(op, state->tc_finger_id, x, y, pressure);
EmuState::TouchEvent ev;
while (ev_stack.size() < 32 && state->touch_take(&ev)) {
// pressure: a small non-zero value keeps z below the 500-palm-reject
// threshold in touch.c (z = (pressure_lo|pressure_hi<<8) << 6 / (mod+0x40)).
uint16_t pressure = (ev.op == FTS4_EV_MULTI_TOUCH_LEAVE) ? 0 : 0x10;
push_event(ev.op, state->tc_finger_id, ev.x, ev.y, pressure);
}
}
// Pop oldest event into 8-byte buffer; on empty, return NO_EVENT.
@@ -307,6 +305,24 @@ uint32_t pull_rx_word() {
} // namespace
void i2c3_reset(EmuState *state) {
slave_addr = 0;
dir_read = false;
cmd_data[0] = cmd_data[1] = 0;
last_cnfg = 0;
pkt_state = PKT_HDR_W1;
pkt_size = pkt_recv = 0;
pkt_is_combined = false;
tx_buf.clear();
rx_buf.clear();
rx_pos = 0;
ev_stack.clear();
EmuState::TouchEvent ev;
while (state->touch_take(&ev)) {
}
state->tc_pressed = false;
}
uint32_t i2c3_read(EmuState *state, uint64_t addr) {
uint32_t offset = (uint32_t)(addr - I2C3_BASE);
switch (offset) {
+4
View File
@@ -12,4 +12,8 @@ struct EmuState;
uint32_t i2c3_read(EmuState *state, uint64_t addr);
void i2c3_write(EmuState *state, uint64_t addr, uint32_t val);
// Soft reboot: controller and touch controller back to power-on, with no
// events left over from the previous run.
void i2c3_reset(EmuState *state);
#endif
+34 -10
View File
@@ -67,7 +67,10 @@ constexpr uint64_t I2C2_BASE = 0x7000C400; // GEN2_I2C, Rohm BH1730 ALS at slave
constexpr uint64_t I2C2_SIZE = 0x100;
constexpr uint64_t I2C3_BASE = 0x7000C500; // GEN3_I2C, used by STMFTS touchscreen at slave 0x49
constexpr uint64_t I2C5_BASE = 0x7000D000;
constexpr uint64_t I2C_SIZE = 0x1000;
constexpr uint64_t I2C_SIZE = 0x1000; // the MMIO page: I2C5, I2C6, SPI2B
constexpr uint64_t I2C_CTRL_SIZE = 0x100; // one controller's registers
constexpr uint64_t I2C4_BASE = 0x7000C700;
constexpr uint64_t I2C6_BASE = 0x7000D100;
constexpr uint64_t I2C3_SIZE = 0x100;
// PWM
@@ -105,6 +108,7 @@ constexpr uint64_t MC_SIZE = 0x1000;
// Display Controller (DC/DSI)
constexpr uint64_t DISPLAY_A_BASE = 0x54200000;
constexpr uint64_t DISPLAY_B_BASE = 0x54240000; // DC1: feeds SOR1 / the dock
constexpr uint64_t DISPLAY_SIZE = 0x40000;
// DSI Controller
@@ -147,10 +151,19 @@ constexpr uint64_t HOST1X_SIZE = 0x40000;
constexpr uint64_t BPMP_CACHE_BASE = 0x50040000;
constexpr uint64_t BPMP_CACHE_SIZE = 0x1000;
// System Registers (SYSREG)
// System Registers (SYSREG). SB (secure boot) sits at +0x200 and holds the
// CCPLEX's AArch64 reset vector (SB_AA64_RESET_LOW/HIGH, +0x230/+0x234).
constexpr uint64_t SYSREG_BASE = 0x6000C000;
constexpr uint64_t SYSREG_SIZE = 0x1000;
// Flow controller: BPMP/CPU halt events, cluster control, RAM repair.
constexpr uint64_t FLOW_CTLR_BASE = 0x60007000;
constexpr uint64_t FLOW_CTLR_SIZE = 0x1000;
// Exception vectors, incl. EVP_CPU_RESET_VECTOR (+0x100) for AArch32 boot.
constexpr uint64_t EXCP_VEC_BASE = 0x6000F000;
constexpr uint64_t EXCP_VEC_SIZE = 0x1000;
// I2S (Audio)
constexpr uint64_t I2S_BASE = 0x702D1000;
constexpr uint64_t I2S_SIZE = 0x1000;
@@ -181,6 +194,16 @@ constexpr uint64_t SE_SIZE = 0x2000;
constexpr uint64_t MSELECT_BASE = 0x50060000;
constexpr uint64_t MSELECT_SIZE = 0x1000;
// USB2 controller USB1 ("OTG"): the device controller bdk's usbd.c drives on
// Erista. Registers, the UTMI PHY at +0x400/+0x800, queue heads at +0x1000.
constexpr uint64_t USB_OTG_BASE = 0x7D000000;
constexpr uint64_t USB_OTG_SIZE = 0x4000;
// XUSB device controller: bdk's xusbd.c on Mariko. XHCI registers, then its
// PCI configuration space at +0x8000 and device registers at +0x9000.
constexpr uint64_t XUSB_DEV_BASE = 0x700D0000;
constexpr uint64_t XUSB_DEV_SIZE = 0xA000;
// XUSB pad controller. Owns the UPHY SERDES lanes shared by PCIe (pcie-0..4)
// and USB 3.0 SuperSpeed (pcie-5/6 on this board), plus UPHY PLL P0.
constexpr uint64_t XUSB_PADCTL_BASE = 0x7009F000;
@@ -194,12 +217,13 @@ constexpr uint64_t XUSB_PADCTL_SIZE = 0x1000;
// bdk's MMU table defines DRAM and IRAM entries only and leaves the fallback
// entry RWX, so PCIe space is reachable and uncached.
//
// Only the windows a payload actually touches are mapped: 16 KiB covering
// both root ports plus PADS and AFI, 128 KiB of configuration aperture (bus
// 0 and bus 1 are all that exist), and one 4 KiB page of downstream memory
// for the endpoint's BAR0 register window. Mapping the architectural sizes
// (256 MiB of config, 208 MiB of memory) would cost the host gigabytes for
// address ranges nothing ever reads.
// These are MMIO windows (callbacks, no backing memory), so they are mapped
// at their architectural sizes: the whole 256 MiB configuration aperture -
// extended registers sit at AXI[27:24] - and the non-prefetchable memory
// window to the end of PCIE_A2, wherever software places the endpoint's BARs.
// A smaller map left a CPU0 access to, say, config offset 0x100 or BAR0 +
// 0x2000 unmapped: nothing answered and the core wedged, where silicon
// returns data or all-ones.
constexpr uint64_t PCIE_RP0_BASE = 0x01000000; // root port 0 registers
constexpr uint64_t PCIE_RP1_BASE = 0x01001000; // root port 1 registers
constexpr uint64_t PCIE_PADS_BASE = 0x01003000;
@@ -207,9 +231,9 @@ constexpr uint64_t PCIE_AFI_BASE = 0x01003800;
constexpr uint64_t PCIE_BLOCK_BASE = 0x01000000;
constexpr uint64_t PCIE_BLOCK_SIZE = 0x4000;
constexpr uint64_t PCIE_CS_BASE = 0x02000000; // type-1 extended config
constexpr uint64_t PCIE_CS_MODEL_SIZE = 0x20000; // buses 0 and 1 only
constexpr uint64_t PCIE_CS_MODEL_SIZE = 0x10000000; // all of it: 256 MiB
constexpr uint64_t PCIE_MEM_BASE = 0x13000000; // non-prefetchable window
constexpr uint64_t PCIE_MEM_MODEL_SIZE = 0x1000;
constexpr uint64_t PCIE_MEM_MODEL_SIZE = 0x0D000000; // up to the end of A2
// TSEC (Falcon control regs are in the 0x1000–0x11FF window within TSEC_BASE)
constexpr uint64_t TSEC_BASE = 0x54500000;
+2559 -1044
View File
File diff suppressed because it is too large. Load diff
+56
View File
@@ -14,9 +14,65 @@
// Forward declarations for peripheral modules.
struct EmuState;
// Which processor issued the access being dispatched. Two masters share one
// register model: the BPMP (the ARM7 every RCM payload runs on) and CPU0 of
// the CCPLEX (Cortex-A57), which a payload can boot through bdk's
// ccplex_boot_cpu0(). They do not see the same bus - PCIe and MSELECT answer
// a CPU-complex master only (Tegra X1 TRM ch.16/ch.19) - so the few models
// that care consult this. Both cores run on the emulator's one thread, one
// slice at a time, so a global is exact: whoever is running is the master.
enum BusMaster : uint8_t {
BUS_BPMP = 0,
BUS_CPU0 = 1,
};
extern BusMaster g_bus_master;
// Initialize all MMIO hooks on the Unicorn engine.
void mmio_init(uc_engine *uc, EmuState *state);
// Map the same peripheral windows into another engine (CPU0's), backed by the
// same register models. Everything in the 0x50000000..0x7FFFFFFF band plus
// the PCIe apertures low in the map.
void mmio_map_bus(uc_engine *uc, EmuState *state);
// Forget the windows mapped into `uc`, before that engine is closed.
void mmio_unmap_bus(uc_engine *uc);
// Map one 4 KiB page of the peripheral band as a register window (CPU0's
// first access to a block the emulator does not model).
bool mmio_map_page(uc_engine *uc, EmuState *state, uint64_t page);
// Display head B's frame clock (interrupt latch, GIC line); called often.
void display_tick(EmuState *state);
// The shared dispatch both engines' MMIO callbacks funnel into. `size` is the
// access width in bytes (1, 2 or 4).
uint32_t mmio_bus_read(EmuState *state, uint64_t addr, unsigned size);
void mmio_bus_write(EmuState *state, uint64_t addr, unsigned size,
uint64_t value);
// Reset the per-run peripheral state that a soft reboot must not carry over.
// `power_cycle`: the PMIC reset too (its register files return to their
// seeds); otherwise only the SoC reset (PMC MAIN_RST) and the PMIC keeps
// its rails.
void mmio_soft_reset(EmuState *state, bool power_cycle);
// PMC power-partition state (APBDEV_PMC_PWRGATE_STATUS bit `part`).
bool pmc_partition_on(int part);
// APBDEV_PMC_SECURE_SCRATCH`n` (n = 0..7), written by hardware: the SE
// deposits its context-save key there.
void pmc_secure_scratch_write(unsigned n, uint32_t value);
// True when the CCPLEX CPU rail is up: the MAX77621 on Erista (enabled, and
// its EN pin driven by MAX77620 GPIO5), the MAX77812 M4 phase on Mariko -
// and no fault has taken its output away.
bool cpu_rail_on(EmuState *state);
// The fault name ("vdd_cpu", or the dead buck's) that keeps the CPU rail
// down, or nullptr. A dead chip takes its rails with it.
const char *cpu_rail_fault(EmuState *state);
// A fault was set or cleared while running: tell the models that cache it.
void faults_changed(EmuState *state);
// Individual peripheral handlers.
uint32_t timer_read(EmuState *state, uint64_t addr);
void timer_write(EmuState *state, uint64_t addr, uint32_t val);
+397
View File
@@ -0,0 +1,397 @@
// A one-client NBD server for the emulated USB host (see nbd.h).
//
// The handshake is the fixed newstyle one every current client speaks
// (nbd-client, qemu-nbd, nbdfuse, libnbd):
//
// server "NBDMAGIC" "IHAVEOPT" handshake flags
// client its flags, then options: "IHAVEOPT", option, length, data
// server answers each option; EXPORT_NAME or GO hands over the disk
//
// then requests (magic 0x25609513, flags, type, handle, offset, length,
// and a WRITE's data) each answered by a simple reply (magic 0x67446698,
// error, handle, and a READ's data). The export has one name - any name
// the client asks for - and takes READ, WRITE, FLUSH and DISC; structured
// replies and the other extensions are refused, which clients handle.
#include "nbd.h"
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#else
#include <arpa/inet.h>
#include <cerrno>
#include <fcntl.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <unistd.h>
#endif
#include <algorithm>
#include <cstdio>
#include <cstring>
namespace {
constexpr uint64_t NBDMAGIC = 0x4E42444D41474943ull; // "NBDMAGIC"
constexpr uint64_t IHAVEOPT = 0x49484156454F5054ull; // "IHAVEOPT"
constexpr uint64_t REPLY_MAGIC = 0x0003E889045565A9ull; // option replies
constexpr uint32_t REQUEST_MAGIC = 0x25609513;
constexpr uint32_t SIMPLE_REPLY_MAGIC = 0x67446698;
constexpr uint16_t FLAG_FIXED_NEWSTYLE = 1 << 0, FLAG_NO_ZEROES = 1 << 1;
constexpr uint16_t FLAG_HAS_FLAGS = 1 << 0, FLAG_READ_ONLY = 1 << 1,
FLAG_SEND_FLUSH = 1 << 2;
constexpr uint32_t OPT_EXPORT_NAME = 1, OPT_ABORT = 2, OPT_LIST = 3,
OPT_INFO = 6, OPT_GO = 7;
constexpr uint32_t REP_ACK = 1, REP_SERVER = 2, REP_INFO = 3,
REP_ERR_UNSUP = 0x80000001, REP_ERR_INVALID = 0x80000003;
constexpr uint16_t INFO_EXPORT = 0, INFO_BLOCK_SIZE = 3;
#ifdef _WIN32
using sock_t = SOCKET;
const sock_t BAD_SOCK = INVALID_SOCKET;
bool net_init() {
static bool ok = [] {
WSADATA d;
return WSAStartup(MAKEWORD(2, 2), &d) == 0;
}();
return ok;
}
void close_sock(sock_t s) { closesocket(s); }
bool would_block() { return WSAGetLastError() == WSAEWOULDBLOCK; }
bool set_nonblocking(sock_t s) {
u_long on = 1;
return ioctlsocket(s, FIONBIO, &on) == 0;
}
const char *sock_error() {
static char buf[32];
snprintf(buf, sizeof(buf), "winsock error %d", WSAGetLastError());
return buf;
}
#else
using sock_t = int;
const sock_t BAD_SOCK = -1;
bool net_init() { return true; }
void close_sock(sock_t s) { ::close(s); }
bool would_block() {
#if EWOULDBLOCK != EAGAIN
if (errno == EWOULDBLOCK)
return true;
#endif
return errno == EAGAIN || errno == EINTR;
}
bool set_nonblocking(sock_t s) {
int fl = fcntl(s, F_GETFL, 0);
return fl >= 0 && fcntl(s, F_SETFL, fl | O_NONBLOCK) == 0;
}
const char *sock_error() { return strerror(errno); }
#endif
#ifdef MSG_NOSIGNAL
constexpr int SEND_FLAGS = MSG_NOSIGNAL; // a gone client is an error, not SIGPIPE
#else
constexpr int SEND_FLAGS = 0;
#endif
sock_t sock(intptr_t s) { return (sock_t)s; }
// Wait up to 10 s for room to send.
bool wait_writable(sock_t s) {
fd_set w;
FD_ZERO(&w);
FD_SET(s, &w);
timeval tv = {10, 0};
return select((int)s + 1, nullptr, &w, nullptr, &tv) > 0;
}
// Everything on the wire is big-endian.
void put16(uint8_t *p, uint16_t v) {
p[0] = v >> 8;
p[1] = (uint8_t)v;
}
void put32(uint8_t *p, uint32_t v) {
put16(p, v >> 16);
put16(p + 2, (uint16_t)v);
}
void put64(uint8_t *p, uint64_t v) {
put32(p, v >> 32);
put32(p + 4, (uint32_t)v);
}
uint16_t get16(const uint8_t *p) { return (uint16_t)(p[0] << 8 | p[1]); }
uint32_t get32(const uint8_t *p) {
return (uint32_t)get16(p) << 16 | get16(p + 2);
}
uint64_t get64(const uint8_t *p) {
return (uint64_t)get32(p) << 32 | get32(p + 4);
}
} // namespace
bool NbdServer::listen(uint16_t port, uint64_t size, bool read_only) {
close();
if (!net_init()) {
printf("[usb-host] NBD: no sockets (%s)\n", sock_error());
return false;
}
sock_t s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == BAD_SOCK) {
printf("[usb-host] NBD: no socket (%s)\n", sock_error());
return false;
}
#ifndef _WIN32
// Windows' SO_REUSEADDR lets another process take a bound port; the
// POSIX one only skips TIME_WAIT, so a restarted run gets its port back.
int one = 1;
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
#endif
sockaddr_in a;
memset(&a, 0, sizeof(a));
a.sin_family = AF_INET;
a.sin_port = htons(port);
a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
if (bind(s, (sockaddr *)&a, sizeof(a)) != 0 || ::listen(s, 1) != 0 ||
!set_nonblocking(s)) {
printf("[usb-host] NBD: cannot listen on 127.0.0.1:%u (%s)\n", port,
sock_error());
close_sock(s);
return false;
}
listen_ = (intptr_t)s;
size_ = size;
read_only_ = read_only;
state_ = Listening;
return true;
}
void NbdServer::close() {
drop_client();
if (listen_ != -1)
close_sock(sock(listen_));
listen_ = -1;
state_ = Idle;
}
void NbdServer::drop_client() {
if (client_ != -1)
close_sock(sock(client_));
client_ = -1;
in_.clear();
peer_closed_ = false;
state_ = listen_ != -1 ? Listening : Idle;
}
uint16_t NbdServer::transmission_flags() const {
return FLAG_HAS_FLAGS | FLAG_SEND_FLUSH | (read_only_ ? FLAG_READ_ONLY : 0);
}
// Read what the client has sent. False once it has closed its end.
bool NbdServer::fill() {
static uint8_t buf[65536];
// Room for the largest WRITE; a client pipelining more waits in the socket.
while (in_.size() < NBD_MAX_PAYLOAD + sizeof(buf)) {
int n = recv(sock(client_), (char *)buf, sizeof(buf), 0);
if (n > 0) {
in_.insert(in_.end(), buf, buf + n);
continue;
}
return n < 0 && would_block();
}
return true;
}
bool NbdServer::send_all(const void *p, size_t n) {
const char *c = (const char *)p;
while (n) {
int k = send(sock(client_), c, (int)std::min<size_t>(n, 1u << 20),
SEND_FLAGS);
if (k > 0) {
c += k;
n -= (size_t)k;
} else if (k < 0 && would_block()) {
if (!wait_writable(sock(client_)))
return false;
} else {
return false;
}
}
return true;
}
bool NbdServer::option_reply(uint32_t opt, uint32_t type,
const std::vector<uint8_t> &data) {
uint8_t h[20];
put64(h, REPLY_MAGIC);
put32(h + 8, opt);
put32(h + 12, type);
put32(h + 16, (uint32_t)data.size());
return send_all(h, sizeof(h)) &&
(data.empty() || send_all(data.data(), data.size()));
}
// One handshake option. False drops the client.
bool NbdServer::option(uint32_t opt, const std::vector<uint8_t> &d) {
switch (opt) {
case OPT_EXPORT_NAME: {
// No reply header: the export's size and flags, then (unless the
// client opted out) 124 zero bytes, and the disk is the client's.
uint8_t r[10 + 124] = {};
put64(r, size_);
put16(r + 8, transmission_flags());
if (!send_all(r, no_zeroes_ ? 10 : sizeof(r)))
return false;
state_ = Transmission;
break;
}
case OPT_ABORT:
option_reply(opt, REP_ACK);
return false;
case OPT_LIST: {
if (!d.empty())
return option_reply(opt, REP_ERR_INVALID);
std::vector<uint8_t> unnamed(4, 0); // one export, the default name
return option_reply(opt, REP_SERVER, unnamed) && option_reply(opt, REP_ACK);
}
case OPT_INFO:
case OPT_GO: {
// Export name length, the name, the count of info requests, the
// requests. Whatever the client asks for, it gets the size and flags
// and the block sizes: 512-byte sectors, 4 KiB preferred.
if (d.size() < 6)
return option_reply(opt, REP_ERR_INVALID);
uint32_t name_len = get32(&d[0]);
if (name_len > d.size() - 6 ||
d.size() != 6 + name_len + 2 * (size_t)get16(&d[4 + name_len]))
return option_reply(opt, REP_ERR_INVALID);
std::vector<uint8_t> e(12), b(14);
put16(&e[0], INFO_EXPORT);
put64(&e[2], size_);
put16(&e[10], transmission_flags());
put16(&b[0], INFO_BLOCK_SIZE);
put32(&b[2], 512);
put32(&b[6], 4096);
put32(&b[10], NBD_MAX_PAYLOAD);
if (!option_reply(opt, REP_INFO, e) || !option_reply(opt, REP_INFO, b) ||
!option_reply(opt, REP_ACK))
return false;
if (opt == OPT_GO)
state_ = Transmission;
break;
}
default:
return option_reply(opt, REP_ERR_UNSUP);
}
if (state_ == Transmission)
printf("[usb-host] NBD client has the disk\n");
return true;
}
NbdEvent NbdServer::poll(NbdRequest *req) {
if (state_ == Idle)
return NbdEvent::None;
if (state_ == Listening) {
sock_t c = accept(sock(listen_), nullptr, nullptr);
if (c == BAD_SOCK)
return NbdEvent::None;
set_nonblocking(c);
int one = 1;
setsockopt(c, IPPROTO_TCP, TCP_NODELAY, (const char *)&one, sizeof(one));
#ifdef SO_NOSIGPIPE
setsockopt(c, SOL_SOCKET, SO_NOSIGPIPE, &one, sizeof(one));
#endif
client_ = (intptr_t)c;
in_.clear();
peer_closed_ = no_zeroes_ = false;
uint8_t hello[18];
put64(hello, NBDMAGIC);
put64(hello + 8, IHAVEOPT);
put16(hello + 16, FLAG_FIXED_NEWSTYLE | FLAG_NO_ZEROES);
if (!send_all(hello, sizeof(hello))) {
drop_client();
return NbdEvent::None;
}
state_ = ClientFlags;
}
if (!fill())
peer_closed_ = true;
for (;;) {
size_t n = in_.size();
if (state_ == ClientFlags) {
if (n < 4)
break;
uint32_t f = get32(&in_[0]);
in_.erase(in_.begin(), in_.begin() + 4);
no_zeroes_ = (f & FLAG_FIXED_NEWSTYLE) && (f & FLAG_NO_ZEROES);
state_ = Options;
} else if (state_ == Options) {
if (n < 16)
break;
uint32_t opt = get32(&in_[8]), len = get32(&in_[12]);
if (get64(&in_[0]) != IHAVEOPT || len > 65536) {
printf("[usb-host] NBD: not an NBD client; dropped\n");
drop_client();
return NbdEvent::None;
}
if (n < 16 + (size_t)len)
break;
std::vector<uint8_t> data(in_.begin() + 16, in_.begin() + 16 + len);
in_.erase(in_.begin(), in_.begin() + 16 + len);
if (!option(opt, data)) {
drop_client();
return NbdEvent::None;
}
} else {
if (n < 28)
break;
uint16_t type = get16(&in_[6]);
uint32_t len = get32(&in_[24]);
if (get32(&in_[0]) != REQUEST_MAGIC ||
(type == NBD_CMD_WRITE && len > NBD_MAX_PAYLOAD)) {
printf("[usb-host] NBD: malformed request; client dropped\n");
drop_client();
return NbdEvent::Closed;
}
size_t need = 28 + (type == NBD_CMD_WRITE ? len : 0);
if (n < need)
break;
req->flags = get16(&in_[4]);
req->type = type;
req->handle = get64(&in_[8]);
req->offset = get64(&in_[16]);
req->len = len;
req->data.assign(in_.begin() + 28, in_.begin() + need);
in_.erase(in_.begin(), in_.begin() + need);
if (type == NBD_CMD_DISC) {
printf("[usb-host] NBD client disconnected\n");
drop_client();
return NbdEvent::Closed;
}
return NbdEvent::Request;
}
}
if (peer_closed_) {
bool had_disk = state_ == Transmission;
printf("[usb-host] NBD client %s\n",
had_disk ? "went away without disconnecting" : "left");
drop_client();
return had_disk ? NbdEvent::Closed : NbdEvent::None;
}
return NbdEvent::None;
}
void NbdServer::reply(uint64_t handle, uint32_t error, const uint8_t *data,
size_t len) {
if (state_ != Transmission)
return;
uint8_t h[16];
put32(h, SIMPLE_REPLY_MAGIC);
put32(h + 4, error);
put64(h + 8, handle);
if (!send_all(h, sizeof(h)) || (!error && len && !send_all(data, len)))
peer_closed_ = true; // the next poll reports it gone
}
+67
View File
@@ -0,0 +1,67 @@
#pragma once
#include <cstdint>
#include <vector>
// A one-client NBD server - the network block device protocol, fixed
// newstyle handshake - that the emulated USB host (usb.cpp) serves a mass
// storage gadget's disk with, so the disk can be mounted on the machine the
// emulator runs on. It listens on 127.0.0.1 only. Single-threaded and
// non-blocking: poll() does whatever the socket allows and returns.
struct NbdRequest {
uint16_t type = 0; // NBD_CMD_*
uint16_t flags = 0;
uint64_t handle = 0, offset = 0;
uint32_t len = 0;
std::vector<uint8_t> data; // what a WRITE carries
};
constexpr uint16_t NBD_CMD_READ = 0, NBD_CMD_WRITE = 1, NBD_CMD_DISC = 2,
NBD_CMD_FLUSH = 3;
constexpr uint32_t NBD_EPERM = 1, NBD_EIO = 5, NBD_EINVAL = 22;
// The largest READ or WRITE a client may send (the protocol's default).
constexpr uint32_t NBD_MAX_PAYLOAD = 32u << 20;
enum class NbdEvent {
None, // nothing to do yet
Request, // *req holds the next command
Closed, // the client that was using the disk disconnected
};
class NbdServer {
public:
~NbdServer() { close(); }
// Listen on 127.0.0.1:port for a client, exporting `size` bytes. False
// (and logged) when the port cannot be had.
bool listen(uint16_t port, uint64_t size, bool read_only);
void close();
bool active() const { return state_ != Idle; }
// Accept, run the handshake, read the next request. A client that goes
// away before it has the disk (a listing, a failed negotiation) is not a
// Closed event: the server just waits for the next one.
NbdEvent poll(NbdRequest *req);
// Answer a request; a READ's data goes with a zero error.
void reply(uint64_t handle, uint32_t error, const uint8_t *data = nullptr,
size_t len = 0);
private:
enum State { Idle, Listening, ClientFlags, Options, Transmission };
State state_ = Idle;
intptr_t listen_ = -1, client_ = -1; // sockets
std::vector<uint8_t> in_;
bool peer_closed_ = false, no_zeroes_ = false, read_only_ = false;
uint64_t size_ = 0;
bool fill();
bool send_all(const void *p, size_t n);
bool option(uint32_t opt, const std::vector<uint8_t> &data);
bool option_reply(uint32_t opt, uint32_t type,
const std::vector<uint8_t> &data = {});
void drop_client();
uint16_t transmission_flags() const;
};
+91 -18
View File
@@ -1,10 +1,12 @@
#include "pcie.h"
#include "ccplex.h"
#include <cstdio>
#include <cstring>
#include "../emu_state.h"
#include "memory_map.h"
#include "mmio.h"
// ==========================================================================
// Register map (tegra210.dtsi pcie@1003000, U-Boot drivers/pci/pci_tegra.c)
@@ -108,6 +110,15 @@
static constexpr uint64_t T_VDD_TO_POR_US = 57000; // WL_REG_ON -> POR done
static constexpr uint64_t T_REFCLK_STABLE_US = 10000; // refclk -> PERST# high
// Reset values, as a CPU-complex master reads them on real silicon.
// MSELECT_CONFIG_0 is the TRM's documented reset value (16.3.1): the PCIe
// aperture (bit 5) is already enabled. AFI_PCIE_CONFIG is what hwtest's CPU0
// stub reads straight after the BPMP has cycled the AFI reset - xbar X4_X1 in
// bits 23:20 and root port 1 disabled (bit 2) until software clears it.
static constexpr uint32_t MSELECT_CONFIG_RESET = 0x07FF4020;
static constexpr uint32_t MSELECT_CFG_ENABLE_PCIE_APERTURE = 1u << 5;
static constexpr uint32_t AFI_PCIE_CONFIG_RESET = 0x00103025;
// Broadcom identity (brcm_hw_ids.h, brcmfmac/pcie.c).
static constexpr uint32_t BRCM_4356_CFG0 = 0x43EC14E4;
static constexpr uint32_t BRCM_BAR0_WINDOW = 0x80;
@@ -158,7 +169,8 @@ struct PcieModel {
bool mgmt_warned = false;
bool plle = false;
bool pllrefe = false;
bool powergated = true;
// The PCIE partition is already up at RCM entry (see pmc_pwrgate_status).
bool powergated = false;
// XUSB pad controller.
uint32_t padctl[0x1000 / 4] = {};
@@ -177,9 +189,11 @@ PcieModel pcie;
// BAR sizing masks: a write of all-ones reads back ~(size-1) with the type
// bits preserved, which is how any enumerator discovers how big a BAR is.
// BAR0 is 32 KiB of registers, BAR2 the 2 MiB TCM; both are 64-bit
// prefetchable, which is why brcmfmac calls them resource 0 and resource 2.
constexpr uint32_t EP_BAR_TYPE = 0x0000000C; // 64-bit, prefetchable
// BAR0 is 32 KiB of registers, BAR2 the 2 MiB TCM; both are 64-bit memory
// BARs, which is why brcmfmac calls them resource 0 and resource 2. They are
// NOT prefetchable: a real CYW4356 in ROM phase reads BAR0 = 0x00000004
// (hwtest's healthy-console capture), i.e. type 64-bit, prefetch clear.
constexpr uint32_t EP_BAR_TYPE = 0x00000004; // 64-bit, non-prefetchable
constexpr uint32_t EP_BAR0_MASK = ~(0x8000u - 1);
constexpr uint32_t EP_BAR2_MASK = ~(0x200000u - 1);
@@ -187,7 +201,7 @@ void ep_init() {
memset(pcie.ep, 0, sizeof(pcie.ep));
pcie.ep[0x00 / 4] = BRCM_4356_CFG0; // 14E4:43EC
pcie.ep[0x04 / 4] = 0x00100000; // status: capability list
pcie.ep[0x08 / 4] = 0x02800000; // network controller, other
pcie.ep[0x08 / 4] = 0x02800003; // network controller, rev 03
pcie.ep[0x0C / 4] = 0x00000000; // header type 0
pcie.ep[0x10 / 4] = EP_BAR_TYPE; // BAR0 lo: 32 KiB registers
pcie.ep[0x18 / 4] = EP_BAR_TYPE; // BAR2 lo: 2 MiB TCM
@@ -215,9 +229,8 @@ bool radio_core_alive(EmuState *state) {
// hardware this is the difference between a register read and a dead
// console, so it is checked before every single access rather than folded
// into the link-training preconditions.
// Everything this emulator executes is BPMP code - Unicorn runs the ARM7,
// there is no CCPLEX model - and the BPMP cannot reach PCIe on real silicon.
// Measured on an Erista and a Mariko: with clocks, resets, power and PLLE all
// The BPMP cannot reach PCIe on real silicon; only a CPU-complex master can
// (CPU0, t210/ccplex.cpp). Measured on an Erista and a Mariko: with clocks, resets, power and PLLE all
// correct, the AFI window reads 0xFFFFFFFF and every offset of MSELECT reads
// one constant. The TRM agrees (ch.19: BPMP-Lite is an AHB master, PCIe is
// not an AHB slave; ch.16: MSELECT is CPU-complex hardware), and so does the
@@ -227,6 +240,9 @@ bool radio_core_alive(EmuState *state) {
// which is how a probe that cannot work on hardware passed here for days.
// Refusing them is the single most valuable thing this file does.
static bool bpmp_pcie_denied(uint64_t addr) {
// CPU0 (t210/ccplex.cpp) is a CPU-complex master and reaches all of it.
if (g_bus_master == BUS_CPU0)
return false;
static bool warned = false;
if (!warned) {
warned = true;
@@ -249,13 +265,29 @@ void mselect_complain(uint64_t addr) {
pcie.mselect_warned = true;
printf("[pcie] *** access to %08X with MSELECT still in reset ***\n",
(unsigned)addr);
printf("[pcie] *** on real silicon this STALLS THE BPMP for good: no ***\n");
printf("[pcie] *** on real silicon this STALLS THE %s for good: no ***\n",
g_bus_master == BUS_CPU0 ? "CPU0" : "BPMP");
printf("[pcie] *** abort, no timeout, no reboot path. Clear ***\n");
printf("[pcie] *** RST_DEV_V bit %d first (bdk ccplex.c:121). ***\n",
CLK_V_MSELECT);
fflush(stdout);
}
// MSELECT_CONFIG bit 5, ENABLE_PCIE_APERTURE (TRM 16.3.1, set at reset):
// with it clear MSELECT does not route the PCIe apertures at all.
static bool pcie_aperture_enabled(uint64_t addr) {
if (pcie.mselect[0] & MSELECT_CFG_ENABLE_PCIE_APERTURE)
return true;
static bool warned = false;
if (!warned) {
warned = true;
printf("[pcie] access to %08X with MSELECT_CONFIG.ENABLE_PCIE_APERTURE "
"clear: MSELECT does not route it\n", (unsigned)addr);
fflush(stdout);
}
return false;
}
const char *link_blocked(EmuState *state, int port) {
if (!mselect_up()) return "MSELECT still in reset";
if (pcie.powergated) return "PCIE partition still gated";
@@ -345,9 +377,13 @@ bool ep_reachable(EmuState *state) {
void pcie_reset(EmuState *state) {
pcie = PcieModel();
ep_init();
pcie.mselect[0] = MSELECT_CONFIG_RESET;
pcie.afi[AFI_PCIE_CONFIG / 4] = AFI_PCIE_CONFIG_RESET;
(void)state;
}
bool pcie_mselect_up() { return mselect_up(); }
void pcie_set_powergate(bool ungated) {
if (pcie.powergated == !ungated)
return;
@@ -374,7 +410,8 @@ void pcie_wl_reg_on(EmuState *state, bool level) {
// ---- clock and reset controller -----------------------------------------
void pcie_car_write(uint32_t offset, uint32_t val) {
void pcie_car_write(EmuState *state, uint32_t offset, uint32_t val) {
bool mselect_was_up = mselect_up();
switch (offset) {
case CAR_RST_DEVICES_U: pcie.rst_u = val; break;
case CAR_CLK_OUT_ENB_U: pcie.enb_u = val; break;
@@ -389,12 +426,17 @@ void pcie_car_write(uint32_t offset, uint32_t val) {
case CAR_RST_DEVICES_V: pcie.rst_v = val; break;
case CAR_RST_DEV_V_SET: pcie.rst_v |= val; break;
case CAR_RST_DEV_V_CLR: pcie.rst_v &= ~val; break;
case CAR_RST_DEVICES_W: pcie.rst_w = val; break;
case CAR_RST_DEV_W_SET: pcie.rst_w |= val; break;
case CAR_RST_DEV_W_CLR: pcie.rst_w &= ~val; break;
case CAR_RST_DEVICES_Y: pcie.rst_y = val; break;
case CAR_PLLE_BASE: pcie.plle = (val & PLLE_BASE_ENABLE) != 0; break;
case CAR_PLLREFE_BASE: pcie.pllrefe = (val & PLLREFE_BASE_ENABLE) != 0; break;
default: break;
}
// MSELECT out of reset is one of the things CPU0 waits on.
if (!mselect_was_up && mselect_up())
ccplex_preconditions_changed(state);
}
// PLLE and PLLREFE do not follow the generic "ENABLE bit 30, LOCK bit 27 in
@@ -447,6 +489,9 @@ uint32_t mselect_read(EmuState *state, uint64_t addr) {
void mselect_write(EmuState *state, uint64_t addr, uint32_t val) {
(void)state;
// Writes from the BPMP go nowhere either, as with the AFI window.
if (bpmp_pcie_denied(addr))
return;
uint32_t off = (uint32_t)(addr - MSELECT_BASE) & 0xFFC;
// Held in reset, MSELECT latches nothing - which is exactly the state a
// payload is in when it thinks it configured the fabric and did not.
@@ -469,7 +514,8 @@ uint32_t padctl_read(EmuState *state, uint64_t addr) {
pcie.padctl_warned = true;
printf("[pcie] *** read of XUSB_PADCTL %08X with the block still ***\n",
(unsigned)addr);
printf("[pcie] *** in reset. On real silicon this STALLS THE ***\n");
printf("[pcie] *** in reset. On real silicon this STALLS THE %s ***\n",
g_bus_master == BUS_CPU0 ? "CPU0" : "BPMP");
printf("[pcie] *** BPMP for good. Clear RST_DEV_W bit %d first. ***\n",
CLK_W_XUSB_PADCTL);
fflush(stdout);
@@ -614,6 +660,8 @@ uint32_t pcie_read(EmuState *state, uint64_t addr) {
mselect_complain(addr);
return 0xFFFFFFFF;
}
if (!pcie_aperture_enabled(addr))
return 0xFFFFFFFF;
// Root port register windows, 0x01000000 and 0x01001000.
if (addr >= PCIE_RP0_BASE && addr < PCIE_RP0_BASE + 0x2000) {
@@ -637,8 +685,11 @@ uint32_t pcie_read(EmuState *state, uint64_t addr) {
// speeds"), so speed = 1 and width = 1.
if (!rp.link)
return rp.reg[off / 4] & 0xFFFF;
// LNKSTA 0x3011 on hardware: gen1, x1, Slot Clock
// Configuration (bit 28 - the endpoint runs off the refclk the
// root port drives) and Data Link Layer Link Active.
return (rp.reg[off / 4] & 0xFFFF) | RP_LINK_DL_ACTIVE |
(1u << 16) | (1u << 20);
(1u << 28) | (1u << 16) | (1u << 20);
default:
return rp.reg[off / 4];
}
@@ -655,10 +706,14 @@ uint32_t pcie_read(EmuState *state, uint64_t addr) {
if (addr >= PCIE_CS_BASE && addr < PCIE_CS_BASE + PCIE_CS_MODEL_SIZE) {
uint32_t a = (uint32_t)(addr - PCIE_CS_BASE);
uint32_t bus = (a >> 16) & 0xFF, dev = (a >> 11) & 0x1F;
uint32_t fn = (a >> 8) & 0x7, reg = a & 0xFC;
uint32_t fn = (a >> 8) & 0x7;
// Register number: {AXI[27:24], AXI[7:0]} (TRM 34.3.3).
uint32_t reg = ((a >> 16) & 0xF00) | (a & 0xFC);
link_update(state, 1);
if (bus != 1 || dev != 0 || fn != 0 || !ep_reachable(state))
return 0xFFFFFFFF; // unsupported request -> all ones
if (reg >= sizeof(pcie.ep))
return 0; // no extended capabilities
return pcie.ep[reg / 4];
}
@@ -671,13 +726,24 @@ uint32_t pcie_read(EmuState *state, uint64_t addr) {
return 0xFFFFFFFF;
if (!(pcie.ep[0x04 / 4] & 0x2)) // MEM space disabled
return 0xFFFFFFFF;
if ((pcie.ep[0x10 / 4] & ~0xFu) != PCIE_MEM_BASE) // BAR0 unassigned
// Decode against wherever software put the BARs: BAR0 is the 32 KiB
// register window (backplane window in its first 4 KiB, core
// registers above), BAR2 the 2 MiB TCM. Anything else is claimed by
// no function: all ones.
uint32_t a32 = (uint32_t)addr;
uint32_t bar0 = pcie.ep[0x10 / 4] & EP_BAR0_MASK;
uint32_t bar2 = pcie.ep[0x18 / 4] & EP_BAR2_MASK;
bool in_bar0 = bar0 && (a32 & EP_BAR0_MASK) == bar0;
bool in_bar2 = bar2 && (a32 & EP_BAR2_MASK) == bar2;
if (!in_bar0 && !in_bar2)
return 0xFFFFFFFF;
if (!radio_core_alive(state))
return 0xFFFFFFFF; // front-end answers, the die does not
if (in_bar2 || (a32 - bar0) >= 0x1000)
return 0; // modelled as quiet registers / RAM
uint32_t win = pcie.ep[BRCM_BAR0_WINDOW / 4] & ~0xFFFu;
uint32_t bp = win + ((uint32_t)(addr - PCIE_MEM_BASE) & 0xFFF);
uint32_t bp = win + ((a32 - bar0) & 0xFFF);
if (bp == BRCM_SI_ENUM_BASE)
return BRCM_4356_CHIPID;
return 0;
@@ -694,10 +760,15 @@ void pcie_write(EmuState *state, uint64_t addr, uint32_t val) {
mselect_complain(addr);
return;
}
if (!pcie_aperture_enabled(addr))
return;
if (addr >= PCIE_RP0_BASE && addr < PCIE_RP0_BASE + 0x2000) {
int port = (addr >= PCIE_RP1_BASE) ? 1 : 0;
pcie.rp[port].reg[(uint32_t)(addr & 0xFFC) / 4] = val;
uint32_t off = (uint32_t)(addr & 0xFFC);
if (off == RP_VEND_XP)
val &= ~RP_VEND_XP_DL_UP; // read-only: the link state
pcie.rp[port].reg[off / 4] = val;
return;
}
@@ -714,8 +785,10 @@ void pcie_write(EmuState *state, uint64_t addr, uint32_t val) {
if (addr >= PCIE_CS_BASE && addr < PCIE_CS_BASE + PCIE_CS_MODEL_SIZE) {
uint32_t a = (uint32_t)(addr - PCIE_CS_BASE);
uint32_t bus = (a >> 16) & 0xFF, dev = (a >> 11) & 0x1F;
uint32_t fn = (a >> 8) & 0x7, reg = a & 0xFC;
if (bus != 1 || dev != 0 || fn != 0 || !ep_reachable(state))
uint32_t fn = (a >> 8) & 0x7;
uint32_t reg = ((a >> 16) & 0xF00) | (a & 0xFC);
if (bus != 1 || dev != 0 || fn != 0 || !ep_reachable(state) ||
reg >= sizeof(pcie.ep))
return;
switch (reg) {
case 0x04: // command: only the low half is RW
+15 -8
View File
@@ -15,17 +15,20 @@ struct EmuState;
* (0x02000000), the endpoint's BAR0 backplane window, and the UPHY PLL P0
* calibration/lock state machine in the XUSB pad controller.
*
* The link only trains when the payload has satisfied every precondition
* real silicon and the CYW4356 datasheet impose -- power partition, clocks,
* resets, PLLE, UPHY, lane mux, IDDQ, and the refclk/PERST#/POR timing of
* Table 62. A payload that skips one gets a link that stays down and a
* `[pcie]` line on stdout naming what it missed.
* The link only trains once the payload has satisfied the preconditions
* this model checks -- power partition, AFI clock, resets, PLLE, UPHY, lane
* mux, IDDQ, and the refclk/PERST#/POR timing of Table 62. A payload that
* skips one gets a link that stays down and a `[pcie]` line on stdout naming
* what it missed. Not every step of the TRM's bring-up (34.3) is checked:
* the PCIe clock enable, PRSNT_MAP, PEX_BIAS_PWRD, the PEX_L1_RST_N pinmux
* and the AUX_MUX_LP0 clamps are not, so a sequence that leaves one out can
* train here and not on silicon.
*/
void pcie_reset(EmuState *state);
// 0x01000000..0x01003FFF (root ports, PADS, AFI), 0x02000000 config
// aperture, and the 0x13000000 BAR0 memory window.
// 0x01000000..0x01003FFF (root ports, PADS, AFI), the 0x02000000 config
// aperture and the 0x13000000 non-prefetchable memory window.
uint32_t pcie_read(EmuState *state, uint64_t addr);
void pcie_write(EmuState *state, uint64_t addr, uint32_t val);
@@ -40,9 +43,13 @@ void padctl_write(EmuState *state, uint64_t addr, uint32_t val);
// Clock-and-reset forwarding. The PCIe model needs PLLE/PLLREFE lock and the
// PCIE/AFI/PCIEXCLK/UPHY reset+enable bits, all of which live in CAR.
// pcie_car_read returns true when it wants to override the CAR model's answer.
void pcie_car_write(uint32_t offset, uint32_t val);
void pcie_car_write(EmuState *state, uint32_t offset, uint32_t val);
bool pcie_car_read(uint32_t offset, uint32_t *out);
// MSELECT clocked out of reset (RST_DEV_V bit 3 clear). The CCPLEX needs it
// as much as PCIe does: it is the CPU cluster's path to every slave.
bool pcie_mselect_up();
// The PCIE power partition, toggled through PMC_PWRGATE_TOGGLE.
void pcie_set_powergate(bool ungated);
+86
View File
@@ -0,0 +1,86 @@
#ifndef T210_REGCACHE_H
#define T210_REGCACHE_H
#include <cstdint>
#include <cstring>
#include <memory>
#include <unordered_map>
// Last-written value of every MMIO address, for the registers whose model is
// "read back what the payload wrote" (PINMUX, PWM, UART LCR, CLK_SOURCE_*...).
//
// This sits on the hottest path in the emulator - every MMIO write stores
// into it and a good share of reads consult it - and it used to be a
// std::map<uint64_t, uint32_t>: a red-black tree walk plus, for a new key, a
// heap allocation per access. Profiling a hwtest sweep put the tree lookups
// on par with the peripheral models themselves.
//
// Registers cluster into a few dozen 4 KiB pages, so this keeps one flat page
// per touched page with a presence bitmap, and caches the last page looked
// up. The interface is the subset of std::map the call sites use (count() and
// operator[]), so they did not have to change. Keys stay byte-granular: a
// byte store at 0x70006001 is its own entry, exactly as it was in the map.
class RegCache {
struct Page {
uint32_t val[4096];
uint64_t present[4096 / 64];
};
std::unordered_map<uint64_t, std::unique_ptr<Page>> pages_;
mutable uint64_t last_key_ = ~0ULL;
mutable Page *last_ = nullptr;
Page *find(uint64_t key) const {
if (key == last_key_)
return last_;
auto it = pages_.find(key);
if (it == pages_.end())
return nullptr;
last_key_ = key;
last_ = it->second.get();
return last_;
}
public:
size_t count(uint64_t addr) const {
const Page *p = find(addr >> 12);
if (!p)
return 0;
uint32_t o = (uint32_t)(addr & 0xFFF);
return (p->present[o >> 6] >> (o & 63)) & 1;
}
uint32_t &operator[](uint64_t addr) {
uint64_t key = addr >> 12;
Page *p = find(key);
if (!p) {
auto page = std::make_unique<Page>();
memset(page.get(), 0, sizeof(Page));
p = page.get();
pages_.emplace(key, std::move(page));
last_key_ = key;
last_ = p;
}
uint32_t o = (uint32_t)(addr & 0xFFF);
p->present[o >> 6] |= 1ULL << (o & 63);
return p->val[o];
}
// Value if ever written, else `dflt`. One lookup instead of the
// count()-then-operator[] pair.
uint32_t get(uint64_t addr, uint32_t dflt = 0) const {
const Page *p = find(addr >> 12);
if (!p)
return dflt;
uint32_t o = (uint32_t)(addr & 0xFFF);
return ((p->present[o >> 6] >> (o & 63)) & 1) ? p->val[o] : dflt;
}
void clear() {
pages_.clear();
last_key_ = ~0ULL;
last_ = nullptr;
}
};
#endif // T210_REGCACHE_H
+481 -143
View File
@@ -1,12 +1,14 @@
#include "se_engine.h"
#include "../emu_state.h"
#include "memory_map.h"
#include "mmio.h"
#include <unicorn/unicorn.h>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <vector>
// =============================================================================
// Tegra X1 Security Engine (SE) emulation
@@ -41,25 +43,20 @@ static const uint32_t K[64] = {
#define ROR32(x, n) (((x) >> (n)) | ((x) << (32 - (n))))
static void compute(const uint8_t *msg, uint32_t len, uint8_t out[32]) {
uint32_t H[8] = {
static const uint32_t H0[8] = {
0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,
0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19,
};
// Total padded length: msg + 0x80 + zeros + 8-byte length, multiple of 64
uint64_t bitlen = (uint64_t)len * 8;
uint32_t padded_len = ((len + 1 + 8 + 63) / 64) * 64;
uint8_t *buf = (uint8_t*)std::calloc(1, padded_len);
std::memcpy(buf, msg, len);
buf[len] = 0x80;
for (int i = 0; i < 8; i++) buf[padded_len - 1 - i] = (uint8_t)(bitlen >> (i * 8));
for (uint32_t off = 0; off < padded_len; off += 64) {
// Compress `nblocks` 64-byte blocks into the running state H.
static void blocks(uint32_t H[8], const uint8_t *p, size_t nblocks) {
for (size_t blk = 0; blk < nblocks; blk++, p += 64) {
uint32_t W[64];
for (int i = 0; i < 16; i++) {
W[i] = ((uint32_t)buf[off + i*4 + 0] << 24) |
((uint32_t)buf[off + i*4 + 1] << 16) |
((uint32_t)buf[off + i*4 + 2] << 8) |
((uint32_t)buf[off + i*4 + 3]);
W[i] = ((uint32_t)p[i*4 + 0] << 24) |
((uint32_t)p[i*4 + 1] << 16) |
((uint32_t)p[i*4 + 2] << 8) |
((uint32_t)p[i*4 + 3]);
}
for (int i = 16; i < 64; i++) {
uint32_t s0 = ROR32(W[i-15],7) ^ ROR32(W[i-15],18) ^ (W[i-15] >> 3);
@@ -79,13 +76,23 @@ static void compute(const uint8_t *msg, uint32_t len, uint8_t out[32]) {
H[0]+=a; H[1]+=b; H[2]+=c; H[3]+=d;
H[4]+=e; H[5]+=f; H[6]+=g; H[7]+=h;
}
std::free(buf);
for (int i = 0; i < 8; i++) {
out[i*4 + 0] = (uint8_t)(H[i] >> 24);
out[i*4 + 1] = (uint8_t)(H[i] >> 16);
out[i*4 + 2] = (uint8_t)(H[i] >> 8);
out[i*4 + 3] = (uint8_t)(H[i]);
}
// Hash the last `len` bytes of a message whose total length is `total_bits`,
// padding as FIPS 180-4 requires. Whole blocks go straight through; only the
// tail is copied.
static void final(uint32_t H[8], const uint8_t *msg, size_t len,
uint64_t total_bits) {
size_t whole = len / 64;
blocks(H, msg, whole);
uint8_t tail[128] = {0};
size_t rest = len - whole * 64;
std::memcpy(tail, msg + whole * 64, rest);
tail[rest] = 0x80;
size_t tail_len = (rest + 1 + 8 <= 64) ? 64 : 128;
for (int i = 0; i < 8; i++)
tail[tail_len - 1 - i] = (uint8_t)(total_bits >> (i * 8));
blocks(H, tail, tail_len / 64);
}
#undef ROR32
@@ -249,8 +256,40 @@ constexpr uint32_t SE_RNG_CONFIG_REG = 0x340;
constexpr uint32_t SE_HASH_RESULT_REG = 0x030; // 16 dwords
constexpr uint32_t SE_STATUS_REG = 0x800;
constexpr uint32_t SE_ERR_STATUS_REG = 0x804;
constexpr uint32_t SE_CONTEXT_SAVE_CONFIG_REG = 0x070;
constexpr uint32_t SE_SHA_CONFIG_REG = 0x200;
constexpr uint32_t SE_SHA_MSG_LENGTH_REG = 0x204; // 4 dwords, in bits
constexpr uint32_t SE_SHA_MSG_LEFT_REG = 0x214; // 4 dwords, in bits
constexpr uint32_t SE_RSA_CONFIG_REG = 0x400;
constexpr uint32_t SE_RSA_KEY_SIZE_REG = 0x404;
constexpr uint32_t SE_RSA_EXP_SIZE_REG = 0x408;
constexpr uint32_t SE_RSA_KEYTABLE_ADDR_REG = 0x420;
constexpr uint32_t SE_RSA_KEYTABLE_DATA_REG = 0x424;
constexpr uint32_t SE_RSA_OUTPUT_REG = 0x428; // 64 dwords
constexpr uint32_t SE_INT_OP_DONE = 1u << 4;
constexpr uint32_t SE_INT_ERR_STAT = 1u << 16;
constexpr uint32_t SE_OP_START = 1;
constexpr uint32_t SE_OP_CTX_SAVE = 3;
constexpr uint32_t ALG_RNG = 2;
constexpr uint32_t ALG_SHA = 3;
constexpr uint32_t ALG_RSA = 4;
constexpr uint32_t MODE_SHA256 = 5;
constexpr uint32_t DST_SRK = 3;
constexpr uint32_t DST_RSAREG = 4;
constexpr uint32_t SHA_INIT_HASH = 1;
// SE_CONTEXT_SAVE_CONFIG: source in 31:29, AES key index in 11:8, word quad
// in 1:0 (bdk se_t210.h).
constexpr uint32_t CTX_SRC_AES_KEYTABLE = 2;
constexpr uint32_t CTX_SRC_SRK = 6;
// A linked-list entry's size field is 24 bits (bdk masks it the same way),
// which also bounds how much one operation can move: 16 MiB, 2^20 blocks.
constexpr uint32_t LL_SIZE_MASK = 0xFFFFFF;
constexpr uint32_t MAX_AES_BLOCKS = (LL_SIZE_MASK + 1) / 16;
constexpr uint32_t ALG_NOP = 0;
constexpr uint32_t ALG_AES_DEC = 1;
@@ -312,106 +351,333 @@ static uint32_t reg_err_status = 0;
static uint32_t reg_rng_config = 0;
static uint32_t spare_regs[256] = {0}; // catch-all for less critical regs
// The two RSA keyslots, as bdk's se_rsa_key_set() loads them: 32-bit words,
// least significant first (it writes the big-endian key backwards, each word
// byte-swapped). SE_RSA_KEYTABLE_ADDR picks the word: PKT in 5:0, EXP (0) or
// MOD (1) in bit 6, the slot in bit 7.
constexpr int kRsaWords = 64; // 2048 bits
struct RsaKey { uint32_t exp[kRsaWords]; uint32_t mod[kRsaWords]; };
static RsaKey rsa_keys[2];
static uint32_t rsa_config = 0;
static uint32_t rsa_key_size = 0;
static uint32_t rsa_exp_size = 0;
static uint32_t rsa_keytable_addr = 0;
static uint32_t rsa_output[kRsaWords] = {0};
// The random number generator's state. The SE's DRBG is seeded from an
// entropy source; this one starts from a constant, so runs repeat.
static uint64_t rng_state = 0;
// Secure random key for context save, and the CBC chain the saved blocks
// are encrypted under. See ctx_save().
static uint8_t srk[16] = {0};
static uint8_t ctx_chain[16] = {0};
// LL descriptor: { num, addr, size }. Hekate often uses num=0 (single descriptor).
struct LLDesc { uint32_t num, addr, size; };
static bool read_ll(uc_engine *uc, uint32_t ll_addr, LLDesc *out) {
if (!ll_addr) return false;
if (uc_mem_read(uc, ll_addr, out, sizeof(LLDesc)) != UC_ERR_OK) return false;
out->size &= LL_SIZE_MASK;
return true;
}
// Encrypt/decrypt a buffer in-place using the keyslot's key (assumes 128-bit).
// The operation touched memory it cannot reach: finish with an error, which
// bdk's _se_op_wait() reports instead of handing back a buffer of zeros.
static void op_fail(const char *what, uint32_t addr) {
std::printf("[se] %s: cannot access 0x%08X - operation failed\n", what, addr);
reg_int_status |= SE_INT_OP_DONE | SE_INT_ERR_STAT;
}
static inline void xor16(uint8_t *d, const uint8_t *s) {
for (int j = 0; j < 16; ++j) d[j] ^= s[j];
}
// SE_CRYPTO_LINEAR_CTR holds the counter as the driver wrote it, bytes in
// memory order; it counts as one big-endian 128-bit number.
static void ctr_add(uint32_t n) {
uint8_t *p = (uint8_t *)linear_ctr;
for (int j = 15; j >= 0 && n; --j) {
uint32_t v = p[j] + (n & 0xFF);
p[j] = (uint8_t)v;
n = (n >> 8) + (v >> 8);
}
}
// One AES operation over `blocks` 16-byte blocks, chained the way the SE
// datapath chains them. The configurations bdk's sec/se.c uses:
//
// ECB INPUT_MEMORY XOR_BYPASS out = AES(in)
// CBC enc INPUT_MEMORY XOR_TOP VCTRAM_AESOUT out = AES(in ^ v); v = out
// CBC dec INPUT_MEMORY XOR_BOTTOM VCTRAM_PREVMEM out = AES(in) ^ v; v = in
// OFB INPUT_AESOUT XOR_BOTTOM v = AES(v); out = v ^ in
// CTR INPUT_LNR_CTR XOR_BOTTOM out = AES(ctr) ^ in; ctr += n
//
// v, the vector RAM, starts from the slot's original or updated IV (IV_SEL).
// When the mode chains, the final v is left in the slot's UPDATED_IV: that is
// how bdk continues a chain into a trailing partial block, and how its CMAC
// feeds the last block after the others. With HASH enabled (CMAC) the last
// AES output goes to SE_HASH_RESULT.
static void run_aes_blocks(uint32_t slot, bool encrypt,
const uint8_t *in, uint8_t *out, size_t blocks,
uint32_t xor_pos, uint32_t input_sel,
uint32_t vctram_sel, uint32_t iv_sel,
bool ctr_mode, bool hash_mode) {
uint32_t ctr_step, bool hash_mode) {
uint8_t rk[176];
aes::key_expand(ks_table[slot].key, rk);
// Pick which IV to use for chaining. Hekate typically uses ORIGINAL_IV for
// CBC starts and switches to UPDATED_IV mid-CMAC; we honour that.
uint8_t chain[16];
if (iv_sel == IV_UPDATED) std::memcpy(chain, ks_table[slot].iv_upd, 16);
else std::memcpy(chain, ks_table[slot].iv_orig, 16);
uint8_t prev_in[16] = {0};
uint8_t hash_state[16] = {0}; // accumulator for HASH=1 (CMAC) — XOR top, encrypt
if (hash_mode) std::memcpy(hash_state, chain, 16);
uint8_t v[16];
std::memcpy(v, iv_sel == IV_UPDATED ? ks_table[slot].iv_upd
: ks_table[slot].iv_orig, 16);
uint8_t aes_out[16] = {0};
for (size_t i = 0; i < blocks; ++i) {
uint8_t in_block[16];
uint8_t out_block[16];
const uint8_t *mem = in + i * 16;
uint8_t a[16];
if (input_sel == INPUT_LNR_CTR) std::memcpy(a, linear_ctr, 16);
else if (input_sel == INPUT_AESOUT) std::memcpy(a, v, 16);
else std::memcpy(a, mem, 16);
if (input_sel == INPUT_LNR_CTR) {
// CTR mode input is the linear counter (big-endian 128-bit), per-block.
// Our linear_ctr[] is stored as 4 dwords little-endian; assemble.
uint8_t ctr_be[16];
for (int j = 0; j < 4; ++j) {
uint32_t w = linear_ctr[j];
ctr_be[j*4 + 0] = (w >> 0) & 0xFF;
ctr_be[j*4 + 1] = (w >> 8) & 0xFF;
ctr_be[j*4 + 2] = (w >> 16) & 0xFF;
ctr_be[j*4 + 3] = (w >> 24) & 0xFF;
}
std::memcpy(in_block, ctr_be, 16);
} else if (input_sel == INPUT_AESOUT) {
// Re-feeding previous AES output (used in some chained constructions).
std::memcpy(in_block, prev_in, 16);
} else {
std::memcpy(in_block, in + i*16, 16);
if (xor_pos == XOR_TOP) xor16(a, v);
if (encrypt) aes::encrypt_block(a, aes_out, rk);
else aes::decrypt_block(a, aes_out, rk);
uint8_t *o = out + i * 16;
std::memcpy(o, aes_out, 16);
// After the core: CBC decrypt XORs the vector; OFB and CTR XOR the data.
if (xor_pos == XOR_BOTTOM) xor16(o, input_sel == INPUT_MEMORY ? v : mem);
if (input_sel == INPUT_AESOUT || vctram_sel == VCTRAM_AESOUT)
std::memcpy(v, aes_out, 16);
else if (vctram_sel == VCTRAM_PREVMEM)
std::memcpy(v, mem, 16);
if (input_sel == INPUT_LNR_CTR) ctr_add(ctr_step);
}
// VCTRAM source: the value XORed at XOR_TOP / XOR_BOTTOM.
uint8_t vctram[16];
if (vctram_sel == VCTRAM_AESOUT) std::memcpy(vctram, prev_in, 16);
else if (vctram_sel == VCTRAM_PREVMEM) std::memcpy(vctram, (i==0)? chain : (in + (i-1)*16), 16);
else std::memcpy(vctram, chain, 16);
if (xor_pos == XOR_TOP) {
for (int j = 0; j < 16; ++j) in_block[j] ^= vctram[j];
if (hash_mode) std::memcpy(hash_result, aes_out, 16);
bool chained = input_sel == INPUT_AESOUT || vctram_sel == VCTRAM_AESOUT ||
vctram_sel == VCTRAM_PREVMEM;
if (chained && blocks) std::memcpy(ks_table[slot].iv_upd, v, 16);
}
if (encrypt) aes::encrypt_block(in_block, out_block, rk);
else aes::decrypt_block(in_block, out_block, rk);
// ---- RSA: x^e mod n, Montgomery multiplication on 32-bit words -------------
//
// Numbers are arrays of words, least significant first, n words long.
if (xor_pos == XOR_BOTTOM) {
// Output XOR with chain (CTR keystream XOR plaintext, etc.)
const uint8_t *xb = (input_sel == INPUT_LNR_CTR)
? (in + i*16) // CTR: XOR with plaintext from memory
: vctram;
for (int j = 0; j < 16; ++j) out_block[j] ^= xb[j];
static bool big_geq(const uint32_t *a, const uint32_t *b, int n) {
for (int i = n - 1; i >= 0; --i)
if (a[i] != b[i]) return a[i] > b[i];
return true;
}
if (out) std::memcpy(out + i*16, out_block, 16);
// Advance chain for next block.
if (xor_pos == XOR_BOTTOM && input_sel != INPUT_LNR_CTR) {
// CBC encrypt: chain = ciphertext = out_block
std::memcpy(chain, out_block, 16);
} else if (xor_pos == XOR_TOP) {
// CBC decrypt: chain = ciphertext (the input block we read)
std::memcpy(chain, in + i*16, 16);
}
std::memcpy(prev_in, out_block, 16);
if (ctr_mode) {
// Increment linear counter (big-endian 128-bit).
for (int j = 15; j >= 0; --j) {
uint8_t *p = (uint8_t*)linear_ctr;
p[j]++;
if (p[j]) break;
}
static void big_sub(uint32_t *a, const uint32_t *b, int n) {
uint64_t borrow = 0;
for (int i = 0; i < n; ++i) {
uint64_t d = (uint64_t)a[i] - b[i] - borrow;
a[i] = (uint32_t)d;
borrow = d >> 63;
}
}
if (hash_mode) {
// For HASH paths the final cipher block is exposed via SE_HASH_RESULT_REG.
std::memcpy(hash_result, prev_in, 16);
// x = (2x + bit) mod m, for x < m.
static void big_shl1_mod(uint32_t *x, uint32_t bit, const uint32_t *m, int n) {
uint32_t carry = bit;
for (int i = 0; i < n; ++i) {
uint32_t top = x[i] >> 31;
x[i] = x[i] << 1 | carry;
carry = top;
}
// Save updated IV (chain) for next call's IV_UPDATED.
std::memcpy(ks_table[slot].iv_upd, chain, 16);
if (carry || big_geq(x, m, n)) big_sub(x, m, n);
}
// r = a mod m, a being na words long.
static void big_mod(const uint32_t *a, int na, const uint32_t *m, int n,
uint32_t *r) {
std::memset(r, 0, n * sizeof(uint32_t));
for (int i = na * 32 - 1; i >= 0; --i)
big_shl1_mod(r, a[i / 32] >> (i % 32) & 1, m, n);
}
// t = a * b / 2^(32n) mod m, for a, b < m and m odd (CIOS).
static void mont_mul(const uint32_t *a, const uint32_t *b, const uint32_t *m,
uint32_t minv, int n, uint32_t *out) {
uint32_t t[kRsaWords + 2] = {0};
for (int i = 0; i < n; ++i) {
uint64_t c = 0;
for (int j = 0; j < n; ++j) {
uint64_t s = (uint64_t)t[j] + (uint64_t)a[j] * b[i] + c;
t[j] = (uint32_t)s;
c = s >> 32;
}
uint64_t s = (uint64_t)t[n] + c;
t[n] = (uint32_t)s;
t[n + 1] = (uint32_t)(s >> 32);
uint32_t u = t[0] * minv;
c = ((uint64_t)t[0] + (uint64_t)u * m[0]) >> 32;
for (int j = 1; j < n; ++j) {
s = (uint64_t)t[j] + (uint64_t)u * m[j] + c;
t[j - 1] = (uint32_t)s;
c = s >> 32;
}
s = (uint64_t)t[n] + c;
t[n - 1] = (uint32_t)s;
t[n] = t[n + 1] + (uint32_t)(s >> 32);
}
if (t[n] || big_geq(t, m, n)) big_sub(t, m, n);
std::memcpy(out, t, n * sizeof(uint32_t));
}
// out = x^e mod m. m must be odd (every RSA modulus is); false if it is not.
static bool mod_exp(const uint32_t *x, const uint32_t *e, int ne,
const uint32_t *m, int n, uint32_t *out) {
if (!(m[0] & 1)) return false;
// -1/m mod 2^32 by Newton's iteration; m0 is its own inverse mod 8.
uint32_t inv = m[0];
for (int i = 0; i < 4; ++i) inv *= 2 - m[0] * inv;
uint32_t minv = 0u - inv;
// R^2 mod m, R = 2^(32n): 1 doubled 64n times.
uint32_t r2[kRsaWords] = {0}, one[kRsaWords] = {0};
one[0] = 1;
big_mod(one, 1, m, n, r2);
for (int i = 0; i < 64 * n; ++i) big_shl1_mod(r2, 0, m, n);
uint32_t xm[kRsaWords], acc[kRsaWords];
big_mod(x, n, m, n, xm);
mont_mul(xm, r2, m, minv, n, xm); // x in Montgomery form
mont_mul(one, r2, m, minv, n, acc); // 1 in Montgomery form
for (int i = ne * 32 - 1; i >= 0; --i) {
mont_mul(acc, acc, m, minv, n, acc);
if (e[i / 32] >> (i % 32) & 1) mont_mul(acc, xm, m, minv, n, acc);
}
mont_mul(acc, one, m, minv, n, out);
return true;
}
// SE_OP_START with ALG_RSA, as bdk's se_rsa_exp_mod() drives it: the input
// arrives over DMA as a little-endian number the size of the modulus, the
// key comes from the slot in SE_RSA_CONFIG, KEY_SIZE gives the modulus in
// 512-bit steps and EXP_SIZE the exponent in words. The result goes to
// SE_RSA_OUTPUT (least significant word first), or to memory.
static void rsa_op(EmuState *state, uint32_t dst_kind) {
const RsaKey &k = rsa_keys[(rsa_config >> 24) & 1];
int n = (int)((rsa_key_size & 3) + 1) * 16;
int ne = (int)(rsa_exp_size > (uint32_t)kRsaWords ? kRsaWords : rsa_exp_size);
uint32_t x[kRsaWords] = {0};
LLDesc in_ll{};
if (read_ll(state->uc, reg_in_ll_addr, &in_ll) && in_ll.size) {
uint32_t copy = in_ll.size < (uint32_t)n * 4 ? in_ll.size : n * 4;
if (uc_mem_read(state->uc, in_ll.addr, x, copy) != UC_ERR_OK) {
op_fail("RSA input", in_ll.addr);
return;
}
}
std::memset(rsa_output, 0, sizeof(rsa_output));
if (!mod_exp(x, k.exp, ne, k.mod, n, rsa_output)) {
std::printf("[se] RSA-%d: even modulus, no result\n", n * 32);
reg_int_status |= SE_INT_OP_DONE | SE_INT_ERR_STAT;
return;
}
std::printf("[se] RSA-%d exp mod, %d-bit exponent -> ...%08X\n", n * 32,
ne * 32, rsa_output[0]);
if (dst_kind == DST_MEMORY) {
LLDesc out_ll{};
if (read_ll(state->uc, reg_out_ll_addr, &out_ll) && out_ll.size) {
uint32_t copy = out_ll.size < (uint32_t)n * 4 ? out_ll.size : n * 4;
if (uc_mem_write(state->uc, out_ll.addr, rsa_output, copy) != UC_ERR_OK) {
op_fail("RSA output", out_ll.addr);
return;
}
}
}
reg_int_status |= SE_INT_OP_DONE;
}
// SplitMix64: small, and its output has no visible pattern.
static uint64_t rng_next() {
uint64_t z = (rng_state += 0x9E3779B97F4A7C15ull);
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull;
z = (z ^ (z >> 27)) * 0x94D049BB133111EBull;
return z ^ (z >> 31);
}
static void rng_fill(uint8_t *p, size_t len) {
for (size_t i = 0; i < len; i += 8) {
uint64_t v = rng_next();
std::memcpy(p + i, &v, len - i < 8 ? len - i : 8);
}
}
// SE_OP_START with ALG_RNG into memory or a keyslot: bdk's se_rng_pseudo()
// and TegraExplorer's se_generate_random() fill a buffer, SE_CRYPTO_LAST_BLOCK
// + 1 blocks of it; Atmosphère-style drivers fill a key quad.
static void rng_op(EmuState *state, uint32_t dst_kind) {
uint32_t blocks = (reg_block_count % MAX_AES_BLOCKS) + 1;
if (dst_kind == DST_KEYTABLE) {
Keyslot &k = ks_table[(reg_keytable_dst >> 8) & 0xF];
uint8_t *target[4] = {k.key, k.key + 16, k.iv_orig, k.iv_upd};
rng_fill(target[reg_keytable_dst & 0x3], 16);
} else if (dst_kind == DST_MEMORY) {
LLDesc out_ll{};
if (read_ll(state->uc, reg_out_ll_addr, &out_ll) && out_ll.size) {
uint32_t len = out_ll.size < blocks * 16 ? out_ll.size : blocks * 16;
std::vector<uint8_t> buf(len);
rng_fill(buf.data(), len);
if (uc_mem_write(state->uc, out_ll.addr, buf.data(), len) != UC_ERR_OK) {
op_fail("RNG output", out_ll.addr);
return;
}
}
}
reg_int_status |= SE_INT_OP_DONE;
}
// SHA-256, one-shot or in parts (bdk _se_sha_hash_256). SHA_INIT_HASH starts
// from the standard initial state, SHA_CONTINUE from the state the previous
// part left in SE_HASH_RESULT - which is where the hardware keeps it, too.
// SE_SHA_MSG_LEFT says whether this is the last part: bdk passes one byte
// more than it feeds for any part but the last, so the engine pads the part
// only when LEFT equals the data it has, using the total from
// SE_SHA_MSG_LENGTH. HASH_RESULT holds the state as 8 dwords, most
// significant byte first; the driver byte-swaps them into the digest.
static void sha_op(EmuState *state) {
LLDesc in_ll{};
if (!read_ll(state->uc, reg_in_ll_addr, &in_ll) || !in_ll.size) {
reg_int_status |= SE_INT_OP_DONE;
return;
}
std::vector<uint8_t> buf(in_ll.size);
if (uc_mem_read(state->uc, in_ll.addr, buf.data(), in_ll.size) != UC_ERR_OK) {
op_fail("SHA-256 input", in_ll.addr);
return;
}
auto reg64 = [](uint32_t off) {
return (uint64_t)spare_regs[off / 4] | ((uint64_t)spare_regs[off / 4 + 1] << 32);
};
uint64_t total_bits = reg64(SE_SHA_MSG_LENGTH_REG);
uint64_t left_bits = reg64(SE_SHA_MSG_LEFT_REG);
bool init = (spare_regs[SE_SHA_CONFIG_REG / 4] & 1) == SHA_INIT_HASH;
uint32_t H[8];
if (init) std::memcpy(H, sha256::H0, sizeof(H));
else std::memcpy(H, hash_result, sizeof(H));
bool last = left_bits <= (uint64_t)in_ll.size * 8;
if (last)
sha256::final(H, buf.data(), in_ll.size, total_bits);
else
sha256::blocks(H, buf.data(), in_ll.size / 64);
std::memcpy(hash_result, H, sizeof(H));
std::printf("[se] SHA-256 %s%s over %u bytes @0x%X -> %08X...\n",
init ? "" : "continued ", last ? "final" : "part",
in_ll.size, in_ll.addr, H[0]);
reg_int_status |= SE_INT_OP_DONE;
}
static void op_start(EmuState *state) {
@@ -423,39 +689,27 @@ static void op_start(EmuState *state) {
bool dec = (dec_alg == ALG_AES_DEC) && (enc_alg == ALG_NOP);
bool enc = (enc_alg == ALG_AES_ENC) && (dec_alg == ALG_NOP);
// ---- SHA-256 path ----
// ALG_SHA=3, MODE_SHA256=5, DST=DST_HASHREG. Driver flow: writes
// SE_SHA_MSG_LENGTH/LEFT, sets up IN_LL pointing at src/src_size, then
// OP_START. Output 32 bytes go into HASH_RESULT_REG as 8 big-endian dwords
// (driver byte_swap_32's each on read). We currently only model the
// oneshot case (SHA_INIT_HASH); save_process_header uses oneshot.
if (enc_alg == 3 /*ALG_SHA*/ && dst_kind == DST_HASHREG && enc_mode == 5 /*MODE_SHA256*/) {
LLDesc in_ll{};
bool got_in = read_ll(state->uc, reg_in_ll_addr, &in_ll);
if (!got_in || !in_ll.size) {
reg_int_status |= SE_INT_OP_DONE;
if (enc_alg == ALG_SHA && dst_kind == DST_HASHREG && enc_mode == MODE_SHA256) {
sha_op(state);
return;
}
std::vector<uint8_t> buf(in_ll.size, 0);
uc_mem_read(state->uc, in_ll.addr, buf.data(), in_ll.size);
uint8_t digest[32];
sha256::compute(buf.data(), in_ll.size, digest);
// Pack into HASH_RESULT_REG as 8 big-endian dwords (driver byteswaps).
for (int i = 0; i < 8; i++) {
hash_result[i] = ((uint32_t)digest[i*4 + 0] << 24) |
((uint32_t)digest[i*4 + 1] << 16) |
((uint32_t)digest[i*4 + 2] << 8) |
((uint32_t)digest[i*4 + 3]);
}
std::printf("[se] SHA-256 over %u bytes @0x%X -> %02X%02X%02X%02X...\n",
in_ll.size, in_ll.addr, digest[0], digest[1], digest[2], digest[3]);
// RNG into the secure random key: the start of a context save. The key is
// fixed rather than random so runs stay reproducible.
if (enc_alg == ALG_RNG && dst_kind == DST_SRK) {
for (int i = 0; i < 16; ++i) srk[i] = (uint8_t)(0xA5 ^ (i * 0x1D));
std::memset(ctx_chain, 0, sizeof(ctx_chain));
reg_int_status |= SE_INT_OP_DONE;
return;
}
if (dst_kind == 4 /* DST_RSAREG */) {
// RSA not implemented — leave output zero.
reg_int_status |= SE_INT_OP_DONE;
if (enc_alg == ALG_RNG) {
rng_op(state, dst_kind);
return;
}
if (enc_alg == ALG_RSA) {
rsa_op(state, dst_kind);
return;
}
@@ -470,46 +724,51 @@ static void op_start(EmuState *state) {
uint32_t iv_sel = (reg_crypto_config >> 7) & 0x1;
uint32_t core_sel = (reg_crypto_config >> 8) & 0x1;
bool hash_en = (reg_crypto_config >> 0) & 0x1;
uint32_t ctr_cnt = (reg_crypto_config >> 11) & 0x1;
uint32_t ctr_step = (reg_crypto_config >> 11) & 0xFF;
uint32_t key_index = (reg_crypto_config >> 24) & 0xF;
bool encrypt = (core_sel == CORE_ENCRYPT);
uint32_t blocks = reg_block_count + 1;
// SE_CRYPTO_LAST_BLOCK is the index of the last block. Bounded by what one
// linked-list entry can describe, so a wild value cannot overflow the
// buffer size below.
uint32_t blocks = (reg_block_count % MAX_AES_BLOCKS) + 1;
uint32_t total_bytes = blocks * 16;
// Read input via IN_LL.
std::vector<uint8_t> in_buf, out_buf;
in_buf.resize(total_bytes, 0);
out_buf.resize(total_bytes, 0);
std::vector<uint8_t> in_buf(total_bytes, 0), out_buf(total_bytes, 0);
LLDesc in_ll{}, out_ll{};
bool got_in = read_ll(state->uc, reg_in_ll_addr, &in_ll);
bool got_out = read_ll(state->uc, reg_out_ll_addr, &out_ll);
(void)got_out;
if (got_in && in_ll.size && input_sel == INPUT_MEMORY) {
// Memory input is data for every mode: the block itself for ECB/CBC, what
// the keystream is XORed with for OFB/CTR.
if (got_in && in_ll.size) {
uint32_t copy = (in_ll.size < total_bytes) ? in_ll.size : total_bytes;
uc_mem_read(state->uc, in_ll.addr, in_buf.data(), copy);
if (uc_mem_read(state->uc, in_ll.addr, in_buf.data(), copy) != UC_ERR_OK) {
op_fail("AES input", in_ll.addr);
return;
}
}
run_aes_blocks(key_index, encrypt, in_buf.data(), out_buf.data(), blocks,
xor_pos, input_sel, vctram_sel, iv_sel,
(input_sel == INPUT_LNR_CTR) || ctr_cnt, hash_en);
xor_pos, input_sel, vctram_sel, iv_sel, ctr_step, hash_en);
if (dst_kind == DST_MEMORY) {
if (got_out && out_ll.size) {
uint32_t copy = (out_ll.size < total_bytes) ? out_ll.size : total_bytes;
uc_mem_write(state->uc, out_ll.addr, out_buf.data(), copy);
if (uc_mem_write(state->uc, out_ll.addr, out_buf.data(), copy) != UC_ERR_OK) {
op_fail("AES output", out_ll.addr);
return;
}
}
} else if (dst_kind == DST_KEYTABLE) {
// Unwrap-key path: store the (single-block) result in the destination slot.
// Unwrap-key path: the (single-block) result lands in the destination
// slot's selected word quad.
uint32_t dst_slot = (reg_keytable_dst >> 8) & 0xF;
uint32_t word_quad = reg_keytable_dst & 0x3;
uint8_t *target = (word_quad == 1)
? ks_table[dst_slot].key + 16
: ks_table[dst_slot].key + 0;
std::memcpy(target, out_buf.data(), 16);
Keyslot &k = ks_table[dst_slot];
uint8_t *target[4] = {k.key, k.key + 16, k.iv_orig, k.iv_upd};
std::memcpy(target[reg_keytable_dst & 0x3], out_buf.data(), 16);
}
// DST_HASHREG: hash_result is already populated by run_aes_blocks.
@@ -522,6 +781,40 @@ static void op_start(EmuState *state) {
got_in ? in_ll.addr : 0, got_out ? out_ll.addr : 0);
}
// SE_OP_CTX_SAVE, as bdk's se_aes_ctx_get_keys() drives it to read keyslots
// back: an RNG op seeds the secure random key (SRK); each save of an AES
// keytable quad writes that quad to memory encrypted under the SRK, CBC-
// chained from one save to the next; saving the SRK source deposits the key
// in PMC SECURE_SCRATCH4..7. The driver then loads the SRK into a slot and
// CBC-decrypts everything it saved in one pass with that slot's original IV,
// which it never sets - zero from reset - so the chain starts from zero.
static void ctx_save(EmuState *state) {
uint32_t cfg = spare_regs[SE_CONTEXT_SAVE_CONFIG_REG / 4];
uint32_t src = cfg >> 29;
if ((reg_config >> 2 & 0x7) == DST_MEMORY && src == CTX_SRC_AES_KEYTABLE) {
const Keyslot &k = ks_table[(cfg >> 8) & 0xF];
const uint8_t *quad[4] = {k.key, k.key + 16, k.iv_orig, k.iv_upd};
uint8_t blk[16], rk[176];
std::memcpy(blk, quad[cfg & 0x3], 16);
xor16(blk, ctx_chain);
aes::key_expand(srk, rk);
aes::encrypt_block(blk, ctx_chain, rk);
LLDesc out_ll{};
if (read_ll(state->uc, reg_out_ll_addr, &out_ll) && out_ll.size >= 16 &&
uc_mem_write(state->uc, out_ll.addr, ctx_chain, 16) != UC_ERR_OK) {
op_fail("context save output", out_ll.addr);
return;
}
} else if (src == CTX_SRC_SRK && reg_config != 0) {
for (int i = 0; i < 4; ++i) {
uint32_t w;
std::memcpy(&w, srk + i * 4, 4);
pmc_secure_scratch_write(4 + i, w);
}
}
reg_int_status |= SE_INT_OP_DONE;
}
// Keytable address layout: bits 4..7 = slot, bits 2..3 = quad, bits 0..1 = pkt
static void keytable_write(uint32_t addr, uint32_t val) {
uint32_t slot = (addr >> 4) & 0xF;
@@ -541,14 +834,19 @@ static void keytable_write(uint32_t addr, uint32_t val) {
// Lockpick's _derive_bis_keys may produce wrong values when our SE engine
// doesn't faithfully model some part of the chain; the override is a
// pragmatic shortcut that lets the BIS XTS layer succeed regardless.
// Two writes are never BIS keys and are left alone: clearing a slot (all
// zeros), and loading the context-save SRK (bdk puts it in slot 3).
if (quad == 0 && pkt == 3 && slot < 6) {
if (bis_override_present[slot]) {
static const uint8_t zero[16] = {0};
bool clear = std::memcmp(ks_table[slot].key, zero, 16) == 0;
bool is_srk = std::memcmp(ks_table[slot].key, srk, 16) == 0;
if (bis_override_present[slot] && !clear && !is_srk) {
std::memcpy(ks_table[slot].key, bis_override_keys[slot], 16);
std::printf("[se] slot %u BIS key overridden from prod.keys:", slot);
for (int i = 0; i < 16; ++i) std::printf(" %02X", ks_table[slot].key[i]);
std::printf("\n");
} else {
std::printf("[se] slot %u key loaded (derived):", slot);
} else if (!clear) {
std::printf("[se] slot %u key loaded:", slot);
for (int i = 0; i < 16; ++i) std::printf(" %02X", ks_table[slot].key[i]);
std::printf("\n");
}
@@ -572,9 +870,12 @@ static uint32_t keytable_read(uint32_t addr) {
return v;
}
} // namespace
static uint32_t &rsa_keytable_word() {
RsaKey &k = rsa_keys[(rsa_keytable_addr >> 7) & 1];
return ((rsa_keytable_addr >> 6) & 1 ? k.mod : k.exp)[rsa_keytable_addr & 0x3F];
}
#include <vector>
} // namespace
uint32_t se_engine_read(EmuState *state, uint64_t addr) {
uint32_t off = (uint32_t)(addr - SE_BASE);
@@ -584,6 +885,9 @@ uint32_t se_engine_read(EmuState *state, uint64_t addr) {
if (off >= SE_CRYPTO_LINEAR_CTR_REG && off < SE_CRYPTO_LINEAR_CTR_REG + 16) {
return linear_ctr[(off - SE_CRYPTO_LINEAR_CTR_REG) / 4];
}
if (off >= SE_RSA_OUTPUT_REG && off < SE_RSA_OUTPUT_REG + kRsaWords * 4) {
return rsa_output[(off - SE_RSA_OUTPUT_REG) / 4];
}
switch (off) {
case SE_OPERATION_REG: return reg_op;
case SE_INT_ENABLE_REG: return reg_int_enable;
@@ -599,6 +903,11 @@ uint32_t se_engine_read(EmuState *state, uint64_t addr) {
case SE_RNG_CONFIG_REG: return reg_rng_config;
case SE_STATUS_REG: return 0; // IDLE
case SE_ERR_STATUS_REG: return reg_err_status;
case SE_RSA_CONFIG_REG: return rsa_config;
case SE_RSA_KEY_SIZE_REG: return rsa_key_size;
case SE_RSA_EXP_SIZE_REG: return rsa_exp_size;
case SE_RSA_KEYTABLE_ADDR_REG: return rsa_keytable_addr;
case SE_RSA_KEYTABLE_DATA_REG: return rsa_keytable_word();
default:
if (off < sizeof(spare_regs)/sizeof(spare_regs[0])*4)
return spare_regs[off / 4];
@@ -616,10 +925,12 @@ void se_engine_write(EmuState *state, uint64_t addr, uint32_t val) {
switch (off) {
case SE_OPERATION_REG:
reg_op = val;
// SE_OP_START runs the configured AES op; other op codes (RESTART_*,
// CTX_SAVE, ABORT) just need OP_DONE so the driver's _se_wait() exits.
if ((val & 0x7) == 1 /*SE_OP_START*/) {
// SE_OP_START runs the configured op and CTX_SAVE saves context;
// the others (RESTART_*) just need OP_DONE so _se_op_wait() exits.
if ((val & 0x7) == SE_OP_START) {
op_start(state);
} else if ((val & 0x7) == SE_OP_CTX_SAVE) {
ctx_save(state);
} else if ((val & 0x7) != 0 /*not ABORT*/) {
reg_int_status |= SE_INT_OP_DONE;
}
@@ -639,6 +950,11 @@ void se_engine_write(EmuState *state, uint64_t addr, uint32_t val) {
case SE_CRYPTO_KEYTABLE_DST: reg_keytable_dst = val; return;
case SE_RNG_CONFIG_REG: reg_rng_config = val; return;
case SE_ERR_STATUS_REG: reg_err_status &= ~val; return;
case SE_RSA_CONFIG_REG: rsa_config = val; return;
case SE_RSA_KEY_SIZE_REG: rsa_key_size = val; return;
case SE_RSA_EXP_SIZE_REG: rsa_exp_size = val; return;
case SE_RSA_KEYTABLE_ADDR_REG: rsa_keytable_addr = val; return;
case SE_RSA_KEYTABLE_DATA_REG: rsa_keytable_word() = val; return;
default:
if (off < sizeof(spare_regs)/sizeof(spare_regs[0])*4)
spare_regs[off / 4] = val;
@@ -647,9 +963,31 @@ void se_engine_write(EmuState *state, uint64_t addr, uint32_t val) {
(void)state;
}
// Keys a prod.keys file pre-loaded, which a soft reboot puts back.
static Keyslot ks_preload[16];
void se_engine_set_aes128_key(uint32_t slot, const uint8_t key[16]) {
if (slot >= 16) return;
std::memcpy(ks_table[slot].key, key, 16);
std::memcpy(ks_preload[slot].key, key, 16);
}
void se_engine_reset() {
std::memcpy(ks_table, ks_preload, sizeof(ks_table));
reg_config = reg_crypto_config = 0;
reg_in_ll_addr = reg_out_ll_addr = 0;
reg_block_count = reg_keytable_addr = reg_keytable_dst = 0;
reg_op = reg_int_status = reg_int_enable = 0;
reg_err_status = reg_rng_config = 0;
std::memset(linear_ctr, 0, sizeof(linear_ctr));
std::memset(hash_result, 0, sizeof(hash_result));
std::memset(spare_regs, 0, sizeof(spare_regs));
std::memset(srk, 0, sizeof(srk));
std::memset(ctx_chain, 0, sizeof(ctx_chain));
std::memset(rsa_keys, 0, sizeof(rsa_keys));
std::memset(rsa_output, 0, sizeof(rsa_output));
rsa_config = rsa_key_size = rsa_exp_size = rsa_keytable_addr = 0;
rng_state = 0;
}
// ---- prod.keys parser -------------------------------------------------------
+12 -7
View File
@@ -10,17 +10,18 @@ struct EmuState;
// operations against an emulated 16-slot keytable.
//
// Currently implemented:
// * AES-128 ECB encrypt/decrypt (single + multi-block, DMA via LL descriptors)
// * AES-128 CBC encrypt/decrypt
// * AES-128 CTR mode
// * AES-128 ECB, CBC, OFB and CTR, single and multi-block, with the IV
// chained through UPDATED_IV the way bdk's partial-block path expects
// * AES-CMAC (HASH_ENABLE into SE_HASH_RESULT)
// * AES "unwrap" (decrypt and store result in destination keyslot)
// * SHA-256, one-shot and in parts (SHA_INIT_HASH / SHA_CONTINUE)
// * Context save of AES keyslots under a secure random key, as bdk's
// se_aes_ctx_get_keys() reads keys back
// * Keyslot programming (CRYPTO_KEYTABLE_ADDR/DATA)
// * Pre-population of keyslots from a Switch prod.keys file
//
// Not implemented (returns zero / no-op):
// * AES-CMAC (HASH+VCTRAM_AESOUT path)
// * SHA / RNG / RSA
// Each unimplemented op still completes (sets OP_DONE) so the boot doesn't hang.
// Not implemented: RNG output, RSA, AES-192/256 key sizes. Those operations
// still complete (set OP_DONE) so a payload does not hang on them.
uint32_t se_engine_read (EmuState *state, uint64_t addr);
void se_engine_write(EmuState *state, uint64_t addr, uint32_t val);
@@ -31,6 +32,10 @@ void se_engine_write(EmuState *state, uint64_t addr, uint32_t val);
// AES, so this is enough.
void se_engine_set_aes128_key(uint32_t slot, const uint8_t key[16]);
// Soft reboot: registers back to reset, keyslots back to what prod.keys
// pre-loaded.
void se_engine_reset();
// Parse a switch-style "prod.keys" file (lines of `name = hex_value`) and
// pre-populate the well-known bootrom-derived keyslots (KS_TSEC=12,
// KS_SECURE_BOOT=14, KS_TSEC_ROOT=13) so Lockpick / Hekate's derivation
+1824
View File
File diff suppressed because it is too large. Load diff
+18
View File
@@ -0,0 +1,18 @@
#pragma once
#include <cstdint>
struct EmuState;
// USB device mode (see usb.cpp): the Erista USB2 device controller, and the
// PC a --usb-host run plugs into it.
uint32_t usb2d_read(EmuState *state, uint64_t addr, unsigned size);
void usb2d_write(EmuState *state, uint64_t addr, unsigned size, uint32_t val);
// The Mariko XUSB device controller (XHCI registers, PCI config at +0x8000,
// the device block at +0x9000).
uint32_t xusbd_read(EmuState *state, uint64_t addr, unsigned size);
void xusbd_write(EmuState *state, uint64_t addr, unsigned size, uint32_t val);
// SoC reset: the controller back to its reset state, the host unplugged.
void usb_reset(EmuState *state);
+10
View File
@@ -0,0 +1,10 @@
/* Loaded and entered at 0x40010000, like any RCM payload. */
ENTRY(_start)
SECTIONS {
. = 0x40010000;
.text : { KEEP(*(.text.start)) *(.text*) }
.rodata : { *(.rodata*) }
.data : { *(.data*) }
.bss : { *(.bss*) *(COMMON) }
/DISCARD/ : { *(.comment) *(.note*) *(.ARM.attributes) *(.ARM.exidx*) }
}
+197
View File
@@ -0,0 +1,197 @@
/*
* CCPLEX regression payload.
*
* A freestanding BPMP payload (ARM mode, loaded at 0x40010000 like any RCM
* payload) that drives the emulator's CPU0 model through the same register
* sequence as bdk's ccplex_boot_cpu0(), and reports what happened on UART-B.
* tests/ccplex/run.sh checks the emulator's log for the expected lines.
*
* 1. Release CPU0 from reset with nothing powered. The core must NOT run,
* and the emulator must say which precondition is missing.
* 2. Do the real bring-up - CPU rail (MAX77620 GPIO5 + MAX77621 VOUT on
* I2C5), CRAIL/C0NC/CE0 partitions, CPUG + MSELECT clocks, MSELECT out
* of reset, PLLX, RAM repair, SB_AA64_RESET_LOW - then release it. An
* AArch64 blob copied to DRAM records CurrentEL and a TIMERUS delta in
* a mailbox, writes a magic word last, and parks in WFE.
* Released first with its clock stopped (CLK_CPUG_CMPLX), it must
* stay still until the stop is cleared.
* 3. Put CPU0 back into reset and power the console off.
*
* Built by `make test` with arm-none-eabi-gcc; no other toolchain needed, as
* the AArch64 side is a handful of pre-assembled words.
*/
typedef unsigned int u32;
#define REG(a) (*(volatile u32 *)(a))
#define TIMERUS 0x60005010u
#define CAR 0x60006000u
#define FLOW 0x60007000u
#define SB 0x6000C200u
#define UARTB_THR 0x70006040u
#define PMC 0x7000E400u
#define I2C5 0x7000D000u
#define CPU_ENTRY 0xA0000000u
#define MBOX 0xA0030000u
#define PCIE_MAGIC 0x50434945u
/* AArch64, entered at EL3 with the MMU off:
* mov w1, #0xa0030000 ; mailbox
* mrs x8, currentel
* str w8, [x1, #4] ; [1] = CurrentEL
* mov w4, #0x5010
* movk w4, #0x6000, lsl #16 ; TIMERUS
* ldr w5, [x4]
* mov w6, #2000
* 1:subs w6, w6, #1
* b.ne 1b
* ldr w7, [x4]
* sub w7, w7, w5
* str w7, [x1, #8] ; [2] = TIMERUS delta across the loop
* mov w2, #0x4945
* movk w2, #0x5043, lsl #16
* str w2, [x1] ; [0] = 'PCIE', written last
* 2:wfe
* b 2b
*/
static const u32 cpu0_blob[] = {
0x52b40061, 0xd5384248, 0xb9000428, 0x528a0204, 0x72ac0004, 0xb9400085,
0x5280fa06, 0x710004c6, 0x54ffffe1, 0xb9400087, 0x4b0500e7, 0xb9000827,
0x528928a2, 0x72aa0862, 0xb9000022, 0xd503205f, 0x17ffffff,
};
static void putc_(char c) { REG(UARTB_THR) = (u32)(unsigned char)c; }
static void puts_(const char *s) {
while (*s)
putc_(*s++);
}
static void puthex(u32 v) {
for (int i = 28; i >= 0; i -= 4)
putc_("0123456789ABCDEF"[(v >> i) & 0xF]);
}
static void udelay(u32 us) {
u32 start = REG(TIMERUS);
while (REG(TIMERUS) - start < us)
;
}
/* bdk-style normal-mode I2C write: [reg, val] in CMD_DATA1, 2 bytes, GO. */
static void i2c5_write(u32 dev, u32 reg, u32 val) {
REG(I2C5 + 0x04) = dev << 1; /* CMD_ADDR0 */
REG(I2C5 + 0x0C) = reg | (val << 8); /* CMD_DATA1 */
REG(I2C5 + 0x00) = (1u << 1) | (1u << 9); /* CNFG: 2 bytes, write, GO */
}
static void pwrgate_on(u32 part) {
if (!(REG(PMC + 0x38) & (1u << part))) /* PWRGATE_STATUS */
REG(PMC + 0x30) = part | (1u << 8); /* PWRGATE_TOGGLE */
}
#define RST_CPU0 ((1u << 30) | (1u << 24) | (1u << 16) | (1u << 0))
#define RST_NONCPU (1u << 29)
static void release_cpu0(void) {
REG(SB + 0x30) = CPU_ENTRY | 1u; /* SB_AA64_RESET_LOW */
REG(SB + 0x34) = 0; /* SB_AA64_RESET_HIGH */
REG(CAR + 0x454) = RST_NONCPU; /* RST_CPUG_CMPLX_CLR */
REG(CAR + 0x454) = RST_CPU0;
}
static void hold_cpu0(void) {
REG(CAR + 0x450) = RST_CPU0; /* RST_CPUG_CMPLX_SET */
REG(CAR + 0x450) = RST_NONCPU;
}
__attribute__((section(".text.start"), noreturn))
void _start(void) {
volatile u32 *mb = (volatile u32 *)MBOX;
puts_("ccplex test: start\n");
for (u32 i = 0; i < sizeof(cpu0_blob) / sizeof(cpu0_blob[0]); i++)
((volatile u32 *)CPU_ENTRY)[i] = cpu0_blob[i];
for (u32 i = 0; i < 4; i++)
mb[i] = 0;
/* 1. Nothing powered: the release must be refused. */
release_cpu0();
udelay(2000);
puts_(mb[0] == PCIE_MAGIC ? "unpowered: CPU0 RAN (wrong)\n"
: "unpowered: CPU0 stayed dark\n");
hold_cpu0();
/* A write to the MAX77812, which the Erista this runs as does not have:
* it must land nowhere, and under --fault max77812 must not be reported
* as a chip that died. */
i2c5_write(0x33, 0x06, 0x00); /* MAX77812 EN_CTRL */
/* 2. The real bring-up, in ccplex_boot_cpu0() order. */
i2c5_write(0x3C, 0x40, 0x1C); /* MAX77620 AME_GPIO: GPIO5 plain */
i2c5_write(0x3C, 0x3B, 0x09); /* GPIO5: push-pull, out high */
i2c5_write(0x1B, 0x00, 0x80 | 55); /* MAX77621 VOUT: on, 0.950 V */
REG(CAR + 0x0E0) = (1u << 30) | (2u << 20) | (156u << 8) | 2u; /* PLLX */
REG(CAR + 0x3B4) = 4u << 1; /* CLK_SOURCE_MSELECT */
REG(CAR + 0x440) = 1u << 3; /* CLK_ENB_V_SET: MSELECT */
REG(CAR + 0x020) = 0x20008888; /* CCLK_BURST: PLLX_OUT0_LJ */
REG(CAR + 0x024) = 1u << 31; /* SUPER_CCLK_DIVIDER */
REG(CAR + 0x440) = 1u << 0; /* CLK_ENB_V_SET: CPUG */
pwrgate_on(0); /* CRAIL */
pwrgate_on(15); /* C0NC */
pwrgate_on(14); /* CE0 */
REG(FLOW + 0x40) = 1; /* RAM_REPAIR_REQ */
/* bdk spins on STS forever. Bounded here so a run with a dead CPU rail
* (the --fault scenarios in run.sh) says where silicon would have hung
* and still reaches its power-off. 10 ms is thousands of times what a
* powered repair takes. */
{
u32 t = REG(TIMERUS);
while (!(REG(FLOW + 0x40) & 2) && REG(TIMERUS) - t < 10000)
;
puts_((REG(FLOW + 0x40) & 2) ? "ram repair: done\n"
: "ram repair: never completed\n");
}
REG(CAR + 0x434) = 1u << 3; /* RST_DEV_V_CLR: MSELECT */
/* Released with its clock stopped, CPU0 must not run until the stop is
* cleared; the strobes and the active-cluster reset view read back. */
REG(CAR + 0x460) = 1u << 8; /* CLK_CPUG_CMPLX_SET: CPU0 */
release_cpu0();
udelay(5000);
puts_(mb[0] == PCIE_MAGIC ? "clock stopped: CPU0 RAN (wrong)\n"
: "clock stopped: CPU0 held still\n");
puts_("clock stop reads ");
puthex(REG(CAR + 0x378)); /* CLK_CPUG_CMPLX */
putc_(' ');
puthex(REG(CAR + 0x464)); /* CLK_CPUG_CMPLX_CLR */
putc_('\n');
puts_(REG(CAR + 0x340) == REG(CAR + 0x450) /* RST_CPU(G)_CMPLX_SET */
? "reset view: RST_CPU_CMPLX matches RST_CPUG_CMPLX\n"
: "reset view: RST_CPU_CMPLX differs\n");
REG(CAR + 0x464) = 1u << 8; /* CLK_CPUG_CMPLX_CLR */
u32 start = REG(TIMERUS);
while (mb[0] != PCIE_MAGIC && REG(TIMERUS) - start < 100000)
udelay(100);
puts_("powered: magic=");
puthex(mb[0]);
puts_(" el=");
puthex(mb[1]);
puts_(" dt=");
puthex(mb[2]);
putc_('\n');
/* Let CPU0 sit in its WFE park for a while: it must cost next to
* nothing, which the retired-instruction count at reset shows. */
udelay(50000);
/* 3. Back into reset, then power off. */
hold_cpu0();
puts_("ccplex test: done\n");
i2c5_write(0x3C, 0x41, 0x02); /* MAX77620 ONOFFCNFG1: PWR_OFF */
for (;;)
;
}
+122
View File
@@ -0,0 +1,122 @@
#!/bin/sh
# CCPLEX regression test: boot CPU0 from a BPMP payload and check what the
# emulator and the payload report. Usage: tests/ccplex/run.sh [rcm_emu] [payload]
EMU=${1:-./rcm_emu}
PAYLOAD=${2:-tests/ccplex/payload.bin}
LOG=${LOG:-tests/ccplex/out.log}
SDL_VIDEODRIVER=dummy RCM_EMU_NO_AUDIO=1 timeout 120 "$EMU" "$PAYLOAD" \
> "$LOG" 2>&1
status=$?
fail=0
expect() {
if grep -q -- "$1" "$LOG"; then
echo " ok $2"
else
echo " FAIL $2 (missing: $1)"
fail=1
fi
}
echo "ccplex test (emulator exit $status):"
expect 'cannot run: CPU rail off' 'an unpowered release is refused, with the reason'
expect 'ram repair: done' 'a powered RAM repair completes'
expect 'unpowered: CPU0 stayed dark' 'and the core really did not execute'
expect 'CPU0 released: AArch64 EL3, MMU off, entry 0xA0000000' 'a powered release boots CPU0 at the SB vector'
expect 'clock stopped: CPU0 held still' 'a core released with its clock stopped does not run'
expect 'clock stop reads 00000100 00000100' 'CLK_CPUG_CMPLX and its CLR strobe read back the stop'
expect 'RST_CPU_CMPLX matches RST_CPUG_CMPLX' 'the active-cluster reset register reads the G cluster'
expect 'powered: magic=50434945' 'CPU0 ran the blob and wrote the mailbox'
expect 'el=0000000C' 'CPU0 came up at EL3'
expect 'CPU0 stopped (held in reset)' 'RST_CPUG_CMPLX_SET stops the core'
expect 'MAX77620 PWR_OFF received' 'the payload ran to its power-off'
if [ "$status" -eq 0 ]; then
echo " ok the emulator exited cleanly"
else
echo " FAIL the emulator exited with status $status (124 = timed out)"
fail=1
fi
# TIMERUS as CPU0 saw it must have moved across its busy loop.
dt=$(sed -n 's/.*dt=\([0-9A-F]*\).*/\1/p' "$LOG" | head -1)
if [ -n "$dt" ] && [ "$dt" != "00000000" ]; then
echo " ok CPU0 sees time advance (TIMERUS delta 0x$dt)"
else
echo " FAIL CPU0's TIMERUS delta is zero or missing"
fail=1
fi
# Parked in WFE for ~50 ms, the core must retire next to nothing: the park
# loop sleeps to the end of each slice instead of spinning.
retired=$(sed -n 's/.*CPU0 stopped (held in reset) after \([0-9]*\) instructions.*/\1/p' "$LOG" | head -1)
if [ -n "$retired" ] && [ "$retired" -lt 100000 ]; then
echo " ok WFE parks the core ($retired instructions retired in total)"
else
echo " FAIL WFE did not park the core (retired: ${retired:-?})"
fail=1
fi
# ---- fault injection ------------------------------------------------------
#
# The same payload against broken hardware. Pinned to Erista, which is what
# the payload's bring-up drives (MAX77621 + MAX77620 GPIO5), so the result
# does not depend on whatever rcm_emu.ini happens to say.
expect_not() {
if grep -q -- "$1" "$FLOG"; then
echo " FAIL $2 (present: $1)"
fail=1
else
echo " ok $2"
fi
}
fexpect() {
if grep -q -- "$1" "$FLOG"; then
echo " ok $2"
else
echo " FAIL $2 (missing: $1)"
fail=1
fi
}
run_fault() {
FLOG=tests/ccplex/out_fault_$1.log
SDL_VIDEODRIVER=dummy RCM_EMU_NO_AUDIO=1 timeout 120 "$EMU" "$PAYLOAD" \
--oem erista --fault "$1" > "$FLOG" 2>&1
fstatus=$?
echo "ccplex test, --fault $1 (emulator exit $fstatus):"
if [ "$fstatus" -ne 0 ]; then
echo " FAIL the emulator exited with status $fstatus (124 = timed out)"
fail=1
fi
}
# A rail whose buck answers and takes its enable, but delivers nothing. Over
# I2C the console looks healthy; only what the rail feeds notices.
run_fault vdd_cpu
fexpect '\[fault\] vdd_cpu (rail)' 'the fault is announced before the run'
fexpect 'RAM repair requested with no CPU rail (fault: vdd_cpu)' 'the RAM repair is held, and says why'
fexpect 'ram repair: never completed' 'so STS never sets (bdk would spin here forever)'
fexpect 'cannot run: CPU rail has no output (fault: vdd_cpu' 'the release is refused, naming the fault'
expect_not 'CPU0 released: AArch64' 'and the core never executes'
fexpect 'powered: magic=00000000' 'the payload sees no mailbox write'
expect_not 'I2C5 0x1B NAK' 'the buck itself still answers on I2C'
fexpect 'MAX77620 PWR_OFF received' 'the payload still runs to its power-off'
# A dead buck: NAKs, takes no writes, and the rail goes with it - even though
# its register file was seeded with VOUT_EN set.
run_fault max77621_cpu
fexpect 'I2C5 0x1B NAK: max77621_cpu is dead' 'the dead chip NAKs its address'
fexpect 'ram repair: never completed' 'its rail is dead with it'
fexpect 'cannot run: CPU rail has no output (fault: max77621_cpu dead)' 'the release is refused, naming the chip'
expect_not 'CPU0 released: AArch64' 'and the core never executes'
fexpect 'MAX77620 PWR_OFF received' 'the main PMIC, not faulted, still powers off'
# A fault on the other generation's chip must change nothing here: Erista
# has no MAX77812 to break.
run_fault max77812
fexpect 'ram repair: done' 'an Erista ignores a dead MAX77812'
fexpect 'CPU0 released: AArch64 EL3, MMU off, entry 0xA0000000' 'and CPU0 boots as normal'
expect_not 'NAK: max77812 is dead' 'a chip this board does not have is not reported dead'
[ $fail -eq 0 ] && echo "ccplex test: PASS" || { echo "ccplex test: FAIL - see $LOG"; exit 1; }
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env python3
"""Compare the emulator's frame snapshot with what a display scenario drew.
Usage: check.py <scenario> <last_fb.rgba> <last_fb.meta>
last_fb.rgba is the host view, ARGB8888 little-endian, as last_fb.meta's
"W H" gives it. The expected picture follows tests/display/payload.c.
"""
import sys
from array import array
def pat(x, y):
return 0xFF000000 | ((x * 7) & 0xFF) << 16 | ((y * 3) & 0xFF) << 8 | ((x ^ y) & 0xFF)
def patq(x, y):
return 0xFF000000 | ((x * 5 + y) & 0xFF) << 16 | 0x4000 | ((y * 9) & 0xFF)
def blend(s, d, k1):
# BLEND_MATCH_SELECT SRC K1, DST NEG_K1 (1 - K1), per channel, opaque.
out = 0xFF000000
for sh in (0, 8, 16):
c = (((s >> sh) & 0xFF) * k1 + ((d >> sh) & 0xFF) * (255 - k1)) // 255
out |= min(c, 255) << sh
return out
def expected(scenario, w, h):
if scenario == 1:
return (720, 1280), lambda x, y: pat(x, y)
if scenario in (2, 3, 4, 5):
# The picture was drawn landscape and turned on its way to the
# panel; the view turns it back.
return (1280, 720), lambda x, y: pat(x, y)
if scenario == 6:
def f(x, y):
a = pat(x, 1279 - y)
if 100 <= x < 300 and 200 <= y < 500:
return blend(patq(x - 100, y - 200), a, 128)
return a
return (720, 1280), f
raise SystemExit("unknown scenario %d" % scenario)
def main():
scenario = int(sys.argv[1])
w, h = map(int, open(sys.argv[3]).read().split())
frame = array("I")
with open(sys.argv[2], "rb") as fh:
frame.frombytes(fh.read())
(ew, eh), f = expected(scenario, w, h)
if (w, h) != (ew, eh):
print(" FAIL scenario %d: view is %dx%d, expected %dx%d" % (scenario, w, h, ew, eh))
return 1
bad = 0
first = None
for y in range(h):
row = y * w
for x in range(w):
want = f(x, y)
if frame[row + x] != want:
bad += 1
if first is None:
first = (x, y, frame[row + x], want)
if bad:
x, y, got, want = first
print(" FAIL scenario %d: %d of %d pixels differ; first at (%d,%d): %08X, expected %08X"
% (scenario, bad, w * h, x, y, got, want))
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
+10
View File
@@ -0,0 +1,10 @@
/* Loaded and entered at 0x40010000, like any RCM payload. */
ENTRY(_start)
SECTIONS {
. = 0x40010000;
.text : { KEEP(*(.text.start)) *(.text*) }
.rodata : { *(.rodata*) }
.data : { *(.data*) }
.bss : { *(.bss*) *(COMMON) }
/DISCARD/ : { *(.comment) *(.note*) *(.ARM.attributes) *(.ARM.exidx*) }
}
+190
View File
@@ -0,0 +1,190 @@
/*
* Display regression payload.
*
* A freestanding BPMP payload that drives the emulator's display controller
* and VIC models the way bdk does - window registers through
* DISPLAY_WINDOW_HEADER and STATE_CONTROL, VIC through its Falcon register
* window and a vic_config_t in DRAM - then parks. tests/display/run.sh
* compares the frame the emulator shows (last_fb.rgba) with the picture the
* payload drew. Built once per scenario with -DSCENARIO=n:
*
* 1 a pitch window (hekate's TUI setup)
* 2 VIC turns a 1280x720 picture 270 degrees into a pitch surface that
* window A shows (Nyx's setup); the view undoes the turn
* 3 as 2, but VIC writes a block-linear surface (16-GOB blocks)
* 4 VIC copies the picture into a block-linear surface, and window A
* shows it turned by the DC itself: SCAN_COLUMN | H_DIRECTION with
* ADDR_H_OFFSET at the top-right pixel's last byte (HOS's setup)
* 5 as 2, but VIC reads a block-linear source surface
* 6 window A mirrored top-bottom (V_DIRECTION, ADDR_V_OFFSET at the
* last line), with window D blended over it at K1 = 128
*
* Every surface holds pat(x, y), which differs between neighbouring
* pixels in both directions, so a wrong stride, turn, flip or offset shows
* up almost everywhere.
*/
#ifndef SCENARIO
#define SCENARIO 1
#endif
typedef unsigned int u32;
#define REG(a) (*(volatile u32 *)(a))
#define UARTB_THR 0x70006040u
#define DC 0x54200000u
#define VIC 0x54340000u
#define DCR(i) REG(DC + (i) * 4u)
/* bdk's _vic_write_priv() for registers with no low address bits. */
#define VICP(r) REG(VIC + 0x1000u + ((r) >> 6))
#define SRC_L 0xC0000000u /* 1280x720 landscape picture, pitch */
#define SURF_B 0xC0400000u /* block-linear intermediate */
#define DST 0xC0800000u /* what window A scans out */
#define SRC_P 0xC0C00000u /* 720x1280 portrait picture, pitch */
#define SRC_Q 0xC1000000u /* 200x300 overlay for window D */
#define CFG 0xC1400000u /* vic_config_t, 256-byte aligned */
/* DC window registers (word indices) and bits. */
#define WINDOW_HEADER 0x042u
#define STATE_CONTROL 0x041u
#define WIN_OPTIONS 0x700u
#define COLOR_DEPTH 0x703u
#define POSITION 0x704u
#define SIZE 0x705u
#define PRESCALED 0x706u
#define LINE_STRIDE 0x70Au
#define BLEND_LAYER 0x716u
#define BLEND_MATCH 0x717u
#define START_ADDR 0x800u
#define ADDR_H_OFFSET 0x806u
#define ADDR_V_OFFSET 0x808u
#define SURFACE_KIND 0x80Bu
#define H_DIRECTION BIT(0)
#define V_DIRECTION BIT(2)
#define SCAN_COLUMN BIT(4)
#define WIN_ENABLE BIT(30)
#define BIT(n) (1u << (n))
#define KIND_PITCH 0u
#define KIND_BLOCK (2u | (4u << 4)) /* block linear, 16-GOB blocks */
static void puts_(const char *s) {
while (*s)
REG(UARTB_THR) = (u32)(unsigned char)*s++;
}
static u32 pat(u32 x, u32 y) {
return 0xFF000000u | ((x * 7u) & 0xFFu) << 16 | ((y * 3u) & 0xFFu) << 8 |
((x ^ y) & 0xFFu);
}
static u32 patq(u32 x, u32 y) {
return 0xFF000000u | ((x * 5u + y) & 0xFFu) << 16 | 0x4000u |
((y * 9u) & 0xFFu);
}
static void fill(u32 base, u32 w, u32 h, u32 (*f)(u32, u32)) {
volatile u32 *p = (volatile u32 *)base;
for (u32 y = 0; y < h; y++)
for (u32 x = 0; x < w; x++)
p[y * w + x] = f(x, y);
}
/* One u64 bitfield word of vic_config_t, written as two halves. */
static void cfg64(u32 off, u32 lo, u32 hi) {
REG(CFG + off) = lo;
REG(CFG + off + 4) = hi;
}
/*
* One VIC compose of a sw x sh X8R8G8B8 surface (slot 0) into a target of
* the same size, with bdk's vic_set_surface() field layout. kind: 0 pitch,
* 1 block linear; gob: log2 GOBs per block.
*/
static void vic_compose(u32 src, u32 skind, u32 sgob, u32 dst, u32 okind,
u32 ogob, u32 sw, u32 sh, u32 flip_x, u32 transpose) {
for (u32 i = 0; i < 0x610; i += 4)
REG(CFG + i) = 0;
/* OutputConfig: FlipX b48, Transpose b50; TargetRect R b16, B b48. */
cfg64(0x10, 0, (flip_x ? BIT(16) : 0) | (transpose ? BIT(18) : 0));
cfg64(0x18, (sw - 1) << 16, (sh - 1) << 16);
/* OutputSurfaceConfig: X8R8G8B8 (36), BlkKind b11, BlkHeight b15,
* width - 1 b32, height - 1 b46. */
cfg64(0x20, 36u | okind << 11 | ogob << 15, (sw - 1) | (sh - 1) << 14);
/* Slot 0: enable; SourceRect in 16.16; DestRect. */
cfg64(0x90, 1, 0);
cfg64(0xB0, 0, (sw - 1) << 16);
cfg64(0xB8, 0, (sh - 1) << 16);
cfg64(0xC0, (sw - 1) << 16, (sh - 1) << 16);
cfg64(0xD0, 36u | skind << 11 | sgob << 15, (sw - 1) | (sh - 1) << 14);
VICP(0x14000) = CFG >> 8; /* VIC_SC_PRAMBASE */
VICP(0x14300) = src >> 8; /* VIC_SC_SFC0_BASE_LUMA(0) */
VICP(0x22000) = dst >> 8; /* VIC_BL_TARGET_BASADR */
VICP(0x10000) = 1; /* VIC_FC_COMPOSE */
}
/* Program window w (0 = A .. 3 = D) and activate it. */
static void window(u32 w, u32 opts, u32 pos, u32 width, u32 height,
u32 stride, u32 kind, u32 addr, u32 h_off, u32 v_off,
u32 blend_layer, u32 blend_match) {
DCR(WINDOW_HEADER) = BIT(4 + w);
DCR(WIN_OPTIONS) = 0;
DCR(COLOR_DEPTH) = 0xC; /* B8G8R8A8 */
DCR(POSITION) = pos;
DCR(SIZE) = height << 16 | width;
DCR(PRESCALED) = height << 16 | width * 4;
DCR(LINE_STRIDE) = stride;
DCR(SURFACE_KIND) = kind;
DCR(START_ADDR) = addr;
DCR(ADDR_H_OFFSET) = h_off;
DCR(ADDR_V_OFFSET) = v_off;
DCR(BLEND_LAYER) = blend_layer;
DCR(BLEND_MATCH) = blend_match;
DCR(WIN_OPTIONS) = opts | WIN_ENABLE;
DCR(STATE_CONTROL) = BIT(8) | BIT(9 + w); /* GENERAL + WIN_x_UPDATE */
DCR(STATE_CONTROL) = BIT(0) | BIT(1 + w); /* GENERAL + WIN_x_ACT_REQ */
}
#define BYPASS 0x01000000u /* BLEND_LAYER_CONTROL reset: blending bypassed */
__attribute__((section(".text.start"), noreturn))
void _start(void) {
#if SCENARIO == 1
fill(SRC_P, 720, 1280, pat);
window(0, 0, 0, 720, 1280, 720 * 4, KIND_PITCH, SRC_P, 0, 0, BYPASS, 0);
#elif SCENARIO == 2
fill(SRC_L, 1280, 720, pat);
vic_compose(SRC_L, 0, 0, DST, 0, 0, 1280, 720, 1, 1);
window(0, 0, 0, 720, 1280, 720 * 4, KIND_PITCH, DST, 0, 0, BYPASS, 0);
#elif SCENARIO == 3
fill(SRC_L, 1280, 720, pat);
vic_compose(SRC_L, 0, 0, DST, 1, 4, 1280, 720, 1, 1);
window(0, 0, 0, 720, 1280, 720 * 4, KIND_BLOCK, DST, 0, 0, BYPASS, 0);
#elif SCENARIO == 4
fill(SRC_L, 1280, 720, pat);
vic_compose(SRC_L, 0, 0, SURF_B, 1, 4, 1280, 720, 0, 0);
window(0, SCAN_COLUMN | H_DIRECTION, 0, 720, 1280, 1280 * 4, KIND_BLOCK,
SURF_B, 1280 * 4 - 1, 0, BYPASS, 0);
#elif SCENARIO == 5
fill(SRC_L, 1280, 720, pat);
vic_compose(SRC_L, 0, 0, SURF_B, 1, 4, 1280, 720, 0, 0);
vic_compose(SURF_B, 1, 4, DST, 0, 0, 1280, 720, 1, 1);
window(0, 0, 0, 720, 1280, 720 * 4, KIND_PITCH, DST, 0, 0, BYPASS, 0);
#elif SCENARIO == 6
fill(SRC_P, 720, 1280, pat);
fill(SRC_Q, 200, 300, patq);
window(0, V_DIRECTION, 0, 720, 1280, 720 * 4, KIND_PITCH, SRC_P, 0, 1279,
BYPASS, 0);
/* K1 = 128, blending on, depth 0; SRC x K1 + DST x (1 - K1). */
window(3, 0, 200u << 16 | 100u, 200, 300, 200 * 4, KIND_PITCH, SRC_Q,
0, 0, 128u << 8, 0x72u);
#endif
puts_("display test: ready\n");
for (;;)
;
}
+59
View File
@@ -0,0 +1,59 @@
#!/bin/sh
# Display regression test: run each scenario payload (tests/display/payload.c,
# built with -DSCENARIO=n) and compare the frame the emulator shows with the
# picture the payload drew.
# Usage: tests/display/run.sh [rcm_emu] [payload dir]
EMU=$(cd "$(dirname "${1:-./rcm_emu}")" && pwd)/$(basename "${1:-./rcm_emu}")
DIR=$(cd "${2:-tests/display}" && pwd)
HERE=$(cd "$(dirname "$0")" && pwd)
LIMIT=${LIMIT:-60}
names="pitch window|VIC 270-degree turn into a pitch surface|VIC turn into a block-linear surface|DC column scan with an address offset|VIC block-linear source|V mirror with window D blended over"
run() {
n=$1
work=$(mktemp -d)
# The frame snapshot lands in the working directory.
(cd "$work" && SDL_VIDEODRIVER=dummy RCM_EMU_NO_AUDIO=1 \
"$EMU" "$DIR/payload_$n.bin" > out.log 2>&1) &
pid=$!
t=0
until grep -q 'display test: ready' "$work/out.log" 2>/dev/null; do
sleep 1
t=$((t + 1))
[ $t -ge "$LIMIT" ] && break
done
# The renderer writes a snapshot about a second after the frame changes.
sleep 3
kill $pid 2>/dev/null
wait $pid 2>/dev/null
name=$(echo "$names" | cut -d'|' -f"$n")
if [ ! -f "$work/last_fb.rgba" ]; then
echo " FAIL $n: $name (no frame snapshot)"
rc=1
elif python3 "$HERE/check.py" "$n" "$work/last_fb.rgba" "$work/last_fb.meta"; then
echo " ok $n: $name"
rc=0
else
echo " FAIL $n: $name (log: $work/out.log)"
rc=1
fi
[ $rc -eq 0 ] && rm -rf "$work"
return $rc
}
echo "display test:"
fail=0
pids=""
for n in 1 2 3 4 5 6; do
run "$n" > "$DIR/result_$n.txt" 2>&1 &
pids="$pids $!"
done
n=0
for p in $pids; do
n=$((n + 1))
wait "$p" || fail=1
cat "$DIR/result_$n.txt"
rm -f "$DIR/result_$n.txt"
done
[ $fail -eq 0 ] && echo "display test: PASS" || { echo "display test: FAIL"; exit 1; }
+31
View File
@@ -0,0 +1,31 @@
#!/bin/sh
# Build hwtest-rcm (https://github.com/Creased/hwtest-rcm) with distro
# toolchains, CPU0 stub included. Usage: tests/hwtest/build.sh <workdir>
# Produces <workdir>/hwtest-rcm/build/hwtest.bin.
#
# hwtest's Makefile only needs $(DEVKITARM)/base_rules to exist - it names
# arm-none-eabi-gcc itself - so an empty file stands in for devkitARM, and
# Debian/Ubuntu's gcc-aarch64-linux-gnu builds the AArch64 stub, which is
# what hwtest's own CI does too.
#
# Pinned so a change on the hwtest side cannot turn this emulator's CI red
# without a commit here; bump HWTEST_REF deliberately.
set -e
WORK=${1:-build-hwtest}
HWTEST_REF=${HWTEST_REF:-3738e9a47e1833605fc5a30eeca0ea95caa3b936}
mkdir -p "$WORK"
cd "$WORK"
if [ ! -d hwtest-rcm/.git ]; then
git init -q hwtest-rcm
git -C hwtest-rcm remote add origin https://github.com/Creased/hwtest-rcm.git
fi
git -C hwtest-rcm fetch -q --depth 1 origin "$HWTEST_REF"
git -C hwtest-rcm checkout -q FETCH_HEAD
git -C hwtest-rcm submodule update -q --init --depth 1 third_party/hekate
mkdir -p devkitARM
: > devkitARM/base_rules
make -C hwtest-rcm -j"$(nproc)" DEVKITARM="$PWD/devkitARM" \
A64_CC=aarch64-linux-gnu-gcc A64_OC=aarch64-linux-gnu-objcopy REQUIRE_A64=1
ls -l hwtest-rcm/build/hwtest.bin
+53
View File
@@ -0,0 +1,53 @@
#!/bin/sh
# End-to-end: run hwtest's whole hardware sweep in the emulator, headless,
# and check the CPU0-driven PCIe probe enumerated the Wi-Fi endpoint.
# Usage: tests/hwtest/run.sh <rcm_emu> <hwtest.bin> [extra emulator args...]
#
# hwtest sits in its pager once the sweep is dumped, so the run is ended as
# soon as the dump's last line appears (with a hard timeout behind it).
EMU=${1:-./rcm_emu}
BIN=${2:-build-hwtest/hwtest-rcm/build/hwtest.bin}
# Anything after the two positional arguments goes to the emulator. (A bare
# `shift 2` with fewer than two arguments makes dash exit on the spot.)
[ $# -ge 2 ] && shift 2 || set --
LOG=${LOG:-tests/hwtest/out.log}
LIMIT=${LIMIT:-300}
# POWER at 3 s picks "Hardware test" on hwtest's launcher.
SDL_VIDEODRIVER=dummy RCM_EMU_NO_AUDIO=1 "$EMU" "$BIN" --input-script "3000 P" "$@" \
> "$LOG" 2>&1 &
pid=$!
t=0
until grep -q 'end of dump' "$LOG" 2>/dev/null || ! kill -0 $pid 2>/dev/null; do
sleep 1
t=$((t + 1))
if [ $t -ge "$LIMIT" ]; then
echo "hwtest: no end of dump after ${LIMIT}s"
break
fi
done
kill $pid 2>/dev/null
wait $pid 2>/dev/null
echo "hwtest: sweep took ~${t}s of wall time"
fail=0
expect() {
if grep -q -- "$1" "$LOG"; then
echo " ok $2"
else
echo " FAIL $2 (missing: $1)"
fail=1
fi
}
expect 'end of dump' 'the whole sweep ran to its end'
expect '\[ccplex\] CPU0 released: AArch64 EL3' 'hwtest booted CPU0'
expect 'CPU0 : ran to completion' 'the CPU0 stub ran to completion'
expect 'AFI (CPU) : cfg=00103025 witness=A5A50000 -> APERTURE LIVE' 'the PCIe aperture decodes for CPU0'
expect 'RP1 link : UP, DL active (LNKSTA=3011' 'root port 1 trained'
expect 'EP config : 14E4:43EC' 'the CYW4356 endpoint enumerated'
expect 'CPU0 : powergated' 'the cluster was powergated again'
expect 'Wireless : pass' 'the Wireless verdict passed'
expect '\[sdmmc\] SDMMC4 tuned: 128 iterations' 'the eMMC passed HS200 tuning'
expect 'card_clock : 199.68 MHz' 'the eMMC runs at HS400 speed'
[ $fail -eq 0 ] && echo "hwtest: PASS" || { echo "hwtest: FAIL - see $LOG"; exit 1; }
+34
View File
@@ -0,0 +1,34 @@
#!/bin/sh
# Builds tests/kernelcpu/payload.bin: cpu0.S with an AArch64 assembler,
# embedded as a word array into the BPMP payload built with arm-none-eabi.
set -e
D=$(dirname "$0")
# devkitPro when it is installed, else the distribution's cross compilers
# (gcc-aarch64-linux-gnu, gcc-arm-none-eabi), as on CI.
DKP=${DEVKITPRO:-/opt/devkitpro}
if [ -z "$A64" ]; then
A64=aarch64-linux-gnu-
if [ -x "$DKP/devkitA64/bin/aarch64-none-elf-gcc" ]; then A64=$DKP/devkitA64/bin/aarch64-none-elf-; fi
fi
if [ -z "$ARM" ]; then
ARM=arm-none-eabi-
if [ -x "$DKP/devkitARM/bin/arm-none-eabi-gcc" ]; then ARM=$DKP/devkitARM/bin/arm-none-eabi-; fi
fi
${A64}gcc -c -o "$D/cpu0.o" "$D/cpu0.S"
${A64}ld -Ttext=0xA0000000 -o "$D/cpu0.elf" "$D/cpu0.o"
${A64}objcopy -O binary "$D/cpu0.elf" "$D/cpu0.bin"
python3 - "$D/cpu0.bin" "$D/cpu0_blob.h" <<'PY'
import sys, struct
b = open(sys.argv[1], "rb").read()
b += b"\0" * (-len(b) % 4)
w = struct.unpack("<%dI" % (len(b) // 4), b)
with open(sys.argv[2], "w") as f:
f.write("/* Generated by build.sh from cpu0.S. */\nstatic const u32 cpu0_blob[] = {\n")
for i in range(0, len(w), 6):
f.write(" " + ", ".join("0x%08x" % x for x in w[i:i + 6]) + ",\n")
f.write("};\n")
PY
${ARM}gcc -march=armv4t -marm -Os -ffreestanding -nostdlib -fno-builtin -I"$D" \
-T "$D/link.ld" -o "$D/payload.elf" "$D/payload.c"
${ARM}objcopy -O binary "$D/payload.elf" "$D/payload.bin"
echo "built $D/payload.bin"
+124
View File
@@ -0,0 +1,124 @@
/*
* CPU0 side of the kernel-CPU test: what a kernel needs from the core
* model, exercised the way Linux uses it.
*
* Entered at EL3, MMU off, at 0xA0000000. Drops to EL1h the way a boot
* shim hands over to a kernel, then:
* [1] CurrentEL at EL1 (expect 0x4)
* [2] PSCI_VERSION over SMC (expect 0x00010000)
* [3] ESR_EL1 seen by the BRK handler (expect 0xF2000123)
* [4] CNTFRQ_EL0 (expect 19200000)
* [5] virtual timer interrupts taken (expect 10)
* [6] CNTVCT ticks across them (expect about 10 x 19200)
* [7] the last interrupt ID acknowledged (expect 27)
* [8] instructions spent waiting: the WFI loop count (expect small)
* [0] magic 'KCPU', written last
* then parks in WFE.
*/
.equ MBOX, 0xA0030000
.equ GICD, 0x50041000
.equ GICC, 0x50042000
.equ TICK, 19200 /* 1 ms at 19.2 MHz */
.text
.global _start
_start:
mov x0, #0x431 /* SCR_EL3: RW, RES1, NS */
msr scr_el3, x0
mov x0, #(1 << 31) /* HCR_EL2.RW: EL1 is AArch64 */
msr hcr_el2, x0
mov x0, #3
msr cnthctl_el2, x0
msr cntvoff_el2, xzr
ldr x0, =0x30C50830 /* SCTLR_EL1: RES1, MMU off */
msr sctlr_el1, x0
mov x0, #0x3C5 /* EL1h, DAIF masked */
msr spsr_el3, x0
adr x0, el1
msr elr_el3, x0
eret
el1:
adr x0, vectors
msr vbar_el1, x0
isb
ldr x1, =MBOX
mrs x2, currentel
str w2, [x1, #4]
ldr x0, =0x84000000 /* PSCI_VERSION */
smc #0
str w0, [x1, #8]
brk #0x123 /* the sync handler steps over it */
mrs x3, cntfrq_el0
str w3, [x1, #16]
ldr x4, =GICD
mov w5, #1
str w5, [x4] /* GICD_CTLR */
mov w5, #(1 << 27)
str w5, [x4, #0x100] /* ISENABLER0: PPI 27 */
ldr w5, [x4, #0x418]
and w5, w5, #0x00FFFFFF
mov w12, #0xA0000000
orr w5, w5, w12
str w5, [x4, #0x418] /* IPRIORITYR[27] = 0xA0 */
ldr x6, =GICC
mov w5, #0xF0
str w5, [x6, #4] /* GICC_PMR */
mov w5, #1
str w5, [x6] /* GICC_CTLR */
mov w7, #TICK
msr cntv_tval_el0, x7
mov w7, #1
msr cntv_ctl_el0, x7
mrs x8, cntvct_el0
mov w11, #0
msr daifclr, #2 /* IRQs on */
1: wfi
add w11, w11, #1
ldr w9, [x1, #20]
cmp w9, #10
b.lo 1b
msr daifset, #2
mrs x10, cntvct_el0
sub x10, x10, x8
str w10, [x1, #24]
str w11, [x1, #32]
mov w7, #0
msr cntv_ctl_el0, x7
ldr w2, =0x4B435055 /* 'KCPU' */
str w2, [x1]
2: wfe
b 2b
.ltorg
.balign 2048
vectors:
.skip 0x200 /* current EL with SP_EL0: unused */
/* 0x200: synchronous, current EL with SP_ELx */
mrs x20, esr_el1
str w20, [x1, #12]
mrs x21, elr_el1
add x21, x21, #4
msr elr_el1, x21
eret
.balign 0x80
/* 0x280: IRQ, current EL with SP_ELx */
ldr w22, [x6, #0x0C] /* GICC_IAR */
ldr w23, [x1, #20]
add w23, w23, #1
str w23, [x1, #20]
str w22, [x1, #28]
mov w24, #TICK
msr cntv_tval_el0, x24
str w22, [x6, #0x10] /* GICC_EOIR */
eret
.balign 0x80
.skip 0x80 * 2 /* FIQ, SError */
.skip 0x400 /* lower ELs: unused */
+10
View File
@@ -0,0 +1,10 @@
/* Loaded and entered at 0x40010000, like any RCM payload. */
ENTRY(_start)
SECTIONS {
. = 0x40010000;
.text : { KEEP(*(.text.start)) *(.text*) }
.rodata : { *(.rodata*) }
.data : { *(.data*) }
.bss : { *(.bss*) *(COMMON) }
/DISCARD/ : { *(.comment) *(.note*) *(.ARM.attributes) *(.ARM.exidx*) }
}
+133
View File
@@ -0,0 +1,133 @@
/*
* Kernel-CPU regression payload: boots CPU0 at cpu0.S and reports its mailbox.
*
* A freestanding BPMP payload (ARM mode, loaded at 0x40010000 like any RCM
* payload) that drives the emulator's CPU0 model through the same register
* sequence as bdk's ccplex_boot_cpu0(), and reports what happened on UART-B.
* tests/ccplex/run.sh checks the emulator's log for the expected lines.
*
* 1. Release CPU0 from reset with nothing powered. The core must NOT run,
* and the emulator must say which precondition is missing.
* 2. Do the real bring-up - CPU rail (MAX77620 GPIO5 + MAX77621 VOUT on
* I2C5), CRAIL/C0NC/CE0 partitions, CPUG + MSELECT clocks, MSELECT out
* of reset, PLLX, RAM repair, SB_AA64_RESET_LOW - then release it. An
* AArch64 blob copied to DRAM records CurrentEL and a TIMERUS delta in
* a mailbox, writes a magic word last, and parks in WFE.
* Released first with its clock stopped (CLK_CPUG_CMPLX), it must
* stay still until the stop is cleared.
* 3. Put CPU0 back into reset and power the console off.
*
* Built by `make test` with arm-none-eabi-gcc; no other toolchain needed, as
* the AArch64 side is a handful of pre-assembled words.
*/
typedef unsigned int u32;
#define REG(a) (*(volatile u32 *)(a))
#define TIMERUS 0x60005010u
#define CAR 0x60006000u
#define FLOW 0x60007000u
#define SB 0x6000C200u
#define UARTB_THR 0x70006040u
#define PMC 0x7000E400u
#define I2C5 0x7000D000u
#define CPU_ENTRY 0xA0000000u
#define MBOX 0xA0030000u
#define KCPU_MAGIC 0x4B435055u
static void putc_(char c) { REG(UARTB_THR) = (u32)(unsigned char)c; }
static void puts_(const char *s) {
while (*s)
putc_(*s++);
}
static void puthex(u32 v) {
for (int i = 28; i >= 0; i -= 4)
putc_("0123456789ABCDEF"[(v >> i) & 0xF]);
}
static void udelay(u32 us) {
u32 start = REG(TIMERUS);
while (REG(TIMERUS) - start < us)
;
}
/* bdk-style normal-mode I2C write: [reg, val] in CMD_DATA1, 2 bytes, GO. */
static void i2c5_write(u32 dev, u32 reg, u32 val) {
REG(I2C5 + 0x04) = dev << 1; /* CMD_ADDR0 */
REG(I2C5 + 0x0C) = reg | (val << 8); /* CMD_DATA1 */
REG(I2C5 + 0x00) = (1u << 1) | (1u << 9); /* CNFG: 2 bytes, write, GO */
}
static void pwrgate_on(u32 part) {
if (!(REG(PMC + 0x38) & (1u << part))) /* PWRGATE_STATUS */
REG(PMC + 0x30) = part | (1u << 8); /* PWRGATE_TOGGLE */
}
#define RST_CPU0 ((1u << 30) | (1u << 24) | (1u << 16) | (1u << 0))
#define RST_NONCPU (1u << 29)
static void release_cpu0(void) {
REG(SB + 0x30) = CPU_ENTRY | 1u; /* SB_AA64_RESET_LOW */
REG(SB + 0x34) = 0; /* SB_AA64_RESET_HIGH */
REG(CAR + 0x454) = RST_NONCPU; /* RST_CPUG_CMPLX_CLR */
REG(CAR + 0x454) = RST_CPU0;
}
static void hold_cpu0(void) {
REG(CAR + 0x450) = RST_CPU0; /* RST_CPUG_CMPLX_SET */
REG(CAR + 0x450) = RST_NONCPU;
}
#include "cpu0_blob.h"
__attribute__((section(".text.start"), noreturn))
void _start(void) {
volatile u32 *mb = (volatile u32 *)MBOX;
puts_("kernelcpu test: start\n");
for (u32 i = 0; i < sizeof(cpu0_blob) / sizeof(cpu0_blob[0]); i++)
((volatile u32 *)CPU_ENTRY)[i] = cpu0_blob[i];
for (u32 i = 0; i < 16; i++)
mb[i] = 0;
/* The bring-up, in ccplex_boot_cpu0() order (Erista). */
i2c5_write(0x3C, 0x40, 0x1C); /* MAX77620 AME_GPIO: GPIO5 plain */
i2c5_write(0x3C, 0x3B, 0x09); /* GPIO5: push-pull, out high */
i2c5_write(0x1B, 0x00, 0x80 | 55); /* MAX77621 VOUT: on, 0.950 V */
REG(CAR + 0x0E0) = (1u << 30) | (2u << 20) | (156u << 8) | 2u; /* PLLX */
REG(CAR + 0x3B4) = 4u << 1; /* CLK_SOURCE_MSELECT */
REG(CAR + 0x440) = 1u << 3; /* CLK_ENB_V_SET: MSELECT */
REG(CAR + 0x020) = 0x20008888; /* CCLK_BURST: PLLX_OUT0_LJ */
REG(CAR + 0x024) = 1u << 31; /* SUPER_CCLK_DIVIDER */
REG(CAR + 0x440) = 1u << 0; /* CLK_ENB_V_SET: CPUG */
pwrgate_on(0); /* CRAIL */
pwrgate_on(15); /* C0NC */
pwrgate_on(14); /* CE0 */
REG(FLOW + 0x40) = 1; /* RAM_REPAIR_REQ */
while (!(REG(FLOW + 0x40) & 2))
;
REG(CAR + 0x434) = 1u << 3; /* RST_DEV_V_CLR: MSELECT */
release_cpu0();
u32 start = REG(TIMERUS);
while (mb[0] != KCPU_MAGIC && REG(TIMERUS) - start < 200000)
udelay(100);
static const char *names[9] = { "magic", "el", "psci", "esr", "cntfrq",
"irqs", "ticks", "irqid", "wfis" };
for (u32 i = 0; i < 9; i++) {
puts_(names[i]);
putc_('=');
puthex(mb[i]);
putc_(i == 8 ? '\n' : ' ');
}
hold_cpu0();
puts_("kernelcpu test: done\n");
i2c5_write(0x3C, 0x41, 0x02); /* MAX77620 ONOFFCNFG1: PWR_OFF */
for (;;)
;
}
+53
View File
@@ -0,0 +1,53 @@
#!/bin/sh
# Kernel-CPU regression test: CPU0 dropped to EL1 takes timer interrupts
# through the GIC, a BRK into its own vector, and a PSCI call over SMC.
# Usage: tests/kernelcpu/run.sh [rcm_emu] [payload]
EMU=${1:-./rcm_emu}
PAYLOAD=${2:-tests/kernelcpu/payload.bin}
LOG=${LOG:-tests/kernelcpu/out.log}
SDL_VIDEODRIVER=dummy RCM_EMU_NO_AUDIO=1 timeout 120 "$EMU" "$PAYLOAD" --oem erista \
> "$LOG" 2>&1
status=$?
fail=0
expect() {
if grep -q -- "$1" "$LOG"; then
echo " ok $2"
else
echo " FAIL $2 (missing: $1)"
fail=1
fi
}
echo "kernelcpu test (emulator exit $status):"
expect 'magic=4B435055' 'CPU0 ran the whole test and wrote the mailbox'
expect 'el=00000004' 'the shim dropped it to EL1'
expect 'psci=00010000' 'PSCI_VERSION over SMC answers 1.0'
expect 'esr=F2000123' 'BRK is taken to the EL1 vector with its ESR'
expect 'cntfrq=0124F800' 'the counter runs at 19.2 MHz'
expect 'irqs=0000000A' 'ten virtual timer interrupts arrive through the GIC'
expect 'irqid=0000001B' 'the GIC acknowledges them as PPI 27'
ticks=$(sed -n 's/.* ticks=\([0-9A-F]*\).*/\1/p' "$LOG" | head -1)
if [ -n "$ticks" ] && [ $((0x$ticks)) -ge 190000 ] && [ $((0x$ticks)) -le 200000 ]; then
echo " ok ten 1 ms ticks take about 192000 counts (0x$ticks)"
else
echo " FAIL the tick count across ten interrupts is off (0x${ticks:-?})"
fail=1
fi
retired=$(sed -n 's/.*CPU0 stopped (held in reset) after \([0-9]*\) instructions.*/\1/p' "$LOG" | head -1)
if [ -n "$retired" ] && [ "$retired" -lt 5000 ]; then
echo " ok WFI sleeps until the timer ($retired instructions retired)"
else
echo " FAIL WFI spun instead of sleeping (retired: ${retired:-?})"
fail=1
fi
if [ "$status" -eq 0 ]; then
echo " ok the emulator exited cleanly"
else
echo " FAIL the emulator exited with status $status (124 = timed out)"
fail=1
fi
[ $fail -eq 0 ] && echo "kernelcpu test: PASS" || echo "kernelcpu test: FAIL"
exit $fail
+55
View File
@@ -0,0 +1,55 @@
#!/usr/bin/env python3
# Writes vectors.h for tests/se/payload.c: two RSA keys (e = 65537), a message
# and its m^d mod n for each, and SHA-256 digests. Seeded, so the output is
# the same every run; vectors.h is checked in and this only needs rerunning
# to change the vectors.
import hashlib, os, random
rnd = random.Random(0x5E)
def is_prime(n):
if n < 2: return False
for p in [2,3,5,7,11,13,17,19,23,29,31,37]:
if n % p == 0: return n == p
d, s = n-1, 0
while d % 2 == 0: d//=2; s+=1
for _ in range(40):
a = rnd.randrange(2, n-2)
x = pow(a, d, n)
if x in (1, n-1): continue
for _ in range(s-1):
x = x*x % n
if x == n-1: break
else: return False
return True
def prime(bits):
while True:
p = rnd.getrandbits(bits) | (1 << (bits-1)) | (1 << (bits-2)) | 1
if is_prime(p): return p
def key(bits, e=65537):
while True:
p, q = prime(bits//2), prime(bits//2)
phi = (p-1)*(q-1)
if p != q and phi % e:
n = p*q
if n.bit_length() == bits:
return n, pow(e, -1, phi)
def arr(name, v, nbytes):
b = v.to_bytes(nbytes, 'big')
lines = ['static const unsigned char %s[%d] = {' % (name, nbytes)]
for i in range(0, nbytes, 12):
lines.append(' ' + ', '.join('0x%02X' % x for x in b[i:i+12]) + ',')
lines.append('};')
return '\n'.join(lines)
out = []
for bits, tag in ((2048, 'k2048'), (1024, 'k1024')):
n, d = key(bits)
m = int.from_bytes(hashlib.sha256(tag.encode()).digest() * (bits // 256), 'big') % n
s = pow(m, d, n)
assert pow(s, 65537, n) == m
nb = bits // 8
out += [arr(tag + '_mod', n, nb), arr(tag + '_exp', d, nb), arr(tag + '_msg', m, nb), arr(tag + '_sig', s, nb)]
msg = bytes((i * 7 + 3) & 0xFF for i in range(200))
out.append(arr('sha_msg', int.from_bytes(msg, 'big'), 200))
out.append(arr('sha_msg_digest', int.from_bytes(hashlib.sha256(msg).digest(), 'big'), 32))
out.append(arr('sha_abc_digest', int.from_bytes(hashlib.sha256(b'abc').digest(), 'big'), 32))
open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'vectors.h'), 'w').write('/* Generated by gen_vectors.py: RSA keys (e = 65537) with\n * m^d mod n, and SHA-256 digests, computed with Python integers and hashlib. */\n\n' + '\n\n'.join(out) + '\n')
+10
View File
@@ -0,0 +1,10 @@
/* Loaded and entered at 0x40010000, like any RCM payload. */
ENTRY(_start)
SECTIONS {
. = 0x40010000;
.text : { KEEP(*(.text.start)) *(.text*) }
.rodata : { *(.rodata*) }
.data : { *(.data*) }
.bss : { *(.bss*) *(COMMON) }
/DISCARD/ : { *(.comment) *(.note*) *(.ARM.attributes) *(.ARM.exidx*) }
}
+252
View File
@@ -0,0 +1,252 @@
/*
* Security Engine regression payload.
*
* A freestanding BPMP payload that drives the emulator's SE model with the
* register sequences bdk uses, checks every result against vectors computed
* outside the emulator (vectors.h, from gen_vectors.py), and reports on
* UART-B. tests/se/run.sh checks the log.
*
* rsa se_rsa_key_set() / se_rsa_exp_mod() as Lockpick's bdk has them:
* a 2048-bit and a 1024-bit key in the two slots, each signing with
* its private exponent and verifying with e = 65537
* sha SHA-256 one-shot, and in two parts (INIT, then CONTINUE)
* aes AES-128 ECB, Lockpick's keyslot-access vector
* rng se_rng_pseudo(): output that is not all zeros, differs from call
* to call, and stops at the size asked for
*/
typedef unsigned int u32;
typedef unsigned char u8;
#define REG(a) (*(volatile u32 *)(a))
#define UARTB_THR 0x70006040u
#define I2C5 0x7000D000u
#define SE 0x70012000u
#define SER(o) REG(SE + (o))
#define SE_OPERATION 0x008
#define SE_INT_STATUS 0x010
#define SE_CONFIG 0x014
#define SE_IN_LL_ADDR 0x018
#define SE_OUT_LL_ADDR 0x024
#define SE_HASH_RESULT 0x030
#define SE_SHA_CONFIG 0x200
#define SE_SHA_MSG_LENGTH 0x204
#define SE_SHA_MSG_LEFT 0x214
#define SE_CRYPTO_CONFIG 0x304
#define SE_LAST_BLOCK 0x318
#define SE_KEYTABLE_ADDR 0x31C
#define SE_KEYTABLE_DATA 0x320
#define SE_RNG_CONFIG 0x340
#define SE_RSA_CONFIG 0x400
#define SE_RSA_KEY_SIZE 0x404
#define SE_RSA_EXP_SIZE 0x408
#define SE_RSA_KT_ADDR 0x420
#define SE_RSA_KT_DATA 0x424
#define SE_RSA_OUTPUT 0x428
#define SE_ERR_STATUS 0x804
#define OP_DONE (1u << 4)
#define ERR_STAT (1u << 16)
#define DST(x) ((x) << 2)
#define DEC_ALG(x) ((x) << 8)
#define ENC_ALG(x) ((x) << 12)
#define ENC_MODE(x) ((x) << 24)
#define DST_MEMORY 0
#define DST_HASHREG 1
#define DST_RSAREG 4
#define ALG_AES 1
#define ALG_RNG 2
#define ALG_SHA 3
#define ALG_RSA 4
#define MODE_SHA256 5
#include "vectors.h"
static void puts_(const char *s) {
while (*s)
REG(UARTB_THR) = (u32)(unsigned char)*s++;
}
static void i2c5_write(u32 dev, u32 reg, u32 val) {
REG(I2C5 + 0x04) = dev << 1; /* CMD_ADDR0 */
REG(I2C5 + 0x0C) = reg | (val << 8); /* CMD_DATA1 */
REG(I2C5 + 0x00) = (1u << 1) | (1u << 9); /* CNFG: 2 bytes, write, GO */
}
static int failed;
static void check(int ok, const char *what) {
puts_(ok ? "se test: ok " : "se test: FAIL ");
puts_(what);
puts_("\n");
if (!ok)
failed = 1;
}
static int same(const u8 *a, const u8 *b, u32 n) {
for (u32 i = 0; i < n; i++)
if (a[i] != b[i])
return 0;
return 1;
}
static u32 be32(const u8 *p) {
return (u32)p[0] << 24 | (u32)p[1] << 16 | (u32)p[2] << 8 | p[3];
}
static void put_be32(u8 *p, u32 v) {
p[0] = v >> 24;
p[1] = v >> 16;
p[2] = v >> 8;
p[3] = v;
}
/* bdk's _se_execute_oneshot(): one linked-list entry each way. */
static volatile u32 ll_in[3], ll_out[3];
static int se_exec(void *dst, u32 dst_size, const void *src, u32 src_size) {
ll_in[0] = 0;
ll_in[1] = (u32)src;
ll_in[2] = src_size;
ll_out[0] = 0;
ll_out[1] = (u32)dst;
ll_out[2] = dst_size;
SER(SE_IN_LL_ADDR) = src ? (u32)ll_in : 0;
SER(SE_OUT_LL_ADDR) = dst ? (u32)ll_out : 0;
SER(SE_ERR_STATUS) = SER(SE_ERR_STATUS);
SER(SE_INT_STATUS) = SER(SE_INT_STATUS);
SER(SE_OPERATION) = 1; /* START */
while (!(SER(SE_INT_STATUS) & OP_DONE))
;
return (SER(SE_INT_STATUS) & ERR_STAT) || SER(SE_ERR_STATUS);
}
/* se_rsa_key_set(): the big-endian key goes in backwards, word by word. */
static void rsa_key_set(u32 ks, const u8 *mod, u32 mod_size, const u8 *exp,
u32 exp_size) {
for (u32 i = 0; i < mod_size / 4; i++) {
SER(SE_RSA_KT_ADDR) = ks << 7 | 1u << 6 | i; /* MOD */
SER(SE_RSA_KT_DATA) = be32(mod + mod_size - 4 - 4 * i);
}
for (u32 i = 0; i < exp_size / 4; i++) {
SER(SE_RSA_KT_ADDR) = ks << 7 | i; /* EXP */
SER(SE_RSA_KT_DATA) = be32(exp + exp_size - 4 - 4 * i);
}
}
/* se_rsa_exp_mod(): the input reversed into a little-endian number, the
* output read back from SE_RSA_OUTPUT into big-endian bytes. */
static int rsa_exp_mod(u32 ks, u8 *dst, const u8 *src, u32 size,
u32 exp_size) {
static u8 buf[256];
for (u32 i = 0; i < size; i++)
buf[i] = src[size - 1 - i];
SER(SE_CONFIG) = ENC_ALG(ALG_RSA) | DST(DST_RSAREG);
SER(SE_RSA_CONFIG) = ks << 24;
SER(SE_RSA_KEY_SIZE) = (size >> 6) - 1;
SER(SE_RSA_EXP_SIZE) = exp_size >> 2;
int res = se_exec(0, 0, buf, size);
for (u32 i = 0; i < size / 4; i++)
put_be32(dst + size - 4 - 4 * i, SER(SE_RSA_OUTPUT + 4 * i));
return res;
}
/* _se_sha_hash_256(): total 0 or equal to the part means INIT; a part
* that is not the last says one byte more is left than it carries. */
static int sha256(u8 *hash, u32 total, const u8 *src, u32 size) {
u32 left = total < size ? size + 1 : size;
SER(SE_CONFIG) = ENC_MODE(MODE_SHA256) | ENC_ALG(ALG_SHA) | DST(DST_HASHREG);
SER(SE_SHA_MSG_LENGTH) = total << 3;
SER(SE_SHA_MSG_LENGTH + 4) = total >> 29;
SER(SE_SHA_MSG_LENGTH + 8) = 0;
SER(SE_SHA_MSG_LENGTH + 12) = 0;
SER(SE_SHA_MSG_LEFT) = left << 3;
SER(SE_SHA_MSG_LEFT + 4) = left >> 29;
SER(SE_SHA_MSG_LEFT + 8) = 0;
SER(SE_SHA_MSG_LEFT + 12) = 0;
SER(SE_SHA_CONFIG) = (total == size || !total) ? 1 : 0;
int res = se_exec(0, 0, src, size);
for (u32 i = 0; i < 8; i++)
put_be32(hash + 4 * i, SER(SE_HASH_RESULT + 4 * i));
return res;
}
/* se_rng_pseudo() for a whole number of blocks. */
static int rng(u8 *dst, u32 size) {
SER(SE_CONFIG) = ENC_ALG(ALG_RNG) | DST(DST_MEMORY);
SER(SE_CRYPTO_CONFIG) = 1u << 3; /* INPUT_RANDOM */
SER(SE_RNG_CONFIG) = 1u << 2; /* SRC_ENTROPY, MODE_NORMAL */
SER(SE_LAST_BLOCK) = (size >> 4) - 1;
return se_exec(dst, size, 0, 0);
}
static const u8 e65537[4] = {0x00, 0x01, 0x00, 0x01};
__attribute__((section(".text.start"), noreturn))
void _start(void) {
static u8 out[256], hash[32], blk[16], a[48], b[48];
puts_("se test: start\n");
/* RSA: both slots loaded before either is used. */
rsa_key_set(0, k2048_mod, 256, k2048_exp, 256);
rsa_key_set(1, k1024_mod, 128, k1024_exp, 128);
check(!rsa_exp_mod(0, out, k2048_msg, 256, 256) &&
same(out, k2048_sig, 256), "RSA-2048 m^d mod n");
check(!rsa_exp_mod(1, out, k1024_msg, 128, 128) &&
same(out, k1024_sig, 128), "RSA-1024 m^d mod n in slot 1");
rsa_key_set(0, k2048_mod, 256, e65537, 4);
check(!rsa_exp_mod(0, out, k2048_sig, 256, 4) &&
same(out, k2048_msg, 256), "RSA-2048 s^e mod n gives m back");
rsa_key_set(1, k1024_mod, 128, e65537, 4);
check(!rsa_exp_mod(1, out, k1024_sig, 128, 4) &&
same(out, k1024_msg, 128), "RSA-1024 s^e mod n gives m back");
/* SHA-256. */
static const u8 abc[3] = {'a', 'b', 'c'};
check(!sha256(hash, 3, abc, 3) && same(hash, sha_abc_digest, 32),
"SHA-256 one-shot");
check(!sha256(hash, 0, sha_msg, 128) &&
!sha256(hash, 200, sha_msg + 128, 72) &&
same(hash, sha_msg_digest, 32), "SHA-256 in two parts");
/* AES-128 ECB decrypt of a zero block under 00..0F. */
static const u8 aes_exp[16] = {0x7B, 0x1D, 0x29, 0xA1, 0x6C, 0xF8,
0xCC, 0xAB, 0x84, 0xF0, 0xB8, 0xA5,
0x98, 0xE4, 0x2F, 0xA6};
for (u32 i = 0; i < 4; i++) {
SER(SE_KEYTABLE_ADDR) = 5u << 4 | i; /* slot 5, KEYS_0_3 */
SER(SE_KEYTABLE_DATA) = (4 * i) | (4 * i + 1) << 8 |
(4 * i + 2) << 16 | (u32)(4 * i + 3) << 24;
}
for (u32 i = 0; i < 16; i++)
blk[i] = 0;
SER(SE_CONFIG) = DEC_ALG(ALG_AES) | DST(DST_MEMORY);
SER(SE_CRYPTO_CONFIG) = 5u << 24; /* KEY_INDEX 5, CORE_DECRYPT */
SER(SE_LAST_BLOCK) = 0;
check(!se_exec(blk, 16, blk, 16) && same(blk, aes_exp, 16),
"AES-128 ECB decrypt");
/* RNG: 32 bytes twice, into zeroed buffers with a sentinel tail. */
for (u32 i = 0; i < 48; i++)
a[i] = b[i] = i < 32 ? 0 : 0x5A;
int res = rng(a, 32) | rng(b, 32);
int zero = 1, tail = 1;
for (u32 i = 0; i < 32; i++)
if (a[i])
zero = 0;
for (u32 i = 32; i < 48; i++)
if (a[i] != 0x5A || b[i] != 0x5A)
tail = 0;
check(!res && !zero, "RNG fills the buffer");
check(!same(a, b, 32), "RNG output changes between calls");
check(tail, "RNG stops at the size asked for");
puts_(failed ? "se test: done, with failures\n" : "se test: done\n");
i2c5_write(0x3C, 0x41, 0x02); /* MAX77620 ONOFFCNFG1: PWR_OFF */
for (;;)
;
}
+26
View File
@@ -0,0 +1,26 @@
#!/bin/sh
# Security Engine regression test: run tests/se/payload.c and check what it
# reports. Usage: tests/se/run.sh [rcm_emu] [payload]
EMU=${1:-./rcm_emu}
PAYLOAD=${2:-tests/se/payload.bin}
LOG=${LOG:-tests/se/out.log}
SDL_VIDEODRIVER=dummy RCM_EMU_NO_AUDIO=1 timeout 60 "$EMU" "$PAYLOAD" \
> "$LOG" 2>&1
status=$?
echo "se test (emulator exit $status):"
# The payload's lines arrive through the UART-B log, tagged [uartB].
grep '^\[uartB\] se test: \(ok\|FAIL\) ' "$LOG" |
sed -e 's/^.*se test: ok */ ok /' -e 's/^.*se test: FAIL */ FAIL /'
fail=0
grep -q 'se test: FAIL' "$LOG" && fail=1
if ! grep -q '^\[uartB\] se test: done$' "$LOG"; then
echo " FAIL the payload did not finish cleanly"
fail=1
fi
if [ "$status" -ne 0 ]; then
echo " FAIL the emulator exited with status $status (124 = timed out)"
fail=1
fi
[ $fail -eq 0 ] && echo "se test: PASS" || { echo "se test: FAIL (log: $LOG)"; exit 1; }
+190
View File
@@ -0,0 +1,190 @@
/* Generated by gen_vectors.py: RSA keys (e = 65537) with
* m^d mod n, and SHA-256 digests, computed with Python integers and hashlib. */
static const unsigned char k2048_mod[256] = {
0xDB, 0x84, 0xB5, 0x8A, 0xA4, 0x6A, 0xC2, 0x45, 0x45, 0x22, 0x94, 0x72,
0x4B, 0xAC, 0xC7, 0xB9, 0x34, 0x68, 0x99, 0xA8, 0x81, 0x91, 0x99, 0x8D,
0xEF, 0x69, 0xA2, 0xFE, 0xAC, 0x99, 0xD5, 0x36, 0x8D, 0x80, 0x27, 0x17,
0x39, 0xC2, 0x33, 0xE5, 0x12, 0x23, 0xF0, 0x81, 0x28, 0xD8, 0x30, 0x5B,
0x20, 0x7E, 0x9B, 0xD2, 0xE1, 0xA0, 0xE4, 0xBB, 0x12, 0x9C, 0xB9, 0x44,
0x45, 0x99, 0x02, 0xEF, 0xDE, 0x5E, 0x21, 0x9B, 0x5E, 0x3E, 0xBF, 0x91,
0x9E, 0x07, 0xBA, 0x6D, 0xE1, 0x5E, 0xBB, 0x2D, 0x10, 0x26, 0x20, 0x97,
0xFC, 0x7F, 0xD4, 0x51, 0xA7, 0x17, 0x94, 0xB1, 0x07, 0x56, 0xD5, 0x7E,
0xE9, 0xBE, 0xD4, 0x8A, 0x0B, 0xA6, 0xF9, 0x2A, 0x7A, 0x78, 0xE6, 0xC0,
0x36, 0xE7, 0x53, 0xD4, 0x77, 0x3D, 0x8A, 0x79, 0x7B, 0xAF, 0x72, 0x80,
0x82, 0x37, 0x00, 0x7E, 0xE4, 0x40, 0xBB, 0x75, 0x85, 0xB1, 0x34, 0xC3,
0x3B, 0xC4, 0xE7, 0xCF, 0xCA, 0x7B, 0xA3, 0x7B, 0xEF, 0x49, 0xC7, 0x52,
0x15, 0x79, 0xDC, 0xF9, 0x6C, 0xAE, 0xFB, 0xDC, 0xA5, 0x7A, 0x5B, 0x35,
0x4C, 0x74, 0xAD, 0x1F, 0x7A, 0xDB, 0x8A, 0x1E, 0x2B, 0xDC, 0xD4, 0x3B,
0x65, 0x21, 0x15, 0x21, 0xB5, 0xD3, 0x20, 0x62, 0x94, 0xAC, 0x11, 0x9F,
0x11, 0xEA, 0x8B, 0xB6, 0xE8, 0xCA, 0xD1, 0x54, 0x26, 0x16, 0xEB, 0xED,
0xF4, 0x7A, 0xFB, 0x92, 0x5C, 0xD7, 0x72, 0xE8, 0x3B, 0xAF, 0x63, 0x58,
0xCC, 0x8B, 0x2B, 0x8A, 0x1D, 0x78, 0x5F, 0xC2, 0xFA, 0xD9, 0xFB, 0x59,
0x50, 0x43, 0x96, 0x1C, 0x03, 0x6C, 0x2D, 0x99, 0x8A, 0xE8, 0x92, 0xA2,
0xE4, 0x62, 0x0A, 0x29, 0x35, 0x93, 0x02, 0x26, 0x31, 0x2D, 0x07, 0xE7,
0x99, 0xE5, 0xDA, 0x37, 0x2B, 0xD4, 0xA4, 0x39, 0x9B, 0xC8, 0x2B, 0x8D,
0x2A, 0x51, 0x34, 0x23,
};
static const unsigned char k2048_exp[256] = {
0xB3, 0xBD, 0x44, 0xDC, 0x41, 0x65, 0xBC, 0xAD, 0xF5, 0x3E, 0xAC, 0x27,
0xAD, 0xB8, 0xCA, 0x4B, 0xE6, 0x12, 0xA3, 0x86, 0x2A, 0x99, 0x2A, 0x0E,
0xE2, 0x72, 0x2F, 0x68, 0xB1, 0xB0, 0xBF, 0xB8, 0x8C, 0x41, 0xDB, 0x40,
0x14, 0x25, 0xE4, 0x51, 0xF2, 0xF9, 0x84, 0x6A, 0x6D, 0x24, 0x1E, 0xEB,
0xEE, 0x7E, 0x5C, 0x5E, 0x5E, 0x2A, 0x5C, 0x3E, 0xA4, 0xAD, 0xB8, 0xB0,
0xA2, 0xFF, 0xF7, 0x3C, 0xAA, 0x69, 0x8E, 0xC0, 0xE5, 0x79, 0x21, 0x68,
0x3C, 0xE9, 0xFD, 0x07, 0x0D, 0x5A, 0x80, 0x8E, 0x14, 0x43, 0xF3, 0xBA,
0x1E, 0xA0, 0x18, 0x1B, 0xC7, 0x61, 0xF2, 0x78, 0xC5, 0x16, 0x9F, 0x76,
0xEC, 0x33, 0x39, 0x59, 0xD2, 0xD2, 0xA3, 0xFF, 0xD9, 0x09, 0xF7, 0x7E,
0x79, 0x36, 0x0E, 0x18, 0xD0, 0x8D, 0x8E, 0x3D, 0x8C, 0x3D, 0x8A, 0xD6,
0x98, 0x48, 0x2A, 0xDA, 0xBB, 0x50, 0x19, 0x6C, 0x4B, 0x8B, 0x24, 0x84,
0xF4, 0x28, 0x0B, 0xFA, 0x6E, 0x64, 0xC4, 0x63, 0xDC, 0x3C, 0xDF, 0x90,
0xF4, 0x8D, 0x02, 0xEC, 0x58, 0xFB, 0x3E, 0xAE, 0x05, 0x3C, 0xFC, 0x20,
0xB8, 0x93, 0x02, 0x8E, 0x62, 0x3B, 0x29, 0xDA, 0x3E, 0xF7, 0x8C, 0xCC,
0x16, 0x30, 0x83, 0xF1, 0xFD, 0xA4, 0x56, 0x0C, 0xD1, 0x09, 0x77, 0x61,
0x58, 0xC0, 0xCE, 0xE7, 0x5E, 0xA1, 0x0F, 0x66, 0x18, 0x81, 0x96, 0x06,
0xD1, 0xCF, 0xCC, 0x5B, 0x1F, 0x9A, 0x1F, 0x25, 0x79, 0xCB, 0x66, 0x28,
0x6A, 0xE1, 0x61, 0x60, 0x16, 0x0E, 0x73, 0x5A, 0x50, 0xDC, 0x9C, 0xE4,
0xB3, 0x0E, 0xFD, 0x50, 0x90, 0xD3, 0x63, 0x2D, 0x9E, 0xDB, 0xEA, 0x61,
0x90, 0x65, 0xB0, 0xE0, 0xB8, 0xFF, 0xE6, 0x9D, 0x78, 0xB3, 0x8F, 0x68,
0x19, 0xFE, 0x45, 0x2B, 0x91, 0xD8, 0x0F, 0xB2, 0x2E, 0x90, 0x47, 0xA7,
0x80, 0xA0, 0x73, 0xB9,
};
static const unsigned char k2048_msg[256] = {
0x7E, 0x8E, 0x33, 0x8D, 0x7B, 0xD2, 0xAE, 0x8D, 0x55, 0xB2, 0xFF, 0x7E,
0x47, 0x6F, 0x6C, 0x3F, 0x8F, 0xAA, 0x20, 0x78, 0xEB, 0xF8, 0x6D, 0xA4,
0x36, 0xF1, 0x6E, 0x98, 0x64, 0x00, 0xCC, 0x4A, 0x7E, 0x8E, 0x33, 0x8D,
0x7B, 0xD2, 0xAE, 0x8D, 0x55, 0xB2, 0xFF, 0x7E, 0x47, 0x6F, 0x6C, 0x3F,
0x8F, 0xAA, 0x20, 0x78, 0xEB, 0xF8, 0x6D, 0xA4, 0x36, 0xF1, 0x6E, 0x98,
0x64, 0x00, 0xCC, 0x4A, 0x7E, 0x8E, 0x33, 0x8D, 0x7B, 0xD2, 0xAE, 0x8D,
0x55, 0xB2, 0xFF, 0x7E, 0x47, 0x6F, 0x6C, 0x3F, 0x8F, 0xAA, 0x20, 0x78,
0xEB, 0xF8, 0x6D, 0xA4, 0x36, 0xF1, 0x6E, 0x98, 0x64, 0x00, 0xCC, 0x4A,
0x7E, 0x8E, 0x33, 0x8D, 0x7B, 0xD2, 0xAE, 0x8D, 0x55, 0xB2, 0xFF, 0x7E,
0x47, 0x6F, 0x6C, 0x3F, 0x8F, 0xAA, 0x20, 0x78, 0xEB, 0xF8, 0x6D, 0xA4,
0x36, 0xF1, 0x6E, 0x98, 0x64, 0x00, 0xCC, 0x4A, 0x7E, 0x8E, 0x33, 0x8D,
0x7B, 0xD2, 0xAE, 0x8D, 0x55, 0xB2, 0xFF, 0x7E, 0x47, 0x6F, 0x6C, 0x3F,
0x8F, 0xAA, 0x20, 0x78, 0xEB, 0xF8, 0x6D, 0xA4, 0x36, 0xF1, 0x6E, 0x98,
0x64, 0x00, 0xCC, 0x4A, 0x7E, 0x8E, 0x33, 0x8D, 0x7B, 0xD2, 0xAE, 0x8D,
0x55, 0xB2, 0xFF, 0x7E, 0x47, 0x6F, 0x6C, 0x3F, 0x8F, 0xAA, 0x20, 0x78,
0xEB, 0xF8, 0x6D, 0xA4, 0x36, 0xF1, 0x6E, 0x98, 0x64, 0x00, 0xCC, 0x4A,
0x7E, 0x8E, 0x33, 0x8D, 0x7B, 0xD2, 0xAE, 0x8D, 0x55, 0xB2, 0xFF, 0x7E,
0x47, 0x6F, 0x6C, 0x3F, 0x8F, 0xAA, 0x20, 0x78, 0xEB, 0xF8, 0x6D, 0xA4,
0x36, 0xF1, 0x6E, 0x98, 0x64, 0x00, 0xCC, 0x4A, 0x7E, 0x8E, 0x33, 0x8D,
0x7B, 0xD2, 0xAE, 0x8D, 0x55, 0xB2, 0xFF, 0x7E, 0x47, 0x6F, 0x6C, 0x3F,
0x8F, 0xAA, 0x20, 0x78, 0xEB, 0xF8, 0x6D, 0xA4, 0x36, 0xF1, 0x6E, 0x98,
0x64, 0x00, 0xCC, 0x4A,
};
static const unsigned char k2048_sig[256] = {
0x84, 0xFE, 0x52, 0x90, 0x0E, 0x74, 0xA7, 0x53, 0xCC, 0xEB, 0x46, 0x40,
0x2D, 0x8A, 0x38, 0xFC, 0x14, 0x52, 0xD7, 0x8E, 0xC9, 0xC8, 0x17, 0xB7,
0xE3, 0x17, 0x8E, 0x8D, 0x4C, 0xB8, 0xB1, 0xDB, 0x2D, 0xCA, 0xD5, 0x34,
0xDE, 0xEC, 0x4B, 0x60, 0x7A, 0x53, 0xBC, 0x96, 0x62, 0xCA, 0xA5, 0x26,
0xB3, 0x35, 0x9C, 0x4F, 0x30, 0xB4, 0xAC, 0x6A, 0x74, 0xDB, 0x6E, 0x13,
0x70, 0xC6, 0xE4, 0x7F, 0xB5, 0x76, 0x4A, 0x41, 0x9D, 0x2C, 0x86, 0xDA,
0x9C, 0xE6, 0x87, 0x32, 0x62, 0x71, 0xB6, 0xE7, 0xDB, 0x79, 0xC2, 0x07,
0xF4, 0x24, 0x33, 0xC4, 0x60, 0x3E, 0xC8, 0x10, 0x17, 0x69, 0xA0, 0x95,
0xBE, 0x6F, 0xD8, 0x69, 0x79, 0x25, 0xB0, 0x4D, 0x20, 0x9B, 0x33, 0xF1,
0x86, 0x56, 0x2F, 0x8D, 0x79, 0xB8, 0xB7, 0x78, 0x63, 0x84, 0xB5, 0x4E,
0xBA, 0x6A, 0xB0, 0x4D, 0xA0, 0x7E, 0x48, 0xDF, 0xD4, 0xC0, 0x96, 0xAD,
0x2E, 0x23, 0x06, 0x7A, 0xE5, 0xC0, 0x79, 0x57, 0xBB, 0x60, 0xF5, 0x15,
0x02, 0xBA, 0xED, 0x65, 0x54, 0x7B, 0x9D, 0x20, 0x03, 0xEB, 0x76, 0xDF,
0xB5, 0xE1, 0xD1, 0x3D, 0x90, 0xD3, 0x73, 0x80, 0xA6, 0x52, 0x27, 0x01,
0x02, 0x72, 0x4D, 0xCA, 0xBA, 0x30, 0xA8, 0xEF, 0x01, 0xC8, 0xC3, 0x3E,
0xFA, 0xC4, 0x12, 0x00, 0x2F, 0x02, 0x12, 0x0F, 0xC4, 0x11, 0x74, 0x30,
0x30, 0x68, 0x4F, 0x16, 0x74, 0x38, 0xBE, 0x25, 0xDA, 0x44, 0xE7, 0xE4,
0xFF, 0x92, 0x3A, 0x20, 0xC5, 0x32, 0xCB, 0x86, 0xAE, 0x10, 0x47, 0x9B,
0x71, 0x43, 0xD8, 0x2C, 0x66, 0xE4, 0x13, 0x93, 0xF6, 0xBE, 0x60, 0x15,
0x51, 0x02, 0x61, 0xD0, 0xAA, 0xAF, 0x13, 0xA1, 0x38, 0x50, 0xF7, 0x0E,
0x66, 0x4C, 0x8B, 0xF7, 0x46, 0x8A, 0x76, 0xD6, 0xC1, 0x6F, 0x87, 0xC2,
0x37, 0x5A, 0x47, 0xB9,
};
static const unsigned char k1024_mod[128] = {
0xA9, 0x97, 0xBA, 0xDB, 0x61, 0x4B, 0x0E, 0x12, 0x16, 0x22, 0xC5, 0xD9,
0x65, 0xD3, 0x01, 0x6E, 0x08, 0xDF, 0x1B, 0x29, 0xFD, 0x01, 0x88, 0xAC,
0xF3, 0x36, 0xE0, 0xA6, 0x21, 0xC2, 0xE5, 0xB9, 0x21, 0x33, 0xB4, 0x22,
0x47, 0xEE, 0x31, 0x66, 0xF8, 0x57, 0x9D, 0xC7, 0x6F, 0x72, 0x7C, 0xD7,
0x30, 0x9B, 0xE7, 0xDF, 0x2E, 0x81, 0xDF, 0xA5, 0x2D, 0x68, 0x0D, 0x5F,
0xFC, 0x0C, 0xEF, 0xFF, 0x06, 0x27, 0x8A, 0xCF, 0xD5, 0xA2, 0x57, 0xB3,
0xAB, 0xDE, 0xF6, 0x37, 0x0A, 0x63, 0xCF, 0xC2, 0xF5, 0x19, 0x03, 0x9D,
0x1E, 0x3C, 0x61, 0xE0, 0x40, 0xAB, 0xAA, 0xC5, 0x39, 0x68, 0x05, 0x9F,
0x6E, 0xE6, 0x8E, 0x0E, 0x08, 0x9F, 0x2C, 0x78, 0x11, 0xEA, 0xA6, 0x7E,
0x16, 0xED, 0x58, 0xBF, 0x55, 0x0C, 0x6B, 0xB1, 0x4D, 0x3E, 0x64, 0x0A,
0x49, 0x47, 0xB7, 0xE3, 0x8F, 0xCF, 0x91, 0x05,
};
static const unsigned char k1024_exp[128] = {
0x61, 0xE6, 0xE6, 0x86, 0xC8, 0x96, 0xB4, 0x6B, 0xBA, 0x7D, 0x9E, 0x6B,
0x8E, 0xBD, 0x8D, 0xC0, 0xC0, 0xBC, 0x53, 0x09, 0x1D, 0x36, 0x6A, 0x79,
0x34, 0xFA, 0x44, 0x1B, 0x83, 0xB7, 0xE8, 0x37, 0xC4, 0x33, 0xFD, 0xD4,
0x20, 0x64, 0x1F, 0xFE, 0xCA, 0x74, 0x81, 0xEF, 0xE4, 0xA5, 0x59, 0xEE,
0x3B, 0xF0, 0x74, 0x9D, 0xC1, 0x52, 0x56, 0x12, 0x1B, 0xB1, 0x4A, 0xAF,
0x53, 0x69, 0x00, 0x8D, 0xEE, 0x06, 0x63, 0x28, 0xA0, 0x34, 0xF8, 0x70,
0xB6, 0x78, 0x5C, 0x0C, 0x9C, 0x16, 0x7D, 0xED, 0x59, 0xA5, 0x05, 0xD4,
0x4B, 0x82, 0x6A, 0x86, 0x09, 0x1B, 0xC3, 0x85, 0x98, 0xE9, 0x71, 0x38,
0x5E, 0x07, 0x3A, 0xF4, 0x51, 0xE2, 0xAF, 0xB3, 0xA6, 0x9C, 0x66, 0x6D,
0x0F, 0x5D, 0xFF, 0x61, 0xF4, 0x45, 0x3B, 0xAE, 0x59, 0xA9, 0xCA, 0xAE,
0x87, 0x95, 0x91, 0x65, 0xB9, 0x87, 0xD5, 0x01,
};
static const unsigned char k1024_msg[128] = {
0x03, 0x64, 0xE7, 0xA2, 0x21, 0x6E, 0xB6, 0x96, 0x08, 0x46, 0xDD, 0x04,
0xAB, 0xB9, 0xD7, 0x96, 0x2B, 0xCE, 0x7C, 0xE7, 0x11, 0xC9, 0x11, 0xD8,
0xEB, 0x51, 0xFA, 0xA5, 0x21, 0xC3, 0xDC, 0x82, 0x03, 0x64, 0xE7, 0xA2,
0x21, 0x6E, 0xB6, 0x96, 0x08, 0x46, 0xDD, 0x04, 0xAB, 0xB9, 0xD7, 0x96,
0x2B, 0xCE, 0x7C, 0xE7, 0x11, 0xC9, 0x11, 0xD8, 0xEB, 0x51, 0xFA, 0xA5,
0x21, 0xC3, 0xDC, 0x82, 0x03, 0x64, 0xE7, 0xA2, 0x21, 0x6E, 0xB6, 0x96,
0x08, 0x46, 0xDD, 0x04, 0xAB, 0xB9, 0xD7, 0x96, 0x2B, 0xCE, 0x7C, 0xE7,
0x11, 0xC9, 0x11, 0xD8, 0xEB, 0x51, 0xFA, 0xA5, 0x21, 0xC3, 0xDC, 0x82,
0x03, 0x64, 0xE7, 0xA2, 0x21, 0x6E, 0xB6, 0x96, 0x08, 0x46, 0xDD, 0x04,
0xAB, 0xB9, 0xD7, 0x96, 0x2B, 0xCE, 0x7C, 0xE7, 0x11, 0xC9, 0x11, 0xD8,
0xEB, 0x51, 0xFA, 0xA5, 0x21, 0xC3, 0xDC, 0x82,
};
static const unsigned char k1024_sig[128] = {
0x36, 0xF0, 0x8F, 0xE4, 0xDD, 0x4A, 0x6C, 0x54, 0x6F, 0xC7, 0x87, 0xC5,
0xD3, 0x5E, 0x08, 0x6F, 0x07, 0x65, 0xDA, 0xCD, 0xC2, 0x05, 0xE7, 0x83,
0x6D, 0x92, 0x6A, 0xB5, 0x26, 0xBA, 0xB0, 0xED, 0xC3, 0x09, 0x11, 0x27,
0xD0, 0x4C, 0x67, 0xF1, 0xC7, 0xF7, 0xA2, 0xA2, 0x46, 0x7E, 0xCB, 0x58,
0x48, 0x21, 0xAB, 0x77, 0x85, 0x75, 0x17, 0xDF, 0xD6, 0xE6, 0xEC, 0x25,
0x3D, 0x77, 0x45, 0x31, 0xAB, 0x0B, 0xD8, 0x6F, 0xF8, 0xCD, 0xD6, 0x11,
0x7B, 0xEF, 0xA5, 0xBB, 0xFC, 0xE6, 0xCB, 0x97, 0x0F, 0x2A, 0xA4, 0x11,
0x25, 0xDA, 0xAC, 0x16, 0x2F, 0x2A, 0x85, 0x28, 0x7C, 0x62, 0xBD, 0xAB,
0x44, 0xC3, 0x34, 0x33, 0x0B, 0x8B, 0x0C, 0x77, 0xEB, 0xDE, 0x07, 0xF3,
0xC3, 0xAA, 0x9C, 0xA6, 0xE3, 0x62, 0x97, 0xF1, 0xA1, 0x05, 0x3C, 0x78,
0x37, 0x99, 0xDE, 0xB7, 0x08, 0x4F, 0x9F, 0x46,
};
static const unsigned char sha_msg[200] = {
0x03, 0x0A, 0x11, 0x18, 0x1F, 0x26, 0x2D, 0x34, 0x3B, 0x42, 0x49, 0x50,
0x57, 0x5E, 0x65, 0x6C, 0x73, 0x7A, 0x81, 0x88, 0x8F, 0x96, 0x9D, 0xA4,
0xAB, 0xB2, 0xB9, 0xC0, 0xC7, 0xCE, 0xD5, 0xDC, 0xE3, 0xEA, 0xF1, 0xF8,
0xFF, 0x06, 0x0D, 0x14, 0x1B, 0x22, 0x29, 0x30, 0x37, 0x3E, 0x45, 0x4C,
0x53, 0x5A, 0x61, 0x68, 0x6F, 0x76, 0x7D, 0x84, 0x8B, 0x92, 0x99, 0xA0,
0xA7, 0xAE, 0xB5, 0xBC, 0xC3, 0xCA, 0xD1, 0xD8, 0xDF, 0xE6, 0xED, 0xF4,
0xFB, 0x02, 0x09, 0x10, 0x17, 0x1E, 0x25, 0x2C, 0x33, 0x3A, 0x41, 0x48,
0x4F, 0x56, 0x5D, 0x64, 0x6B, 0x72, 0x79, 0x80, 0x87, 0x8E, 0x95, 0x9C,
0xA3, 0xAA, 0xB1, 0xB8, 0xBF, 0xC6, 0xCD, 0xD4, 0xDB, 0xE2, 0xE9, 0xF0,
0xF7, 0xFE, 0x05, 0x0C, 0x13, 0x1A, 0x21, 0x28, 0x2F, 0x36, 0x3D, 0x44,
0x4B, 0x52, 0x59, 0x60, 0x67, 0x6E, 0x75, 0x7C, 0x83, 0x8A, 0x91, 0x98,
0x9F, 0xA6, 0xAD, 0xB4, 0xBB, 0xC2, 0xC9, 0xD0, 0xD7, 0xDE, 0xE5, 0xEC,
0xF3, 0xFA, 0x01, 0x08, 0x0F, 0x16, 0x1D, 0x24, 0x2B, 0x32, 0x39, 0x40,
0x47, 0x4E, 0x55, 0x5C, 0x63, 0x6A, 0x71, 0x78, 0x7F, 0x86, 0x8D, 0x94,
0x9B, 0xA2, 0xA9, 0xB0, 0xB7, 0xBE, 0xC5, 0xCC, 0xD3, 0xDA, 0xE1, 0xE8,
0xEF, 0xF6, 0xFD, 0x04, 0x0B, 0x12, 0x19, 0x20, 0x27, 0x2E, 0x35, 0x3C,
0x43, 0x4A, 0x51, 0x58, 0x5F, 0x66, 0x6D, 0x74,
};
static const unsigned char sha_msg_digest[32] = {
0x2C, 0x7E, 0x18, 0xC9, 0x42, 0xEF, 0x06, 0x5B, 0x52, 0x6A, 0x2D, 0x4E,
0x55, 0x46, 0x28, 0x37, 0x49, 0xCD, 0x3D, 0xDF, 0xB5, 0x1D, 0x8F, 0xC7,
0x1F, 0x42, 0x71, 0x73, 0x63, 0x68, 0x5F, 0x46,
};
static const unsigned char sha_abc_digest[32] = {
0xBA, 0x78, 0x16, 0xBF, 0x8F, 0x01, 0xCF, 0xEA, 0x41, 0x41, 0x40, 0xDE,
0x5D, 0xAE, 0x22, 0x23, 0xB0, 0x03, 0x61, 0xA3, 0x96, 0x17, 0x7A, 0x9C,
0xB4, 0x10, 0xFF, 0x61, 0xF2, 0x00, 0x15, 0xAD,
};
+10
View File
@@ -0,0 +1,10 @@
/* Loaded and entered at 0x40010000, like any RCM payload. */
ENTRY(_start)
SECTIONS {
. = 0x40010000;
.text : { KEEP(*(.text.start)) *(.text*) }
.rodata : { *(.rodata*) }
.data : { *(.data*) }
.bss : { *(.bss*) *(COMMON) }
/DISCARD/ : { *(.comment) *(.note*) *(.ARM.attributes) *(.ARM.exidx*) }
}
+153
View File
@@ -0,0 +1,153 @@
#!/usr/bin/env python3
"""NBD client for tests/usb/run.sh: talks to the disk the emulator's
--usb-host nbd serves and checks what comes back.
Usage: nbd_check.py <port> <log> rw|ro
Waits for the host to say it is serving, negotiates with NBD_OPT_GO, reads
the whole disk (tests/usb/payload.c fills it with a known pattern), checks
that bad requests are refused, then - on a writable disk - writes two
sectors, reads them back and flushes, or - on a write-protected one - checks
that the write is refused. Two reads go out back to back to check that
pipelined requests are answered in turn. Prints the CRC32 the disk should
have once the client is done, then disconnects.
"""
import socket
import struct
import sys
import time
import zlib
NBDMAGIC = 0x4E42444D41474943
IHAVEOPT = 0x49484156454F5054
REPLY_MAGIC = 0x0003E889045565A9
OPT_GO, OPT_LIST = 7, 3
REP_ACK, REP_SERVER, REP_INFO = 1, 2, 3
CMD_READ, CMD_WRITE, CMD_DISC, CMD_FLUSH = 0, 1, 2, 3
FLAG_READ_ONLY, FLAG_SEND_FLUSH = 1 << 1, 1 << 2
EPERM, EINVAL = 1, 22
LBAS = 384
failed = False
def check(ok, what):
global failed
print((" ok " if ok else " FAIL ") + what)
if not ok:
failed = True
def pattern():
return bytes(((i * 7) ^ (i >> 9)) & 0xFF for i in range(LBAS * 512))
def recv_all(s, n):
b = b""
while len(b) < n:
c = s.recv(n - len(b))
if not c:
raise EOFError("server closed the connection")
b += c
return b
def option(s, opt, data=b""):
s.sendall(struct.pack(">QII", IHAVEOPT, opt, len(data)) + data)
replies = []
while True:
magic, ropt, rtype, rlen = struct.unpack(">QIII", recv_all(s, 20))
if magic != REPLY_MAGIC or ropt != opt:
raise ValueError("bad option reply")
replies.append((rtype, recv_all(s, rlen)))
if rtype == REP_ACK or rtype & 0x80000000:
return replies
def request(s, cmd, handle, offset, length, data=b""):
s.sendall(struct.pack(">IHHQQI", 0x25609513, 0, cmd, handle, offset,
length) + data)
def reply(s, want_handle, length=0):
magic, err, handle = struct.unpack(">IIQ", recv_all(s, 16))
if magic != 0x67446698 or handle != want_handle:
raise ValueError("bad reply (magic %08X, handle %d)" % (magic, handle))
return err, (recv_all(s, length) if not err and length else b"")
def main():
port, log, mode = int(sys.argv[1]), sys.argv[2], sys.argv[3]
deadline = time.time() + 60
while "serving the disk over NBD" not in open(log, errors="replace").read():
if time.time() > deadline:
check(False, "the host serves the disk over NBD")
return 1
time.sleep(0.1)
s = socket.create_connection(("127.0.0.1", port), timeout=30)
magic, opt_magic, hflags = struct.unpack(">QQH", recv_all(s, 18))
check(magic == NBDMAGIC and opt_magic == IHAVEOPT and hflags & 1,
"NBD %s: fixed newstyle greeting" % mode)
s.sendall(struct.pack(">I", 3)) # fixed newstyle, no zeroes
listing = option(s, OPT_LIST)
check([r[0] for r in listing] == [REP_SERVER, REP_ACK],
"NBD %s: NBD_OPT_LIST names one export" % mode)
go = option(s, OPT_GO, struct.pack(">IH", 0, 0))
size = flags = None
for rtype, data in go:
if rtype == REP_INFO and struct.unpack(">H", data[:2])[0] == 0:
size, flags = struct.unpack(">QH", data[2:12])
check(go[-1][0] == REP_ACK and size == LBAS * 512,
"NBD %s: NBD_OPT_GO, export of %s bytes" % (mode, size))
check(bool(flags & FLAG_READ_ONLY) == (mode == "ro") and
bool(flags & FLAG_SEND_FLUSH),
"NBD %s: transmission flags %s" % (mode, flags and hex(flags)))
disk = bytearray(pattern())
request(s, CMD_READ, 1, 0, len(disk))
err, data = reply(s, 1, len(disk))
check(err == 0 and data == disk,
"NBD %s: reading the whole disk returns it" % mode)
request(s, CMD_READ, 2, 100, 512)
check(reply(s, 2)[0] == EINVAL, "NBD %s: an unaligned read is refused" % mode)
request(s, CMD_READ, 3, len(disk), 512)
check(reply(s, 3)[0] == EINVAL, "NBD %s: a read past the end is refused" % mode)
new = bytes((i * 13 + 5) & 0xFF for i in range(1024))
request(s, CMD_WRITE, 4, 10 * 512, len(new), new)
err = reply(s, 4)[0]
if mode == "rw":
check(err == 0, "NBD rw: writing blocks 10-11")
disk[10 * 512:12 * 512] = new
else:
check(err == EPERM, "NBD ro: a write is refused")
request(s, CMD_READ, 5, 8 * 512, 4 * 512)
request(s, CMD_READ, 6, (LBAS - 1) * 512, 512)
e5, d5 = reply(s, 5, 4 * 512)
e6, d6 = reply(s, 6, 512)
check(e5 == 0 and d5 == disk[8 * 512:12 * 512] and
e6 == 0 and d6 == disk[(LBAS - 1) * 512:],
"NBD %s: two pipelined reads%s" %
(mode, ", the first seeing the write" if mode == "rw" else ""))
request(s, CMD_FLUSH, 7, 0, 0)
check(reply(s, 7)[0] == 0, "NBD %s: flush" % mode)
request(s, CMD_DISC, 8, 0, 0)
s.close()
print("nbd check: disk crc32 %08X" % (zlib.crc32(disk) & 0xFFFFFFFF))
return 1 if failed else 0
if __name__ == "__main__":
try:
sys.exit(main())
except (OSError, EOFError, ValueError) as e:
print(" FAIL NBD client: %s" % e)
sys.exit(1)
+668
View File
@@ -0,0 +1,668 @@
/*
* USB device mode regression payload.
*
* A freestanding BPMP payload that brings up a small USB mass storage gadget
* - one LUN, a 384-block RAM disk - on one of the two device controllers,
* with the register sequences bdk's drivers use, and serves whatever the
* emulator's --usb-host PC asks. Built once per scenario with -DSCENARIO=n:
*
* 1 the USB2 controller USB1 (bdk usbd.c, Erista): queue heads in the
* controller at +0x1000, transfer descriptors in DRAM
* 2 the XUSB device controller (bdk xusbd.c, Mariko): event ring,
* transfer rings and endpoint contexts in IRAM
* 3 the USB2 controller again, as a HID gadget: after the report
* descriptor and SET_IDLE it sends three interrupt IN reports
* 4 scenario 1 with the disk write-protected
*
* Either way the gadget answers the standard requests and GET_MAX_LUN, then
* the Bulk-Only Transport: INQUIRY, TEST UNIT READY, REQUEST SENSE, READ
* CAPACITY, MODE SENSE(6), READ(10), WRITE(10), SYNCHRONIZE CACHE, PREVENT
* ALLOW MEDIUM REMOVAL and START STOP UNIT. When the host ejects, it stops
* the controller and powers off. It prints the CRC32 of the disk ranges the
* host reads, and of the whole disk after the eject, which tests/usb/run.sh
* compares with what the host logs and what its NBD client wrote. Run without
* --usb-host, scenario 1 sees no bus reset and says so.
*/
#ifndef SCENARIO
#define SCENARIO 1
#endif
typedef unsigned int u32;
typedef unsigned short u16;
typedef unsigned char u8;
#define REG(a) (*(volatile u32 *)(a))
#define B(a) (*(volatile u8 *)(a))
#define TIMERUS 0x60005010u
#define UARTB_THR 0x70006040u
#define I2C5 0x7000D000u
#define DISK 0xC0000000u /* 384 blocks of 512 bytes */
#define DISK_LBAS 384u
#define EP0BUF 0xC0110000u
#define CMDBUF 0xC0111000u /* CBW / CSW / small replies */
#define SCRATCH 0xC0120000u /* a rejected WRITE's data */
#define READ_ONLY (SCENARIO == 4)
static void putc_(char c) { REG(UARTB_THR) = (u32)(unsigned char)c; }
static void puts_(const char *s) {
while (*s)
putc_(*s++);
}
static void puthex(u32 v) {
for (int i = 28; i >= 0; i -= 4)
putc_("0123456789ABCDEF"[(v >> i) & 0xF]);
}
#if SCENARIO != 3
static void putdec(u32 v) {
char b[10];
int n = 0;
do {
b[n++] = (char)('0' + v % 10);
v /= 10;
} while (v);
while (n)
putc_(b[--n]);
}
#endif
static void i2c5_write(u32 dev, u32 reg, u32 val) {
REG(I2C5 + 0x04) = dev << 1;
REG(I2C5 + 0x0C) = reg | (val << 8);
REG(I2C5 + 0x00) = (1u << 1) | (1u << 9);
}
static __attribute__((noreturn)) void finish(const char *msg) {
puts_(msg);
i2c5_write(0x3C, 0x41, 0x02); /* MAX77620 ONOFFCNFG1: PWR_OFF */
for (;;)
;
}
static void copy(u32 dst, const u8 *src, u32 n) {
for (u32 i = 0; i < n; i++)
B(dst + i) = src[i];
}
#if SCENARIO != 3
static void zero(u32 dst, u32 n) {
for (u32 i = 0; i < n; i += 4)
REG(dst + i) = 0;
}
#endif
static u32 crc32(u32 addr, u32 n) {
u32 c = 0xFFFFFFFFu;
for (u32 i = 0; i < n; i++) {
c ^= B(addr + i);
for (int k = 0; k < 8; k++)
c = (c >> 1) ^ (0xEDB88320u & (0u - (c & 1)));
}
return ~c;
}
/* ---- Descriptors --------------------------------------------------------- */
static const u8 dev_desc[18] = {
18, 1, 0x00, 0x02, 0, 0, 0, 64,
0x09, 0x12, 0x57, 0x7E, /* 1209:7E57 */
0x00, 0x01, 1, 2, 3, 1,
};
#if SCENARIO == 3
static const u8 hid_report[21] = {
0x06, 0x00, 0xFF, 0x09, 0x01, 0xA1, 0x01, /* vendor page, application */
0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x08,
0x09, 0x01, 0x81, 0x02, 0xC0, /* 8 bytes of input */
};
static const u8 cfg_desc[34] = {
9, 2, 34, 0, 1, 1, 0, 0x80, 50,
9, 4, 0, 0, 1, 0x03, 0x00, 0x00, 0, /* HID */
9, 0x21, 0x11, 0x01, 0, 1, 0x22, 21, 0, /* HID descriptor */
7, 5, 0x81, 3, 8, 0, 4, /* interrupt IN, 8 bytes */
};
#else
static const u8 cfg_desc[32] = {
9, 2, 32, 0, 1, 1, 0, 0x80, 50,
9, 4, 0, 0, 2, 0x08, 0x06, 0x50, 0, /* mass storage, SCSI, BOT */
7, 5, 0x81, 2, 0x00, 0x02, 0, /* bulk IN, 512 */
7, 5, 0x01, 2, 0x00, 0x02, 0, /* bulk OUT, 512 */
};
#endif
static const u8 str_lang[4] = {4, 3, 0x09, 0x04};
static const char *const strs[3] = {"RCM-Emulator", "USB test disk", "0001"};
#if SCENARIO != 3
static const u8 inquiry[36] = {
0x00, 0x80, 0x02, 0x02, 31, 0, 0, 0,
'R', 'C', 'M', 'E', 'M', 'U', ' ', ' ',
'T', 'e', 's', 't', ' ', 'd', 'i', 's', 'k', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
'1', '.', '0', '0',
};
#endif
/* ---- Transport ------------------------------------------------------------ */
/*
* What the gadget needs from a controller:
* poll_setup(pkt) a SETUP packet, if one came (1) or not (0)
* ep0_in(len) send EP0BUF[0..len), then the status stage
* ep0_status() a no-data request's status stage
* ep0_stall() reject the request
* set_address(a) after its status stage
* configure() bring up the bulk endpoints
* bulk(in, buf, len) one bulk transfer; returns bytes moved
* stop() detach
*/
#if SCENARIO != 2
/* ---- USB2 controller USB1 (bdk usbd.c) ---- */
#define USB 0x7D000000u
#define U(o) REG(USB + (o))
#define USBCMD 0x130
#define USBSTS 0x134
#define DEVADDR 0x144
#define EPLIST 0x148
#define USBMODE 0x1F8
#define SETUPST 0x208
#define PRIME 0x20C
#define FLUSH 0x210
#define STATUS 0x214
#define COMPL 0x218
#define EPCTRL(n) (0x21C + 4 * (n))
#define SUSP 0x400
#define QHB (USB + 0x1000)
#define QH(i) (QHB + 64 * (i))
#define DTD 0xC0100000u /* 4 dTDs per queue head, 32 bytes each */
static void init(void) {
U(SUSP) |= (1u << 12) | (1u << 11); /* UTMIP_PHY_ENB, UTMIP_RESET */
U(SUSP) &= ~(1u << 11);
while (!(U(SUSP) & (1u << 7))) /* PHY_CLK_VALID */
;
U(USBCMD) |= 1u << 1; /* RESET */
while (U(USBCMD) & (1u << 1))
;
U(USBMODE) = 2; /* device */
for (u32 i = 0; i < 4; i++) {
for (u32 w = 0; w < 16; w++)
REG(QH(i) + 4 * w) = 0;
REG(QH(i) + 8) = 1; /* no dTD */
}
REG(QH(0)) = 64u << 16 | 1u << 15; /* EP0 OUT: 64, IOS */
REG(QH(1)) = 64u << 16;
U(EPLIST) = QHB;
U(USBCMD) |= 1; /* RUN: attach */
}
/* One transfer on queue head idx (2 * ep + in), in up to four 16 KiB dTDs as
* bdk builds them. Returns the bytes moved, or -1 if it never completed. */
static int xfer(u32 idx, u32 buf, u32 len) {
u32 base = DTD + idx * 4 * 32, off = 0, n = 0;
do {
u32 d = base + n * 32, sz = len - off > 16384 ? 16384 : len - off;
REG(d) = 1;
REG(d + 4) = sz << 16 | 0x80; /* bytes, ACTIVE */
for (u32 p = 0; p < 5; p++)
REG(d + 8 + 4 * p) = buf ? buf + off + 4096 * p : 0;
if (n)
REG(base + (n - 1) * 32) = d;
off += sz;
n++;
} while (off < len && n < 4);
REG(QH(idx) + 8) = base;
REG(QH(idx) + 0xC) = 0;
u32 bit = idx & 1 ? 1u << (16 + idx / 2) : 1u << (idx / 2);
U(PRIME) = bit;
u32 start = REG(TIMERUS);
while ((U(PRIME) | U(STATUS)) & bit)
if (REG(TIMERUS) - start > 5000000)
return -1;
U(COMPL) = bit;
u32 left = 0;
for (u32 i = 0; i < n; i++)
left += (REG(base + i * 32 + 4) >> 16) & 0x7FFF;
return (int)(len - left);
}
static int poll_setup(u8 *pkt) {
u32 sts = U(USBSTS);
U(USBSTS) = sts;
if (sts & (1u << 6)) { /* bus reset */
U(DEVADDR) = 0;
U(SETUPST) = U(SETUPST);
U(COMPL) = U(COMPL);
U(FLUSH) = 0xFFFFFFFFu;
}
if (!(U(SETUPST) & 1))
return 0;
U(SETUPST) = 1;
u32 lo = REG(QH(0) + 0x28), hi = REG(QH(0) + 0x2C);
for (int i = 0; i < 4; i++) {
pkt[i] = lo >> (8 * i);
pkt[4 + i] = hi >> (8 * i);
}
return 1;
}
static void ep0_in(u32 len) {
xfer(1, EP0BUF, len);
xfer(0, 0, 0);
}
static void ep0_status(void) { xfer(1, 0, 0); }
static void ep0_stall(void) { U(EPCTRL(0)) |= 1u | 1u << 16; }
static void set_address(u32 a) { U(DEVADDR) = a << 25; }
static void configure(void) {
for (u32 i = 2; i < 4; i++) {
for (u32 w = 0; w < 16; w++)
REG(QH(i) + 4 * w) = 0;
REG(QH(i)) = 512u << 16 | 1u << 29; /* 512, no ZLP, as bdk */
REG(QH(i) + 8) = 1;
}
U(EPCTRL(1)) = 2u << 2 | 1u << 7 | 2u << 18 | 1u << 23; /* bulk RX/TX on */
}
static int bulk(int in, u32 buf, u32 len) { return xfer(in ? 3 : 2, buf, len); }
static void stop(void) {
U(USBCMD) &= ~1u;
(void)U(USBCMD); /* let the host see it go */
}
/* Without a host nothing resets the bus: say so after half a second. */
static int bus_reset_seen(void) {
u32 start = REG(TIMERUS);
while (REG(TIMERUS) - start < 500000)
if (U(USBSTS) & (1u << 6))
return 1;
return 0;
}
#else
/* ---- XUSB device controller (bdk xusbd.c) ---- */
#define XU 0x700D0000u
#define X(o) REG(XU + (o))
#define X_DB 0x04
#define X_ERSTSZ 0x08
#define X_ERST0 0x10
#define X_ERST1 0x18
#define X_ERDP 0x20
#define X_EREP 0x28
#define X_CTRL 0x30
#define X_ST 0x34
#define X_IMOD 0x38
#define X_PORTSC 0x3C
#define X_ECP 0x40
#define X_HALT 0x50
#define X_RELOAD 0x58
#define XMEM 0x40030000u
#define SEG0 (XMEM)
#define SEG1 (XMEM + 0x100)
#define CTX (XMEM + 0x500) /* four 64-byte endpoint contexts */
struct ring { u32 base, idx, pcs; };
static struct ring rings[4]; /* by context index: 0 control, 2 OUT, 3 IN */
static u32 evt_deq, ccs, seq;
static void ring_init(u32 dci, u32 base) {
struct ring *r = &rings[dci];
r->base = base;
r->idx = 0;
r->pcs = 1;
zero(base, 16 * 16);
REG(base + 15 * 16) = base; /* Link TRB back to the start */
REG(base + 15 * 16 + 12) = 6u << 10 | 2; /* type LINK, toggle cycle */
u32 ctx = CTX + 64 * dci;
zero(ctx, 64);
REG(ctx) = 1; /* EP_RUNNING */
REG(ctx + 4) = (dci ? 512u : 64u) << 16; /* max packet size */
REG(ctx + 8) = base | 1; /* dequeue pointer, DCS */
}
static void queue(u32 dci, u32 w0, u32 w2, u32 w3) {
struct ring *r = &rings[dci];
u32 t = r->base + r->idx * 16;
REG(t) = w0;
REG(t + 4) = 0;
REG(t + 8) = w2;
REG(t + 12) = w3 | r->pcs;
if (++r->idx == 15) {
REG(r->base + 15 * 16 + 12) = 6u << 10 | 2 | r->pcs;
r->idx = 0;
r->pcs ^= 1;
}
X(X_DB) = dci << 8 | (dci ? 0 : seq << 16);
}
static void init(void) {
zero(XMEM, 0x600);
X(X_ERST0) = SEG0;
X(X_ERST1) = SEG1;
X(X_ERSTSZ) = 16u << 16 | 16;
X(X_EREP) = SEG0 | 1;
X(X_ERDP) = SEG0;
evt_deq = SEG0;
ccs = 1;
ring_init(0, XMEM + 0x200);
X(X_CTRL) |= 1u << 4 | 1u << 1; /* IE, LSE */
X(X_ECP) = CTX;
X(X_IMOD) = 0;
X(X_PORTSC) = (X(X_PORTSC) & ~(0xFu << 5)) | 1u << 16 | 5u << 5; /* RxDetect */
X(X_CTRL) |= 1u << 31; /* ENABLE */
}
/* The next event, if any. Polling ST lets the host run. */
static int next_event(u32 *ev) {
(void)X(X_ST);
if ((REG(evt_deq + 12) & 1) != ccs)
return 0;
for (int i = 0; i < 4; i++)
ev[i] = REG(evt_deq + 4 * i);
if (evt_deq == SEG0 + 15 * 16)
evt_deq = SEG1;
else if (evt_deq == SEG1 + 15 * 16) {
evt_deq = SEG0;
ccs ^= 1;
} else
evt_deq += 16;
X(X_ERDP) = evt_deq;
X(X_ST) = 1u << 4; /* IP, write 1 to clear */
return 1;
}
static void port_change(void) {
u32 ps = X(X_PORTSC);
X(X_PORTSC) = ps; /* write the change bits back */
}
/* Wait for the Transfer event of endpoint dci; the bytes it left over. */
static int wait_xfer(u32 dci) {
u32 ev[4], start = REG(TIMERUS);
for (;;) {
if (REG(TIMERUS) - start > 5000000)
return -1;
if (!next_event(ev))
continue;
u32 type = ev[3] >> 10 & 0x3F;
if (type == 34)
port_change();
else if (type == 32 && (ev[3] >> 16 & 0x1F) == dci)
return (int)(ev[2] & 0xFFFFFF);
}
}
static int poll_setup(u8 *pkt) {
u32 ev[4];
if (!next_event(ev))
return 0;
u32 type = ev[3] >> 10 & 0x3F;
if (type == 34) {
port_change();
return 0;
}
if (type != 63)
return 0;
for (int i = 0; i < 4; i++) {
pkt[i] = ev[0] >> (8 * i);
pkt[4 + i] = ev[1] >> (8 * i);
}
seq = ev[2] & 0xFFFF;
return 1;
}
static void ep0_in(u32 len) {
queue(0, EP0BUF, len, 3u << 10 | 1u << 16 | 1u << 5); /* Data IN, IOC */
wait_xfer(0);
queue(0, 0, 0, 4u << 10 | 1u << 5); /* Status OUT */
wait_xfer(0);
}
static void ep0_status(void) {
queue(0, 0, 0, 4u << 10 | 1u << 16 | 1u << 5); /* Status IN */
wait_xfer(0);
}
static void ep0_stall(void) { X(X_HALT) |= 1; }
static void set_address(u32 a) { X(X_CTRL) = (X(X_CTRL) & 0x80FFFFFFu) | a << 24; }
static void configure(void) {
ring_init(2, XMEM + 0x300);
ring_init(3, XMEM + 0x400);
X(X_RELOAD) = 0xC;
while (X(X_RELOAD) & 0xC)
;
X(X_HALT) &= ~0xCu;
X(X_CTRL) |= 1; /* RUN */
}
static int bulk(int in, u32 buf, u32 len) {
u32 dci = in ? 3 : 2;
queue(dci, buf, len, 1u << 10 | 1u << 5 | 1u << 2); /* Normal, IOC, ISP */
int left = wait_xfer(dci);
return left < 0 ? -1 : (int)(len - left);
}
static void stop(void) {
X(X_CTRL) = 0;
(void)X(X_CTRL);
}
static int bus_reset_seen(void) { return 1; }
#endif
/* ---- The gadget ----------------------------------------------------------- */
static int configured, lun_asked, report_asked, idle_set;
static void control(const u8 *p) {
u32 bm = p[0], req = p[1], val = p[2] | p[3] << 8, len = p[6] | p[7] << 8;
u32 n = 0;
if (bm == 0x80 && req == 6) { /* GET_DESCRIPTOR */
u32 type = val >> 8, idx = val & 0xFF;
if (type == 1) {
copy(EP0BUF, dev_desc, n = 18);
} else if (type == 2) {
copy(EP0BUF, cfg_desc, n = sizeof(cfg_desc));
} else if (type == 3 && idx == 0) {
copy(EP0BUF, str_lang, n = 4);
} else if (type == 3 && idx <= 3) {
const char *s = strs[idx - 1];
n = 2;
while (*s) {
B(EP0BUF + n) = *s++;
B(EP0BUF + n + 1) = 0;
n += 2;
}
B(EP0BUF) = n;
B(EP0BUF + 1) = 3;
} else {
ep0_stall();
return;
}
ep0_in(n < len ? n : len);
} else if (bm == 0x00 && req == 5) { /* SET_ADDRESS */
ep0_status();
set_address(val & 0x7F);
} else if (bm == 0x00 && req == 9) { /* SET_CONFIGURATION */
configure();
ep0_status();
configured = 1;
puts_("usb test: configured\n");
} else if (bm == 0xA1 && req == 0xFE) { /* GET_MAX_LUN */
B(EP0BUF) = 0;
ep0_in(1);
lun_asked = 1;
#if SCENARIO == 3
} else if (bm == 0x81 && req == 6 && (val >> 8) == 0x22) { /* HID report */
copy(EP0BUF, hid_report, n = sizeof(hid_report));
ep0_in(n < len ? n : len);
report_asked = 1;
} else if (bm == 0x21 && req == 0x0A) { /* SET_IDLE */
ep0_status();
idle_set = 1;
#endif
} else {
ep0_stall();
}
}
#if SCENARIO != 3
static void put_be32(u32 a, u32 v) {
B(a) = v >> 24;
B(a + 1) = v >> 16;
B(a + 2) = v >> 8;
B(a + 3) = v;
}
/* Serve Bulk-Only Transport commands until the host ejects the disk. */
static void bot(void) {
u32 sense = 6, asc = 0x29; /* a unit attention first, like a real disk */
for (;;) {
int n = bulk(0, CMDBUF, 512);
if (n != 31 || REG(CMDBUF) != 0x43425355u) /* "USBC" */
finish("usb test: FAIL bad CBW\n");
u32 tag = REG(CMDBUF + 4), want = REG(CMDBUF + 8);
u8 op = B(CMDBUF + 15);
u32 cdb = CMDBUF + 15, status = 0, sent = 0, eject = 0;
switch (op) {
case 0x12: /* INQUIRY */
copy(CMDBUF + 0x100, inquiry, 36);
sent = bulk(1, CMDBUF + 0x100, want < 36 ? want : 36);
break;
case 0x00: /* TEST UNIT READY */
status = sense ? 1 : 0;
break;
case 0x03: /* REQUEST SENSE */
zero(CMDBUF + 0x100, 20);
B(CMDBUF + 0x100) = 0x70;
B(CMDBUF + 0x102) = sense;
B(CMDBUF + 0x107) = 10;
B(CMDBUF + 0x10C) = asc;
sense = asc = 0;
sent = bulk(1, CMDBUF + 0x100, want < 18 ? want : 18);
break;
case 0x25: /* READ CAPACITY(10) */
put_be32(CMDBUF + 0x100, DISK_LBAS - 1);
put_be32(CMDBUF + 0x104, 512);
sent = bulk(1, CMDBUF + 0x100, 8);
break;
case 0x1A: /* MODE SENSE(6) */
zero(CMDBUF + 0x100, 4); /* the header, no pages */
B(CMDBUF + 0x100) = 3;
B(CMDBUF + 0x102) = READ_ONLY ? 0x80 : 0; /* WP */
sent = bulk(1, CMDBUF + 0x100, want < 4 ? want : 4);
break;
case 0x28: /* READ(10) */
case 0x2A: { /* WRITE(10) */
u32 lba = (u32)B(cdb + 2) << 24 | B(cdb + 3) << 16 | B(cdb + 4) << 8 |
B(cdb + 5);
u32 cnt = B(cdb + 7) << 8 | B(cdb + 8);
int bad = lba + cnt > DISK_LBAS || cnt * 512 != want;
if (op == 0x28) {
/* In 32 KiB transfers, as bdk sends a read: the host has to
* go on to the next one after a full-sized packet. */
if (bad)
status = 1;
for (u32 off = 0; !bad && off < want; off += 32768) {
u32 n = want - off > 32768 ? 32768 : want - off;
if (bulk(1, DISK + lba * 512 + off, n) != (int)n)
break;
sent += n;
}
break;
}
/* The host sends the data whatever happens to it. */
if (bad || READ_ONLY) {
sent = bulk(0, SCRATCH, want);
status = 1;
break;
}
sent = bulk(0, DISK + lba * 512, want);
status = sent != want;
puts_("usb test: WRITE(10) blocks ");
putdec(lba);
putc_('-');
putdec(lba + cnt - 1);
putc_('\n');
break;
}
case 0x35: /* SYNCHRONIZE CACHE(10) */
puts_("usb test: SYNCHRONIZE CACHE\n");
break;
case 0x1E: /* PREVENT ALLOW MEDIUM REMOVAL */
break;
case 0x1B: /* START STOP UNIT */
eject = B(cdb + 4) & 2;
break;
default:
status = 1;
break;
}
REG(CMDBUF + 0x200) = 0x53425355u; /* "USBS" */
REG(CMDBUF + 0x204) = tag;
REG(CMDBUF + 0x208) = want - sent;
B(CMDBUF + 0x20C) = status;
bulk(1, CMDBUF + 0x200, 13);
if (eject)
return;
}
}
#endif
__attribute__((section(".text.start"), noreturn))
void _start(void) {
for (u32 i = 0; i < DISK_LBAS * 512; i++)
B(DISK + i) = (u8)((i * 7) ^ (i >> 9));
puts_("usb test: disk crc32 first ");
puthex(crc32(DISK, 64 * 512));
puts_(" last ");
puthex(crc32(DISK + (DISK_LBAS - 8) * 512, 8 * 512));
puts_(" all ");
puthex(crc32(DISK, DISK_LBAS * 512));
putc_('\n');
init();
if (!bus_reset_seen()) {
stop();
finish("usb test: no bus reset, nothing on the cable\n");
}
u8 pkt[8];
u32 start = REG(TIMERUS);
while (!(configured && (SCENARIO == 3 ? report_asked && idle_set : lun_asked))) {
if (poll_setup(pkt))
control(pkt);
if (REG(TIMERUS) - start > 10000000)
finish("usb test: FAIL enumeration timed out\n");
}
#if SCENARIO == 3
for (u32 k = 1; k <= 3; k++) {
for (u32 i = 0; i < 8; i++)
B(CMDBUF + i) = (u8)(k * 0x10 + i);
if (bulk(1, CMDBUF, 8) != 8)
finish("usb test: FAIL report not taken\n");
}
puts_("usb test: hid reports sent\n");
#else
bot();
puts_("usb test: ejected; disk crc32 ");
puthex(crc32(DISK, DISK_LBAS * 512));
putc_('\n');
#endif
stop();
finish("usb test: done\n");
}
+150
View File
@@ -0,0 +1,150 @@
#!/bin/sh
# USB device mode regression test: tests/usb/payload.c brings up a mass
# storage gadget on each device controller and the emulator's --usb-host PC
# enumerates it, reads it back, writes its last sectors back unchanged and
# ejects it; on a write-protected disk it leaves the write out. With
# --usb-host nbd the disk is served over NBD instead, and nbd_check.py reads
# and writes it. Without a host the gadget must see nothing on the cable.
# Usage: tests/usb/run.sh [rcm_emu] [payload dir]
EMU=${1:-./rcm_emu}
DIR=${2:-tests/usb}
fail=0
run() {
log=$DIR/out_$1.log
shift
SDL_VIDEODRIVER=dummy RCM_EMU_NO_AUDIO=1 timeout 60 "$EMU" "$@" > "$log" 2>&1
echo $?
}
expect() {
if grep -q -- "$2" "$1"; then
echo " ok $3"
else
echo " FAIL $3 (missing: $2)"
fail=1
fi
}
expect_not() {
if grep -q -- "$2" "$1"; then
echo " FAIL $3 (found: $2)"
fail=1
else
echo " ok $3"
fi
}
crc() { sed -n "s/.*disk crc32 first [0-9A-F]* last [0-9A-F]* all \([0-9A-F]*\).*/\1/p" "$1"; }
# Enumeration and the reads, the same in every mass storage run.
check_disk() {
log=$1
name=$2
expect "$log" '\[usb-host\] device attached' "$name: the host sees the device attach"
expect "$log" 'high-speed device 1209:7E57 "RCM-Emulator" "USB test disk" serial "0001", address 1' \
"$name: enumerated, strings read, address set"
expect "$log" 'configuration 1: mass storage, bulk-only (EP 81 IN, EP 01 OUT, 512-byte packets)' \
"$name: configuration parsed"
expect "$log" 'LUN 0: "RCMEMU Test disk ", removable' "$name: INQUIRY"
expect "$log" 'TEST UNIT READY: sense key 6, ASC 29/00' "$name: unit attention, then REQUEST SENSE"
expect "$log" '384 blocks of 512 bytes (192 KiB)' "$name: READ CAPACITY"
}
check_end() {
log=$1
name=$2
want=$3
expect "$log" "usb test: ejected; disk crc32 $want" "$name: START STOP UNIT ejects, the disk as expected"
expect "$log" '\[usb-host\] device detached' "$name: the host sees the device go"
expect "$log" 'usb test: done' "$name: the payload ran to its end"
}
check_host() {
log=$1
name=$2
check_disk "$log" "$name"
first=$(sed -n 's/.*disk crc32 first \([0-9A-F]*\) last.*/\1/p' "$log")
last=$(sed -n 's/.*disk crc32 first [0-9A-F]* last \([0-9A-F]*\).*/\1/p' "$log")
expect "$log" "read blocks 0-63 (crc32 $first)" "$name: READ(10) of blocks 0-63 returns the disk"
expect "$log" "read blocks 376-383 (crc32 $last)" "$name: READ(10) of the last 8 blocks returns the disk"
if [ "$3" = ro ]; then
expect "$log" '\[usb-host\] write-protected' "$name: MODE SENSE reports write protection"
expect "$log" 'write check skipped: the disk is write-protected' "$name: no write to a write-protected disk"
expect_not "$log" 'usb test: WRITE(10)' "$name: the gadget sees no WRITE(10)"
else
expect "$log" '\[usb-host\] writable' "$name: MODE SENSE reports a writable disk"
expect "$log" 'usb test: WRITE(10) blocks 376-383' "$name: WRITE(10) of the last 8 blocks"
expect "$log" 'usb test: SYNCHRONIZE CACHE' "$name: SYNCHRONIZE CACHE"
expect "$log" 'wrote blocks 376-383 back unchanged; read back: the same data' \
"$name: the blocks read back as written"
fi
check_end "$log" "$name" "$(crc "$log")"
}
# --usb-host nbd: nbd_check.py reads, writes (or is refused) and disconnects.
check_nbd() {
n=$1
name=$2
mode=$3
shift 3
port=$((PORT_BASE + n))
log=$DIR/out_nbd$n.log
SDL_VIDEODRIVER=dummy RCM_EMU_NO_AUDIO=1 timeout 60 "$EMU" "$@" --usb-host nbd:$port > "$log" 2>&1 &
emu=$!
python3 "$DIR/nbd_check.py" $port "$log" $mode > "$DIR/out_nbd${n}_client.log" 2>&1
client=$?
wait $emu
st=$?
cat "$DIR/out_nbd${n}_client.log"
[ $client -eq 0 ] || { echo " FAIL $name: NBD client"; fail=1; }
check_disk "$log" "$name"
expect "$log" "serving the disk over NBD at 127.0.0.1:$port" "$name: serving over NBD"
expect "$log" 'NBD client has the disk' "$name: the client negotiated"
expect "$log" 'NBD client disconnected' "$name: the client disconnected"
expect "$log" 'ejecting the disk' "$name: the disk is ejected on disconnect"
want=$(sed -n 's/^nbd check: disk crc32 \([0-9A-F]*\)$/\1/p' "$DIR/out_nbd${n}_client.log")
check_end "$log" "$name" "${want:-none}"
[ "$st" -eq 0 ] || { echo " FAIL $name: emulator exit $st"; fail=1; }
}
echo "usb test:"
st=$(run 1 "$DIR/payload_1.bin" --usb-host)
check_host "$DIR/out_1.log" "USB2 controller"
[ "$st" -eq 0 ] || { echo " FAIL USB2 controller: emulator exit $st"; fail=1; }
st=$(run 2 "$DIR/payload_2.bin" --usb-host --oem mariko)
check_host "$DIR/out_2.log" "XUSB controller"
[ "$st" -eq 0 ] || { echo " FAIL XUSB controller: emulator exit $st"; fail=1; }
st=$(run 4 "$DIR/payload_4.bin" --usb-host)
check_host "$DIR/out_4.log" "write-protected disk" ro
[ "$st" -eq 0 ] || { echo " FAIL write-protected disk: emulator exit $st"; fail=1; }
st=$(run 3 "$DIR/payload_3.bin" --usb-host)
log=$DIR/out_3.log
expect "$log" 'configuration 1: HID (EP 81 IN, interrupt every 4)' "HID gadget: configuration parsed"
expect "$log" 'HID report descriptor: 21 bytes' "HID gadget: report descriptor read"
expect "$log" 'SET_IDLE done; polling EP 81 for reports' "HID gadget: SET_IDLE"
expect "$log" 'HID report 1: 10 11 12 13 14 15 16 17' "HID gadget: first interrupt report"
expect "$log" 'HID report 3: 30 31 32 33 34 35 36 37' "HID gadget: third interrupt report"
expect "$log" '\[usb-host\] device detached' "HID gadget: the host sees the device go"
[ "$st" -eq 0 ] || { echo " FAIL HID gadget: emulator exit $st"; fail=1; }
st=$(run 0 "$DIR/payload_1.bin")
expect "$DIR/out_0.log" 'usb test: no bus reset, nothing on the cable' "no host: the gadget waits on an empty cable"
if grep -q '\[usb-host\]' "$DIR/out_0.log"; then
echo " FAIL no host: the host logged activity"
fail=1
fi
if command -v python3 > /dev/null; then
PORT_BASE=${USB_TEST_NBD_PORT:-$((20000 + $$ % 20000))}
check_nbd 1 "NBD, USB2 controller" rw "$DIR/payload_1.bin"
check_nbd 2 "NBD, XUSB controller" rw "$DIR/payload_2.bin" --oem mariko
check_nbd 4 "NBD, write-protected disk" ro "$DIR/payload_4.bin"
else
echo " skip NBD: no python3"
fi
[ $fail -eq 0 ] && echo "usb test: PASS" || { echo "usb test: FAIL (logs: $DIR/out_*.log)"; exit 1; }