Skip to content

fix(agc): close the poll sleep timer when its thread exits - #22067

Merged
oneandonlydean merged 1 commit into
boykopovar:mainfrom
nicolasabosch:fix/agc-poll-sleep-timer-close
Nov 26, 2026
Merged

oneandonlydean merged 1 commit into
boykopovar:mainfrom
nicolasabosch:fix/agc-poll-sleep-timer-close

Conversation

@nicolasabosch

Copy link
Copy Markdown
Contributor

What

On Windows PollSleep created a high-resolution waitable timer in a thread_local handle that nothing closed, so every thread that polled kept one timer handle until process exit. It now sleeps through PreciseSleepWaitableTimerWithHandle(PreciseWaitThreadTimer(), ...), whose per-thread timer is closed when the thread exits; the 200 us wait is unchanged and the other platforms are untouched. This is a resource-lifetime fix; no failure was observed.

Tested

Windows 11, MinGW (GCC, Release), NVIDIA GeForce RTX 4070 Laptop GPU, no title. ctest -R '^agc_driver_(queue_zero|store_idle|idle_store|wait_|submit_progress|flip|eop_interrupts)' passed (15/15). These tests run the changed wait and none of them counts handles, so none fails on main.

Validation layer: the same tests on main (be4613d) and on this branch with VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation, VK_LOADER_DEBUG=layer, ANYPS5_NO_SHADER_CACHE=1 and ANYPS5_REQUIRE_VULKAN=1 through ctest -V (Khronos validation layer 1.4.363.1): every log shows Insert instance layer "VK_LAYER_KHRONOS_validation", none reports was not found but was requested by env var VK_INSTANCE_LAYERS, and neither run logs a VUID- error.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt and the licence notice of code adapted from upstream (see AGENTS.md)
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Fixes: none
  • Unblocks: none
  • GPUs tested: NVIDIA GeForce RTX 4070 Laptop GPU, driver 616.92, Windows 11 Pro 26300
  • AI-assisted: yes

🤖 Generated with Claude Code

PollSleep created a high-resolution waitable timer per thread and never closed it. Use the
per-thread timer of PreciseWait, which is released with the thread; the 200 us wait is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions github-actions Bot added the agc libSceAgc* label Nov 17, 2026
@github-actions

github-actions Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Some comparisons could not be completed because a pull request conflicts with the base branch. Review these shared files manually before concluding that there is no overlap.

Pull request Shared files not compared
PR 13863 core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/WaitMemory.cpp
PR 13920 core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/WaitMemory.cpp
PR 15845 core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/WaitMemory.cpp

@kurexw kurexw left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

macOS GPU test (Apple M4, MoltenVK 1.4.2, validation layer 1.4.363.1, x86-64 build under Rosetta)

Base: upstream/main a72186d + #22056 + #22074 (both needed for the macOS build); PR head 0912308e48 merged on top. Built clean (only the known libcurl link failure, #17425).
Env per AGENTS.md: ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1 VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation VK_LOADER_DEBUG=layer, ctest -R 'recorder|constant_phi|masked_select|sample_bit_descriptor|pixel_ancillary|scalar_buffer|shader_mode_registers|agc_driver_f64|command_batch|awaited_slot|agc_driver_idle|detiler' -V, 3 runs each on base and PR.

  • Every test has the same status on base and PR in all 3 runs; no new VUID- errors.
  • Every test that creates a Vulkan instance logs Insert instance layer "VK_LAYER_KHRONOS_validation"; none logs was not found but was requested. The tests without layer lines (agc_constant_phi, agc_masked_select, agc_command_batch_*, pixel_ancillary, ...) never touch the loader.
  • Same on base and PR: 11 agc_driver_f64_* tests skip (the M4 has no shaderFloat64); agc_driver_recorder fails with a kept vertex window was not mirrored (#20831); the recorder tests each log one VUID-VkDeviceCreateInfo-sType-unique for a duplicated VkPhysicalDevicePortabilitySubsetFeaturesKHR in the test's own device (#21965).
  • The PR adds no test; I could not exercise the thread-exit path directly on macOS, so this only shows no regression in the driver tests above (agc_driver_idle_*, agc_command_batch_*, the recorder tests).

AI-assisted: yes

@MarcZX10 MarcZX10 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed — looks good

The per-thread wait timer is now owned by a helper that closes it when the thread exits, and the 200 us wait is unchanged. Nothing blocks this; the points below are optional.

What I ran

  • Exact head 0912308e48560bd83b2587927b79f955d24b4785, base main. The diff was read from the review folder; the diff was not fetched again.
  • Read the changed function and its includes at the head. No build and no test run in this review.
repo_read.py search PreciseWaitThreadTimer
repo_read.py search PreciseSleepWaitableTimerWithHandle
repo_read.py cat core/libs/prx/libc/include/PreciseWait.hpp 1 70
repo_read.py cat core/libs/prx/libc/include/HostThreadLocal.hpp 1 28

Results

Check Result Note
Diff read passed One file, three new lines
Changed code read passed WaitMemory.cpp lines 1–40
Helpers read at head passed PreciseWait.hpp, HostThreadLocal.hpp
Build not run Windows-only code; no builds in this review
Author's ctest runs not run Author-reported, not repeated here

Findings

Blocking

None.

Non-blocking

  • core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/WaitMemory.cpp:25 — On Windows, PreciseWaitThreadTimer() throws std::runtime_error if FlsAlloc or FlsSetValue fails (HostThreadLocal.hpp, lines 13–18). The old code never threw there; it fell back to a plain sleep. Those failures are not expected, so this is a behaviour difference to know about, not a defect shown by the code.
  • core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/WaitMemory.cpp:25 — No test checks that the timer handle is released. The description says none of the listed tests counts handles. A test for this is optional.

Sources

Not verified

  • The Windows build and the ctest runs (15/15, and the validation-layer logs) are author-reported. They were not run here.
  • That the FLS callback closes the timer when the thread exits relies on Windows behaviour that was not tested here.
  • Lines 41 to 440 of WaitMemory.cpp are unchanged and were not read.
  • Non-Windows builds: unchanged by reading the #else branch only.

To get this to a good state

Nothing is required.

@MarcZX10

Copy link
Copy Markdown
Contributor

Reviewed — changes requested

Eight findings can break correctness or security. The main problems are stale cache reuse, stale reads after a pending write, and guest-triggered crashes in output writes. Fix these before merging.

What I ran

  • Read the automated review output for head 0912308.
  • No tests or builds were run for this review.

Results

Check Result Note
Merge risk High Stale guarded-range and pending-serial reuse, plus crashes from guest output pointers.
Security architecture High Five guest-output writes and an unbounded name size can fault or overflow. The automated rating of Minimal does not hold for these.
Inline findings 27 8 blocking, 19 non-blocking.

Findings

Blocking

  • core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleTarget.cpp:2007: GuardOneFragmentFmask adds an FMASK guard but does not bump guardedGeneration(). RequireNoMultisampleColorTarget removes retired guards without bumping it either. A table built before either change can be reused with stale exclusions. Bump the generation at both sites, as the other guard-list changes do. For removals, bump only when guards were actually removed. Keep the moveGuardSpans() calls.
  • core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp:4852: When wasLent is false, the pending serial is not bumped, even when the write adds a pending unit. A later revalidateFull can skip the imported-buffer flush and read stale bytes. Keep the previous newUnits result and bump the serial when newUnits || wasLent is true. Keep the skip for writes that add no pending units.
  • core/libs/prx/libSceFont/src/Render.cpp:567: The attribute is written through a guest pointer with a direct store. A non-writable pointer faults the emulator, and nothing recovers from that. Use Font::CopyOutGuest and return SCE_FONT_ERROR_INVALID_PARAMETER on failure, as the other output writes in this file do.
  • core/libs/prx/libSceNet/Export.cpp:3070: All three resolver output writes are now direct stores or memcpy. A bad guest pointer crashes the process instead of returning NET_EFAULT. In sceNetResolverStartNtoa, the process can also die before complete_async_lookup runs. Restore GuestCopyOut_nid_no_patch at all three sites and return fail(NET_EFAULT) on failure. Build the resolver info in a local NetResolverInfo before copying it out.
  • core/libs/prx/libSceUserService/Export.cpp:465: sceUserServiceGetUserName writes the name with memset and strncpy in both the short-buffer and the sufficient-buffer branch. An unwritable buffer faults instead of returning USER_SERVICE_ERROR_INVALID_ARGUMENT. Use the guest-copy helper in both branches and keep the existing errno handling.
  • core/libs/prx/libSceUserService/Export.cpp:468: The size limit of 1ULL << 47 was removed. A guest can pass a very large size, and the strncpy then writes past the buffer or the guest mapping. Restore the check before the copy and return USER_SERVICE_ERROR_INVALID_ARGUMENT without writing.
  • core/shader/recompiler/Optimization/src/ResourceMaterializer.cpp:2179: With GcnGuestShaders() enabled, table-selected image descriptors reach imageRecord as raw GCN words. The direct path converts the same descriptor with GcnImageWords first. Table and direct lookups can therefore decode different formats for the same descriptor. Convert the raw fallback with GcnImageWords and leave sampler records unconverted. Confirm whether normalizeRegisteredImageView needs the converted form too, and convert there only if it does.
  • core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterHelpers.hpp:301: The direct OpMemoryBarrier call ignores APS5_NO_ATOMIC_BARRIER for non-LDS updates. The documented workaround no longer disables these fences. Honor the switch for non-LDS resources and keep the resource-specific memory mask. Keep LDS fence emission independent of the switch.

Non-blocking

  • core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleTarget.cpp:1723: Readback, ColorSnapshots, and ColorSnapshotRefusals build nonuniform fixtures without the new formatless multisampled storage-image-write check. On a device without that capability, these cases fail with an escaping exception. Add the capability check using the tests' existing query, skip unsupported cases or assert the intended refusal, and keep the uniform-clear cases active.
  • core/libs/tests/GuestFstatFault.cpp:137: RequireNonEfaultFailureThrows() now runs on every Linux test run. Hosts that reject PR_SET_NO_NEW_PRIVS or PR_SET_SECCOMP fail the test. Either treat that rejection as a skip or keep the test opt-in. PreciseWait treats the same failure as non-fatal, so the two tests now behave differently.
  • core/libs/tests/GuestOutputPointerFault.cpp:130: Same invocation and same problem as the finding above. Apply the same skip or opt-in behavior here.
  • docs/dev/debt/libSceUserService.md:155: The sceUserServiceGetUserName entry changed, but no fragment under docs/dev/debt/changes/ records the change. Add a fragment that describes the removal of the host-safety fallback sentence, following the fragment format in docs/dev/TechnicalDebt.md.
  • docs/dev/debt/shader.md:54: The "Device fence after atomics" entry changes directly. The related updates at lines 64 and 293 do the same. Move all three updates into a fragment under docs/dev/debt/changes/.
  • tools/tests/test_check_conventions_blob_reads.py:27: The fixture's Git call does not disable tag signing. With tag.gpgsign=true, the call opens an editor and fails in a noninteractive run. Add -c tag.gpgsign=false next to the existing overrides.
  • tools/tests/test_check_conventions_env_reference.py:20: The fixture's Git calls have the same problem. Add tag.gpgsign=false to each call, next to the existing identity and commit-signing settings.
  • tools/tests/test_check_main_sync.py:30: Repo.git does not pass tag.gpgsign=false, so creating literal-base can require signing or an editor. Add the override to every invocation and keep the other arguments and environment.
  • core/libs/prx/libSceAgcDriver/tests/Recorder.cpp:9251: The non-local gateHookRelease can call a lambda that captures the local span. The lambda can outlive its capture. Fix the capture or its lifetime.
  • core/libs/prx/libSceAgcDriver/tests/Recorder.cpp:9310: The non-local gateHookRelease can call a lambda that captures the local created. Same fix as above.
  • core/libs/prx/libSceAgcDriver/tests/Recorder.cpp:17101: An exception can escape an entry point. Catch it there or document why it cannot be thrown.
  • core/libs/prx/libSceAgcDriver/tests/Recorder.cpp:10786: A path can leave this non-void function without a return. Add the return or fix the control flow.
  • core/libs/prx/libSceAgcDriver/tests/Recorder.cpp:10865: A path can leave this non-void function without a return. Same fix as above.
  • core/libs/prx/libSceAgcDriver/tests/Recorder.cpp:10869: A path can leave this non-void function without a return. Same fix as above.
  • core/libs/prx/libSceAgcDriver/tests/Recorder.cpp:9820: Pointer arithmetic on a null pointer if allocation fails. Check the allocation before the arithmetic.
  • core/libs/prx/libSceAgcDriver/tests/Recorder.cpp:10291: Pointer arithmetic on a null pointer if allocation fails. Same fix as above.
  • core/libs/prx/libSceAgcDriver/tests/Recorder.cpp:13216: Pointer arithmetic on a null pointer if allocation fails. Same fix as above.
  • core/libs/prx/libSceAgcDriver/tests/Recorder.cpp:13402: Pointer arithmetic on a null pointer if allocation fails. Same fix as above.
  • core/libs/prx/libSceAgcDriver/tests/Recorder.cpp:15883: Pointer arithmetic on a null pointer if allocation fails. Same fix as above.

Not verified

  • No tests or builds were run, so none of the changes were executed.
  • The Recorder.cpp reports were not checked against the code. The report output was cut off, so the list may be incomplete.
  • The security rating of Minimal says the removed Linux fault hook creates no new crash path. I did not confirm that. The export findings above point the other way.
  • I did not reproduce the guest-triggered faults in the font, network, and user-service exports on a real host.
  • I did not confirm the runtime effect of the guarded-generation and pending-serial defects. The findings come from reading the code.
  • The seccomp test behavior on CI hosts is unknown. I did not check which hosts deny the filter.
  • Some checks on the documentation text did not finish, so some doc issues may be missing.
  • I relied on the input for the documented behavior of APS5_NO_ATOMIC_BARRIER.

To get this to a good state

Fix the eight blocking findings first. Bump the guarded generation and the pending serial at the sites named above. Restore the guest-copy writes in the font, network, and user-service exports. Restore the name-size check, convert the GCN table descriptors, and honor the atomic-barrier switch for non-LDS updates. Then rerun the full test suite on a host that allows the seccomp filter and one that denies it. Run one device case without formatless multisample writes. After that, add the debt fragments, set tag.gpgsign=false in the three test fixtures, and resolve the Recorder.cpp reports.

@kiwe147

kiwe147 commented Nov 21, 2026

Copy link
Copy Markdown

Tested head 0912308e48, applied with git apply on main fd4aeed483 together with the other 29 PRs of one batch (#24470, #24601, #17439, #17546, #21117, #21261, #21741, #21995, #22398, #23111, #23346, #23864, #24377, #24475, #24556, #14106, #14109, #19966, #20050, #20161, #20622, #21237, #22215, #22764, #22884, #22938, #23745, #24399, #24460). All applied without conflicts and the whole tree built.

Setup: Windows 11 Pro 10.0.26200, Ryzen 7 9800X3D, WinLibs GCC 15.2.0 r7, Release, BUILD_TESTING=ON. GPUs: NVIDIA GeForce RTX 3080 (driver 621.24) and the AMD Radeon iGPU of the CPU (gfx1036, driver 32.0.21036.18). No validation layer. iGPU run: ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1 ANYPS5_GPU="AMD Radeon", agc_/video tests only.

tests RTX 3080 iGPU
none: no test of its own in this PR - -

Whole batch: the full ctest -j 12 (6525 tests) on the RTX 3080 has 5 failing tests; the 4 that also fail on main fd4aeed483 are agc_driver_stencil_plane_memory, agc_driver_msaa_dcc_unwatch, agc_storage_write_back_host_retile, and pr_overlap_names, which needs a newer Python than my 3.10. Traced to other PRs of the batch, each by reverting it and testing again: #21117 (guest_pad); none is in this PR's area. The 2125 agc_/video tests on the iGPU have 1 failing: agc_driver_stencil_plane_memory (agc_driver_stencil_plane_memory also fails on main).

This is one combined tree, not a run of this PR alone.

AI-assisted: yes (Claude Code)

@oneandonlydean
oneandonlydean merged commit 00e4860 into boykopovar:main Nov 26, 2026
14 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agc libSceAgc*

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants