Console CPU instructions: serialize CLWB hot-patching and flush icache (#278) #321
No reviewers
Labels
No labels
accessibility
bug
documentation
duplicate
enhancement
goal:world-load
good first issue
help wanted
invalid
keep-open
off-goal
question
stale
test-only
wontfix
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
github/xcl-dev--xcl!321
Loading…
Reference in a new issue
No description provided.
Delete branch "github-bot/gh-321"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
@TG0000 on GitHub · 2026-11-23 23:25 UTC · original
TG0000:fix/clwb-hotpatch-race→main· +283 −6 · 1 files · 2 commits · openPart of #278 (item 4: the CLWB hot-patch race). Items 1 and 2 (the CLZERO loop) are in #295 and #290; item 3 (
is_writable) is not in this PR.A CLWB was hot-patched like this: make its bytes writable, fill them with
0x90one byte at a time, put the protection back. Nothing was shared between threads, which caused four problems:PAGE_EXECUTE_READWRITE, or become read-only again while the other thread was still writing.90 0F AE 30is a nop followed byxsaveopt [rax].FlushInstructionCachewas never called.What is in it
FlushInstructionCache. The lock also guards the set of addresses already patched. Everything is incrates/xcl/src/eh.rs.EB, len - 2), written by a singlelock cmpxchg, so another thread runs either the whole CLWB or the whole jump. The bytes after the jump are left as they were.Tested
stable-x86_64-pc-windows-gnuwith llvm-mingw, debug build.emulate_console_only) directly on code pages registered as a title module and set toPAGE_EXECUTE_READ. The patched code is then actually executed.eh::tests, all passing:clwb_patch_is_a_short_jump_over_the_instruction: the jump bytes for lengths 4 to 15; no patch when the bytes cross a cache line or a page, or for an invalid length.clwb_is_patched_into_a_jump_and_the_page_keeps_its_protection:clwb [rax],clwb [rsp+8]at an odd address, andclwb [r8]. Only two bytes change, the page isPAGE_EXECUTE_READafterwards, a second (late) fault resumes at the jump, and the code runs.clwb_across_a_cache_line_is_stepped_overclwb_patching_from_many_threads_at_once: 8 threads fault on 64 CLWBs on one page at once, in different orders, some twice. A watcher thread checks that each CLWB's first two bytes are only ever the old bytes or the jump. Every fault is handled, every CLWB is patched, the page endsPAGE_EXECUTE_READ, and all the patched code runs. Passed 5 of 5 runs.cargo test --workspace --exclude testgame-mw --no-fail-fast -- --test-threads=4:xcllib 614 passed, 1 failed, 20 ignored. All other targets passed apart from thee2etarget, which had 1 failure. Neither failure involves this change:pe::tests::parses_own_test_binary_tlsexpects the test binary to have a PE TLS directory. Awindows-gnubinary doesn't have one; the MSVC target does.e2e::test_title_runs_and_game_folder_is_untouchedneedstestgame_mw.dll, andtestgame-mwwas excluded because it doesn't build with this local toolchain.fetch_updatedeprecation inhle/xgameruntime/mod.rs, was already there (see #251).Regression run
Windows 11, Ryzen 9 5900X, AMD Radeon RX 6800, Rust stable
x86_64-pc-windows-msvc(VS 2022 Build Tools, link.exe),cargo build --release -p xcl,scripts/smoke.ps1 -Seconds 45, one run at a time under a RAM watchdog.main (
a6f5f7a, currentorigin/main, this PR's base):PR (head commit, no local changes):
No regression: 790 frames against 828 on its base, no device removals or crashes, peak commit 15155 MB against 15144 MB. The 5900X has CLWB natively, so this run doesn't reach the hot-patching path; it only shows nothing else changed. Frame counts move by about 10 % between runs of the same commit on this machine (earlier runs of
maingave 843, 709 and 828), and more when other builds are running: a first run of this head, made while other builds were compiling on the machine, gave 524 frames, so I reran it once the machine was idle and give that run above.Rebased onto current
main(a6f5f7a): the one conflict, ineh.rs, is resolved by keepingmain's tests (cmp_eflags_matches_x86_64_sub_flags, the CLZERO loop test,code_bytes_on_the_instructions_page_are_not_asked_about) next to the CLWB ones. On the rebased head, built withstable-x86_64-pc-windows-msvc,cargo test -p xcl --lib ehpasses: 11 passed, 0 failed, including the fourclwb_*tests.Not tested
hook_gs_failure) doesn't take this lock. Those patches run at load time, not from the exception handler.AI use
🤖 Generated with Claude Code
@mastrr9 on GitHub · 2026-11-23 23:39 UTC · original
Static code audit of
7d5f5f0(not tested on Windows / pre-Ice Lake CPU; no game files):Overall this is a very clean fix for the CLWB hot-patch race in #278:
CLWB_PATCHESacrossVirtualProtect(RWX)->cas_u16->VirtualProtect(old)->FlushInstructionCache->patches.insert(rip)ensures any concurrent thread that reads[0xEB, len - 2]aftercas_u16and entersclwb_patched(rip)blocks untilripis inserted, so it never leaks to the title's exception handler.rip % 64 == 63keeps the 2-bytelock cmpxchgwithin one cache line, andcas_u16correctly omitspreserves_flagssincecmpxchgclobbersEFLAGS.CLWB_PATCHESis only acquired on theILLEGAL_INSTRUCTIONVEH path (emulate_console_only).One small hardening suggestion
eh.rs:360): Currentlyif clwb_patched(rip) { return -1; }unconditionally resumes atrip. If a DLL containing a patched CLWB is ever unloaded and another module/code is later mapped at the same address and hits a genuine#UDatrip, returning-1without checking the bytes would spin indefinitely. Checkingcode.first() == Some(&0xEB) && clwb_patched(rip)(and/or pruningCLWB_PATCHESif a module is unregistered) prevents that cleanly.clwb_patching_from_many_threads_at_once,k * 0x20 + 2 * (k % 4)fork % 4 == 3puts the 2-byte load at offset+6..+8, which is aligned inside the qword rather than crossing a qword boundary — harmless, just slightly different from the comment.)AI use: static code audit of
7d5f5f0with Antigravity (Gemini 4 Neon).@ghost on GitHub · 2026-11-24 00:19 UTC · original
MSVC run, since Not tested lists the MSVC toolchain. This PR's head
7d5f5f0builds and passes withx86_64-pc-windows-msvc. It no longer merges cleanly withmaina6f5f7a, which changedeh.rs(#306'sis_writablewindow check), so I ran the head as it is, not merged.Tested
stable-x86_64-pc-windows-msvc; debug build.cargo test -p xcl --lib clwb: all 4 pass (clwb_patch_is_a_short_jump_over_the_instruction,clwb_is_patched_into_a_jump_and_the_page_keeps_its_protection,clwb_across_a_cache_line_is_stepped_over,clwb_patching_from_many_threads_at_once).clwb_patching_from_many_threads_at_oncerepeated 20 times: 20 of 20 pass.cargo test -p xcl --libon the head: 615 passed, 0 failed, 20 ignored.Not tested
main(conflict ineh.rs).AI use
@H0UNDZER0 on GitHub · 2026-11-24 03:05 UTC · original
Tested on an RTX 5080, release build: pass at the current head
dfa332a, 680 passed, 0 failed. This adds a run of the current head to the MSVC run of the earlier head7d5f5f0above.dfa332a5a4217d8a90fdeac1f8a049cfd808c699, this PR's head as is (on its basea6f5f7a), release build.XCL_*variables set.cargo build --release --workspace --locked: OK, the same singlefetch_updatewarning asmain.cargo test --workspace --release --no-fail-fast --locked -- --test-threads=4, run twice (the second with--show-output): 680 passed, 0 failed, 41 ignored both times.main2997c9a, which differs froma6f5f7aonly inREADME.md, gives 676 / 0 / 41 on this PC: the difference is the 4 newclwb_*tests, which pass.SKIPPED: the usual 2,gpu_geometry_wave32_prefix_count_over_a_maskandgpu_wave32_program_in_wave64_hardware(no wave64).cargo test --release --locked -p xcl --lib eh::tests::clwb, 3 runs: 4 passed each time,clwb_patching_from_many_threads_at_onceincluded.Not tested
main. When this was written that wasdd2ae9a;git merge-treeshowed no conflict.scripts/smoke.ps1.AI use: Claude Code (Claude Opus 5.5, Claude Fable 5.2)
@MesshM on GitHub · 2026-11-24 04:27 UTC · original
Test run of
dfa332a5a4217d8a90fdeac1f8a049cfd808c699on AMD RDNA4. I merged it onto currentmain64b3f35locally (clean merge) and tested that tree.Tested
stable-x86_64-pc-windows-msvc, debugcargo build --workspace+cargo test --workspace -- --test-threads=4on the merge: 705 passed, 0 failed, 41 ignored, exit code 0;xcllib tests 664 passed, 0 failed, 21 ignoredSKIPPED; theclwbtests inehpass, includingclwb_patching_from_many_threads_at_once.Review: Hot-patching is serialized and the patched range's instruction cache is flushed, so a thread that faults on a CLWB while another patches the same site sees either the old bytes or the whole jump. I did not trace every interaction with the CLZERO loop handling (#278, #295).
Not tested: no retail title or regression run (I have no unpacked game), no
XCL_SAMPLE_*tests, release build; the PR's head on its old base was not run, only its merge ontomain.Run and review by Claude Code (Claude Opus 5.5) on this machine; the review points were checked against the code.
@bunbeans2-arch on GitHub · 2026-11-24 04:42 UTC · original
Test report for
dfa332a5a4217d8a90fdeac1f8a049cfd808c699on an Intel CPU that lacks CLWB (i9-9900K, Coffee Lake), so the instruction raises a realSTATUS_ILLEGAL_INSTRUCTIONandeh's handler gets a real fault, not a made-upCONTEXT. The other reports here ran on Ryzen CPUs, which run CLWB natively.Tested
stable-x86_64-pc-windows-msvc, debug.a6f5f7a):cargo build --workspace+cargo test --workspace -- --test-threads=4: 680 passed, 0 failed, 41 ignored, 0SKIPPED(D3D12 backend on the RX 9070 XT). Control,mainf4ce27c: 701 passed, 0 failed, 41 ignored.eh.rs, not part of this PR; source below). It ran onmainf4ce27cand on this PR's head merged ontof4ce27c(clean merge), each built in its own target dir:clwb [rcx]; retfunctions on onePAGE_EXECUTE_READpage registered as a title module, 4 passes each in their own order, while a watcher thread reads each CLWB's first two bytes. One new process per run, 100 runs each:eb 02 ae 31after each run), the watcher saw 0 two-byte states other than66 0f,eb 02or90 90, 0 bytes written into the threads' buffers, the page endsPAGE_EXECUTE_READ; 73 to 92 illegal-instruction faults a run.mainf4ce27c: 0 of 100 passed. Exit status as Git Bash reports it: 139 in 83 runs, 132 in 16, 3 in 1; cargo's line for the first run of each build named0xc0000005 STATUS_ACCESS_VIOLATION(one build) and0xc000001d STATUS_ILLEGAL_INSTRUCTION(the other). XCL's own log printed 47 linesillegal instruction in real_clwb_threads.exe+...: code bytes 90 90 90 90over the 100 runs: my reading is that a thread faulted on the CLWB and its handler found the bytes already NOPed by another thread, so it passed the fault on (item 4 of #278).clwb [rcx]becomeseb 02 ae 31andclwb [rcx+8]becomeseb 03 ae 71 08(faults per call 1, 0, 0); aclwb [rcx]whose first two bytes cross a cache line is stepped over each call (1, 1, 1) and left as66 0f ae 31; the page staysPAGE_EXECUTE_READ. Onmainall three become NOPs (1, 0, 0) and this part passes too.90 0f ae 31(nop; xsaveopt [rcx]), run once, write 7 non-zero bytes into the buffer, so the check can see a torn patch.Not tested
scripts/smoke.ps1run (no game files were used),XCL_SAMPLE_*tests, a release build.mainthanf4ce27c(the real-fault test ran on the merge ontof4ce27c, the suite on the head as is), other Intel generations, an AMD CPU (where CLWB never faults).AI use
The real-fault test module (appended to the end of
crates/xcl/src/eh.rs; run withcargo test -p xcl --lib real_fault_tests -- --nocapture --test-threads=1, thenreal_d_clwb_faults_from_many_threadsalone, one process a run)@TG0000 on GitHub · 2026-11-24 10:39 UTC · original
Thanks @mastrr9 for the hardening note — pushed $sha\ checking \code.first() == Some(&0xEB) && clwb_patched(rip)\ so a stale \CLWB_PATCHES\ entry after a DLL unload / address reuse cannot spin on a genuine #UD, with a regression assertion in \clwb_is_patched_into_a_jump_and_the_page_keeps_its_protection\ (and fixed the offset comment nit).
Verified \cargo test -p xcl --lib eh::tests::clwb -- --test-threads=1: 4 passed, 0 failed.
Also huge thanks to @bunbeans2-arch for the real-fault i9-9900K verification (100/100), and @MesshM / @H0UNDZER0 / @nullmarsh for the independent MSVC + AMD/NVIDIA runs!
(Note: \scripts/smoke.ps1\ will need a quick refresh on $sha\ to update the \PR description\ check.)
(AI-assisted)
@DavidM1911 on GitHub · 2026-11-25 14:33 UTC · original
Verification on RTX 3060 Ti (Windows 11), branch merged with current
main:cargo test -p xcl --lib: 1038 passed, 1 failed in one parallel run; the failing test passes on a single-threaded rerun (1039/0). Intermittent single-test flake / 0xc0000005 abort under parallel scheduling — tracked in #1978; clean on single-threaded rerun.Thanks!
View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.Merge
Merge the changes and update on Forgejo.