Skip to content

feat(agc): import shared direct memory through udmabuf on Linux - #943

Merged
adriadam10 merged 4 commits into
boykopovar:mainfrom
alfalfa-star:feat/linux-direct-memory-dmabuf-import
Oct 7, 2026
Merged

adriadam10 merged 4 commits into
boykopovar:mainfrom
alfalfa-star:feat/linux-direct-memory-dmabuf-import

Conversation

@alfalfa-star

Copy link
Copy Markdown
Contributor

What

On Linux with an AMD GPU, no host import of direct memory ever succeeded, so every direct-memory range the GPU used was copied.

Since #203, direct memory is a memfd mapped MAP_SHARED (before that it was a /tmp file). RADV imports a host pointer through amdgpu userptr, and libdrm's amdgpu_create_bo_from_user_mem sets AMDGPU_GEM_USERPTR_ANONONLY, so the kernel refuses any file-backed VMA. Measured on Linux 7.2 with libdrm 2.4.134:

mapping amdgpu_create_bo_from_user_mem
anonymous MAP_PRIVATE ok
anonymous MAP_SHARED EPERM
memfd MAP_SHARED EPERM

In the driver this showed up as [gpu] host import of … failed at vkAllocateMemory (-1000072003); falling back to copies. In PPSA14632 all 466 import attempts failed, and every one was a rw-s /memfd:direct memory mapping.

This PR imports such ranges as dma-bufs instead:

  • createImport tries the host pointer import first, so a driver that accepts shared mappings behaves as before. When that fails and libkernel reports a memfd backing for the range, the range's slice of the memfd becomes a dma-buf through /dev/udmabuf (UDMABUF_CREATE). It is then imported with VK_EXT_external_memory_dma_buf (VK_KHR_external_memory_fd), bound to the same buffer usage and device address as a host pointer import.
  • The direct memory backing is created with MFD_ALLOW_SEALING and sealed with F_SEAL_SHRINK | F_SEAL_GROW after ftruncate, as udmabuf requires. It is never resized afterwards.
  • libkernel registers a resolver through GuestArenaSetSharedBacking_nid_postfix (libc). The driver asks GuestArenaSharedBacking_nid_postfix(address, bytes, &file, &offset) and gets a CLOEXEC duplicate of the memfd and the range's offset in it. The range must lie in direct mappings that continue in one backing; adjacent mappings that continue contiguously count as one. Flexible memory, unmapped ranges and non-contiguous ranges return false.
  • If /dev/udmabuf cannot be opened, or the range exceeds udmabuf's size_limit_mb (64 MiB by default), the import fails as before and the range is copied.
  • On Linux, APS5_TRACE_HOST_IMPORT now prints the /proc/self/maps lines behind a failed import, as it already printed the VirtualQuery regions on Windows.

Windows is unchanged.

Tested

Linux: Arch, kernel 7.2.7, GCC 16.2.1, RX 9070 XT (RADV GFX1201, Mesa 26.2.3).

  • ctest: 359/359 pass.

  • New CheckDirectMemorySharedBacking in guest_memory_tests covers:

    • the offset of a range inside a mapping;
    • data written through the guest mapping, read back through the returned file;
    • the shrink and grow seals, and CLOEXEC on the duplicate;
    • a range past its mapping, an empty range, flexible memory and an unmapped range are refused;
    • two separately mapped neighbours that continue in the backing are found as one range, and non-contiguous neighbours are refused.
  • A standalone check of the import path (memfd slice → udmabuf → dma-buf → RADV, then vkCmdCopyBuffer/vkCmdFillBuffer) found 0 wrong words in either direction and nothing written outside the slice. The imported memory type is host-visible, coherent and cached. udmabuf accepted 64 MiB and refused 65 MiB.

  • PPSA14632 (LEGO Horizon Adventures, --to-intel), 3-minute runs from boot into its boot-flow movie, on a test branch that also has perf(agc): query guest page access with PROCMAP_QUERY on Linux #157:

    imports ok / failed [guestmem] read write-changed
    before 0 / 466 604 GB, 53.8 s 150 GB, 19.5 s
    this PR 416 / 6 236 GB, 24.3 s 48 GB, 7.9 s
    this PR + feat(agc): host import windows, least-recent eviction under the budget #290 443 / 11 182 GB, 17.4 s 36 GB, 5.5 s

    The remaining failures are ranges above 64 MiB (UDMABUF_CREATE): 112 to 576 MiB whole allocations, plus feat(agc): host import windows, least-recent eviction under the budget #290 windows above 64 MiB. The title's present rate did not change (5 per 10 s), so its frame rate is limited by something else.

  • Windows: not tested. The Windows code paths are unchanged.

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. feat(agc): host import windows, least-recent eviction under the budget #290 changes importAllocation around the createImport call this PR extends, and the two cherry-pick onto each other without conflicts. /dev/udmabuf is root:kvm 0660 on many distributions; this test machine had a per-user ACL on it.
  • AI-assisted: yes

🤖 Generated with Claude Code

@alfalfa-star

Copy link
Copy Markdown
Contributor Author

A note for whoever tests this on RADV: with these imports active, PPSA14632 (LEGO Horizon Adventures) hit amdgpu page faults and a ring reset within 1.5 to 3 minutes, and Unreal then aborted with GameThread timed out waiting for RenderThread after 120.00 secs:

amdgpu: [gfxhub] page fault ... Faulty UTCL2 client ID: SQC (data)
amdgpu: ring gfx_0.0.0 timeout, signaled seq=612273, emitted seq=612275

The cause is not in this PR. It is a RADV bug that the larger number of in-place bindings exposes sooner. RADV (Mesa 26.0 and later) gives a FREE_DESCRIPTOR_SET pool's allocator bo_size + RADV_POOL_HEAP_OFFSET as its size, so a set can be placed up to 32 bytes past the pool's buffer. Our chain pools are 0x26000 bytes, a page multiple. In the RADV_DEBUG=hang dump, a 160-byte set sat at offset 0x25f80, and the shader's s_load_b128 of its storage buffer descriptor read 0x26000. Under GPU-assisted validation, the same overrun showed up on the CPU side as a segfault in radv_write_sampler_descriptor. A standalone repro on RADV: a FREE_DESCRIPTOR_SET pool sized for four sampled images (128 bytes) accepts a set of five (160 bytes), while a linear pool returns VK_ERROR_OUT_OF_POOL_MEMORY.

#1065 keeps the overrun on the pool buffer's last page. With it and this PR, the title ran 5 minutes without a fault. With the udmabuf size_limit_mb raised to 1024, its 576 and 463 MiB direct memory buffers are imported too, guest memory upload time drops from 190 s to 13 s over the run, and the present rate goes from 5 to 15 per 10 s.

Environment: Arch Linux, kernel 7.2.9, Mesa 26.2.4 RADV, RX 9070 XT (RDNA4), i7-13700KF.

@alfalfa-star

Copy link
Copy Markdown
Contributor Author

Follow-up commit fc81399 fixes a large slowdown this PR caused on its own.

The import write-watch probe imports private anonymous scratch pages through VK_EXT_external_memory_host. On amdgpu that path makes the pages read as written after every GPU submission (4 of 4 scratch pages written after a GPU read), so the probe decided that imported ranges are compared, not watched. Before this PR no import succeeded on Linux/AMD, so that decision never mattered. With the udmabuf path, most of direct memory gets imported, every import was unwatched, and every surface in direct memory lost its write stamps:

  • each storage-image refresh re-uploaded the whole surface (upload reason untracked);
  • draw snapshots of imported ranges could never be reused.

On PPSA14632 that was over 800 GiB of storage uploads in 90 s.

udmabuf takes the memfd's pages without touching the process page tables, so these imports don't need that treatment. The commit:

  • records each import's kind and decides watch or unwatch after the import, by kind (ImportWatched already absorbs the pages the import itself touches);
  • adds ProbeDmaBufImportWriteProtection: a sealed shared memfd scratch range imported through udmabuf, read on the GPU, then stored to from the CPU. dma-buf imports stay watched only when the GPU read marks no page written and the CPU store is still collected. Otherwise, or if the probe fails, they are compared like host-pointer imports;
  • APS5_WRITE_WATCH_IMPORTS=watch|unwatch still overrides both kinds.

On RADV (RX 9070 XT, kernel 7.2.9):

[write-watch] host imports resolve write protection: yes (4 of 4 scratch pages written after a GPU read, 4 after the import); imported ranges are compared
[write-watch] dma-buf imports keep write protection: yes (0 of 4 scratch pages written after a GPU read, 0 after the import, 1 seen after a CPU store); imported ranges stay watched

PPSA14632 storage uploads drop from ~2.7 s to ~0.1 s of GPU time per 10 s, with no untracked uploads left. Presents go from ~10 to ~17 per 10 s with this alone, and to ~38 together with two separate fixes I'll open next (a larger draw-snapshot budget and a staging pool budget scaled to the device heap). ctest: 359/359 on this branch.

@EdouardSence

Copy link
Copy Markdown
Contributor

Test on the same GPU, with PPSA21567 (Astro Bot).

Setup: Linux (CachyOS, kernel 7.2.8, GCC 16.2.1), Ryzen 7 7800X3D, RX 9070 XT (RADV GFX1201, Mesa 26.2.3). oneandonlydean's astrobot (93faece) with this PR's two commits cherry-picked (aa83df4, fc81399; no conflict), bundled libc.prx excluded and std::_Fiopen exported (both only to get this branch to load PPSA21567).

  • Without this PR: 42 host import of … failed at vkAllocateMemory (-1000072003), then FATAL: an address-based build copies 12403 MiB of 35 registered ranges, past 64 MiB. The largest ranges are 0x10ca000000+0x120000000 (4608 MiB), 0x1000000000+0xca000000 (3232 MiB) and 0x500000000+0x87c00000 (2172 MiB).
  • With this PR: [write-watch] dma-buf imports keep write protection: yes, the FATAL is gone, and 7 imports still fail. All 7 are mappings of the executable itself (4 read-only, 3 file-backed rw-p), not direct memory.
  • I ran only with udmabuf.size_limit_mb=8192, plus an ACL on /dev/udmabuf (root:kvm 660 here, and the user is not in kvm). Given the range sizes above, the default 64 MiB would leave the large ranges copied; I did not run with the default.
  • The next stop is in AddSnapshot: compute shader 0x5005f6100: AGC graphics: guest snapshot differs from registered memory. With APS5_NO_SNAPSHOT_CHECK=1 the title runs through the intro. I have not established whether the dma-buf path causes that difference.
  • The 3 file-backed rw-p executable mappings become writable image mirrors that each address-based build compares in full (~3.7 ms per BDA draw here). fix(libc): back the main image's writable mappings with anonymous memory on Linux #1176 makes them anonymous so they import.

AI-assisted: yes (Claude Code ran the builds and wrote this report; the runs are on my machine).

alfalfa-star and others added 4 commits October 7, 2026 23:09
On Linux, direct memory is a memfd mapped MAP_SHARED. amdgpu accepts only
private anonymous memory for a host pointer import (libdrm sets
AMDGPU_GEM_USERPTR_ANONONLY), so every import of direct memory failed with
VK_ERROR_INVALID_EXTERNAL_HANDLE and its ranges were copied.

When a host pointer import fails, the range's memfd slice is turned into a
dma-buf through /dev/udmabuf and imported with VK_EXT_external_memory_dma_buf.
The direct memory backing is sealed against shrinking and growing, as
udmabuf requires. libkernel reports the backing of a guest range through
GuestArenaSharedBacking. Without /dev/udmabuf, or past its size limit, the
range is copied as before. APS5_TRACE_HOST_IMPORT now prints the mappings
behind a failed import on Linux too.

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

The import write-watch probe imports private anonymous scratch pages
through VK_EXT_external_memory_host. On amdgpu that path resolves the
pages' write protection (the userptr is revalidated at every submission),
so the probe decides that imported ranges are compared instead of
watched, and every import is unwatched. Shared direct memory is never
imported that way: its imports go through udmabuf, which takes the
memfd's pages without touching the process page tables. Unwatching them
anyway left every surface in direct memory without write stamps: each
storage image refresh re-uploaded the whole surface ("untracked"), and
draw snapshots of imported ranges could never be reused. On PPSA14632
that was over 800 GiB of uploads in 90 s.

- HostImport records whether it is a dma-buf import, and the import
  decides watch or unwatch after the import by its kind (ImportWatched
  already absorbs the pages the import itself touches).
- A second probe, ProbeDmaBufImportWriteProtection, imports a sealed
  shared memfd scratch range through udmabuf: dma-buf imports stay
  watched when a GPU read of it marks no page written and a CPU store
  after that is still collected. Otherwise, or when the probe fails,
  they are compared like host-pointer imports.
- Both probes also report whether a CPU store after the GPU read was
  collected (ImportProbe::writtenByCpu).
- APS5_WRITE_WATCH_IMPORTS=watch or unwatch overrides both kinds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude <noreply@anthropic.com>
…er a direct mapping

Co-Authored-By: Claude <noreply@anthropic.com>
@adriadam10
adriadam10 force-pushed the feat/linux-direct-memory-dmabuf-import branch from fc81399 to c572650 Compare October 7, 2026 21:21
@adriadam10

Copy link
Copy Markdown
Collaborator

Rebased onto main (mechanical conflict with ClearImageMirrors in GuestBufferMemory.cpp). Build + ctest 406/406 on RADV (gfx1035). Ran importWatchTests on RADV with /dev/udmabuf: dma-buf import probe: 0 of 4 scratch pages written after a GPU read, 0 after the import, 1 after a CPU store, which matches your RDNA4 numbers.

Added two test commits:

  • Recorder.cpp: the test Device never enabled VK_KHR_external_memory_fd/VK_EXT_external_memory_dma_buf, so context.dmaBufImport was always false and the new dma-buf probe branch never ran. It is enabled now when the device has both extensions.
  • GuestMemory.cpp: added a range that is not 16 KiB aligned (offset == page * 2 + 0x1000). Before this, dropping phys % PS5_PAGE_SIZE from the returned offset still passed. Also added a gap after a direct mapping, which must be refused.

Note on merge order: your comment says that with these imports active, RADV's descriptor pool overrun faults sooner, and that #1065 fixes it. #1065 should land before or together with this PR.

johnmaia added a commit to johnmaia/AnyPS5 that referenced this pull request Oct 9, 2026
On Linux, shared direct memory is imported through /dev/udmabuf (boykopovar#943).
Many distributions create it as root:kvm 0660, so a user outside the
kvm group cannot open it. The ranges are then copied instead of
imported, and GPU stores through FLAT/GLOBAL addresses to them fail
with "BDA access failed": DOOM PPSA99666's compute presenter falls back
to its CPU scaler. The only trace was "failed at open /dev/udmabuf
(-1000072003)", a Vulkan result that hides errno.

Print the open error once, with the fix for EACCES, and document the
requirement in USAGE.md.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants