fix(libc): track writes to singly mapped direct memory without faults on Windows #637
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/637"
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 DotDebian on 2026-10-05T10:18:04Z.
What
Part of #361: on Windows, writes to direct memory mapped at a single guest address are now tracked without raising a fault on the guest thread.
Problem. Direct memory is mapped as section views, and
WindowsMappings::Collectwrite-protects the views it collects. The next guest write faults and is resumed by the vectored handler. Windows builds the exception frame directly belowrsp, over the System V red zone, so a leaf function resumes with its locals overwritten when its AVX state is live (mechanism and standalone reproduction in #361). The bytes are gone before any handler runs, so the fault has to be avoided.Change.
MEM_WRITE_WATCHmemory at that address ("resident").Collectreads its writes withGetWriteWatch, as it already does for flexible memory. No page is write-protected, no fault is raised.GetWriteWatchcall per run.MapAliasneeds views of it. The run is made read-only, copied into the section and replaced by views of the section, tracked by write protection as before. Nothing is copied back into live memory. A write that hits the fence, and a read or write that hits the placeholder between the release and the views, is retried by the fault handler once the views exist.sceKernelMapDirectMemoryand the unmap paths wait for the leases and host imports of every registered range that shares the run (RequireUnpinned), as an unmap of those ranges does, so no import keeps the replaced pages.SEC_RESERVE: it commits only the pages of broken runs.Not changed, still open in #361.
HandleSse4astill resumes an exception on the guest stack.Behaviour to know about.
MapAliasreturns null when a resident run of the range extends outside it, and the import falls back to copies.SEC_RESERVEpage cannot be decommitted, which is why unmapped pages are not stored in the section.CheckPinnedSharedPagesand the shared block ofagc_driver_dcc_keys_first_writenow map their memory twice, andCheckFailedCollectKeepsWritesexpects one 4 KiB page.Tested
Windows 11 Pro 10.0.26200, Intel Core Ultra 9 285K (no AVX-512, so the red zone overwrite from #361 reproduces here), RTX 5080, MinGW-w64 GCC 15.2.0. Head
dcffc098, onmain5edae353.ctest: 710 of 710 run pass, 5 skipped (fourvideo_out_flip_*,guest_video_out_wqhd_detection_no_vulkan).guest_memory,agc_host_import_second_mappingandagc_driver_dcc_keys_first_writepass 10 of 10 repeats.CheckSingleDirectMappingTracksWritesWithoutFaults(guest_memory): two writes to a singly mapped range raise no access violation and are collected as two pages; contents and tracking survive a partial unmap, a second mapping and a full unmap and remap.CheckSecondDirectMappingWaitsForLeases(guest_memory): a second mapping of a page returns only after a lease on the first mapping is dropped. Without the wait it returns at once.agc_host_import_second_mapping(agc_driver_recorder_tests --host-import-second-mapping-only): a host import of singly mapped direct memory is replaced after its first page is mapped again. Without the wait it fails withthe import of direct memory whose pages were replaced was kept.CheckBreakingAResidentRunKeepsConcurrentAccesses(guest_memory): 20 rounds; one thread writes every byte of four runs once and another reads them while the main thread maps a page of each run a second time, or unmaps it. On the previous head the reader faults; with the reader off, bytes are lost in 3 of 3 runs.CheckRemappedDirectMemoryIsChargedOnce(guest_memory): mapping, filling, unmapping and remapping 256 MiB raises the system commit by less than 384 MiB. On the previous head it fails.d6bb6c5bonly, see below) and Linux. The change is inside#ifdef _WIN32code, apart from the new tests, which are compiled out on Linux.Measured on the first version (
d6bb6c5b) on top of theastrobotbranch (b58df66c, discussion #357), not repeated since:SceSndzAudioOutMainat 12 s (eboot+0xec64b5), the crash described in #361;APS5_NO_WRITE_WATCH=1workaround.Not measured: titles that map most of their direct memory twice, and the cost of unmapping large resident ranges.
Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed in TechnicalDebt.mdfiles or images added to the repository (attach them to this PR)🤖 Generated with Claude Code
Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-05T19:45:34Z.
#650 and #652 have landed, and each conflicts with this on one line. Both resolutions keep both sides:
DirectMemory.cpp:CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_EXECUTE_READWRITE | SEC_RESERVE, ...)together with #650's error message block.GuestArena.cpp:throw OutsideArena("shared mapping", pointer, bytes);followed byWindowsMappings::Get().Map(pointer, bytes, section, offset, protection, Arena::Get().WriteWatched());.#650 also added a paragraph to
docs/user/USAGE.mdsaying the backing is "committed in full when the title allocates it, not when its pages are first used". WithSEC_RESERVEthat's no longer the case, so could you reword that sentence in the same rebase?Imported from boykopovar/AnyPS5. Originally posted by Celegans12 on 2026-10-05T20:29:16Z.
Tested
d6bb6c5bon Windows 11 Pro 10.0.26200, i9-11900H, RTX 3080 Laptop (NVIDIA 610.62), MinGW-w64 GCC 15.2.0.ctest: Release,
-DBUILD_TESTING=ON, full build,--target libs: 284/284 pass. That includes the two AGC tests that failed on your RTX 5080. With this branch'sGuestMemory.cppon main33e9a121,guest_memoryfails atGuestMemory.cpp:400(g_accessViolations == 0). On the branch it passes 10 of 10 repeats.PPSA26344 v1.008 on our integration branch, with and without this PR. It allocates 13.5 GiB of direct memory and makes 835 maps (4.7 GiB). No page is mapped twice and nothing is unmapped.
compute shader 0x800027c200: AGC driver: null or misaligned address). Neither has an access violation, so this does not test #361.0x5000000000takes under 2 s instead of about 6 s. On an idle host, the time to reach that point drops from about 22 s to about 11 s.[gpu] storage image 0x504a7c0000: guest memory changed while GPU results were pending; keeping the CPU's blocks, right afterhost import of 0x5000000000+0xd3400000. Likely cause:importAllocationimports the guest address itself (GuestBufferMemory.cpp:295,:312).MEM_WRITE_WATCHmemory sets every page's watch bit. Standalone, 64 of 64 pages are set aftervkAllocateMemory.ImportWatched(GuestMemory.cpp:1050) probably stamps all 3.3 GiB as written.Problems. Each has a standalone repro against this branch's libc/libkernel. Main's libs pass all three.
share()/cut()(WindowsMappings.hpp:124,:405,:429). These replace the pages of the whole run. An existing import of the first mapping survivesrefreshImports, because its registered range is unchanged (GuestBufferMemory.cpp:391). In a 64 KiB repro, after page 0 is mapped again:0x11111111where the CPU wrote0x22222222.cut()/share()copy the pages while they are still writable (:414,:437), then release them (:415,:440).cut()also recommits the run read-write before it copies the bytes back (:417-:419). A write from another thread in those windows does not fault, so it never reachesHandleWriteand is lost. Repro: one thread writes each slot of a 2 MiB run once while another thread maps the run's last page a second time, or munmaps it. Writes were lost in 14-16 of 20 rounds in each mode.SEC_RESERVEsection stay committed when they are mapped again as resident copies (:105-:108). Mapping, filling, unmapping and remapping 2 GiB gives +2.1 GiB private plus +2.1 GiB section. On main it is 2.1 GiB.For the
USAGE.mdrewording: running out of commit no longer fails at allocation. It fails insceKernelMapDirectMemorywithreplace guest placeholder with resident direct memory(:386). On a second mapping or a munmap, it can also fail withcommit a direct memory page(:381).Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-06T21:20:55Z.
Do you plan to address Celegans12's Windows report from 10-05 here? It found three problems, each with a repro:
cut()/share();The branch also conflicts with main in
GuestArena.cppandDirectMemory.cpp. If you'd rather stop here, please say so.Imported from boykopovar/AnyPS5. Originally posted by SP4C3B4R-8 on 2026-10-06T21:21:49Z.
Tested
d6bb6c5bon Windows 11, Ryzen 7 7800X3D (AVX-512, so this host never hit blocker B), RTX 5070 Ti, MinGW-w64 GCC 15.2.0, PPSA21564 v01.007.000. Cherry-picked cleanly ontooneandonlydean/astrobot80c8adae;APS5_HOST_IMPORT_MIB=20480 APS5_PROFILE_DRAW=1, write watching on, warm shader and pipeline caches,-lvl underwater_aerial_garden, 300 s per run.No regression here; in the level the queue 0 worker is CPU-bound on draws either way, so the frame rate there doesn't change.
Tested with AI assistance (Claude Code).
Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-07T15:49:36Z.
Review: CHANGES_REQUESTED
Thanks for the work. Not repeating @oneandonlydean's question: the three problems @Celegans12 reproduced on
d6bb6c5bare still open, and the diff confirms them. They need to be fixed before this can merge:share()/cut()(WindowsMappings.hpp:124,:405,:429) replace the pages of the whole run, but the existing import keeps its registered range. Either invalidate imports of every page in the run, or avoid touching siblings.cut()/share()copy pages while still writable (:414,:437) andcut()recommits read-write before copying back (:417-:419). A write from another thread in those windows never faults, so it is lost. Keep the pages protected (or otherwise fenced) until the copy is done.SEC_RESERVEsection stay committed once mapped again as resident copies (:105-:108). Decommit the section page after copying it out.Also:
maininGuestArena.cppandDirectMemory.cpp, anddocs/user/USAGE.mdneeds the commit-charge wording updated (as @oneandonlydean noted).CollectcallsGetWriteWatchfor resident runs even whenwatchResidentis false (:281); that memory isn'tMEM_WRITE_WATCH. Please guard it or explain why it can't happen.The test and the Windows paths can't run on Linux CI; once pushed, a Windows run of
guest_memorylinked in the PR would help.Imported from boykopovar/AnyPS5. Originally posted by Celegans12 on 2026-10-08T01:15:03Z.
@DotDebian are you still planning to work on this? It matters a lot for Ghost of Yōtei: the process now peaks at about 37 GiB private on a 32 GiB machine and pages heavily, and with this branch its commit charge dropped from 15.3 to about 7 GiB in my test on 10-05.
If you don't have time, I'd be glad to continue it: rebase onto
main(including the #650/#652 resolutions oneandonlydean described), fix the three problems from my report (the stale import after a second mapping, the lost writes incut()/share(), the double commit charge after a remap), and open it as a follow-up that keeps your commits and authorship and supersedes this one. I'll wait a day or two for your answer before starting.Imported from boykopovar/AnyPS5. Originally posted by DotDebian on 2026-10-10T15:40:03Z.
Sorry for the silence. Rebased onto
main(dcffc098) and pushed fixes for the three problems @Celegans12 reported, plus the review items.RequireUnpinned), as an unmap of those ranges does.SEC_RESERVEpage cannot be decommitted withVirtualFree, so decommitting the section page after the copy is not available. Unmapped resident pages are kept in private memory instead, released when they are mapped again or when the backing is destroyed. A page that was once in the section stays a view.Collect: resident pages are refused when the arena has no write watch.USAGE.mdreworded with the new failure messages.Cost: pages that share a run (up to 2 MiB) with a page mapped twice or partly unmapped become views and are back on the fault path. Three existing tests assumed a collect write-protects singly mapped direct memory and were adapted; details in the description.
Four new tests, each failing without its fix (a lease wait, a GPU import replaced after a second mapping, concurrent writes and reads over 20 rounds, a 256 MiB remap charged once). Windows
cteston this head: 710 of 710 run pass, 5 skipped. Astro Bot was not rerun on this head.@Celegans12 thanks for the offer and for the repros. A rerun of your three and of the Yōtei commit numbers on this head would help.
Written with AI assistance (Claude Code).
Imported from boykopovar/AnyPS5. Originally posted by orishamir on 2026-10-10T21:12:51Z.
Windows run of
dcffc098merged ontomain262c0316(3d5546c7, clean merge): Windows 11 Pro 26300, RTX 4080 (driver 616.56), WinLibs MinGW-w64 GCC 15.2.0 r7, Release,BUILD_TESTING=ON, the CIwindowsjob's configure line.Revert-pin (non-test files back to
main, the PR's tests, CMake and docs kept):agc_host_import_second_mappingfails withAGC graphics: the import of direct memory whose pages were replaced was kept, so it pins the stale-import fix.guest_memoryfails atCheckFailedCollectKeepsWrites(GuestMemory.cpp:1246in the merged tree), one of the adapted existing checks, before any of the four new checks runs. Running each new check on its own (a local env-var switch inmain(), not part of the PR):CheckSingleDirectMappingTracksWritesWithoutFaultsfails atRequire(g_accessViolations == 0)andCheckSecondDirectMappingWaitsForLeasesfails atRequire(released), so those two pin.CheckBreakingAResidentRunKeepsConcurrentAccessesandCheckRemappedDirectMemoryIsChargedOncepass without the fix, 5 of 5 runs each. That follows from whatmainis: it has no resident runs, so there is nothing to break, and it commits the direct memory section in full inCreateFileMappingW, so a remap cannot add charge. The two tests guard against thed6bb6c5bbehaviour Celegans12 reproduced, not againstmain; a reviewer who reverts the non-test files will see them pass. Worth a sentence in the description, or a variant that also fails onmainif there is one.agc_storage_baseline_settled,agc_host_import_unmap,agc_driver_dcc_keys_first_write) pass both with and without the fix.With the fix: full ctest 720 of 720 pass (6 skipped: the SDL-offscreen
video_out_flip_*and the two no-Vulkan video-out tests),guest_memory10 of 10 with--repeat until-fail:10, and the new Windows-onlyagc_host_import_second_mappingpasses on the NVIDIA driver.Head vs reviewed commit:
d6bb6c5bchanged 4 files,dcffc098changes 11 (+564/-18). Each review item is present in the merged source: resident views refuseCollectwhenwatchResidentis false (WindowsMappings.hpp:319,:398),fence resident guest pagesmakes a run read-only before it is copied (:497,breakRunat:517),RequireResidentUnpinned/RequireAliasesUnpinnedrun before the map and unmap paths inDirectMemory.cpp, the section isSEC_RESERVEwithGuestArenaForgetSection, andUSAGE.mdnow says commit happens at map time and names the three failure messages.Merges: clean onto
main262c0316. #2864 (the overlap bot's hit) merges clean on its own but conflicts intests/Recorder.cppafter this PR; whichever lands second needs a rebase.Not checked: a title run (no dump here) and Linux, where the maintainers build.
Thanks for the quick turnaround on the three problems and the rebase, @DotDebian.
AI-assisted: yes (Claude Code Fable 5.1 xhigh)
Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-10T22:12:04Z.
Thanks for the rebase and the fixes; @orishamir's Windows run of
dcffc098is a good confirmation.This one overlaps #2054, which makes the same change (singly mapped direct memory as private
MEM_WRITE_WATCHpages until it is aliased) inWindowsMappings.hpp,DirectMemory.cpp,GuestArena.cpp,CrashReport.cppandGuestMemory.cpp. The two conflict with each other inGuestArena.cpp,DirectMemory.cppandGuestMemory.cpp, so only one can land. @boykopovar @oneandonlydean: which design do you want?SEC_RESERVEsection, fenced break into views, unmapped pages kept in private memory.Open points on this PR whichever way it goes:
CheckBreakingAResidentRunKeepsConcurrentAccessesandCheckRemappedDirectMemoryIsChargedOncepass onmain(see @orishamir's revert-pin), so they don't pin the change; a variant that fails onmain, or a sentence in the description saying so, would help.Imported from boykopovar/AnyPS5. Originally posted by orishamir on 2026-10-10T22:40:11Z.
Linux evidence for
dcffc098, since CI'slinuxjob is gated on push/workflow_dispatchand never ran here. Same replica as on #374 (the CI image rebuilt locally: ubuntu:24.04, GCC 13.3, Mesa 25.2.8 llvmpipe LLVM 20.1.2, SPIRV-Tools on, CI env, write watch active), the head as pushed on its base5edae353,ctest --parallel 4 --timeout 120.libs: clean. Full suite, 701 tests, 3 runs: two pass 701/701.agc_driver_flat_store(a serial test), and not a timeout: after[gpu] recorded batch still running on the GPU after 10 sthe process ended with*** stack smashing detected ***: terminatedat 11.4 s. It did not recur in 30 serial runs of the test on this tree, 30 on the base commit with the PR reverted, or 2 further full suites on each tree (1 abort in 65 runs across both trees; our seven full runs on the #374 tree last night also passed it). Not attributable to this PR; noted because it is a stack-protector abort rather than a hang, and the repo has no report of one.GuestArena.cpp/.hpp,DirectMemory.cpp,GuestBufferMemory.cpp) is under#ifdef _WIN32or callsRequireResidentUnpinned/RequireAliasesUnpinned, whose non-Windows bodies are empty; the newGuestMemory.cpp,Recorder.cppandDccKeysFirstWrite.cppcases are_WIN32-only, andagc_host_import_second_mappingis registered underif(WIN32). So Linux here means "compiles, and nothing changed", which the clean runs confirm; the Windows runs remain the behavioural evidence.AI-assisted: yes (Claude Code Fable 5.1 xhigh)
Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-11T01:08:14Z.
#637: it's rebased, each of the three problems has a fix and a test, and it has Windows and Linux runs; #2054 still has open asks and conflicts. Two things before it can go in: it now conflicts with main in
tests/Recorder.cpp, andCheckBreakingAResidentRunKeepsConcurrentAccessesandCheckRemappedDirectMemoryIsChargedOncepass on main, so either make them fail there or say in the description that they guard the earlierd6bb6c5bbehaviour.Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-11T08:48:14Z.
Review: CHANGES_REQUESTED
Thanks for the rebase and the fixes; @orishamir's Windows and Linux runs of
dcffc098are a good confirmation. It now conflicts withmain, and one of the conflicts needs a change in your code:GuestBufferMemory.cpp(importAllocation):mainnow makesWindowsMappings::MapAliasthrowstd::runtime_erroron every refusal, and the caller catches it, adds the base tostate.unaliasedSpansand falls back to copies.MapAliasstill doesreturn nullptrwhen a resident run extends outside the range (WindowsMappings.hpp:259). Please make it throw through the samerefuse(...)helper, keep the caller as onmain, and drop theentry.alias == nullptrbranch. Without that,entry.aliasstays null after the merge.tests/Recorder.cpp: keep both--unit-shadow-only/--cmask-onlyand--host-import-second-mapping-only.CheckBreakingAResidentRunKeepsConcurrentAccessesandCheckRemappedDirectMemoryIsChargedOncepass onmain. Make them fail there, or say in the description that they guard the earlierd6bb6c5bbehaviour.We can't build or run the Windows paths here, so we didn't resolve the
MapAliaschange ourselves. This overlaps #2054 (same change, conflicting too), so only one of them can land; once this one is rebased and green on Windows it is the one with runs on several titles.Imported from boykopovar/AnyPS5. Originally posted by Mouhand-Kaddo on 2026-10-11T21:47:46Z.
Windows real-title result for head
dcffc098c, integrated with main989146c3b, #4018 and the Windows build guard #4021. Both commits from this PR were applied. Merge conflicts were resolved by retaining current main's multi-range alias handling and test command switches, and adding this PR's null-alias check and second-mapping test switch.Demon's Souls PPSA01342 v1.04 normally stops after approximately 14 s on this host with an audio DSP access violation at
DemonsSouls.exe+0x1f91a90, reading0x2f8410000. With this PR, that stop did not recur: initialization reached the main loop at 14.28 s and the run continued through shader preparation and GPU texture creation. It ended at 89.07 s with a later explicit unsupported operation:No main menu or presented frame verified. This is one bounded real-game run, not a claim that all remaining #361 paths are fixed.
The full
libsbuild succeeded.guest_memory,fiber,windows_exceptions,agc_host_import_second_mapping, andagc_driver_dcc_keys_first_write: 5/5 pass (2.72 s). Windows 11 x64, i7-13700K (AVX2, no AVX-512), RX 6900 XT, MinGW GCC 15.2 Release,ANYPS5_ENABLE_SPIRV_TOOLS=OFF(default), default write tracking and host import. No Linux tests for this comparison. Original game files preserved; no game code or payload attached. AI-assisted with Codex.Imported from boykopovar/AnyPS5. Originally posted by tibzejoker on 2026-10-13T21:48:05Z.
@DotDebian GTA V (PPSA04264) still needs this on current
main(665ad7da7). Without it, with write watch on, the title crashes in the RAGE main thread right after the save loads (access violation at eboot 0x28aacee). #5052's relink-time framing doesn't cover GTA: it frames 0 of the 875 red-zone leaves, because none of them has an RBP prologue.WindowsMappings.hpphas moved a lot sincedcffc098c: shared views now track 4 KiB subpages. Are you still planning to rebase this? If not, would you mind if we tried a port onto currentmainthat addresses the review points, with you kept as the author? We can test it on GTA either way.AI-assisted (Claude Code).
Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-14T00:10:06Z.
@tibzejoker yes, please port it onto current main and keep DotDebian as the author. The points from the 10-11 review still apply:
MapAliasthrows on every refusal on main, so thereturn nullptratWindowsMappings.hpp:259and theentry.alias == nullptrbranch go, and the two tests that already pass on main should go or be marked as guards. Aguest_memoryrun on Windows of the ported head is needed.Imported from boykopovar/AnyPS5. Originally posted by tibzejoker on 2026-10-14T00:42:18Z.
@oneandonlydean @DotDebian the port is up as #5596, on
maince5c83953. DotDebian is the author of the main commit, and our changes are separate commits. It covers the 10-11 review points (MapAliasthrows throughrefuse, thenullptrbranch is gone, and the two tests now fail onmain).guest_memoryand the full ctest (1112/1112) pass on Windows 11.AI-assisted (Claude Code).
Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-14T01:24:31Z.
Closing in favour of #5596, the port of this onto current main with DotDebian's commit kept as the author's; follow-ups go there.
Pull request closed