Skip to content

runtime: console DirectStorage (DStorageGetFactory) with file-to-memory reads - #4348

Open
mariuslozo-boop wants to merge 7 commits into
ItsNotRexed:mainfrom
mariuslozo-boop:rt/directstorage
Open

mariuslozo-boop wants to merge 7 commits into
ItsNotRexed:mainfrom
mariuslozo-boop:rt/directstorage

Conversation

@mariuslozo-boop

Copy link
Copy Markdown

Claimed in the coordination issue as: new RT item, DirectStorage (claim).

What and why

registry.cpp marked DStorageGetFactory as returning an error code, and xcrdapi.dll was not named at all, so a title that loads through DirectStorage got no data. The package's textures are BCPack, which the console decodes through DirectStorage (docs/textures.md), so the game likely streams through it. The executable's imports are not measured, so this is an inference.

This first PR serves the console DirectStorage API, file to memory:

  • Exports: DStorageGetFactory under dstorage_xs.dll, xcrdapi.dll and dstorage.dll, all with the console ABI.
  • Files: opened through the runtime's own CreateFileW shim, so GAME: paths and the overlay work.
  • Queues: one worker thread per queue, entries run in order. File-to-memory and memory-to-memory reads.
  • Completion: status arrays, ID3D12Fence signals and events.
  • Other behaviour: cancel by tag, auto-submit, error records, and close or release while requests are still running.
  • Not yet: zlib, BCPack, swizzle and physical-page requests return E_NOTIMPL. They and GPU-backed destinations are later PRs.

ABI. The declarations in runtime/shims/dstorage_xs_abi.h are our own, written from Microsoft's public GDK reference for the console API (IDStorageFactoryX and so on). No header is vendored, and no GPL code was read. Struct sizes are pinned with static_assert. docs/directstorage.md records the evidence and its confidence:

  • Struct layouts: high, straight from the documented declarations.
  • Vtable order: not public. Medium for the queue, file and status array, low for the factory. A bad argument is logged once per method, so a wrong slot guess shows up in the first boot's log.
  • Console interface IDs: not public. A creating call accepts a new ID and logs it, so the first boot records the real ones. System COM IDs and PC DirectStorage IDs are refused (except the PC status-array ID, whose interface has the same shape). QueryInterface then answers only IUnknown and IDs learned for that kind of object, and returns E_NOINTERFACE otherwise, as docs/d3d12_vulkan.md asks.
  • Which DLL the game imports it from: unknown. dstorage_xs.dll medium, xcrdapi.dll and dstorage.dll low.
  • Side effect: owning these modules means a run-time LoadLibrary of them gets the shims' handle, and GetProcAddress for any other name returns NULL. Static imports are unchanged. This is noted in the doc.

Tested

Windows 11 (build 26300), RTX 5070 Ti (driver 616.92), MSVC 19.44, Vulkan SDK 1.4.363.0, RelWithDebInfo, on main 03b09a08.

  • Full ctest: 138/138 passed, serial and -j 8. The skips are the usual ones.
  • New dstorage test (synthetic files only): 258 checks. They cover:
    • reads through GAME: and the overlay;
    • offsets past the end, the offset-plus-size wrap and zero-size requests;
    • status arrays, fences and events (including a closed event whose handle value is reused);
    • cancel, error records, and close or release with requests in flight;
    • a full queue;
    • interface-ID policy on all four object kinds;
    • GetHandle opening its own handle, so it does not share the shim's file position.
  • -R dstorage --repeat until-fail:30: all 30 runs passed.
  • Python: every tests/test_*.py that CI runs passed, except 5 that fail identically on clean main on this machine. This includes the docs, registry, fallback-build and line-ending tests.

An independent reviewer read the change, built it, and ran stress probes: four enqueuing threads with Close, two queues on one file, file Close racing submits. The 7 items it raised are fixed with tests.

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 applicable: no translator change.)

AI-assisted (Claude Code). No game files.

🤖 Generated with Claude Code

mariuslozo-boop and others added 2 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>
@molodayamama

Copy link
Copy Markdown

Independent Windows 10 check of c77338e673ccee869fc9aa4cef8f7869e135e39f: Windows 10 22H2 (19045.7058), MSVC 19.40, Windows SDK headers 10.0.26100.0, Ninja RelWithDebInfo.

I built dstorage_test and ran ctest -R '^dstorage$' --repeat until-fail:50 -V. All 50/50 runs passed, each reporting 258 checks, 0 failures (about 21 seconds total). This exercises the synthetic DirectStorage shim tests on Windows 10, including file/overlay routing and queue, cancellation, close and completion behavior. Synthetic files only. AI-assisted (Codex).

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

Built dstorage_test at c77338e6 on Windows 11 and ran it: 258 checks, 0 failures, exit 0; ctest -R dstorage -> 1/1 passed (0.42 s).

The test covers DStorageGetFactory, the console ABI objects and the QueryInterface policy: unknown/system/PC-DirectStorage ids return E_NOINTERFACE, a wrong-kind id is refused, and the queue interface is served; the file-to-memory queue/status paths run. No blocking issue.

@ricardotanaka

Copy link
Copy Markdown

Tested c77338e6 on Windows 11 26200 (pt-BR locale), MSVC 19.44, merged on main 03b09a08: pass. The two conditions here are ones the checks above didn't cover:

  • Concurrent processes: dstorage_test.exe 4 at a time, 25 rounds: 100/100 exit 0, each 258 checks, 0 failures, no hang (120 s limit per run). Each run uses its own %TEMP%\leonida_dstorage_test_<pid>, so this stresses the per-queue worker threads under CPU contention, not shared files.
  • %TEMP% with a space and a non-ASCII character (TEMP/TMP set to C:\dev\lw\tmp com espaço ç): exit 0, 258 checks, 0 failures, and nothing left behind in that folder.

Synthetic files only, no game data. AI-assisted (Claude Code).

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

P2 — Ordinary buffers above 32 MiB are accepted (runtime/shims/dstorage.cpp:763-771)

The GDK request contract allows ordinary destinations up to 32 MiB. Above that, the request must use 64-KiB or 2-MiB physical pages for each buffer exceeding 32 MiB, while remaining under the 1-GiB combined limit. This shim rejects requests that explicitly ask for pages, but the ordinary-buffer path checks only the 1-GiB cap. A 33-MiB file-to-memory read (or memory-to-memory request with an unpaged source/destination over 32 MiB) therefore reaches read_file_range/guarded_move and can report success despite violating the console request contract. Please reject unpaged oversized buffers before touching them, or implement the required page path. GDK request size rules

P2 — GetStats counts requests before Submit and never reports pending work (runtime/shims/dstorage.cpp:514-518)

TotalRequestCount and both byte totals are incremented in EnqueueRequest, so enqueueing a request and never calling Submit already changes the cumulative totals. PendingRequestCount is never updated, so it remains zero while a submitted request is executing. GDK defines total requests as submitted requests and pending requests as work whose processing has started but has not completed. Please move cumulative accounting to submission and update the pending count around actual processing. A regression can enqueue without submitting, then observe stats, and separately block/observe a submitted request in flight. GDK priority statistics

@AirKyzzZ

Copy link
Copy Markdown
Contributor

Tested c77338e6 on RTX 2060, NVIDIA 566.14, Windows 10 22H2 (19045), clang-cl 23.1.6 + SDK 10.0.26100: dstorage crashes with an access violation (0xC0000005) under clang-cl.

Full ctest: same as main 03b09a08 (only the 2 known failures) except dstorage, which dies every run, right after the status/fence error cases. The only __try in the shim is guarded_move (runtime/shims/dstorage.cpp:398), and clang-cl only catches a fault there with asynchronous EH. Without /EHa, the access violation from the copy into the reserved page (test_memory_queue) is never caught. runtime/CMakeLists.txt:363 already explains the same thing for tiny_dll. With target_compile_options(dstorage_test PRIVATE $<$<CXX_COMPILER_ID:Clang>:/EHa>) added locally: 258 checks, 0 failures, 10/10 repeats. gta6rt compiles dstorage.cpp without that flag too, so a clang-cl runtime would crash on a bad memory destination instead of returning E_DSTORAGE_ACCESS_VIOLATION. It needs the same flag, or a set_source_files_properties on dstorage.cpp. MSVC is unaffected, which fits the MSVC 50/50 run above. unimplemented_policy passes. AI-assisted.

mariuslozo-boop and others added 3 commits November 23, 2026 06:37
…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>
@mariuslozo-boop

Copy link
Copy Markdown
Author

Thanks for the reviews and test reports. Fixed in ac1843da, and merged the newest main (de671352; the only conflict was the build_runtime.ps1 file list).

@Flyander, P2: unpaged buffers over 32 MiB. A request with a destination over 32 MiB (DSTORAGE_MAX_4K_PAGE_DESTINATION_SIZE) now fails with E_DSTORAGE_REQUEST_TOO_LARGE before any memory is touched. The 64 KiB and 2 MiB page paths are not implemented yet (they return E_NOTIMPL), so this covers every buffer over 32 MiB. The source must equal the destination for uncompressed requests, so the check covers memory-to-memory requests too. The test puts the over-limit buffers in reserved, uncommitted memory, so a request that was not refused would report an access violation. It also checks that an exactly 32 MiB copy succeeds.

@Flyander, P2: GetStats.

  • TotalRequestCount and the two byte totals now grow when a request is submitted (Submit, auto-submit or Close), not when it is enqueued.
  • PendingRequestCount counts a request while the worker processes it.
  • The test enqueues without submitting and checks the totals have not changed. It then holds a copy on a guard page with a vectored exception handler, and checks that the request is counted and pending while it is held and no longer pending once it completes.
  • TotalStatusCount and TotalFenceCount are still counted at enqueue. The reference calls them "the total number of status requests" and "fence requests", without "submitted". docs/directstorage.md says so.

@AirKyzzZ, clang-cl. dstorage.cpp now gets /EHa under clang-cl through set_source_files_properties, so both gta6rt and dstorage_test get it, as tiny_dll does. This is the same flag you tested locally. I have only MSVC here, so I did not run it under clang-cl myself.

Tested: Windows 11, RTX 5070 Ti, MSVC 19.44, RelWithDebInfo.

  • dstorage: 272 checks, 0 failures, 30/30 repeats.
  • The three new checks that matter (over 32 MiB refused, not counted before Submit, pending while running) fail with the previous shim.
  • Full ctest -j 8: 157/157 on the merged tree. The Python tests match main.

An independent reviewer read the fix (lock order, the CMake property scope, the guard-page test) and found nothing blocking. Its two small points, checking the VirtualAlloc results in the test, are in the commit.

AI-assisted (Claude Code).

@Ayinaki

Ayinaki commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Tested 45c39cf on Windows 10.0.26200, MSVC 14.52 (Visual Studio 18 2026, x64, RelWithDebInfo): pass. These targets are CPU-only (file-to-memory DirectStorage), no GPU path.

Built dstorage_test and unimplemented_policy_test from this head and ran them:

  • dstorage_test: 272 checks, 0 failures. The only stderr line is the expected per-code log ("dstorage: an entry failed with 0x80070006 (command type 3; logged once per code)"), i.e. the shim's failure reporting, not a failing check.
  • unimplemented_policy_test: 98 checks, 0 failed.

@JRamos1993

Copy link
Copy Markdown
Contributor

Tested 45c39cf merged onto main 3faac55 on an RTX 5090 (driver 616.92), Windows 11, MSVC 19.44, Vulkan SDK 1.4.363, RelWithDebInfo:

  • Full ctest: 179/179.
  • dstorage and unimplemented_policy: pass 20 of 20 runs each, and pass under LEONIDA_VK_VALIDATION=1 with 0 validation messages.
  • Warnings: none new in the files this PR changes.

AI-assisted (Claude Code).

@Stalkerino

Copy link
Copy Markdown

Wine 11.22 on CachyOS x86-64, clang-cl/xwin + SDL3. I compared local runs with the same GameInput fix, experimental CPU-side XMem backing and isolated display. Before adding your change, startup stops at xcrdapi.dll!DStorageGetFactory. With head 45c39cf6 integrated, the title obtains the factory, opens a file through IDStorageFactoryX::OpenFile and reaches XMemAllocatePhysicalPages. No GPU was used in this comparison.

The synthetic DirectStorage test passed 270 of 272 checks in this environment. The file/overlay reads returned the expected bytes. Both failures were in test_stats_timing: the guard-page rendezvous timed out and the pending count was then sampled after the copy had finished. The final copy and completion checks passed. I have not established the cause of that timing difference on Wine.

@jlric

jlric commented Nov 23, 2026

Copy link
Copy Markdown

Tested 45c39cf6 on CachyOS x86-64, Wine 11.22, clang-cl/xwin. unimplemented_policy passed 10/10 runs (98 checks each). dstorage reproduced 2 failures out of 272 checks: the guard-page timing fixture never signals entry, and the pending-count assertion then fails. The copy and completion assertions pass. Synthetic, CPU-only. AI-assisted.

ASTROWwwW pushed a commit to ASTROWwwW/Leonida that referenced this pull request Nov 23, 2026
…StorageGetFactory) with file-to-memory reads

Author: mariuslozo-boop

Two conflicts, both resolved by keeping each side: the docs/README.md
index row and the dstorage ctest entry next to the XTaskQueue tests in
runtime/CMakeLists.txt. Not built here: no Windows toolchain.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UkEUa9YfGQH4p9g1Guw9gq
@aidity

aidity commented Nov 23, 2026

Copy link
Copy Markdown

Windows MSVC integration validation on current main 1cc6e3c with executable TLS slot-zero support: dstorage and unimplemented_policy CTests pass, together with all three loader_tls_index0 scenarios and run_tiny_tls_ga (6/6). A local startup diagnostic now reaches DStorageGetFactory and IDStorageFactoryX::OpenFile through xcrdapi.dll, then stops at the still-unimplemented XMemAllocatePhysicalPages export. This diagnostic uses CPU-only backing for unsupported committed graphics allocations, so it does not establish normal boot or GPU correctness. No game files, bytes or logs included. Thanks for the implementation; no duplicate PR opened.

@quackottu

Copy link
Copy Markdown
Contributor

Rebased onto current main (1cc6e3c) with the conflicts resolved: runtime/CMakeLists.txt (dstorage_test added next to main's new test blocks, if/endif nesting checked), scripts/build_runtime.ps1 (dstorage.cpp added to the cl.exe fallback list) and docs/README.md (DirectStorage row added beside the new xcl_compare/gameinput rows). Tests: build OK; ctest dstorage, file_system, registry, unimplemented_policy, xgameruntime* and xmem pass. Branch: https://github.com/quackottu/Leonida/tree/rebase-pr4348 — feel free to take it (e.g. git reset --hard to it and force-push), or I can open a replacement PR crediting you if you prefer.

@Etoile-Bleu

Copy link
Copy Markdown
Contributor

This PR conflicts with main now (docs/README.md and runtime/CMakeLists.txt, one hunk each), and DirectStorage is the stop after the TLS index in the retail boot: with the memory and TLS PRs in, the title calls xcrdapi.dll!DStorageGetFactory (exe+0x1d8e4f5) and breaks on an int3 when it is unimplemented; with this PR the trace goes through DStorageGetFactory and IDStorageFactoryX::OpenFile to the next stop. A conflict-free merge of main (c25b9f28) into this head is on my fork: Etoile-Bleu/Leonida, branch rebase-pr4348, commit cdb566a85 (https://github.com/Etoile-Bleu/Leonida/tree/rebase-pr4348). git fetch https://github.com/Etoile-Bleu/Leonida rebase-pr4348; I did not touch your branch.

The resolution is mechanical: main's test and XTaskQueue block stays and the dstorage_test registration follows in its own if(), and docs/README.md has main's rows plus the directstorage.md row.

Tested at cdb566a85 on Windows 11 26200, MSVC 14.44, RTX 5070 Ti: full runtime build, ctest -R 'dstorage|xgameruntime|run_tiny': 25 of 25 pass (dstorage included); the docs tests and test_ci_registration pass. No game data in this comment. AI-assisted: yes.

@0klavair

Copy link
Copy Markdown
Contributor

Heads-up for the rebase, from merging this onto current main (8d85654b) twice locally: runtime/CMakeLists.txt conflicts at the wait_registration_test block. Both a plain resolution (keep both sides) and a union merge drop the endif() that closes if(WIN32 AND TARGET gta6rt_xtaskqueue), right before this PR's if(WIN32 AND TARGET dstorage_test). CMake then stops with Flow control statements are not properly nested (CMakeLists.txt:449). With that endif() restored, it builds, and on the retail executable (own 1.0.2.1 copy, Windows 11 23H2, RTX 5060) the boot gets past DStorageGetFactory to XMemAllocatePhysicalPages, as expected. AI-assisted (Claude Code).

@Zunraz

Zunraz commented Nov 23, 2026

Copy link
Copy Markdown

Independent native Windows check of 45c39cf6f4148aebbc8a88d476bea755887d35bd, integrated with main 8575d36ed, #4313, #6919 and #6991 (plus the previously reported RT-488 cache initialization). clang-cl 21.1.8 + xwin SDK 10.0.26100, static CRT; Windows build 26300, NVIDIA RTX 5090. The earlier #7017 VM shim was superseded locally by main's merged implementation.

  • dstorage_test: 272 checks, 0 failures.
  • Retail unimplemented-import count falls from 22 to 21. The previous DStorageGetFactory stop is gone.
  • The bounded --run then creates the Vulkan device successfully and reaches the known proxy_slot<26> access violation (d3d12_xs: device slot 26 takes the return buffer in RCX and the device in RDX, as the retail executable calls it (RT-5) #6964). No image/frame yet; this is progress past the storage factory, not a complete DirectStorage/GPU validation.
  • Resolved the existing CMake conflict by keeping main's complete XTaskQueue test block, its closing endif(), and the separate dstorage test registration. Both docs-index rows are retained.

All raw traces stay local. Socket creation, DNS and network-transmission entry points were debugger-guarded; only local Winsock initialization was permitted. No game files, title offsets or register contents attached. AI-assisted (Codex).

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.