fix(agc): make host imports over writable pages on macOS #5101

Merged
Zheorgyan merged 1 commit from upstream-pr/5101 into main 2026-10-14 01:33:56 +00:00
Zheorgyan commented 2026-10-13 11:40:55 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Zheorgyan on 2026-10-13T11:40:55Z.


What

Metal keeps the protection a page had when it was imported. a host import made while the write watch has the guest pages read-only drops every GPU store into it, also after the protection is lifted, so render targets and storage images written back through an import kept their old contents on macOS. ImportWatched now opens the range with GuestArena::HostWrite for the import call only, and the watch protects it again after, so the import stays watched. the pages the open marks as written are compared with the copy taken before the import, so an import that stores nothing is not taken for a CPU store

the approach and the standalone Metal repro are mrzacarias's, see the comment below. other hosts are unchanged

Tested

  • macOS 15.6.1 on an M1 Pro, x86-64 under Rosetta, MoltenVK from Vulkan SDK 1.4.363.0, on mugurc's macos-port at b7eb6b6b, the same open around the import. the agc GPU tests with -j1 --timeout 30, without the flip, display and lds_atomics64 tests: 23 fail before, 13 after. fixed are srgb8_color_target, packed_unorm_color_target, swap_alt_blend, alpha_to_coverage, dual_source_blend, array_layer_target, storage_one_slice_alias, depth_compare_copy, cross_workgroup_flag and agc_unchanged_cpu_stamps, none added. dcc_keys_first_write still fails there with "an unchanged pending image was uploaded again": that branch predates the import window compare from #3874 that this relies on, and I could not run main itself on macOS
  • Linux, Ubuntu 24.04 in Docker, GCC 14.2. libSceAgcDriver builds, the change is macOS only
  • tools/check_conventions.py passes

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
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed in TechnicalDebt
  • 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
  • AI-assisted: yes
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4842658441 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/5101). Originally posted by [Zheorgyan](https://github.com/Zheorgyan) on 2026-10-13T11:40:55Z. --- ### What Metal keeps the protection a page had when it was imported. a host import made while the write watch has the guest pages read-only drops every GPU store into it, also after the protection is lifted, so render targets and storage images written back through an import kept their old contents on macOS. `ImportWatched` now opens the range with `GuestArena::HostWrite` for the import call only, and the watch protects it again after, so the import stays watched. the pages the open marks as written are compared with the copy taken before the import, so an import that stores nothing is not taken for a CPU store the approach and the standalone Metal repro are mrzacarias's, see the comment below. other hosts are unchanged ### Tested - macOS 15.6.1 on an M1 Pro, x86-64 under Rosetta, MoltenVK from Vulkan SDK 1.4.363.0, on mugurc's `macos-port` at `b7eb6b6b`, the same open around the import. the `agc` GPU tests with `-j1 --timeout 30`, without the flip, display and `lds_atomics64` tests: 23 fail before, 13 after. fixed are `srgb8_color_target`, `packed_unorm_color_target`, `swap_alt_blend`, `alpha_to_coverage`, `dual_source_blend`, `array_layer_target`, `storage_one_slice_alias`, `depth_compare_copy`, `cross_workgroup_flag` and `agc_unchanged_cpu_stamps`, none added. `dcc_keys_first_write` still fails there with "an unchanged pending image was uploaded again": that branch predates the import window compare from #3874 that this relies on, and I could not run `main` itself on macOS - Linux, Ubuntu 24.04 in Docker, GCC 14.2. `libSceAgcDriver` builds, the change is macOS only - `tools/check_conventions.py` passes ### Checklist - [x] Based on current `main`; no other open PR implements the same functions - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except [technical debt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md) - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed in [TechnicalDebt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/TechnicalDebt.md#silent-stubs) - [x] No notes, investigation `.md` files or images added to the repository (attach them to this PR) - [x] New third-party code is a submodule built from source - [x] Generic behaviour, not specific to one title - [x] Depends on: none - [x] AI-assisted: yes
mrzacarias commented 2026-10-13 14:09:27 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by mrzacarias on 2026-10-13T14:09:27Z.


Same here on a different setup: M1 Pro, macOS 26.4.1, native arm64 through the FEXCore runner, MoltenVK 1.4.2. It is Metal, not Rosetta: a standalone Metal program gives the same result built as arm64 and as x86-64.

  • Import over PROT_READ pages, then fill: the fill is lost with the command buffer completed (status 4), and it stays lost after mprotect(PROT_READ | PROT_WRITE).
  • Import over writable pages, then switch them between PROT_READ and PROT_READ | PROT_WRITE before each fill: every fill lands, including while the pages are read-only.

So only the protection at the moment of the import matters, which leaves room to keep imports watched instead of comparing them: open the range for the import call only and let the watch protect it again after. That is what I run locally in ImportWatched:

bool imported = false;
{
#ifdef __APPLE__
    const GuestArena::HostWrite open(reinterpret_cast<void*>(first), static_cast<std::size_t>(stop - first));
#endif
    imported = import();
}
if (!imported) return false;

With it, Balatro, God of War Sons of Sparta, Vampire Crawlers and Rogue Prince of Persia render and keep imported ranges watched. On an earlier branch with its own mprotect watch, God of War without the open stalled at about 0.4 FPS, the guest waiting on labels the GPU never wrote. I have not run the agc tests with this variant, so I can't say it fixes the same 10.

Repro (clang -fobjc-arc -framework Metal -framework Foundation repro.m):

#import <Metal/Metal.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>

int main(void) {
    id<MTLDevice> device = MTLCreateSystemDefaultDevice();
    id<MTLCommandQueue> queue = [device newCommandQueue];
    const size_t size = 65536;
    for (int readOnlyAtImport = 1; readOnlyAtImport >= 0; --readOnlyAtImport) {
        unsigned char* pages = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
        memset(pages, 1, size);
        if (readOnlyAtImport) mprotect(pages, size, PROT_READ);
        id<MTLBuffer> buffer = [device newBufferWithBytesNoCopy:pages length:size options:MTLResourceStorageModeShared deallocator:nil];
        for (int round = 0; round < 2; ++round) {
            mprotect(pages, size, round == 0 && !readOnlyAtImport ? PROT_READ : PROT_READ | PROT_WRITE);
            id<MTLCommandBuffer> commands = [queue commandBuffer];
            id<MTLBlitCommandEncoder> blit = [commands blitCommandEncoder];
            [blit fillBuffer:buffer range:NSMakeRange(16384, 16384) value:(uint8_t)(0x20 + round)];
            [blit endEncoding];
            [commands commit];
            [commands waitUntilCompleted];
            printf("imported %s, round %d: status %ld, byte %#x (expect %#x)\n", readOnlyAtImport ? "read-only" : "writable", round, (long)commands.status, pages[16484], 0x20 + round);
        }
    }
    return 0;
}
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6147464046 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/5101#issuecomment-6147464046). Originally posted by [mrzacarias](https://github.com/mrzacarias) on 2026-10-13T14:09:27Z. --- Same here on a different setup: M1 Pro, macOS 26.4.1, native arm64 through the FEXCore runner, MoltenVK 1.4.2. It is Metal, not Rosetta: a standalone Metal program gives the same result built as arm64 and as x86-64. - Import over `PROT_READ` pages, then fill: the fill is lost with the command buffer completed (status 4), and it stays lost after `mprotect(PROT_READ | PROT_WRITE)`. - Import over writable pages, then switch them between `PROT_READ` and `PROT_READ | PROT_WRITE` before each fill: every fill lands, including while the pages are read-only. So only the protection at the moment of the import matters, which leaves room to keep imports watched instead of comparing them: open the range for the import call only and let the watch protect it again after. That is what I run locally in `ImportWatched`: ```cpp bool imported = false; { #ifdef __APPLE__ const GuestArena::HostWrite open(reinterpret_cast<void*>(first), static_cast<std::size_t>(stop - first)); #endif imported = import(); } if (!imported) return false; ``` With it, Balatro, God of War Sons of Sparta, Vampire Crawlers and Rogue Prince of Persia render and keep imported ranges watched. On an earlier branch with its own mprotect watch, God of War without the open stalled at about 0.4 FPS, the guest waiting on labels the GPU never wrote. I have not run the `agc` tests with this variant, so I can't say it fixes the same 10. Repro (`clang -fobjc-arc -framework Metal -framework Foundation repro.m`): ```objc #import <Metal/Metal.h> #include <stdio.h> #include <string.h> #include <sys/mman.h> int main(void) { id<MTLDevice> device = MTLCreateSystemDefaultDevice(); id<MTLCommandQueue> queue = [device newCommandQueue]; const size_t size = 65536; for (int readOnlyAtImport = 1; readOnlyAtImport >= 0; --readOnlyAtImport) { unsigned char* pages = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); memset(pages, 1, size); if (readOnlyAtImport) mprotect(pages, size, PROT_READ); id<MTLBuffer> buffer = [device newBufferWithBytesNoCopy:pages length:size options:MTLResourceStorageModeShared deallocator:nil]; for (int round = 0; round < 2; ++round) { mprotect(pages, size, round == 0 && !readOnlyAtImport ? PROT_READ : PROT_READ | PROT_WRITE); id<MTLCommandBuffer> commands = [queue commandBuffer]; id<MTLBlitCommandEncoder> blit = [commands blitCommandEncoder]; [blit fillBuffer:buffer range:NSMakeRange(16384, 16384) value:(uint8_t)(0x20 + round)]; [blit endEncoding]; [commands commit]; [commands waitUntilCompleted]; printf("imported %s, round %d: status %ld, byte %#x (expect %#x)\n", readOnlyAtImport ? "read-only" : "writable", round, (long)commands.status, pages[16484], 0x20 + round); } } return 0; } ```
Zheorgyan commented 2026-10-13 19:10:35 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Zheorgyan on 2026-10-13T19:10:35Z.


@mrzacarias thanks, that is better, the imports stay watched. I will run the agc set on the M1 Pro with it and switch this PR if the same tests pass

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6153143339 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/5101#issuecomment-6153143339). Originally posted by [Zheorgyan](https://github.com/Zheorgyan) on 2026-10-13T19:10:35Z. --- @mrzacarias thanks, that is better, the imports stay watched. I will run the `agc` set on the M1 Pro with it and switch this PR if the same tests pass
Zheorgyan commented 2026-10-13 20:10:10 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Zheorgyan on 2026-10-13T20:10:10Z.


@mrzacarias switched to your open around the import, with you as co-author. on the M1 Pro with macos-port at b7eb6b6b it fixes the same tests plus agc_unchanged_cpu_stamps. dcc_keys_first_write still fails there because that branch has no import window compare from #3874 yet, on main the unchanged pages should be filtered out

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6154222416 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/5101#issuecomment-6154222416). Originally posted by [Zheorgyan](https://github.com/Zheorgyan) on 2026-10-13T20:10:10Z. --- @mrzacarias switched to your open around the import, with you as co-author. on the M1 Pro with `macos-port` at `b7eb6b6b` it fixes the same tests plus `agc_unchanged_cpu_stamps`. `dcc_keys_first_write` still fails there because that branch has no import window compare from #3874 yet, on `main` the unchanged pages should be filtered out
krishalivaibhav commented 2026-10-13 20:28:02 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by krishalivaibhav on 2026-10-13T20:28:02Z.


Additional independent M2 reproduction of the protected-import ordering problem, using our older local macOS integration (base 197ffac97203 plus unpublished macOS runtime patches), x86-64 under Rosetta and MoltenVK. This is not a build/test of the exact #5101 head.

I added a small diagnostic using the actual host-pointer import helper. It fills a 16 KiB imported buffer with 0x02020202, records a transfer-write → host-read barrier, waits for the real fence, and checks every byte, counting incorrect 4 KiB regions. Both submissions completed successfully:

watched: failure=none result=0 pages=4 wrongGpuWritePages=4 writtenAtImport=0 writtenAfterSubmit=0 writtenByCpu=1
unwatch-before-import: failure=none result=0 pages=4 wrongGpuWritePages=0 watchCounts=unmeasured

I then adapted the ordering to our older ImportWatched API: collect/stamp pending CPU writes under the tracker lock, remove write-watch protection, then invoke the Vulkan import callback. The control now uses that actual production tracker path rather than unregistering protection directly. It passed three consecutive runs, each with failure=none, result=0, pages=4, wrongGpuWritePages=0. Watch counts in the unwatched control are explicitly unmeasured.

This independently supports the ordering diagnosis on M2. It does not establish an FPS improvement, stable game sessions, or validation of all changes in this PR. I have not opened a duplicate upstream implementation PR.

AI-assisted: yes (Codex; low-reasoning subagent implementation, parent review and execution).

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6154550629 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/5101#issuecomment-6154550629). Originally posted by [krishalivaibhav](https://github.com/krishalivaibhav) on 2026-10-13T20:28:02Z. --- Additional independent M2 reproduction of the protected-import ordering problem, using our older local macOS integration (base `197ffac97203` plus unpublished macOS runtime patches), x86-64 under Rosetta and MoltenVK. This is not a build/test of the exact #5101 head. I added a small diagnostic using the actual host-pointer import helper. It fills a 16 KiB imported buffer with `0x02020202`, records a transfer-write → host-read barrier, waits for the real fence, and checks every byte, counting incorrect 4 KiB regions. Both submissions completed successfully: ```text watched: failure=none result=0 pages=4 wrongGpuWritePages=4 writtenAtImport=0 writtenAfterSubmit=0 writtenByCpu=1 unwatch-before-import: failure=none result=0 pages=4 wrongGpuWritePages=0 watchCounts=unmeasured ``` I then adapted the ordering to our older `ImportWatched` API: collect/stamp pending CPU writes under the tracker lock, remove write-watch protection, then invoke the Vulkan import callback. The control now uses that actual production tracker path rather than unregistering protection directly. It passed three consecutive runs, each with `failure=none`, `result=0`, `pages=4`, `wrongGpuWritePages=0`. Watch counts in the unwatched control are explicitly unmeasured. This independently supports the ordering diagnosis on M2. It does not establish an FPS improvement, stable game sessions, or validation of all changes in this PR. I have not opened a duplicate upstream implementation PR. AI-assisted: yes (Codex; low-reasoning subagent implementation, parent review and execution).
yripper commented 2026-10-14 01:25:22 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by yripper on 2026-10-14T01:25:22Z.


Data point from macOS 26 on an M1 Pro (Rosetta 2, MoltenVK), God of War: Sons of Sparta (PPSA28997): I hit the same Metal refusal. A single write-watched page inside a label range made the no-copy import fail with VK_ERROR_OUT_OF_DEVICE_MEMORY, so the range was copied and every label store drained the GPU, about 900 drains a second. Making the import succeed took the title screen at 1080p from 19 to 24 FPS (GPU idle per frame 13.7 → 2.3 ms, GPU mutex waits 928 → 28 ms per 10 s). I fixed it one level higher, by releasing the watched pages before the import, but your approach in ImportWatched is more precise, so I'll drop mine and test this PR on my branch.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6158796152 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/5101#issuecomment-6158796152). Originally posted by [yripper](https://github.com/yripper) on 2026-10-14T01:25:22Z. --- Data point from macOS 26 on an M1 Pro (Rosetta 2, MoltenVK), God of War: Sons of Sparta (PPSA28997): I hit the same Metal refusal. A single write-watched page inside a label range made the no-copy import fail with `VK_ERROR_OUT_OF_DEVICE_MEMORY`, so the range was copied and every label store drained the GPU, about 900 drains a second. Making the import succeed took the title screen at 1080p from 19 to 24 FPS (GPU idle per frame 13.7 → 2.3 ms, GPU mutex waits 928 → 28 ms per 10 s). I fixed it one level higher, by releasing the watched pages before the import, but your approach in `ImportWatched` is more precise, so I'll drop mine and test this PR on my branch.
yripper commented 2026-10-14 22:19:44 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by yripper on 2026-10-14T22:19:44Z.


Follow-up: I merged main with this PR and dropped my workaround. On PPSA28997 (M1 Pro, Rosetta 2, MoltenVK) the label ranges now import, with 0 device drains per packet and 0 labels left unimported in a 10 s window, the same result my workaround gave. Thanks!

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6179769107 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/5101#issuecomment-6179769107). Originally posted by [yripper](https://github.com/yripper) on 2026-10-14T22:19:44Z. --- Follow-up: I merged `main` with this PR and dropped my workaround. On PPSA28997 (M1 Pro, Rosetta 2, MoltenVK) the label ranges now import, with 0 device drains per packet and 0 labels left unimported in a 10 s window, the same result my workaround gave. Thanks!
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
boykopovar/AnyPS5!5101
No description provided.