upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/docs
diff options
context:
space:
mode:
authorubiquitarianism <283527159+ubiquitarianism@users.noreply.github.com>2026-11-23 22:36:12 -0500
committerGitHub <noreply@github.com>2026-11-23 22:36:12 -0500
commitfabe844cd88e6fd6469ffd3d869bbe062ebefe1f (patch)
treeffd126d5d76910e65b140c235dfdcf629f292cc5 /docs
parentf9e7e3e1bfa718eb4d8ca84fd1dbe617038d48d7 (diff)
parent2d7be48dec529446e0ead3393e2b3acabb29ff64 (diff)
Merge pull request #131 from Mumogg/restore-directstorage
runtime: restore the console DirectStorage shim, with the typed-error inflate it needs (RT-DSTORAGE-RESTORE, #47)
Diffstat (limited to 'docs')
-rw-r--r--docs/directstorage.md197
1 files changed, 197 insertions, 0 deletions
diff --git a/docs/directstorage.md b/docs/directstorage.md
new file mode 100644
index 000000000..dc2987a55
--- /dev/null
+++ b/docs/directstorage.md
@@ -0,0 +1,197 @@
1# DirectStorage
2
3The console title reads its streamed data through Xbox DirectStorage: `DStorageGetFactory` hands out a factory, the
4factory opens files and creates queues, and a queue reads file or memory ranges into memory and reports completion
5through status arrays, `ID3D12Fence` signals and events. `runtime/shims/dstorage.cpp` serves that API on the PC:
6files open through the runtime's `GAME:` mapping and write overlay, and a worker thread per queue does the reads
7and inflates zlib requests.
8This page records which DLL and ABI the console title is expected to use, how sure that is, and what the shim does.
9
10## Which DLL and which ABI: the evidence
11
12The game executable is not in the package available here, so its import table is unmeasured
13([runtime_imports.md](runtime_imports.md)). What is known:
14
15| Evidence | Source | What it says |
16|---|---|---|
17| None of the 16 shipped DLLs imports DirectStorage | [runtime_imports.md](runtime_imports.md) (6 Xbox-specific imports, all `xmem`/`d3d12_xs`), [textures.md](textures.md) "The shipped binaries" (no `DStorage` import, export or string) | DirectStorage, if used, is called by the executable itself |
18| The texture chunks carry the `DSTORAGE_BCPACK_MODE` values 1-7 and mix zlib and BCPack chunks | [textures.md](textures.md) "What BCPack is" | The data is laid out for console DirectStorage's decompression (DEFLATE, then BCPack, then swizzle) |
19| A sibling console layer's export inventory names `dstorage_xs.dll` as console DirectStorage | [d3d12_vulkan.md §7](d3d12_vulkan.md#7-prior-art-and-measured-xbox-abi) | The console module name, measured elsewhere, not here |
20| A retail title run by a sibling layer has `xcrdapi` in its console-only library set | [d3d12_vulkan.md §7](d3d12_vulkan.md#7-prior-art-and-measured-xbox-abi) | Only the name. Nothing in this repository says what `xcrdapi.dll` exports |
21| The GDK reference: `DStorageGetFactory` is in header `dstorage_xs.h`, library `dstorage_xs.lib`; the interface pages give library `dstorage.lib`; all say "Xbox Series consoles" | [GDK DStorage reference](https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/system/dstorage/dstorage_members) | The console API has its own names (`IDStorageFactoryX`, `IDStorageQueueX`, `IDStorageFileX`, `IDStorageStatusArrayX`) and structures that differ from the PC API |
22| `registry.cpp` classified `dstorage.dll`/`dstorage_xs.dll` `DStorageGetFactory` as returning an HRESULT | `runtime/shims/registry.cpp` | It was an unimplemented import; `xcrdapi.dll` was not named |
23
24**Chosen ABI: the console one** (the GDK's `IDStorageFactoryX2`/`IDStorageQueueX2`/`IDStorageFileX`/
25`IDStorageStatusArrayX` and its `DSTORAGE_REQUEST`), served as `DStorageGetFactory` under all three names:
26
27| Module | Confidence | Why |
28|---|---|---|
29| `dstorage_xs.dll` | medium | The reference's `dstorage_xs.lib` and the sibling inventory agree; not measured in this title |
30| `xcrdapi.dll` | low | Only a name in a library list. Owning the module also means a title's `LoadLibrary("xcrdapi.dll")` gets the shims' pseudo-handle, and `GetProcAddress` for any other name returns `NULL` (logged). Static imports of other `xcrdapi` names are unchanged |
31| `dstorage.dll` | low | The interface pages name `dstorage.lib`. Every caller of `gta6rt`'s import table is a console build, so this name serves the console ABI too, not the PC one |
32
33The PC DirectStorage ABI (`dstorage.h`: `IDStorageFactory` with `DSTORAGE_REQUEST` source and destination unions,
34`ID3D12Resource` destinations) is **not served**. A caller that asks for a PC interface id gets `E_NOINTERFACE` and a
35log line, never an object of the wrong shape. The one exception is `IDStorageStatusArray`, whose two methods are the
36console interface's in the same order (console D3D12 binaries reuse the PC SDK's ids), so a status array accepts its
37id.
38
39Owning a module has a run-time side: `LoadLibrary` of `xcrdapi.dll` or `dstorage.dll` (or `dstorage_xs.dll`) gets
40the shims' pseudo-handle even when the package ships its own copy of that DLL, so the shim shadows a packaged copy
41at run time (`library_loader.cpp` asks the registry before the bundled loader). None of the 16 shipped DLLs is one
42of these, so nothing is shadowed today.
43
44### What is not public, and the choice made
45
46| Unknown | Choice | Confidence | Where to change it |
47|---|---|---|---|
48| Vtable order of the console interfaces (the reference lists methods alphabetically) | The PC header's order for the methods both APIs have; console-only methods where the overview lists them: factory `CreateQueue, OpenFile, CreateStatusArray, SetCpuAffinity, SetDebugFlags, SetStagingBufferSize`, then `GetStats` (X1), `CreateQueue1` (X2); queue `EnqueueRequest, EnqueueStatus, EnqueueSignal, Submit, CancelRequestsWithTag, Close, GetErrorEvent, RetrieveErrorRecord, Query`, then `EnqueueSetEvent` (X1), `Query1` (X2); status array `IsComplete, GetHResult`; file `Close, GetHandle` | queue, status array: medium; file: medium; factory: low (the `SetCpuAffinity` slot is a guess) | `runtime/shims/dstorage_xs_abi.h`, one declaration per interface |
49| Interface ids of the X interfaces | A creating call (`DStorageGetFactory`, `CreateQueue*`, `OpenFile`, `CreateStatusArray`) accepts an id it has not seen for the kind of object it hands out and logs it once (`[rt] dstorage: ... asked for {...}: serving the ... interface`), so the first boot records them. It refuses an id seen for another kind, a PC DirectStorage id, and the system COM interfaces (the `{xxxxxxxx-0000-0000-C000-000000000046}` range with `IMarshal`, `IClientSecurity`, ..., and `IAgileObject`, `INoMarshal`, `IInspectable` and a few more). `QueryInterface` follows [d3d12_vulkan.md](d3d12_vulkan.md)'s rule (an unknown id is `E_NOINTERFACE`, logged): it accepts only `IUnknown`, the declared `IDStorageStatusArray` id for a status array, and the ids a creating call accepted for that kind of object | n/a (a policy, not a fact) | `IidPolicy` in `runtime/shims/dstorage.cpp` |
50| `DSTORAGE_MIN_QUEUE_CAPACITY`, `DSTORAGE_MAX_QUEUE_CAPACITY`, `DSTORAGE_REQUEST_MAX_NAME` | The PC header's values: `0x80`, `0x2000`, 64 | medium | `dstorage_xs_abi.h` |
51| `E_DSTORAGE_*` values | The PC `dstorageerr.h` values (`FACILITY_GAME`, `0x8924xxxx`). That header also defines the console-only failures (zlib, BCPack, swizzle, XVD), so the space is shared. `E_DSTORAGE_DECOMPRESSION_ERROR` (`0x89240030`) is on the public constants page; `E_DSTORAGE_ZLIB_BAD_HEADER`, `_ZLIB_BAD_DATA` and `_ZLIB_PARITY_FAIL` (`0x89240031`-`33`) have no public description, and their names and values come from the header-generated bindings of the `direct-storage` crate (Sources). Which failure the console reports with each zlib code is inferred from the names | medium-high (values); medium (zlib codes' meaning) | `dstorage_xs_abi.h` |
52| Struct layouts | The compiler's x64 layout of the reference's declarations, pinned with `static_assert` (`DSTORAGE_REQUEST` 72 bytes, `DSTORAGE_QUEUE_DESC` 24, `DSTORAGE_QUEUE_DESC1` 32); `DSTORAGE_REQUEST_OPTIONS` is decoded from `AsUINT64` by explicit bit positions (zlib bit 0, BCPack 1-4, swizzle 5-20, destination pages 21, source type 22, source pages 23, reserved 24-63) | high for member order and types, medium for the bit allocation (MSVC allocates bit-fields from bit 0 up) | `dstorage_xs_abi.h` |
53
54The first boot with the executable settles most of this: the dry-run report shows which module it imports
55`DStorageGetFactory` from, and the log lines give the interface ids.
56
57## What the shim does
58
59- **Factory**: one object for the process, never freed (its reference count does not drop below one).
60 `SetDebugFlags` and `SetCpuAffinity` are stored only (a console core mask means nothing on the host).
61 `SetStagingBufferSize` accepts 0, 16, 20, 24, 28 and 32 MiB, fails with `E_DSTORAGE_INVALID_STAGING_BUFFER_SIZE`
62 otherwise and with `E_DSTORAGE_STAGING_BUFFER_LOCKED` while a queue or file exists; there is no staging buffer.
63 `GetStats` reports the counts the shim keeps (queues per priority, requests, bytes, files, errors, zlib
64 inflates: `TotalDecompressionRequestCount` grows when a zlib request's inflate starts, which is after its checks
65 passed and its source was read, `PendingDecompressionRequestCount` is the inflates running, and
66 `DecompressionErrors` the streams that failed). As
67 `DSTORAGE_PRIORITY_STATS` defines them, `TotalRequestCount` and the byte totals grow when a request is submitted
68 (not when it is enqueued), and `PendingRequestCount` counts the requests the worker is processing; status and fence
69 entries are counted when they are enqueued. A bad
70 argument (a null pointer, an invalid queue desc or staging size) is logged once per method and kind, so a wrong
71 vtable guess shows up in the log as arguments that make no sense for the method.
72- **Files**: `OpenFile` goes through the registry's `kernel32.dll!CreateFileW`, the shim in `file_system.cpp`, so a
73 `GAME:` path reads the overlay copy first, then the package, and a path that climbs out is refused (a host path is
74 passed through). Read access, `FILE_SHARE_READ`, as the overview says; a failed open returns the Win32 error as an
75 HRESULT. `GetHandle` returns a handle of its own (`ReOpenFile`, read access, `FILE_SHARE_READ`) that the caller
76 closes; it has its own file position, which the shim's reads do not move. `Close` waits for the submitted requests
77 that read the file; a request processed after it fails with `E_DSTORAGE_FILE_NOT_OPEN`. A request holds a reference
78 on its file, so the last `Release` cannot close a file a request still reads.
79- **Queues**: capacity `0x80`..`0x2000`, priority `LOW`..`REALTIME`, a memory-sourced queue must be `REALTIME`
80 (`E_DSTORAGE_INVALID_QUEUE_CAPACITY`, `_INVALID_QUEUE_PRIORITY`, `_INVALID_MEMORY_QUEUE_PRIORITY`). A queue
81 holds `capacity - 1` entries; `Query` reports the empty slots and the entries left before the automatic submit,
82 which happens when the entries enqueued since the last submit reach half the capacity (unless
83 `DSTORAGE_QUEUE_OPTIONS::AutoSubmitDisabled`). An enqueue into a full queue waits for space, as the reference
84 says; with auto-submit disabled only a `Submit` from another thread frees it. One worker thread per queue runs
85 the submitted entries in order, so every notification follows all the entries before it.
86- **Requests**: copied at enqueue. A file request reads `SourceSize` bytes at `FileOffset` into `Destination`; a
87 memory request copies `Source` to `Destination` (`memmove`, so an overlapping pair is safe); a zlib request
88 inflates those `SourceSize` bytes into `Destination` (below). Checked in this order when the worker reaches the
89 request:
90 1. cancelled: a success, whatever else is wrong with it;
91 2. found at enqueue: a null request pointer (`E_INVALIDARG`) or a file object the shim did not make
92 (`E_DSTORAGE_INVALID_FILE_HANDLE`);
93 3. reserved option bits (`E_DSTORAGE_RESERVED_FIELDS`), then the source type against the queue's
94 (`E_DSTORAGE_INVALID_SOURCE_TYPE`);
95 4. BCPack mode above 7, swizzle mode above 4 (`_INVALID_BCPACK_MODE`, `_INVALID_SWIZZLE_MODE`), then BCPack or
96 swizzle, with or without zlib, then physical pages (`E_NOTIMPL`, logged once: later PRs);
97 5. an `IntermediateSize` (`_INVALID_INTERMEDIATE_SIZE`: it is the size between the inflate and the BCPack decode,
98 so only a zlib + BCPack request has one), a `DestinationSize` other than `SourceSize` without zlib, or not
99 larger than `SourceSize` with it (`_INVALID_DESTINATION_SIZE`: the rule `dstorageerr.h` gives for that code,
100 and what `DSTORAGE_REQUEST` says of `DestinationSize`), more than 1 GiB in total, then a buffer over 32 MiB
101 (`_REQUEST_TOO_LARGE` for both: `DSTORAGE_REQUEST` allows a buffer over 32 MiB only with 64 KiB or 2 MiB pages,
102 which are not implemented yet; the source is never larger than the destination here, so the destination's
103 limit covers it), then a zlib file request whose `FileOffset` is not 16-byte aligned (`_INVALID_FILE_OFFSET`,
104 as `DSTORAGE_REQUEST` requires);
105 6. a null destination, a null source (memory) or a null file (`E_INVALIDARG`), a closed file (`_FILE_NOT_OPEN`);
106 7. a zero size: a success that touches no memory (an assumption: the reference does not say);
107 8. a range past the end of the file (`E_DSTORAGE_END_OF_FILE`), then a destination or source the process cannot
108 access (`E_DSTORAGE_ACCESS_VIOLATION`; the worker survives it). This needs asynchronous exceptions under
109 clang-cl, so `runtime/CMakeLists.txt` builds `dstorage.cpp` with `/EHa` there; MSVC always catches it.
110
111 Step 7 does not apply to a zlib request (its `DestinationSize` is never 0 after step 5); its stream fails as
112 described next.
113- **zlib** (`ZlibDecompress` alone): the source, `SourceSize` bytes of the file or of memory, is read into a staging
114 buffer and inflated there by the runtime's RFC 1950 inflater (`leonida::zlib_inflate` in
115 `runtime/src/shader_library.h`, the one the shader library uses for XBCH blobs). The result is copied to
116 `Destination` only when it is exactly `DestinationSize` bytes, so a stream that fails leaves the destination as it
117 was, and a memory source inside its own destination (in-place loading) inflates correctly. Both buffers are at
118 most 32 MiB (step 5). Step 5 also means a stream of stored blocks only, which is larger than what it holds, is
119 refused with `_INVALID_DESTINATION_SIZE` before it is read, as the documented rule implies. The stream is a zlib
120 stream: the two header bytes, the deflate blocks (stored, fixed and
121 dynamic Huffman), the Adler-32 of the result. Bytes after the Adler-32 are not read, so a `SourceSize` rounded up
122 over padding works (an assumption: the reference does not say). The game's own data agrees with RFC 1950: the
123 texture pools' codec-8 chunks, laid out for this decompression ([textures.md](textures.md)), inflate with
124 Python's `zlib.decompress`, which checks the header and the Adler-32 (`tools/ttpf_mips.py`). A failure:
125
126 | Stream | HRESULT |
127 |---|---|
128 | header not deflate, a window over 32 KiB, a wrong check value, or a preset dictionary | `E_DSTORAGE_ZLIB_BAD_HEADER` (`0x89240031`) |
129 | a reserved block type, an invalid code, a distance before the start, or a truncated stream | `E_DSTORAGE_ZLIB_BAD_DATA` (`0x89240032`) |
130 | Adler-32 mismatch | `E_DSTORAGE_ZLIB_PARITY_FAIL` (`0x89240033`) |
131 | inflates to more or fewer bytes than `DestinationSize` | `E_DSTORAGE_DECOMPRESSION_ERROR` (`0x89240030`; no code names a size mismatch, so the generic one) |
132
133 The inflater decodes one bit at a time, on the queue's worker: correct, not fast. A faster decoder (table lookup)
134 can replace it behind `zlib_inflate` without touching the request path.
135- **Cancel**: `CancelRequestsWithTag(mask, value)` marks every request enqueued before the call and not yet started
136 whose `(CancellationTag & mask) == value`. A cancelled request completes as a success without reading and is not
137 counted as a failure, as the overview and the reference say, even when it also had an error found at enqueue.
138- **Notifications**: `EnqueueStatus` sets the entry to `E_PENDING` at once and, when reached, to the first failure
139 since the previous status or signal (else `S_OK`); `IsComplete` is `GetHResult != E_PENDING`; an index past the
140 array is `E_DSTORAGE_INDEX_BOUND`, a foreign or null array `E_DSTORAGE_INVALID_STATUS_ARRAY`. `EnqueueSignal` calls
141 `ID3D12Fence::Signal` (PC slot 10, which the `d3d12_xs` fence proxies forward) on the worker thread; a null fence is
142 `E_DSTORAGE_INVALID_FENCE`. `EnqueueSetEvent` duplicates the handle at once and sets the duplicate, then closes it,
143 so an event the title closes in the meantime (and a handle value reused for another object) is never the one set; a
144 null or invalid handle is recorded as a failure. Each notification holds a reference on its array or fence until it
145 has run.
146- **Errors**: a failure goes into the status entry, the queue's error record (failure count and the first failure
147 since the last `RetrieveErrorRecord`, with the file name the title opened) and sets the error event.
148 `GetErrorEvent` returns a duplicate handle (the reference says the caller closes it). `RetrieveErrorRecord`
149 clears the record and resets the event; with nothing recorded it returns `DSTORAGE_COMMAND_TYPE_NONE`. A failed
150 `SetEvent` is recorded with command type 3 (the PC API's `EVENT`; the console enum stops at 2).
151- **Close and release**: `Close` submits what is enqueued, waits until the worker has run it all and stops the
152 worker; later enqueues are dropped and recorded as `E_DSTORAGE_QUEUE_CLOSED`. The last `Release` closes the same
153 way, so a queue released with requests in flight finishes them first.
154
155## Not done yet (later PRs)
156
157- **BCPack** (`BcpackMode`; `tools/bcpack.py` is the reference decoder), then **swizzle** (`SwizzleMode`). The
158 decode order is DEFLATE, BCPack, swizzle; with both zlib and BCPack `IntermediateSize` is the size between them
159 (the inflate's output, the BCPack decoder's input), and `FileOffset` must be 16-byte aligned. Each becomes a stage
160 after `inflate_request`'s inflate and before its destination write, so the request checks above stay where they
161 are.
162- **Physical pages** (`SourceIsPhysicalPages`, `DestinationIsPhysicalPages`): arrays of 64 KiB page numbers from
163 `XMemAllocatePhysicalPages`; needs the `xmem` shim to translate a page number to the address it mapped.
164- **GPU memory**: the console API has no GPU destinations of its own (memory is unified, so a destination is an
165 address). An address inside memory the Vulkan layer backs will need its write routed to that memory. The destination
166 is written in two places, both in `execute_request` (`read_file_range` for a file source, `guarded_move` for a
167 memory source), so that change stays inside the request path.
168- **Parallel reads**: the worker reads one request at a time. Overlapped reads with in-order retirement of
169 notifications would keep the order guarantee.
170
171## Tests
172
173`runtime/test/dstorage_test.cpp` (ctest `dstorage`) runs on synthetic files in `%TEMP%` through the registry entries
174under all three module names: `GAME:` reads with an overlay copy winning, offsets, zero size, a range past the end,
175cancellation, auto-submit, a full queue, status arrays, fences (a CPU fence object that checks the data is in place
176when it is signalled), events, error records, file and queue close with requests in flight, a destination the
177process cannot write, four threads enqueueing at once, the interface-id policy (unknown and system ids refused by
178`QueryInterface`, learned by creating calls), a `GetHandle` handle with its own file position, an event closed (and
179its handle value reused) before it is set, and cancelled requests that also had an enqueue error. zlib requests use
180synthetic streams only: two made with Python's `zlib` (level 9: one dynamic-Huffman block; level 1: one
181fixed-Huffman block) from text the test rebuilds, and stored-block streams the test builds, one of them a stored
182block followed by the dynamic one. They are read from a file and from memory (also in place); a bad header, a
183preset dictionary, a reserved block type, a truncated stream, an Adler-32 mismatch, a stream shorter and one longer
184than `DestinationSize`, a stored stream larger than its result, an unaligned offset, an `IntermediateSize`, zlib with
185BCPack or swizzle (`E_NOTIMPL`), an unreadable source and an unwritable destination each get their code, a failed
186stream leaves its destination untouched, and the decompression statistics count them.
187
188## Sources and licences
189
190| Source | Facts used | Licence / use |
191|---|---|---|
192| [GDK DStorage reference](https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/system/dstorage/dstorage_members) and its function, interface, structure and enumeration pages | Names, method signatures, structure members, enum values, requirements rows | [Microsoft Learn Terms of Use](https://learn.microsoft.com/en-us/legal/termsofuse); facts paraphrased, no text copied |
193| [DirectStorage overview (GDK)](https://learn.microsoft.com/en-us/gaming/gdk/docs/features/console/storage/directstorage/directstorage-overview) | Queue, auto-submit, cancellation, notification order, file sharing, decode order | Same terms; paraphrased |
194| `dstorage.h`, `dstorageerr.h` in the public `Microsoft.Direct3D.DirectStorage` 1.3.0 NuGet package | PC method order, interface ids (to refuse them), capacity and name-length constants, `E_DSTORAGE_*` values | Read for facts only; not vendored. `runtime/shims/dstorage_xs_abi.h` is Leonida's own declaration |
195| [DirectStorage constants](https://learn.microsoft.com/en-us/windows/win32/dstorage/dstorage-constants) (Win32 reference) | `E_DSTORAGE_DECOMPRESSION_ERROR` = `0x89240030`; `E_DSTORAGE_INVALID_DESTINATION_SIZE`: equal to the length without decompression, larger with it; `E_DSTORAGE_INVALID_FILE_OFFSET` is the offset invalid for a decompression mode | [Microsoft Learn Terms of Use](https://learn.microsoft.com/en-us/legal/termsofuse); paraphrased |
196| [`direct-storage` crate](https://docs.rs/direct-storage/0.5.1/src/direct_storage/bindings.rs.html) 0.5.1 (bindings generated by `windows-bindgen` from the DirectStorage headers; 0.2.0's `errors.rs` has the same values) | `E_DSTORAGE_ZLIB_BAD_HEADER` `0x89240031`, `E_DSTORAGE_ZLIB_BAD_DATA` `0x89240032`, `E_DSTORAGE_ZLIB_PARITY_FAIL` `0x89240033` (names and values only) | MIT/Apache-2.0; two constants' names and values, no code copied |
197| [RFC 1950](https://www.rfc-editor.org/rfc/rfc1950) and [RFC 1951](https://www.rfc-editor.org/rfc/rfc1951) | The zlib stream and DEFLATE formats `zlib_inflate` decodes | Public specifications |