Skip to content

Rosetta direct path: build libSceAgc, libSceAgcDriver and libSceVideoOut on Metal for x86_64 - #397

Merged
RINNECODER merged 3 commits into
mainfrom
rosetta/metal-gpu-libs
Oct 11, 2026
Merged

RINNECODER merged 3 commits into
mainfrom
rosetta/metal-gpu-libs

Conversation

@RINNECODER

Copy link
Copy Markdown
Owner

Summary

Phase 3 (graphics) of the Rosetta direct path (docs/design/rosetta-direct-execution.md). With -DANYPS5_ROSETTA_LIBS=ON -DCMAKE_OSX_ARCHITECTURES=x86_64, libSceAgc, libSceAgcDriver and libSceVideoOut now build for x86_64 on the fork's Metal backend and are NID-patched. They are removed from ANYPS5_ROSETTA_EXCLUDED_LIBS (first line only).

  • cmake/RosettaGraphics.cmake (fork-only, included by RosettaLibs.cmake):
    • libSceAgcDriver is built from the upstream exports that do not need the Vulkan driver (Eq, Resource, State, Submit), plus the native Metal execution set (the same one MetalReplay links), the SPIR-V to MSL bridge (SPIRV-Cross) and the shader recompiler, all built for x86_64.
    • libSceVideoOut keeps its upstream sources except the SDL window.
    • libSceAgc builds from its upstream CMakeLists through the generic loop.
    • AnyPS5Utilities.metallib is copied next to the libraries.
  • No TCG translation (Execution/Metal/DirectDriver.mm, fork-only):
    • On first use, the Metal driver configures itself with the system device, the utility metallib, and EOP interrupts delivered to the AGC event queues.
    • It borrows the libc guest allocation registry as identity BorrowedRanges. The ranges are refreshed when the registry generation changes.
    • MetalGuestHostAliases then aliases those host pages with no copy.
  • NativeGuestMemory gets an optional process-wide range provider. Guest threads that validate buffers outside a driver scope (for example VideoOut buffer registration or multi-submit arrays) resolve against the same identity ranges. There is no provider in core/cpu, so its behaviour is unchanged.
  • Submissions: packet descriptors are read as host pointers. Command words built outside guest memory (VideoOut's flip packet on a thread stack) are staged in a driver-owned range before the driver captures them.
  • libSceVideoOut/src/DirectDisplayWindow.mm (fork-only) replaces the SDL window:
    • It uses the native host window (AppKit window + CAMetalLayer), created and pumped asynchronously on the main dispatch queue.
    • Until that window exists, frames go to an offscreen CAMetalLayer.
    • SDL keeps game controllers on its offscreen video driver.
    • ANYPS5_FRAME_CAPTURE_DIR capture works unchanged.
    • Contract for the launcher: the guest runs off the main thread, and the main dispatch queue is serviced, as in the native runner.
  • Shared-file edits are minimal and Apple/fork-only:
    • EntryPoints.cpp has new lines inside the existing ANYPS5_METAL_BACKEND blocks, under ANYPS5_ROSETTA_DIRECT.
    • MetalHostExports.cpp has its mmap stub guarded.
    • MetalDriver gets OnDriverWorkerThread().
    • Linux and Windows code paths are untouched.
  • CI: the Rosetta job also initializes SPIRV-Cross, SPIRV-Headers, Vulkan-Headers and glslang. It builds metal_utility_tests and rosetta_direct_graphics_tests and runs them.

Evidence (local, macOS arm64 host, x86_64 build, run under arch -x86_64)

Build: cmake --build … --target libSceAgcDriver libSceAgc libSceVideoOut rosetta_patch_libSceAgcDriver rosetta_patch_libSceAgc rosetta_patch_libSceVideoOut rosetta_metallib succeeded, with no undefined symbols in the three libraries:

OK: …/rosetta/libs/libSceAgc.prx
OK: …/rosetta/libs/libSceAgcDriver.prx
OK: …/rosetta/libs/libSceVideoOut.prx

New direct-path test (ctest -R rosetta_direct_graphics: Passed):

ok: map direct memory
ok: mapped direct memory is a writable identity range of the Metal driver
ok: a guest thread outside the driver validates guest memory against the identity ranges
ok: submit the clear
ok: the Metal driver cleared the whole display buffer
ok: open the video output
ok: the native window opens on the main thread
ok: register the display buffer
ok: flip the cleared buffer
{"event":"frame_captured",…,"width":3456,"height":2104,"nonblack_ratio":0.9444,"distinct_colors":2,"guest_width":1280,"guest_height":720}
capture …png: 3456x2104, center rgb 224 128 32
rosetta direct graphics: clear + flip presented and captured

Existing Metal fixtures built for x86_64 in this configuration: metal_utility_tests passed. That covers texture detile, colour transfer, mesh arguments, sample counter, presentation, guest memory, converted shader pipeline and shader alignment.

Not in this PR / blocked elsewhere

  • The libc and libkernel link gaps on main block the test here and in CI until they are fixed. I worked around them locally with uncommitted stubs:
    • libc.prx is missing GuestArenaCommit/Reset_nid_postfix; unit deps is fixing this.
    • libkernel.prx has an inline-asm call to Aps5GetcontextFinish_nid_no_patch that is missing the Mach-O _ prefix (UserContext.cpp).
  • Patched libraries do not load yet. Every patched prx, including the existing libkernel.prx and libScePad.prx, fails dlopen with Symbol not found: ___stack_chk_guard (bound to libc.prx, whose export the patcher renames). That is runtime/patcher work. The in-process test links the unpatched builds.
  • The GuestMetal replay fixtures (ANYPS5_METAL_GUEST_REPLAY) belong to the utilities-only build mode and are not built here.
  • Not wired yet:
    • window events (close request, keyboard and mouse) from the native window into VideoOut input;
    • per-submit range refresh cost (phase 4: batch the write watch).

🤖 Generated with Claude Code

https://claude.ai/code/session_01DgW4n3qYgi5jAAohEmXRQj

… Metal for x86_64

Phase 3 (graphics) of the Rosetta direct path. Under ANYPS5_ROSETTA_LIBS the
three graphics libraries now build for x86_64 and are NID-patched like the
rest; they are no longer in ANYPS5_ROSETTA_EXCLUDED_LIBS.

A fork-only cmake/RosettaGraphics.cmake defines libSceAgcDriver from the
upstream exports that do not need the Vulkan driver (Eq, Resource, State,
Submit) plus the fork's native Metal execution, the SPIR-V to MSL bridge
(SPIRV-Cross) and the shader recompiler, all built for x86_64. libSceVideoOut
keeps its upstream sources except the SDL window; libSceAgc builds from its
upstream CMakeLists. AnyPS5Utilities.metallib is copied next to the libraries.

Guest pointers are host pointers on this path, so there is no TCG translation:
- DirectDriver.mm configures the Metal driver on first use (system device,
  utility metallib, EOP interrupts to the AGC event queues) and hands it the
  libc guest allocation registry as identity BorrowedRanges, refreshed when
  the registry generation changes.
- NativeGuestMemory gets an optional process-wide range provider, so guest
  threads validating buffers outside a driver scope resolve against the same
  identity ranges. Without a provider (core/cpu) nothing changes.
- Submission descriptors are read as host pointers; host-built command words
  (VideoOut's flip packet on a thread stack) are staged in a driver-owned range.
- DirectDisplayWindow.mm replaces the SDL window with the native host window
  (AppKit + CAMetalLayer), created and pumped on the main dispatch queue, with
  an offscreen CAMetalLayer until it exists. SDL keeps game controllers on its
  offscreen video driver. Frame capture (ANYPS5_FRAME_CAPTURE_DIR) is unchanged.

rosetta_direct_graphics_tests (arch -x86_64) maps direct memory through
libkernel, checks it is an identity range, submits a DMA_DATA clear through
sceAgcDriverSubmitMultiDcbs, flips it into the native window through
libSceVideoOut and checks the captured PNG shows the clear colour.
metal_utility_tests is built x86_64 in the same configuration. The CI Rosetta
job initializes the graphics submodules and runs both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DgW4n3qYgi5jAAohEmXRQj
@coderabbitai

coderabbitai Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

Important

  • 🔍 Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: fe5512f4-14fd-43de-80b7-cdbe7e2e3f4a

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-11T21:15:36.417475Z 1e9c19c PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

…stroy

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1e9c19ced0

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

if (!state.configured) {
Configure(state, driver, ranges);
} else if (ranges != state.applied) {
driver.ReplaceBorrowedRanges(*ranges, ++state.driverGeneration);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Synchronize registry mutations before replacing borrowed ranges

When guest memory is unmapped or protected after a submission, this refresh happens only on the next non-worker driver entry, after the CPU mapping mutation has already completed. IdentityRanges() discards the GuestAllocationsAcquire_nid_postfix() lease and retains only raw spans, so GuestAllocationsRequireUnpinned_nid_postfix() cannot detect pending Metal work; a worker can consequently access pages that have already been unmapped or had their permissions changed. Mapping changes need to enter the driver through the mutation transaction before the host mapping is modified, with the allocation owner/lease retained until prior work drains.

Useful? React with 👍 / 👎.

std::lock_guard lock(live->mutex);
if (!live->window) return;
try {
live->window->PumpMainThread(std::chrono::milliseconds(0));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Drain native events into the input and close flow

For a non-headless direct-path window, this timer pumps AppKit but never calls NativeHostWindow::DrainEvents(). NativeHostWindow stores keyboard, mouse, and CloseRequested events in its private queue, while the existing VideoOut loop only consumes SDL events from the offscreen SDL driver; therefore keyboard/mouse input never reaches the guest, and clicking the close button is ineffective because windowShouldClose returns NO after merely enqueueing the request. The pumped native events must be drained and routed to the guest input and process-exit handling.

Useful? React with 👍 / 👎.

Comment on lines +89 to +90
std::lock_guard lock(state->mutex);
state->window = std::move(window);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Recheck destruction before publishing the async window

If Destroy() runs after the initial destroyed check but while CreateMainThread() is creating the window, it marks the state destroyed, observes no installed window, and returns; this code then installs and resumes a window in the abandoned state without rechecking the flag. Once the queued block releases its last shared_ptr, destruction of that still-open NativeHostWindow invokes its terminate guard, so a rapid startup/shutdown can abort the process. Recheck destroyed under this lock and close the newly created window instead of publishing it.

Useful? React with 👍 / 👎.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant