Skip to content

runtime: DirectStorage requests with DestinationIsPhysicalPages (written through the xmem shim's pages) - #7652

Closed
larelgit wants to merge 11 commits into
ProjectLeonida:mainfrom
larelgit:dstorage-destination-pages
Closed

larelgit wants to merge 11 commits into
ProjectLeonida:mainfrom
larelgit:dstorage-destination-pages

Conversation

@larelgit

Copy link
Copy Markdown

Claimed in the coordination issue as: #7599 (comment)

Depends on: #7180 (this branch is main with #7180 merged, plus one commit; the diff shrinks to that commit once #7180 lands). Touches the page backing that #7556 changes, so whichever lands second needs a small rebase.

What and why

A DirectStorage request with DestinationIsPhysicalPages has no destination address: the union that holds Destination holds DestinationPageArray (64 KiB page numbers from XMemAllocatePhysicalPages) and DestinationPageOffset (a UINT16 into the first page). #7180 answers these with E_NOTIMPL.

The retail executable builds them. Read from its code, with nothing run: its chunked read path checks whether the destination lies in the range it backs with physical pages, and if so passes the address of that page's entry in its own page table as the array and the low 16 bits of the address as the offset, with the option bit set. So those reads never arrive today. How often this happens in a boot I have not counted.

The change, one commit on top of #7180:

  • rt::xmem::write_physical_pages (shims/xmem_pages.h, implemented in shims/xmem.cpp) writes to pages by number through views of their backing sections, one view per run of pages that follow one another in one allocation. Every page number is checked before a byte is written. A page needs no mapping to be written, and a mapped page shows the bytes at once.
  • dstorage.cpp stages the source (file range or memory, inflated for a zlib request) and passes it to write_destination, which copies the page numbers out of the title's array under the same guard as the other reads of title memory. An unreadable array, page number 0, a number never handed out and a freed page are E_DSTORAGE_ACCESS_VIOLATION and leave the pages untouched.
  • The 32 MiB limit for 4 KiB-page destinations no longer applies to these requests (the reference allows more with 64 KiB pages); an address keeps it.
  • SourceIsPhysicalPages, BCPack and swizzle stay E_NOTIMPL.
  • docs/directstorage.md gets a "Physical-page destinations" section, including what is unverified: the console's failure code for a bad page number, and whether the console requires the pages to be mapped.

Tested

Windows 11, MSVC (VS Build Tools 18.9), RelWithDebInfo, CPU only, no game files:

  • dstorage_test: 362 checks, 0 failures. New: a file read that starts inside one page and ends in the fourth, with pages from two allocations out of backing order; zlib from memory across a page boundary; a copy that ends exactly at the end of a page; pages mapped during the request and pages mapped only afterwards; a request over 32 MiB; and the four failure cases, checked to leave every page untouched. Results are read back through a window the pages are mapped into with the shim's own XMemVirtualAlloc and XMemMapPhysicalPages.
  • xmem_test: 173 checks, OK.
  • python -I scripts/check_no_game_data.py on the changed files: clean.
  • tests/test_docs_repo_paths.py, test_docs_repeated_lines.py, test_docs_list_items.py, test_docs_env_vars.py: OK. test_docs_links.py and test_docs_cli_flags.py fail the same way on main (other files).

Not run: the full ctest, the clang-cl cross build, and a retail boot with this branch (my local boot stack stops at stop 9 before any such request).

AI-assisted: yes (Claude Code)

Checklist

  • No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here.
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed. (not a translator change)

🤖 Generated with Claude Code

mariuslozo-boop and others added 11 commits November 23, 2026 01:48
…ry reads

Serve the Xbox DirectStorage API (IDStorageFactoryX2, IDStorageQueueX2,
IDStorageFileX, IDStorageStatusArrayX) under dstorage_xs.dll, xcrdapi.dll and
dstorage.dll. Declarations are our own (shims/dstorage_xs_abi.h), written from
the public GDK reference; layouts are pinned with static_asserts.

- OpenFile goes through the registry's kernel32!CreateFileW, so GAME: paths use
  the console path mapping and the write overlay. GetHandle returns a ReOpenFile
  handle with its own file position.
- One worker thread per queue runs submitted entries in order: file and memory
  requests, status arrays, ID3D12Fence::Signal, EnqueueSetEvent (on a duplicate
  of the title's handle taken at enqueue).
- Auto-submit at half the capacity (or disabled through DSTORAGE_QUEUE_OPTIONS),
  enqueue into a full queue waits, CancelRequestsWithTag (a cancelled request is
  a success and not a failure), error record and error event, Close and the last
  Release drain the queue, IDStorageFileX::Close waits for the file's submitted
  reads.
- Request checks: reserved bits, source type, BCPack/swizzle ranges, sizes,
  1 GiB limit, null and foreign objects and closed files (also for zero-size
  requests), end of file, inaccessible memory.
- zlib, BCPack, swizzle and physical pages return E_NOTIMPL (later PRs).
- Interface ids of the X interfaces are not public: a creating call accepts and
  logs a new id per object kind, but refuses system COM ids (IMarshal,
  IAgileObject, ...) and the PC DirectStorage ids; QueryInterface accepts only
  IUnknown, the PC IDStorageStatusArray id (same shape) and the ids creating
  calls accepted for that kind. Bad arguments are logged once per method.
- registry.cpp classifies xcrdapi.dll!DStorageGetFactory as HRESULT; the cl.exe
  fallback in build_runtime.ps1 builds the new shim too.

ctest dstorage: 258 checks over synthetic files in %TEMP%, no GPU, no game data.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/directstorage.md records which DLL and ABI the console title is expected
to use (dstorage_xs.dll medium, xcrdapi.dll and dstorage.dll low confidence),
what is not public (vtable order, interface ids, some constants) and the choice
made for each, what owning the modules shadows at run time, what the shim does
(including the order of its request checks), and what later PRs add (zlib,
BCPack, swizzle, physical pages, GPU-backed destinations, parallel reads).
Index row in docs/README.md; the owned-module list in runtime_imports.md and
the shim list in runtime/README.md name the new modules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…mit, /EHa under clang-cl

Review fixes for ItsNotRexed#4348 (Flyander, AirKyzzZ):
- DSTORAGE_REQUEST allows a buffer over 32 MiB only with 64 KiB or 2 MiB
  pages, which are not implemented yet, so such a request now fails with
  E_DSTORAGE_REQUEST_TOO_LARGE before any memory is touched.
- TotalRequestCount and the byte totals grow when a request is submitted,
  not when it is enqueued, and PendingRequestCount counts the request the
  worker is processing (DSTORAGE_PRIORITY_STATS).
- dstorage.cpp is built with /EHa under clang-cl, so guarded_move's __try
  catches an access violation in a title's buffer there too.

Tests: an over-limit and an at-limit 32 MiB copy, and stats checked
before Submit and while a copy is held on a guard page. The three new
failing checks fail with the previous shim.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A request with ZlibDecompress alone now reads SourceSize bytes of the file or of memory into a staging buffer,
inflates them with the runtime's RFC 1950 inflater (leonida::zlib_inflate in src/shader_library.h) and copies the
result to Destination only when it is exactly DestinationSize bytes. A failed stream leaves the destination
untouched, and a memory source inside its own destination inflates correctly.

Checks follow DSTORAGE_REQUEST and dstorageerr.h: DestinationSize must be larger than SourceSize with zlib
(E_DSTORAGE_INVALID_DESTINATION_SIZE), a zlib FileOffset must be 16-byte aligned (E_DSTORAGE_INVALID_FILE_OFFSET),
IntermediateSize stays 0 without BCPack. Stream failures map to E_DSTORAGE_ZLIB_BAD_HEADER, _ZLIB_BAD_DATA,
_ZLIB_PARITY_FAIL (Adler-32) and E_DSTORAGE_DECOMPRESSION_ERROR (a result of another size). GetStats counts
the inflates, the pending ones and the decompression errors.

zlib_inflate gains an optional failure reason (header, data, checksum, limit); its existing callers are unchanged.
BCPack, swizzle and physical-page requests still fail with E_NOTIMPL.

dstorage_test: synthetic streams only (Python zlib levels 9 and 1, stored blocks built by the test), from a file
and from memory, with every failure code; shader_library_test checks the new failure reasons.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
# Conflicts:
#	docs/README.md
#	runtime/CMakeLists.txt
… xmem shim's pages

A request with DestinationIsPhysicalPages names its destination as an array of
64 KiB page numbers from XMemAllocatePhysicalPages and a 16-bit offset into the
first page. The shim answered E_NOTIMPL. The retail executable's chunked read
path builds such requests whenever its destination lies in the range it backs
with physical pages.

- rt::xmem::write_physical_pages (shims/xmem_pages.h, shims/xmem.cpp) writes
  through views of the pages' backing sections, one view per run of pages that
  follow one another in one allocation. Every page number is checked before a
  byte is written; a page needs no mapping, and a mapped page shows the bytes.
- dstorage.cpp stages the source (file range or memory, inflated for zlib) and
  hands it to write_destination, which copies the page numbers out of the
  title's array under the usual guard. A bad array or page number is
  E_DSTORAGE_ACCESS_VIOLATION and leaves the pages untouched.
- The 32 MiB limit for 4 KiB-page destinations no longer applies to these
  requests (64 KiB pages); an address keeps it.
- SourceIsPhysicalPages, BCPack and swizzle stay E_NOTIMPL.

dstorage_test: 362 checks, xmem_test: 173 checks, both pass (MSVC, Windows 11).
Synthetic data only.

Co-Authored-By: Claude Mythos 5.2 <noreply@anthropic.com>
@MartinIndra02

Copy link
Copy Markdown
Contributor

Independent Windows test of d528947d4: pass.

Setup: Windows 11 x64, MSVC 19.44.35220 (RelWithDebInfo, Windows SDK 10.0.26100.0), no game files.

  • dstorage_test.exe: PASS (exit 0) — confirms DirectStorage DestinationIsPhysicalPages writes through the xmem shim's physical pages.

AI-assisted review/test.

Cattn added a commit to Cattn/Leonida that referenced this pull request Nov 23, 2026
A writer that copies into physical pages through its own view of their
section (a DirectStorage destination given as page numbers, ItsNotRexed#7652) sees
reserve-only memory for pages the title has not touched yet, and no
fault handler can resolve that address. commit_physical_pages commits
the given pages through each section's own view, one VirtualAlloc per
contiguous run, so such a writer can commit before it copies. Raised by
nurtrino in ItsNotRexed#7599.
@MatyEjsr

Copy link
Copy Markdown

Independent Windows build, full CTest run (CPU + GPU), and code review on d528947d4 (Depends on: #7180).

Environment

  • Windows 11 x64, MSVC 14.44.35207 (VS 2022 Build Tools), CMake + Ninja (RelWithDebInfo, 8 parallel jobs), Vulkan SDK 1.4.363.0
  • GPU: NVIDIA GeForce RTX 3090, driver 617.42
  • Synthetic tests only, no game files (LEONIDA_GAME_DIR / LEONIDA_MOVIE unset; no SDL3 installed so gameinput is disabled)

Verification results

  • Runtime build (scripts/build_runtime.ps1 -jobs 8): 647/647 targets built cleanly (0 warnings in runtime/shims/dstorage.cpp, runtime/shims/xmem.cpp, and runtime/test/dstorage_test.cpp).
  • Targeted tests:
    • ctest --test-dir runtime/build -C RelWithDebInfo -j 8 -R "^(dstorage|xmem|shader_library|unimplemented_policy)$" --output-on-failure: 4/4 passed
    • dstorage_test: 362 checks, 0 failures
    • xmem_test: 173 checks, OK
    • shader_library_test: OK
  • Full runtime suite (ctest --test-dir runtime/build -C RelWithDebInfo -j 8 --output-on-failure): 259 passed, 11 skipped (retail-file / optional-env gated), 1 disabled (gameinput), 2 failed (both pre-existing NVIDIA failures unrelated to DirectStorage/xmem):
  • Python / repo checks:
    • python -I scripts/check_no_game_data.py on all 15 changed files: clean
    • python -m compileall -q make_game.py tools tests and python -I make_game.py --help: OK
    • tests/test_docs_repo_paths.py (3/3), tests/test_docs_repeated_lines.py (2/2), tests/test_docs_list_items.py (3/3), tests/test_docs_env_vars.py (4/4): OK (tests/test_docs_links.py fails only on pre-existing docs/dev-tools.md and docs/gpu_test_results.md entries).

Review findings

  1. docs/README.md duplicate row & stale summary (in e1ea71041): Resolving the conflict in docs/README.md left the [gameinput.md](gameinput.md) table row duplicated directly above and below [directstorage.md](directstorage.md), and the [directstorage.md](directstorage.md) row still ends with BCPack, swizzle and physical pages still open instead of noting that DestinationIsPhysicalPages is implemented.
  2. docs/directstorage.md lines 100-103 and 117-118: Step 5 still says DSTORAGE_REQUEST allows a buffer over 32 MiB only with 64 KiB or 2 MiB pages, which are not implemented yet and Both buffers are at most 32 MiB (step 5), which contradicts runtime/shims/dstorage.cpp:801-805 and lines 200-202 of docs/directstorage.md.
  3. runtime/shims/xmem.cpp:732-736 (minor): rt::xmem::write_physical_pages validates every page number under g_phys_mutex before writing, so bad/zero/freed page numbers fail atomically. If MapViewOfFile itself were to fail on a second or later contiguous run (first > 0), bytes from earlier runs would already be written before returning false (unlikely on 64-bit Windows outside virtual address space exhaustion).

AI-assisted review and testing (Gemini 4 Hydrogen).

@rideinstead

Copy link
Copy Markdown

✅ Automated security review: CLEAN (commit d528947d)

  • No findings.

Scope: static analysis of added diff lines only; no code was executed. Please review findings manually.

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

This goes after #8461 and #7180. Merged onto #8461 (git merge-tree) it conflicts only in docs/README.md; onto main it conflicts in docs/runtime_imports.md. Its own commit is d528947d4. dstorage_test from this head passes on MSVC: 362 checks, 0 failures.

  1. Plausible, needs an answer before merge: write_destination reads count entries of 8 bytes from DestinationPageArray (runtime/shims/dstorage.cpp:856). The GDK type is PULONG_PTR, so that is right for the API. But the description says the title passes "the address of that page's entry in its own page table", and main's runtime/shims/xmem.cpp:253-255 says the measured title "stores them packed and assumes each is a non-zero multiple of 16 below 2^25". If the title's table holds narrower or flagged entries, an 8-byte read gives a page number g_pages does not know, and every such request fails with E_DSTORAGE_ACCESS_VIOLATION. What entry width did you read at that call site? One line in docs/directstorage.md would settle it.
  2. Plausible: no measured boot reaches a page request yet. The retail runs on #7180 report every request succeeding with page requests still E_NOTIMPL, and the description says the count is unmeasured. A --trace count of DestinationIsPhysicalPages requests from a later stop would show when this starts to matter.
  3. Confirmed (code read of #7556): #7556 backs physical pages with SEC_RESERVE sections and commits them on first touch (xmem.cpp:609 and commit_physical_pages at :821 on its head). write_physical_pages here maps a view and memcpys into it, which faults on a page nothing has touched yet. The description says whichever lands second needs a rebase; concretely, that rebase has to call commit_physical_pages for the range before the copy.

AI-assisted review (Opus 5.5). Read the diff against main; built dstorage_test (with xmem.cpp) with MSVC and ran it (362 checks, 0 failures).

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.

8 participants