perf(libc): copy checked guest bytes without a syscall on Linux x86-64 #21156
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/21156"
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?
Imported from boykopovar/AnyPS5. Originally posted by milescoviello on 2026-11-15T21:30:51Z.
What
On Linux x86-64,
GuestCopyIn_nid_no_patchandGuestCopyOut_nid_no_patchnow copy with arep movsbwhose faults the copy itself handles, instead of aprocess_vm_readv/process_vm_writevsystem call. A checked 8-byte copy goes from about 327 ns to about 6 ns. This removes the cost that has kept checked copies out of per-element paths: #20589, #20600, #20588, and #20682's Json2Value(const char*)going from 136 to 511 ns.This uses the same technique as the kernel's
copy_from_userexception table. AnyPS5 already uses it on Windows: #14799 addedGuardedCopy/GuardedCopyAvx2toGuestArena.cppfor committed guest reads. Those are assembly loads at known labels; the first thingReportCrash's vectored handler does is callGuestArenaRecoverRead_nid_no_patch, which movesRiptoGuardedReadFailed. This PR brings the same scheme to Linux, for every checked copy:GuestFaultCopyBytes(new,src/specifics/linux/GuestFaultCopy.cpp) ismov %rdx, %rcx; rep movsb; mov %rcx, %rax; ret. It returns the number of bytes it did not copy.REG_RIPis exactly therep movsb, the handler movesREG_RIPto the next instruction and returns.rcxstill holds the bytes left, so the copy returns non-zero and the caller returnsfalse, as it does today onEFAULT.SIG_DFLis restored and the fault re-raised (the same chaining asCrashReport.cpp).CrashReport.cpp'sOnFatalSignalmakes the same check first, so a copy fault never prints a crash report, whichever handler was installed first.Handler order: libc's crash report is installed when libc loads, so the copy handler, installed later, runs first and chains to it. libkernel's
DeliverFault(installed when a title registers an exception handler) runs before both. It sends a fault whoseripisn't in guest code to the previous handler, and libc.prx isn't guest code, so copy faults still reach the copy handler. libkernel'sSignals.cppalso changes the host SIGSEGV disposition, withstd::signal, when a title registers or resets a SIGSEGV handler (Install,ResetToDefault). After each change it now callsGuestFaultCopyReinstall_nid_no_patch(), which puts the copy handler back in front and chains it to the new disposition: the guest'sDispatch,SIG_DFLorSIG_IGN. The previous dispositions are kept in two slots, swapped once the new one is written, so a fault handler never reads one that's being rewritten. The copy handler is installed withSA_NODEFER, but it keeps the previous disposition'ssa_mask, and a guest handler installed throughstd::signalblocks SIGSEGV in that mask. So a copy that faults inside the guest's own SIGSEGV handler does not resolve: the fault stays fatal there, wheremain'sprocess_vm_readvreturnsfalse. The reinstall after a guest registration takes over SIGSEGV only, the signal libkernel replaced: SIGBUS keeps the chain it had, so aDeliverFaultthat already chains to the copy handler is never saved as that handler's previous. A raised SIGSEGV that the guest ignores (SIG_IGN) is ignored, asChainFaultdoes, instead of reaching theSIG_DFLfallback. The install takes no lock, because it can run inside a signal handler: a guest handler registered withSA_RESETHANDresets SIGSEGV fromDispatch. One thread installs at a time, set by an atomic owner thread id, and a nested call on that thread asks the outer install to run once more instead of waiting on itself. Besides these, the only hostsigactioncallers for SIGSEGV/SIGBUS incoreare the crash report andDeliverFault(git grep -n "sigaction(\|std::signal(" -- core, tests aside; the write watch's handler is macOS-only). A guest'ssigprocmaskis emulated in libkernel and never blocks the host's SIGSEGV.Unchanged:
GuestArenaPrepareHostRead_nid_no_patchbefore reads; theGuestArena::HostWritebracket around writes.errno: the copy never touches it, so nothing needs saving.process_vm_writev's page walk.GuestCopyInUnsynced_nid_no_patchand the per-page reads inCopyGuestString_nid_no_patchgo through the sameCopyGuestBytes, so they get the new path too.VirtualQuery+memcpy), macOS (mach_vm_*), Linux on other CPUs, andGuestWritable_nid_no_patchkeep their current code.APS5_GUEST_COPY_SYSCALL=1keeps the system-call path; it is read once, on the first copy. The test that blocksprocess_vm_readvwith seccomp to pin the throw on a non-EFAULTfailure (guest_output_pointer_fault) now runs that check only on that path, in a newguest_output_pointer_fault_syscallregistration. The rest of that test runs on both paths.Measured at this PR's head
a889c2afab(the patch as tested, before the one-line test change inf5c078a51f), with a release build on an i7-13700K (Ubuntu 26.04.1, kernel 7.0, GCC 15.2). Pinned to one core, best of 7 rounds of 1M calls (20k for 64 KiB). The cells are the two values from two runs of the benchmark in one logged job:APS5_GUEST_COPY_SYSCALL=1)A failed copy costs more, about 1 µs for the signal round trip, but that only happens on a bad pointer, where today's alternative is a host crash or an error return.
strace -conguest_fault_copy_testsat the same head shows noprocess_vm_readvorprocess_vm_writevcalls on the new path, against 160,035 and 80,035 withAPS5_GUEST_COPY_SYSCALL=1.Draft, for discussion: the signal-handler approach is the part to agree on before I go further. If this goes in, the cost note in #20691 changes to cover Windows and the fallback only, and I'll update whichever of the two lands second. Possible follow-ups:
GuestCopyIn_nid_no_patchthrough #14799'sGuardedCopyandGuestArenaRecoverRead_nid_no_patch(with a guarded store forGuestCopyOut_nid_no_patch), in place ofReadProcessMemoryandVirtualQueryper call;GuestWritable_nid_no_patchas a probe through the same handler.Tested
Linux (Ubuntu 26.04.1, kernel 7.0), GCC 15.2, Ninja, Release,
-DBUILD_TESTING=ON, i7-13700K.guest_fault_copy(this path) andguest_fault_copy_syscall(APS5_GUEST_COPY_SYSCALL=1) run the same checks:falsewitherrnokept for0x10, a non-canonical address (0x8000000000000000, a #GP rather than a page fault), aPROT_NONEpage, a span running into it, and a write to a read-only page, which still reads back;false.sigaction_nid_postfix(a plain handler, anSA_SIGINFOone,SIG_IGN, a reset to the default, and anSA_RESETHANDhandler run once by a raised SIGSEGV, so the reset happens in signal context), copies from and to0x10still returnfalse. Negative control: without the twoGuestFaultCopyReinstall_nid_no_patch()calls, the plain-handler child loops on the fault until its 10 s alarm;0x10returntrue.SIG_IGNfor SIGSEGV, a raised SIGSEGV is ignored and the child exits 0. Negative control, atfa9ec0d269'sGuestFaultCopy.cpp: the child is killed (check failed at line 45);sigaction, a raised SIGBUS kills the child with SIGBUS. Negative control, with only theSIG_IGNfix and the reinstall of both signals: the child loops between the copy handler andDeliverFaultuntil its 10 s alarm (check failed at line 129).guest_output_pointer_faultand the newguest_output_pointer_fault_syscall: pass.tools/check_conventions.pypasses on the branch and this body.33364ad1eb:guest_fault_copyandguest_fault_copy_syscallpass, 3 runs of 3.fa9ec0d269: the 10 copy, fault and signal registrations (guest_fault_copy,guest_output_pointer_fault,guest_fstat_fault, each with its_syscalltwin,guest_signal_handler_mask,guest_sigvec,guest_kernel_sig_pending) pass, 3 runs of 3. Without the reinstall inResetToDefault,guest_fault_copyaborts.guest_umtx_oppasses 5 of 5 on each copy path.fa9ec0d269(ctest -j4): 5761 passed, 59 skipped, 1 failed, of 5821. The failure isagc_driver_image_table_packed_guards, described below. In that run 22 display tests (guest_video_out_*,agc_driver_gcn_display_present*,video_out_hdr_present) skipped because the shell had no display. Rerun on the desktop session, all 22 pass; they're counted as passed here.8b3b02c012(ctest -j4): 5760 passed, 59 skipped, 2 failed, of 5821.agc_driver_image_table_packed_guardsis the failure described below, andguest_umtx_opaborted once under the-j4load without captured output. Ata889c2afab, before the signal-registration change, it was 5759 passed, 59 skipped, 2 failed, of 5820:guest_fstat_faulthad a second seccomp check of the same kind asguest_output_pointer_fault's: it blocksprocess_vm_writevand expectsGuestCopyOut_nid_no_patchto throw.f5c078a51fruns it only withAPS5_GUEST_COPY_SYSCALL=1, in a newguest_fstat_fault_syscallregistration. Both registrations pass, and no other test blocks those system calls (grep -rln "SYS_process_vm_" core/libs/tests).agc_driver_image_table_packed_guards(unrecoverable packed table format was not poisoned) fails in the same way withAPS5_GUEST_COPY_SYSCALL=1on the same build, two runs each way, so it isn't from this change.mainb2779012aeagainst this patch on it (557565b461), A B A B A B. The result is 39.7 fps onmainagainst 40.25 fps here, inside the spread; details in the comment below. Expected, since that scene is bound by queue worker 0x0, not by guest copies.APS5_TRACE_SECONDS=300:30, onmaine4caa07950(A1) and on this headfa9ec0d269merged onto it (c5ada12bb1, B2 and B4).main, against 22.26 and 21.40 ms here.mainrun against two, and MGS4 varies 2 to 3.5 % from run to run, so I read it as neutral, like the A/B above.mainrun (A3) crashed at 157 s (EXIT-139) on the unchangedmainbuild. Its core wasn't kept.pr21156-mgs4-trace-e4caa07950.performance_compare.pyandtrace_digest.pyoutput is in the comment below.mainA1 then this PR B2:Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file.mdfiles or images added to the repository (attach them to this PR)Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-16T06:08:25Z.
Review: CHANGES_REQUESTED
Reviewed — changes requested
Changes are required before merge: preserve the existing SIGSEGV/SIGBUS handler chain when guest fault delivery and write-watch handlers are installed after the copy handler.
What I ran
Inspected the prepared diff and the changed implementation, call sites, signal-handler callers, and tests at head
557565b46194084e43021894b38b45c9efe03af0. No commands or tests were run; the run environment provides the review reader only. No merged-preview check was run.Results
Findings
Blocking
core/libs/prx/libc/src/specifics/linux/GuestFaultCopy.cpp:168— the copy handler replaces the current SIGSEGV/SIGBUS handler and saves it for chaining. Later,GuestWriteWatch::Watch()replaces those handlers and savesOnCopyFaultas its predecessor. Its fault handler delegates ordinary faults to that predecessor, butOnCopyFaultchains to the handler captured when the copy handler was installed, skipping any handler installed in between. If libkernel'sDeliverFaultis installed after the first checked copy, it is lost from the chain for faults that reach write-watch first; guest exception delivery can therefore be bypassed. Preserve a chain that accounts for handlers installed both before and after the copy handler, or coordinate the handler installation order. The PR's stated claim that handler order is safe does not cover this ordering.Non-blocking
None.
Sources
Not verified
No tests, build, full Linux suite, title runs, or physical-console behavior were verified. Author-reported test and benchmark results were not run by this review. Read all changed files listed in the manifest; no files were excluded by rule.
To get this to a good state
Update signal-handler chaining so handlers installed after the copy handler remain in the chain even when write-watch wraps them; then rerun the targeted copy and guest exception tests and the full Linux suite on the updated head.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-16T12:05:18Z.
Review: COMMENTED
Reviewed — comments
Nothing blocks this; the points below are optional.
What I ran
Reviewed head
fa9ec0d26942fcc018a0e34083405d57a4bfc8fausing the prepared diff and pinned reader. No test or build commands were run.Results
Findings
Blocking
None.
Non-blocking
None.
Sources
core/libs/prx/libc/CMakeLists.txt,core/libs/prx/libc/include/General.hpp,core/libs/prx/libc/include/specifics/linux/GuestFaultCopy.hpp,core/libs/prx/libc/src/General.cpp,core/libs/prx/libc/src/specifics/linux/CrashReport.cpp,core/libs/prx/libc/src/specifics/linux/GuestFaultCopy.cpp,core/libs/prx/libc/tests/cmake/guest_fault_copy.cmake,core/libs/prx/libkernel/CMakeLists.txt,core/libs/prx/libkernel/System/src/Signals.cpp,core/libs/tests/GuestFaultCopy.cpp,core/libs/tests/GuestFstatFault.cpp,core/libs/tests/GuestOutputPointerFault.cpp, anddocs/dev/ENVIRONMENT.md.Not verified
Builds and tests were not run. The test results and measurements in the description are author-reported. The review bundle lists all 13 changed files as included; no changed files were excluded.
To get this to a good state
Nothing is required. Optionally, run the Linux build and tests on this head to independently confirm the reported results.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-16T15:15:42Z.
Review: APPROVED
Reviewed — looks good
Nothing blocks this change based on the code reviewed; the reported test runs were supplied by the author and were not run here.
What I ran
Reviewed head
33364ad1ebffdf867ac414d34f56ed1c9f9170f0using the prepared diff andrepo_read.pyreader tools. No build or tests were run. The description reports Linux test runs, including copy-path tests at this head; these are author supplied.Results
Findings
Blocking
None.
Non-blocking
None.
Not verified
No changed file was excluded:
files.jsonreports no excluded files. The provided prepared diff, manifest, description, and commits were read; all 13 files markedreviewedwere read. Runtime behavior, builds, and tests were not independently verified.To get this to a good state
Nothing is required.