Skip to content

cpu_emulation: rewrite bare MONITORX/MWAITX in place at first #UD (RT-MONITORX-PATCH) - #1576

Open
madhyn wants to merge 2 commits into
ProjectLeonida:mainfrom
madhyn:feat/monitorx-mwaitx-inplace-patch
Open

madhyn wants to merge 2 commits into
ProjectLeonida:mainfrom
madhyn:feat/monitorx-mwaitx-inplace-patch

Conversation

@madhyn

@madhyn madhyn commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

Claimed in the coordination issue as: RT-MONITORX-PATCH (new item; coordination issue #14 is at GitHub's 2,500-comment cap with no open successor at PR time — confirmed 0 open PRs touch MONITORX/MWAITX patching; placed cleanly apart from #1472's CLWB helper so the two do not conflict).

What and why

On Intel hosts (CPUID.80000001H:ECX[29] == 0), AMD-only MONITORX (0F 01 FA) and MWAITX (0F 01 FB) instructions inside spin-wait loops currently raise #UD on every loop iteration, paying full Windows/Wine VEH exception dispatch overhead repeatedly.

This change rewrites bare 3-byte MONITORX / MWAITX sites in place on their first #UD in runtime/src/cpu_emulation.h:

  • MONITORX (0F 01 FA) -> canonical 3-byte NOP (0F 1F 00)
  • MWAITX (0F 01 FB) -> PAUSE; NOP (F3 90 90)

Patching uses a page-bounded atomic 32-bit InterlockedCompareExchange under an SRWLOCK (switching the target page temporarily to PAGE_EXECUTE_READWRITE and restoring its prior protection plus FlushInstructionCache). When a 3-byte site starts at page offset 0xFFD, the 4-byte CAS shifts back 1 byte so the write never crosses a page boundary. Sites starting at 0xFFE/0xFFF or prefixed forms (prefix_len > 0) fall back to existing per-fault emulation. Set LEONIDA_MONITORX_PATCH=0 to disable in-place patching.

Tested

  • Cross-compiled runtime/test/cpu_emulation_test.cpp with clang-cl --target=x86_64-pc-windows-msvc /std:c++20 /O2 /W4 /WX (0 warnings) and ran under Wine 11.22 on Arch Linux (Intel Core i7-12700, MONITORX 0):
    • Default mode: live rewrite of bare MONITORX (0F 1F 00) and MWAITX (F3 90 90), 0 repeat #UD faults on subsequent executions, prefixed fallback, 0xFFD page-end shift-back, and 0xFFE page-straddling fallback — cpu_emulation: all checks passed.
    • LEONIDA_MONITORX_PATCH=0: verified bytes remain unpatched and per-fault emulation path stays intact — cpu_emulation: all checks passed.
  • python3 scripts/check_no_game_data.py: passed.

GPUs tested: n/a (CPU instruction emulation only; tested on Intel Core i7-12700, Arch Linux x86_64 / Wine 11.22).

AI-assisted: yes (Antigravity)

Checklist

  • Based on current main and merges cleanly (a conflicting pull request is labeled needs rebase).
  • One topic; follow-up work goes in a new pull request.
  • No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here.
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed. (n/a: no translator change)

…-MONITORX-PATCH)

On Intel hosts, AMD-only MONITORX (0F 01 FA) and MWAITX (0F 01 FB) spin-wait
sites raise #UD on every loop iteration. Rewrite bare 3-byte sites in place at
their first #UD via a page-bounded atomic 32-bit compare-exchange under SRWLOCK:
MONITORX -> 3-byte NOP (0F 1F 00) and MWAITX -> PAUSE; NOP (F3 90 90). Prefixed
and page-straddling forms fall back to per-fault emulation. Opt out with
LEONIDA_MONITORX_PATCH=0.
@madhyn

madhyn commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

Rebased on main and fixed the Windows CI failure in cpu_emulation_test: the two two_pages boundary cases (0xFFD and 0xFFE) previously entered directly with ECX = lines != 0 and uninitialized EAX/EDX, which triggers #GP(0) instead of #UD on AMD EPYC runners with MONITORX=0 under Hyper-V. Added valid register prologues before the boundary instructions and flushed the instruction cache after VirtualProtect. Re-verified locally under Wine with clang-cl /W4 /WX (default mode and LEONIDA_MONITORX_PATCH=0).

@MoonEyes

Copy link
Copy Markdown
Collaborator

Hi @madhyn, thanks for this pull request.

CONTRIBUTING.md asks contributors to claim their work in the coordination issue ("Coordinating who works on what", currently #1608) before opening a pull request: post claiming: <ID> there, or a one-line description if the item is not listed yet, and put the ID in the pull request. I could not find a claim from you for this one (the ID RT-MONITORX-PATCH appears in the pull request, but there is no claiming: line for it).

The claim matters because "it is claimed in the coordination issue by the pull request's author" is the first item on the maintainers' checklist for a mergeable pull request, and because it lets others see that the work is taken before they write it a second time.

Could you post the claim in #1608 and add the ID to the pull request description? If you already claimed it in another form, a link to your comment is enough.

AI-assisted (Claude Code, Claude Opus 5.5).

@zmasi

zmasi commented Nov 28, 2026

Copy link
Copy Markdown
Contributor

Independent Verification Report — 44e437bda4 + origin/main (a8465211fb)

Environment: Windows 11 (26200), AMD Ryzen 9 5950X, MSVC 19.44.35228 (x64, /std:c++20 /EHsc /W4 /permissive- /utf-8, Debug /Od /MDd & Release /O2 /MD).
Verdict: C++ implementation & silicon probe PASS; 1 CI doc-check blocker (tests/test_docs_env_vars.py) noted below — clean Git merge with origin/main (a8bcfd49d2c2).

1. C++ Build & Hardware Probe Verification

  • cpu_emulation_test (Debug /Od /MDd & Release /O2 /MD): PASS (0 warnings under /W4 /permissive-).
  • Because Ryzen 9 5950X executes MONITORX/MWAITX natively (host.monitorx == true), we also compiled and ran a dedicated direct rt::cpu_emulation::patch_monitorx_mwaitx + live-execution harness on PAGE_EXECUTE_READ allocations:
    • Bare 3-byte MONITORX (0F 01 FA -> 0F 1F 00 3-byte NOP) and MWAITX (0F 01 FB -> F3 90 90 PAUSE; NOP): PASS (rewritten atomically via 32-bit InterlockedCompareExchange and executed cleanly).
    • Page-end 0xFFD shift-back 4-byte atomic window (window_addr = rip - 1 = 0xFFC): PASS (rewrites [0xFFD..0xFFF] while preserving [0xFFC] == 0x90 and [0x1000] == 0xC3).
    • Page-straddling 0xFFE ([0xFFE..0x1000]) and prefixed length == 4 (66 0F 01 FA): PASS (rejected cleanly without touching code bytes so per-fault emulation handles them).

2. CI Blocker (tests/test_docs_env_vars.py)

  • Running python -I tests/test_docs_env_vars.py on 44e437bda4 merged with origin/main fails (rc = 1):
    • AssertionError: read by the code and named in no .md file: LEONIDA_MONITORX_PATCH (runtime/src/cpu_emulation.h:302)
  • Fix: Mention LEONIDA_MONITORX_PATCH (LEONIDA_MONITORX_PATCH=0 disables in-place MONITORX/MWAITX patching) in docs/cpu_features.md or runtime/README.md alongside LEONIDA_CLWB_PATCH.

AI-assisted.

@OreoFR

OreoFR commented Nov 28, 2026

Copy link
Copy Markdown
Contributor

Verified by OreoFR

  • Base: main c1ecf04ed + PR head 44e437bda; green run in a merge package of 15 PRs, no new ctest failure vs main
  • Test: ctest -R ^cpu_emulation$
  • Red on main: 5 FAIL (MONITORX/MWAITX not rewritten in place)
  • Green with the PR: OK
  • Verdict: READY (this PR introduces the MONITORX/MWAITX rewrite; the cross-thread race on an already-rewritten site is a separate fix, not included here)
  • Machine: RTX 4070 Laptop 8 GB, NVIDIA 621.40, Intel Core Ultra 7 155H, Windows 11

AI-assisted (Claude Code, Claude Opus 5.5).

@OreoFR

OreoFR commented Nov 28, 2026

Copy link
Copy Markdown
Contributor

Fix proposal for a race in this PR's MONITORX/MWAITX rewrite (OreoFR)

@madhyn: the in-place rewrite here has the same race CLWB had before #2559. When several threads fault on the same MONITORX or MWAITX site at once, the ones whose #UD is handled after another thread rewrote the site decode 0F 1F 00 / F3 90 90 as Op::none and return EXCEPTION_CONTINUE_SEARCH, which ends the title.

Fix (one commit on top of this PR's head 44e437bda, merged with current main): OreoFR@1844fc6 (branch OreoFR:fix/monitorx-patch-race), runtime/src/cpu_emulation.h +91/-61 and runtime/test/cpu_emulation_test.cpp +147:

  • the handler continues at a site that already holds one of the two forms the rewrite writes (neither raises #UD), so the CPU runs it;
  • one lock, code_patch_lock(), shared with patch_clwb: both rewrites unprotect, re-check, write and re-protect the same code pages; with a lock each, one could set a page back to execute-read while the other writes into it (a separate lock made the mixed test hang: ctest timeout, 5 runs out of 5);
  • the rewrite stays one 4-byte compare-exchange, now kept inside one 64-byte cache line rather than one page (no half-written state; a site crossing a cache line keeps per-fault emulation);
  • monitorx_sites() counts each site once, by the thread that wrote it.

Tests: test_monitorx_rewrite (first #UD, a second #UD on the rewritten site, 16 threads on 2048 fresh execute-read sites) and test_mixed_rewrite (CLWB, MONITORX and MWAITX sites side by side on 6 pages, 16 threads). Before the fix 30,304 of 32,768 concurrent #UDs were passed on (29,599 of 49,152 in the mixed case); with it every check passes, 10 runs out of 10. Windows 11, RTX 4070 Laptop 8 GB, NVIDIA 621.40, MSVC RelWithDebInfo.

Feel free to cherry-pick it into this PR (it is GPL like the rest). If there is no answer in 48 h, I will open it as a small PR of its own that depends on this one, with you as co-author.

AI-assisted (Claude Code, Claude Opus 5.5).

@TheGeogeo

Copy link
Copy Markdown
Contributor

Ready for testing: merges cleanly with main 3535eb5c4. Not in main yet: git cherry finds 2 commit(s) not there, and 5 of the 102 lines it adds are already present. No duplicate found: its claim RT-MONITORX-PATCH appears in no other open pull request and in no main commit.

AI-assisted (Claude Code).

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.

5 participants