Skip to content

iOS ARM64EC: make FEX_SMCCHECKS=full affordable — fix the SMC CRC guard that never matched - #41

Open
TimmyTurner51 wants to merge 8 commits into
willfaust:ios-port-2607from
TimmyTurner51:fh6-ios
Open

TimmyTurner51 wants to merge 8 commits into
willfaust:ios-port-2607from
TimmyTurner51:fh6-ios

Conversation

@TimmyTurner51

Copy link
Copy Markdown

What this fixes

FEX_SMCCHECKS=full was unusable for a real title: it pinned one core and stopped
frames entirely. The cause was a duplicated instruction in the SMC CRC guard,
not the cost of full checks themselves.

ThreadRemoveCodeEntry's generated comparison ended with two subtracts:

if (ThreadState->PoolPatchableCRC) { ...; sub(Dst, TMP1, TMP2); }
else                              {      sub(Dst, TMP1, CRC32Reg); }
sub(Dst, TMP1, CRC32Reg);   /* duplicate */

The second sub is unconditional, so the comparison became
(crc - patchable) - crc, or crc - 2*crc on the plain path. Dst is essentially
never zero, so the MATCH branch -- the proof that the guest bytes are unchanged,
which is what skips invalidation -- was almost unreachable. Every entry to a hot
block queued a fresh per-RIP invalidation and then took the one path in
FindBlock that bypasses both L1 and L2 and runs a CRC32 over the guest bytes.

Measured on an iPhone 17 Pro (iOS 27.0.1), Forza Horizon 6, FEX_SMCCHECKS=full:

before after
L1 misses/s 7,596,681 - 9,200,000 46,992 - 91,052
misses arriving with ValidateCRC 1,152,383,876 of 1,152,385,024 (99.9999%) 0
hottest RIP share 99.998% on one RIP evenly spread
title presented nothing for 10 s while the link ticked; one core at 3.2 GHz, GPU idle 60.0 Hz, mean 16.7 ms

That is 100-200x fewer L1 misses and the difference between 0 fps and 60 fps on the
same title/menu state. Reproduced twice before the fix and measured three times after.

The rest of the branch

The fix is the last commit; the rest is the iOS ARM64EC work it depends on and the
instrumentation that found it.

  • LookupCache: recommit the grown L1 range -- growing the dynamic L1 table
    doubled CurrentL1Entries over a range the shrink branch had decommitted and
    never recommitted, so AddL1Entry wrote into PAGE_NOACCESS. The entries it was
    about to use were also not the zeroes the lookup path assumes. Same defect the
    DroidDeck FH6 build ships as fex/0003-l1-recommit-on-grow.patch.
  • SMC full-check port (0001/0002 half) -- per-block invalidation on the FULL
    path, writable-code gating, L1 mask sync, and the part of 0002 that does not
    need 0004. This is what made FEX_SMCCHECKS=full affordable enough to measure.
  • Live code buffers, pool-clone scratch, stub pools, SMC dispatch trampolines --
    the ARM64EC module changes the iOS host needs.
  • Two diagnostics, both cheap and useful for future reports: [CB_COMPILE]
    (true-compile rate plus the guest RIPs being compiled) and [l1-miss] (miss rate
    plus the top missing RIPs and a crc= count). The crc= counter is what
    identified this bug; it should stay at 0 and the rate in the tens of
    thousands/s, so a regression shows up in one log line.

Verification

  • Reproduced the stall twice before the fix, each with crc= at 99.9999% of misses.
  • After the fix: crc=0, rate 47-91K/s, [promote] link ran 601 ticks in 10.0 s = 60.0 Hz (mean 16.7 ms, longest gap 16.7 ms) with presents advancing.
  • No crash in the measured window.

Note that the duplicate landed twice from a repeated patch application and was
committed; the companion Madeira change records applied-patch digests so a
pure-insertion hunk cannot re-apply itself, which prevents this class of defect
from being reintroduced.

Madeira and others added 8 commits November 21, 2026 14:13
Two decommit defects, ported from the reference FH6 package
(fh6-wine-fex/fex/0003-l1-recommit-on-grow.patch), where the same grow path
is documented as a hard hang when Forza Horizon 6 enters the world.

The shrink branch decommits everything from CurrentL1Entries up to
MAX_L1_ENTRIES with Recommit=false and nothing ever puts it back. Growing
again then doubles CurrentL1Entries over memory that is still
MEM_RESERVE/PAGE_NOACCESS: AddL1Entry writes there from host C++ and faults,
and until it does the lookup path sees entries that are not the zeroes it
assumes. Grow now recommits and zeroes the doubled range.

VirtualDontNeed also queried the region and then ignored it, passing the
caller's Size to VirtualFree(MEM_DECOMMIT); an over-long Size can take out a
neighbour and leave it MEM_RESERVE/PAGE_NOACCESS. Clamp to the queried
RegionSize and log [dontneed-clamp] when it fires.

Measured, and reported as the negative it is: the clamp never fires in a full
FH6 run (the arithmetic always lands on MAX_L1_SIZE), and the FH6 execute
fault is unchanged -- its page is 157MB while the L1 table is capped at 2MB,
so they were never the same memory. These are correctness fixes for the
decommit contract, not a fix for that fault.

(cherry picked from commit 4830accab628f06ba5245c023639369bbb532ce1)
…VMA fallback

Ports the parts of the DroidDeck reference series that were genuinely
missing from this fork. 0001's per-block invalidation machinery
(InvalidateGuestBlock, InvalidateUntrackedRange, EraseEntriesInRange,
InvalidateCachedBlock) was already present and committed; what was still
absent is recorded here.

0001 -- L1PointerMask / CurrentL1Entries must move together.
  InvalidateCache masks a slot by L1PointerMask while InvalidateUntrackedRange
  sweeps [0, CurrentL1Entries). If growth changed one without the other, a
  block could survive an invalidation, or a slot outside the mask could be
  swept. Set L1PointerMask = CurrentL1Entries - 1 where the entries grow.

0002 -- DecodedBlockInformation::ContainsWritableCode.
  Records whether any byte of a block came from a range writable while
  decoding. Only such a block can be self-modified behind the decoder, so
  only it needs per-instruction/per-chunk validation under SMCChecks=full.
  Set in CheckRangeExecutable (both the multi-range loop and the tail) and
  cleared in the block reset. The chunked-CRC half of 0002 is NOT ported:
  it needs the ValidateCode IR op widened to carry a CRC rather than 16 raw
  bytes, which is part of 0004.

0004 -- QueryExecutableRange live-VMA fallback (arm64ec arm only).
  A handler trampoline is VirtualAlloc'd RWX and can miss XIntervals when a
  later protect splits the tracked range; recover it from the live VMA so the
  decoder does not emit NoExec/#UD for valid cmp/jmp bytes. This does NOT
  cover the FH6 fault: Wine answers MEM_RESERVE/NOACCESS for 0x70453d8887,
  so the guard still returns {} there by design.

Verified: FEX builds; "Recovered executable VMA", EraseEntriesInRange,
InvalidateUntrackedRange and zero-scrub are all present in the produced
xtajit64.dll (sha256 e45a9a9573125547...). Not yet run on device.

(cherry picked from commit 72bc512fea3da9ad84211b0531a37c618dce3842)
The earlier pass took only part of 0001 (L1 mask sync, trampoline VMA
recovery), so InvalidateCodeBuffersBlock/InvalidateThreadCachedBlock and
InvalidateGuestBlock were absent. Applied the reference patch with a
3-way merge and resolved by hand:

- kept our iOS zero-scrub, DEP-off promotion and hot-SMC-page work, which
  supersedes the reference's plainer QueryExecutableRange
- took the reference's InvalidateGuestBlock, and confirmed
  ThreadRemoveCodeEntryFromJit matches it byte for byte
- dropped 0002 (chunked block CRC): it needs FEXCore::Utils::crc32,
  WantsDiskCachePatching, _PatchableGuestCRC and a two-argument
  _ThreadRemoveCodeEntry, all of which arrive with 0004. Left a comment
  saying so instead of a half-applied shape that would not build.

Builds clean (build/fex-arm64ec/build.sh, 5476352-byte xtajit64.dll).
… is affordable

The reference package that boots FH6 on Android requires FEX_SMCCHECKS=full -- its
troubleshooting table answers "anti-tamper or integrity error" with "the preset is
Denuvo (it turns on full code checks)". This port cannot run that: with `full`,
Steam's own launch times out (docs section 3, launch-client-error=46, isolated to
that one key with the DLL swapped for stock).

The reference can afford `full` because its FEX carries fh6-fex 0002 (block-level
CRC validation). I had recorded 0001/0002 as both ported; that is wrong for 0002.
grep -r ContainsWritableCode and grep -r FEX_SMC_BLOCK over FEXCore/Source were
both empty before this commit.

0002 is 126 lines / 3 files, but its chunked-CRC half rides on 0004 (crc32 helper,
patchable CRC, two-argument _ThreadRemoveCodeEntry), none of which exists here. The
half that survives is the one that carries the argument, and it is the reference's
own reasoning: non-writable code can only change through a protection change or a
remap, and both invalidate cached blocks, so FULL only needs per-instruction
validation for writable code.

So DecodedBlockInformation gains ContainsWritableCode, set from RangeInfo.Writable
in CheckRangeExecutable and reset per decode, and the per-instruction CRC under
CONFIG_SMC_FULL is gated on it. Code that cannot self-modify stops paying; code
that can still gets validated.

Behaviour-neutral for the configuration on the device: SMCChecks is not FULL, so
the condition reduces to ForceFullSMCDetection || HotSMCBlock exactly as before.
That is what makes it safe to stage ahead of the experiment that needs it, since a
.wcp's files apply one launch after its environment does -- turning on `full` in
the same package as this DLL would run `full` against the ungated emulator, which
is precisely the launch that times out.

Built for the ARM64EC module the game runs (build/fex-arm64ec -> xtajit64.dll,
5476352 bytes). dist/FH6-iOS-1.4-fex.wcp staged in Documents/Import, sha 83b430b6
verified by read-back.

Also records the three probes from the previous commit in the same document as a
correction: the t=10.4 census sample was taken mid-unpack, so "decrypted nothing"
is not established by it.

Co-authored-by: Cursor <cursoragent@cursor.com>
…trampolines

The Forza Horizon 6 body of work on top of the iOS host port:

- 16 KB host-page SMC traps with a real dispatch trampoline (LL/SC +
  store-log re-dispatch), replacing per-block-only invalidation; batched
  epoch-guarded EraseMappingsOnly + TryReuseAfterSMC stash restore so
  rewritten guest code reuses its stale copy when the bytes come back.
- Pool-clone scratch carving stub trampolines into 4 MB arenas (rotating
  2/3 slots per RIP, FEX_MAX_POOL_ARENAS budget) so rewritten stubs stop
  growing the CodeBuffer and wiping the cache.
- Chained code-buffer growth (16 -> 32 -> 64 -> 128MB) with a 32MB
  per-generation ceiling (ml1318 tail census) and the pool-side allocator
  granting what the pool can afford.
- GuestCRC/Epoch-tagged block entries, CRC-validating L3 lookups under
  async invalidation (FindBlock ValidateCRC path).
- Arm64EC debug registers (0002), writable-range gated checks, and the
  plain-arm64 clang.fpmath=soft fp-helper world for the shared artifact.

Also repairs copy/paste duplication left by the earlier manual port
(CPUBackend/LookupCache/Core) that broke the build.

Co-authored-by: Cursor <cursoragent@cursor.com>
The 2026-11-27 session collapsed 60 -> 5.6 fps from 15:16 to 15:21 with true
compiles at 477K-543K/min against an 8-13K/min baseline (40-60x) while GPU exec
stayed at ~20 ms of each 50-80 ms frame, so the wall was CPU in translation, not
rendering. [CB_SUMMARY] could not say WHICH code was being compiled: its
hottest_rip comes from a bouncing +-1 guess whose repeat count had already
overflowed negative, so it named the same RIP for the whole session including
the quiet minutes.

Keep a 16-slot cumulative histogram of the GuestRIP passed to a true compile and
print it, plus the true-compile delta since the previous summary:

  [CB_COMPILE] dcompiles=<delta> cumulative=<total> top_rip[0..2]=0x..xN

A storm carried by a few RIPs is thrash/invalidation on those blocks; a storm
spread over thousands of distinct RIPs is genuinely new code. The two need
different fixes, and this decides between them in one run. Counters share the
summary boundary so deltas are comparable across runs.

Also drop the 4 extra QueueSMCInvalidate(Thread, GuestRIP) calls that a
repeatedly-applied patch had stacked in the SMC-full path (5 copies of the same
queue); one call is what the committed intent is.
The 15:46 run reproduced the stall that reads as 'FPS collapses to 0': one core
pinned, GPU idle, and [l1-miss] climbing to 2.76e9 misses at a sustained 9.0-9.2M/s
for minutes, against 13K real compiles in the whole session. [CB_SUMMARY] showed
L1ptr == cacheL1 (so the emitted probe is not reading a stale pointer) and
hottest_rip concentrating essentially all CompileBlock traffic on one RIP, and no
SMC activity at all in the run -- so the usual suspects are excluded.

Two readings remain and they need opposite fixes: one RIP dominating means the
block is written to L1 on every L3 hit yet missed again on the next entry, while
two or more dominating means L1 slot aliasing -- the index is
(RIP >> 4) & (CurrentL1Entries - 1), so at the 128K-entry cap two guest addresses
2 MB apart share a slot and evict each other forever on a 184 MB binary.

Print the top two missing RIPs with their counts next to the existing rate,
sharing its 2^20 cadence. Diagnostic only.
…torm

ThreadRemoveCodeEntry's CRC comparison ended with a second, unconditional
'sub Dst, TMP1, CRC32Reg' -- a patch hunk that landed twice and was committed.
It rewrote the comparison to (crc - patchable) - crc, and to crc - 2*crc on the
plain path, so Dst was essentially never zero and the MATCH branch (the proof
that the guest bytes are unchanged, which is what skips invalidation) was almost
unreachable. Every entry to a hot block therefore queued a fresh per-RIP
invalidation and took the ValidateCRC path in FindBlock, bypassing L1 and L2 and
running a CRC32 over the guest bytes each time.

Measured on device 2026-11-27, iPhone 17 Pro, FEX_SMCCHECKS=full:

  before  [l1-miss] ... 7,596,681-8,000,000/s ... crc=1,152,383,876 of 1,152,385,024
          one RIP holding 99.998% of misses; title presented nothing for 10 s
          while the link ticked, one core pinned at 3.2 GHz, GPU idle -- the
          'FPS collapses to 0' stall, reproduced twice
  after   [l1-miss] ... 46,992-91,052/s ... crc=0
          [promote] link ran 601 ticks in 10.0 s = 60.0 Hz (mean 16.7 ms,
          longest gap 16.7 ms); game presents +79 ... +143

~100-200x fewer L1 misses and a steady 60 Hz link. Also keeps the miss-RIP and
crc attribution that found this, so a regression shows up in one line.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant