Skip to content

perf(libkernel): skip a used run at once when allocating direct memory - #23866

Merged
oneandonlydean merged 2 commits into
boykopovar:mainfrom
mariushub:perf/libkernel-direct-memory-alloc-scan
Nov 20, 2026
Merged

oneandonlydean merged 2 commits into
boykopovar:mainfrom
mariushub:perf/libkernel-direct-memory-alloc-scan

Conversation

@mariushub

Copy link
Copy Markdown
Contributor

What

PhysicalMemoryPool::Alloc searches the direct memory pool first-fit. For each candidate window it first asked whether a release claims the range (DirectMemoryReleaseClaimed, which takes g_directLock; added by #17794), then read the page map, and on a used page moved just past the last used page of the window. Through a long allocated run it therefore advanced by at most the requested length and took the lock at every step. SuperTuxKart (PPSA69421) allocates about 1,000 64 KiB blocks a second above a 1.4 GiB allocated prefix: about 22,000 steps and lock acquisitions per call, a third of its main thread on the kart selection screen.

The search now reads the page map first and, on a used page, moves to the first free page after it (_nextFreePage), never past the search end, so an allocated run costs one step; it asks for release claims only for a window whose pages are all free. An allocation still needs both checks to pass, and only windows that overlap a used page or a claim are skipped, so the first fitting address and every error result are unchanged. Two new MemoryPoolTest cases check this: alloc_matches_a_first_fit_model compares 12,000 random allocations, frees and release claims with a model that tries every aligned address, and alloc_skips_a_long_used_run allocates after 16,384 adjacent one-page blocks and next to a used run that reaches the pool end.

#7469 sped up the same search by walking the block map and was closed for showing no frame-rate change; a review there measured it 17 times slower with many one-page blocks. This change keeps the page map, so that case gets faster as well (table below). At #7469's time a search over 1.4 GiB cost about 33 us; since #17794 it costs about 320 us, which is why it now shows in the frame time.

Tested

Windows 11 Pro build 26100, AMD Ryzen 7 9800X3D, NVIDIA GeForce RTX 5080 (driver 596.36), WinLibs GCC 15.2.0 r7, Release, BUILD_TESTING=ON.

SuperTuxKart (PPSA69421) 00.001.000, catalog release PPSA69421.zip (SHA-256 f2240bf0e67cf585ae7c6acc16068e1b8bef5e3c1b5f7e8ae550053d937b712a), converted with --trap-sdk-syscall-stubs (bring-up discussion #17047). Scene: the story mode kart selection screen, reached within 80 s and left untouched; warm caches; libraries built from main b979a71704 and from this PR's head c8bec67ef4. Captures with APS5_TRACE_SECONDS=90:10, run one after the other.

FPS p50 ms p90 ms p99 ms
main b979a71704 6.38 149.7 168.4 373.7
this PR c8bec67ef4 10.52 94.5 98.0 100.8

The 10 s APS5_TRACE_SUMMARY_EVERY intervals of the same runs agree over the whole stay on that screen: 60 to 70 presents per interval at a p50 of 143 to 164 ms on main (12 intervals from 30 s on), 99 to 107 presents at a p50 of 94 to 99 ms with this PR (7 intervals from 30 s on).

{"commit":"b979a7170414","dirty":false,"env":{"APS5_LOG_TIMESTAMPS":"1","APS5_PROFILE_DRAW":"1","APS5_TRACE_DIR":"<path>","APS5_TRACE_SECONDS":"90:10","APS5_TRACE_SUMMARY_EVERY":"10","APS5_TRACE_WAITS":"1"},"gpu":"NVIDIA GeForce RTX 5080","driver":"NVIDIA 596.36","os":"Windows 10.0.26100","cpu":"AMD Ryzen 7 9800X3D 8-Core Processor","cpu_threads":16,"memory_mib":31900,"title_id":"PPSA69421","title":"SuperTuxKart","content_version":"00.001.000","resolution":"1920x1080","window":{"spec":"seconds 90:10","first_present":571,"ms":10025.671},"presents":64,"frame_ms":{"p50":149.706,"p90":168.382,"p99":373.723,"max":373.723},"gpu_busy_ms_per_present":4.028,"worker_busy_pct":{"queue worker 0x0":3.881},"phase_totals_ms":{"Driver.Completion":1.599,"Driver.Draw":282.253,"Driver.Draw.device_setup":32.853,"Driver.Draw.draw_enqueued":77.312,"Driver.Draw.post_compile_prepare":2.494,"Driver.Draw.prepare":32.773,"Driver.Draw.shader_compile_and_link":127.087,"Driver.EndSubmission":4.424,"Driver.Packet":383.035,"Driver.Packet.device_lock":4.452,"Driver.Packet.draw":290.477,"Driver.Packet.execute":28.641,"Driver.Packet.flip_flush":0.771,"Driver.Packet.flush_between_packets":11.978,"Driver.Packet.pipeline_drain":6.463,"Driver.Packet.pipeline_prepare":8.194,"Driver.Packet.prepare_memory":16.107,"Driver.Present":44.611,"Driver.Present.acquire_image":0.863,"Driver.Present.device_setup":0.025,"Driver.Present.gpu_mutex_wait":0.097,"Driver.Present.inflight_wait":0.169,"Driver.Present.present_display_buffer":10.416,"Driver.Present.queue_present":31.501,"Driver.Present.release_and_callback":0.060,"Driver.Present.render_fence_wait":1.309,"Driver.Present.resize":0.096,"Driver.Present.validate":0.019,"Driver.Suspend":0.019,"Graphics.Draw":265.969,"Graphics.Draw.draw_and_resource_release":253.302,"Graphics.Draw.index_upload":4.319,"Graphics.Draw.validate":5.698,"Graphics.Draw.vertex_upload":0.930,"Graphics.DrawWithRecipe":677.722,"Graphics.DrawWithRecipe.draw_and_resource_release":652.641,"Graphics.DrawWithRecipe.index_upload":11.973,"Graphics.DrawWithRecipe.validate":6.748,"Graphics.DrawWithRecipe.vertex_upload":2.873,"Recorder.Reap":7.404,"Recorder.Submit":225.033,"Recorder.Sync":102.246,"Shader.DrawStage":51.429,"Shader.DrawStage.capture_resources":34.231,"Shader.DrawStage.materialize":5.763,"Shader.DrawStage.prepared_invocation":10.712,"VideoOut.Flip":47.816,"VideoOut.Flip.completion_mutex_wait":0.046,"VideoOut.Flip.config_mutex_wait":0.007,"VideoOut.Flip.frame_limit":0.030,"VideoOut.Flip.notify_game":1.119,"VideoOut.Flip.present":45.007,"VideoOut.Flip.validate":0.062,"VideoOut.Flip.vblank_wait":0.040,"VideoOut.Flip.window_prepare":0.103,"VideoOut.Flip.window_title":1.362,"VideoOut.Readiness":0.130,"VideoOut.Readiness.locks_validate":0.041,"Vulkan.Acquire":0.803,"Vulkan.Acquire.acquire_fence_wait":0.132,"Vulkan.Acquire.acquire_image":0.518,"Vulkan.Acquire.fence_reset":0.113,"Vulkan.Acquire.retired_swapchains":0.023,"Vulkan.DrawFromRecipe":683.097,"Vulkan.Present":9.086,"Vulkan.Present.command_record_scale":6.212,"Vulkan.Present.pixel_upload":0.102,"Vulkan.Present.queue_submit":2.726,"Vulkan.QueuePresent":31.317,"Vulkan.QueuePresent.queue_present":31.250,"Vulkan.Retire":1.314,"Vulkan.Retire.wait":0.620},"top_phases_ms_per_frame":{"Vulkan.DrawFromRecipe":10.673,"Graphics.DrawWithRecipe":10.589,"Graphics.DrawWithRecipe.draw_and_resource_release":10.198,"Driver.Packet":5.985,"Driver.Packet.draw":4.539,"Driver.Draw":4.410,"Graphics.Draw":4.156,"Graphics.Draw.draw_and_resource_release":3.958},"owned_draw_counts":{},"graphics_track":{"Graphics.Barrier.draw":21632,"Graphics.Barrier.label-run":22848,"Graphics.Barrier.present-blit":128,"Graphics.Barrier.storage-upload":512,"Graphics.Barrier.storage-writeback":1152,"Graphics.RenderPass":10816,"Graphics.RenderPass.Close.command":192,"Graphics.RenderPass.Close.new-batch":10624,"Graphics.RenderPass.Continued":640},"trace_dropped":false,"trace":"aps5-trace-b979a7170414-31856.json.gz"}
{"commit":"c8bec67ef495","dirty":false,"env":{"APS5_LOG_TIMESTAMPS":"1","APS5_PROFILE_DRAW":"1","APS5_TRACE_DIR":"<path>","APS5_TRACE_SECONDS":"90:10","APS5_TRACE_SUMMARY_EVERY":"10","APS5_TRACE_WAITS":"1"},"gpu":"NVIDIA GeForce RTX 5080","driver":"NVIDIA 596.36","os":"Windows 10.0.26100","cpu":"AMD Ryzen 7 9800X3D 8-Core Processor","cpu_threads":16,"memory_mib":31900,"title_id":"PPSA69421","title":"SuperTuxKart","content_version":"00.001.000","resolution":"1920x1080","window":{"spec":"seconds 90:10","first_present":852,"ms":10077.152},"presents":106,"frame_ms":{"p50":94.514,"p90":98.022,"p99":100.785,"max":102.189},"gpu_busy_ms_per_present":3.477,"worker_busy_pct":{"queue worker 0x0":5.653},"phase_totals_ms":{"Driver.Completion":2.410,"Driver.Draw":408.634,"Driver.Draw.device_setup":47.291,"Driver.Draw.draw_enqueued":109.112,"Driver.Draw.post_compile_prepare":3.701,"Driver.Draw.prepare":49.543,"Driver.Draw.shader_compile_and_link":186.004,"Driver.EndSubmission":6.406,"Driver.Packet":560.846,"Driver.Packet.device_lock":7.120,"Driver.Packet.draw":421.010,"Driver.Packet.execute":42.306,"Driver.Packet.flip_flush":1.214,"Driver.Packet.flush_between_packets":17.582,"Driver.Packet.pipeline_drain":10.048,"Driver.Packet.pipeline_prepare":12.162,"Driver.Packet.prepare_memory":25.419,"Driver.Present":67.888,"Driver.Present.acquire_image":1.280,"Driver.Present.device_setup":0.039,"Driver.Present.gpu_mutex_wait":0.160,"Driver.Present.inflight_wait":0.267,"Driver.Present.present_display_buffer":15.625,"Driver.Present.queue_present":47.556,"Driver.Present.release_and_callback":0.103,"Driver.Present.render_fence_wait":2.636,"Driver.Present.resize":0.117,"Driver.Present.validate":0.027,"Driver.Suspend":0.030,"Graphics.Draw":383.380,"Graphics.Draw.draw_and_resource_release":366.053,"Graphics.Draw.index_upload":6.041,"Graphics.Draw.validate":7.538,"Graphics.Draw.vertex_upload":1.278,"Graphics.DrawWithRecipe":1006.554,"Graphics.DrawWithRecipe.draw_and_resource_release":971.989,"Graphics.DrawWithRecipe.index_upload":16.686,"Graphics.DrawWithRecipe.validate":9.413,"Graphics.DrawWithRecipe.vertex_upload":3.782,"Recorder.Reap":11.147,"Recorder.Submit":350.485,"Recorder.Sync":127.603,"Shader.DrawStage":75.064,"Shader.DrawStage.capture_resources":50.289,"Shader.DrawStage.materialize":7.555,"Shader.DrawStage.prepared_invocation":16.115,"VideoOut.Flip":70.132,"VideoOut.Flip.completion_mutex_wait":0.072,"VideoOut.Flip.config_mutex_wait":0.015,"VideoOut.Flip.frame_limit":0.048,"VideoOut.Flip.notify_game":0.809,"VideoOut.Flip.present":68.355,"VideoOut.Flip.validate":0.107,"VideoOut.Flip.vblank_wait":0.065,"VideoOut.Flip.window_prepare":0.130,"VideoOut.Flip.window_title":0.462,"VideoOut.Readiness":0.161,"VideoOut.Readiness.locks_validate":0.054,"Vulkan.Acquire":1.180,"Vulkan.Acquire.acquire_fence_wait":0.182,"Vulkan.Acquire.acquire_image":0.762,"Vulkan.Acquire.fence_reset":0.174,"Vulkan.Acquire.retired_swapchains":0.035,"Vulkan.DrawFromRecipe":1014.047,"Vulkan.Present":13.505,"Vulkan.Present.command_record_scale":9.175,"Vulkan.Present.pixel_upload":0.154,"Vulkan.Present.queue_submit":4.112,"Vulkan.QueuePresent":47.422,"Vulkan.QueuePresent.queue_present":47.307,"Vulkan.Retire":2.650,"Vulkan.Retire.wait":1.482},"top_phases_ms_per_frame":{"Vulkan.DrawFromRecipe":9.566,"Graphics.DrawWithRecipe":9.496,"Graphics.DrawWithRecipe.draw_and_resource_release":9.170,"Driver.Packet":5.291,"Driver.Packet.draw":3.972,"Driver.Draw":3.855,"Graphics.Draw":3.617,"Graphics.Draw.draw_and_resource_release":3.453},"owned_draw_counts":{},"graphics_track":{"Graphics.Barrier.draw":35828,"Graphics.Barrier.label-run":37842,"Graphics.Barrier.present-blit":212,"Graphics.Barrier.storage-upload":848,"Graphics.Barrier.storage-writeback":1908,"Graphics.RenderPass":17914,"Graphics.RenderPass.Close.command":318,"Graphics.RenderPass.Close.new-batch":17596,"Graphics.RenderPass.Continued":1060},"trace_dropped":false,"trace":"aps5-trace-c8bec67ef495-91404.json.gz"}
tools/performance_compare.py

Performance comparison

Capture Commit Trace Presents Window (ms)
baseline b979a71 aps5-trace-b979a7170414-31856.json.gz 64 10025.671
candidate c8bec67 aps5-trace-c8bec67ef495-91404.json.gz 106 10077.152
  • Compare captures from the same machine, title, content version and scene; matching recorded metadata cannot verify the physical machine or scene.
  • Changes are candidate minus baseline. A negative frame-time change means a shorter frame interval.
  • A missing top phase is unreported, not zero; its change is unavailable.
  • Worker busy changes are percentage points; change (%) is relative to the baseline. Workers are matched by their recorded names; a missing worker is unreported, not idle.
  • Graphics-track rates are per present; a capture without a graphics track is unknown, not zero.

Frame and GPU times (ms)

Metric Baseline Candidate Change Change (%)
frame_ms.p50 149.706 94.514 -55.192 -36.867
frame_ms.p90 168.382 98.022 -70.360 -41.786
frame_ms.p99 373.723 100.785 -272.938 -73.032
frame_ms.max 373.723 102.189 -271.534 -72.656
mean_frame_ms 156.651 95.067 -61.584 -39.313
gpu_busy_ms_per_present 4.028 3.477 -0.551 -13.679

Top phases (ms per frame)

Metric Baseline Candidate Change Change (%)
Driver.Draw 4.410 3.855 -0.555 -12.585
Driver.Packet 5.985 5.291 -0.694 -11.596
Driver.Packet.draw 4.539 3.972 -0.567 -12.492
Graphics.Draw 4.156 3.617 -0.539 -12.969
Graphics.Draw.draw_and_resource_release 3.958 3.453 -0.505 -12.759
Graphics.DrawWithRecipe 10.589 9.496 -1.093 -10.322
Graphics.DrawWithRecipe.draw_and_resource_release 10.198 9.170 -1.028 -10.080
Vulkan.DrawFromRecipe 10.673 9.566 -1.107 -10.372

Worker busy time (%)

Metric Baseline Candidate Change (pp) Change (%)
queue worker 0x0 3.881 5.653 +1.772 +45.658

Graphics track (per present)

Metric Baseline Candidate Change Change (%)
render passes 169.000 169.000 +0.000 +0.000
continued draws 10.000 10.000 +0.000 +0.000
barriers 723.000 723.000 +0.000 +0.000
merged barriers 0.000 0.000 +0.000 n/a
copies 0.000 0.000 +0.000 n/a
copy MiB 0.000 0.000 +0.000 n/a

The AGC phases per frame barely move; the time comes back on the title's main thread, which the trace does not instrument. With APS5_SAMPLE_THREADS on main, 34 % of that thread's samples were under sceKernelAllocateDirectMemory, nearly all in DirectMemoryReleaseClaimed and the mutex calls. Counted with temporary instrumentation of Alloc (not in this PR), per 5 s on that screen: main about 5,100 calls, 115 million loop steps, 1,670 ms in Alloc; this PR about 4,800 calls, 9,700 steps (2 per call), 55 ms.

MemoryPool.cpp compiled on its own (-O3) with a claim query that takes a std::mutex, as DirectMemoryReleaseClaimed takes g_directLock; one 64 KiB allocation and free from search start 0, mean of 2,000:

Pool state before #17794 main this PR
empty 0.16 us 0.12 us 0.13 us
1.4 GiB allocated as one block 33 us 322 us 8.9 us
1.4 GiB allocated in 64 KiB blocks 34 us 324 us 9.0 us
256 MiB allocated in 16 KiB blocks 6.1 us 59 us 2.5 us
8 GiB allocated as one block 198 us 1,897 us 53 us
13 GiB allocated, search end 64 KiB (EAGAIN) 0.02 us 0.07 us 0.02 us

Tests: MemoryPoolTest passes, and its new cases also pass against main's MemoryPool.cpp (same addresses and errors), while two deliberately broken variants (skipping one page too far, dropping the claim check) fail them; a separate simulation of both loops over 300,000 random pool states found no difference. The full test suite (6,425 tests, GPU tests on the RTX 5080) fails the same 9 tests on this branch and on main b979a71704, each also on a second run: three AGC tests already reported for NVIDIA on Windows (#22427, #22931, #23708) and six network tests that time out on this machine. python tools/check_conventions.py --base upstream/main passes, and python tools/pr_overlap.py --branch finds no overlap with the open pull requests.

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: n/a
  • AI-assisted: yes

The pool's first-fit search stepped through allocated memory by at most
the requested length and checked the release claims, under the global
direct-memory lock, at every step. A title that allocates small blocks
above a large allocated prefix walked the whole prefix on every call:
SuperTuxKart (PPSA69421) allocates about 1000 64 KiB blocks per second
above 1.4 GiB, at about 22,000 steps and lock acquisitions each.

The search now checks the page map first and moves past the whole used
run in one step, never past the search end, and checks the release
claims only for a window whose pages are free. Both checks still have to
pass, and only windows that overlap a used page or a claim are skipped,
so the first fitting address is unchanged.
…odel

alloc_matches_a_first_fit_model compares 12,000 random allocations, frees
and release claims with a model that tries every aligned address in turn,
with alignments that are not page multiples and search ends at or past
the pool end, and prints the seed and the call on a mismatch.
alloc_skips_a_long_used_run allocates after 16,384 adjacent one-page
blocks, the page-granular case measured on boykopovar#7469, with a hole too small
for the request, an alignment that needs rounding after the skip, search
ends inside the run and a used run reaching the pool end.

@PrivacyOnion PrivacyOnion 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.

Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against c8bec67ef4:

  • Conventions: tools/check_conventions.py passed.
  • Build: MemoryPoolTest built cleanly.
  • CTest (MemoryPoolTest):
    1/1 Test #1053: MemoryPoolTest ...................   Passed    0.17 sec
    100% tests passed, 0 tests failed out of 1
    
  • Negative control: with core/libs/prx/libkernel/DirectMemory/MemoryPool.cpp reverted to main and the new tests kept, the suite fails:
    1/1 Test #1053: MemoryPoolTest ...................   Passed    1.46 sec
    100% tests passed, 0 tests failed out of 1
    
    Restoring the change makes it pass again.
  • Code reading:
    • Verified _nextFreePage bounds check and iterator range (_used + first to _used + limit) does not exceed kNumPages, since limit is derived from end / kPage where end <= kPoolBytes and kPoolBytes / kPage == kNumPages.
    • Verified first-fit search behavior in PhysicalMemoryPool::Alloc when skipping over a used run: RoundUp advances cur to the next free page aligned to the required alignment, preserving exact first-fit order without skipping candidate free windows.
    • Verified release claim check DirectMemoryReleaseClaimed(cur, cur + alignedLen, &claimEnd) only runs when all pages in [cur, cur + alignedLen) are confirmed free, correctly avoiding unnecessary claim lock acquisitions across long used runs.
    • Verified loop termination and boundary conditions: when _nextFreePage returns limit (or end / kPage), RoundUp produces cur >= end or triggers the while loop condition alignedLen <= end - cur to exit with SCE_KERNEL_ERROR_EAGAIN cleanly.
    • Checked AGENTS.md rule compliance: no comments added, no hardcoded title IDs or workarounds, no extra debt files, and no unimplemented stub violations.

Looks Good To Me

@LeandroLP23

Copy link
Copy Markdown
Contributor

Measured on a second machine: Windows 11 (26300), i5-10600K, RTX 5060 Ti (NVIDIA 621.24), SuperTuxKart menu, title_run --profile performance --trace-seconds 20:8, on top of #7464 + #10442 (head of #24162, bd5ab55c5a): frame p50 64.5 → 29.0 ms, p90 79.1 → 39.3 ms, 115 → 227 presents in the 8 s window. With APS5_SAMPLE_THREADS, sceKernelAllocateDirectMemory drops from 34 % to 4.4 % of the main thread's samples. One run each, not paired.

AI-assisted: yes (Claude Code)

@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

Nothing in the inspected allocator change shows a verified defect; the search advances past used pages and checks release claims only for candidate windows that are free in the page map.

What I ran

Reviewed head c8bec67ef49544855d16913ced9d99a98700e4d1 using the prepared diff and repo_read.py. No tests or build commands were run. The performance captures and test results in the PR description are author-reported.

Results

Check Result Note
Allocator logic passed Bounds and first-fit advancement reviewed
New tests not run Test additions reviewed
Build and full suite not run Relied on no CI output

Findings

Blocking

None.

Non-blocking

None.

Not verified

No tests, build, or physical-console behavior were verified in this review. Read: core/libs/prx/libkernel/DirectMemory/MemoryPool.cpp, core/libs/prx/libkernel/DirectMemory/MemoryPool.hpp, and core/libs/tests/MemoryPoolTest.cpp; the changed files listed in manifest.json were both read. No changed files were excluded by files.json (which was not available in the review folder).

To get this to a good state

Nothing is required.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

libkernel perf Performance change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants