upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/shims
diff options
context:
space:
mode:
authormariuslozo-boop <254631011+mariuslozo-boop@users.noreply.github.com>2026-11-23 01:48:51 +0100
committermariuslozo-boop <254631011+mariuslozo-boop@users.noreply.github.com>2026-11-23 01:48:51 +0100
commitf87d05fdd3a96b5f42e712d376cfc0b9b4e398d5 (patch)
tree6ec9160e28831d6d4a7170e9b06249cc0658827d /runtime/shims
parent03b09a086592a197db64d91655c6e65c30764d96 (diff)
runtime: console DirectStorage (DStorageGetFactory) with file-to-memory 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>
Diffstat (limited to 'runtime/shims')
-rw-r--r--runtime/shims/dstorage.cpp1030
-rw-r--r--runtime/shims/dstorage_xs_abi.h378
-rw-r--r--runtime/shims/registry.cpp7
3 files changed, 1413 insertions, 2 deletions
diff --git a/runtime/shims/dstorage.cpp b/runtime/shims/dstorage.cpp
new file mode 100644
index 000000000..9766186fa
--- /dev/null
+++ b/runtime/shims/dstorage.cpp
@@ -0,0 +1,1030 @@
1// Xbox DirectStorage for a mapped title: DStorageGetFactory and the IDStorageFactoryX2 / IDStorageQueueX2 /
2// IDStorageFileX / IDStorageStatusArrayX objects of the console API (dstorage_xs_abi.h).
3//
4// Served as dstorage_xs.dll, xcrdapi.dll and dstorage.dll!DStorageGetFactory; docs/directstorage.md has the evidence
5// for those names, the console ABI and what each method does here. In short:
6// - OpenFile resolves kernel32.dll!CreateFileW through the shim registry, so a GAME: path goes through the
7// runtime's console path mapping and write overlay (file_system.cpp) exactly as the title's own CreateFileW.
8// - Each queue has one worker thread that runs its submitted entries in order: a request reads a file range or
9// copies a memory range into the destination, a status entry, fence signal or event runs when every entry before
10// it has. Completion is therefore in queue order, as the API guarantees.
11// - zlib, BCPack, swizzle and physical-page requests fail with E_NOTIMPL for now (later PRs: they become stages
12// between execute_request's read and its destination write).
13// Nothing here goes online or touches the GPU.
14#include <windows.h>
15#include <d3d12.h>
16
17#include <algorithm>
18#include <atomic>
19#include <condition_variable>
20#include <cstdio>
21#include <cstring>
22#include <deque>
23#include <memory>
24#include <mutex>
25#include <new>
26#include <set>
27#include <string>
28#include <thread>
29#include <unordered_set>
30#include <vector>
31
32#include "dstorage_xs_abi.h"
33#include "shims.h"
34
35using namespace dsx;
36
37namespace {
38
39// ---- Logging ------------------------------------------------------------------------------------------------------
40
41// Process-lifetime state is allocated once and never freed: a worker thread may still run while statics are destroyed
42// at exit.
43std::mutex& log_mutex() {
44 static auto* m = new std::mutex;
45 return *m;
46}
47
48void log_once(const std::string& key, const std::string& line) {
49 static auto* seen = new std::set<std::string>;
50 std::lock_guard lock(log_mutex());
51 if (!seen->insert(key).second) return;
52 std::fprintf(stderr, "[rt] dstorage: %s\n", line.c_str());
53}
54
55std::string guid_text(const GUID& g) {
56 char b[48];
57 std::snprintf(b, sizeof b, "{%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}", g.Data1, g.Data2, g.Data3,
58 g.Data4[0], g.Data4[1], g.Data4[2], g.Data4[3], g.Data4[4], g.Data4[5], g.Data4[6], g.Data4[7]);
59 return b;
60}
61
62bool same_guid(const GUID& a, const GUID& b) { return std::memcmp(&a, &b, sizeof(GUID)) == 0; }
63
64std::string hr_text(HRESULT hr) {
65 char b[16];
66 std::snprintf(b, sizeof b, "0x%08lx", static_cast<unsigned long>(hr));
67 return b;
68}
69
70// ---- Interface ids ------------------------------------------------------------------------------------------------
71//
72// The X interfaces' ids are not public. A creating call (DStorageGetFactory, CreateQueue*, OpenFile,
73// CreateStatusArray) accepts an id it has not seen for the kind of object it hands out and logs it the first time, so
74// the first boot records the console's ids. It refuses an id seen for another kind, a PC DirectStorage id of another
75// shape, and the system COM interfaces (IMarshal, IAgileObject, ...), which a DirectStorage object never implements.
76// QueryInterface is stricter (docs/d3d12_vulkan.md: an unknown id is E_NOINTERFACE): it accepts IUnknown, the
77// declared ids (dstorage_xs_abi.h) and the ids a creating call accepted for that kind, and logs anything else. This is
78// a policy, not a fact; it lives here so a measured id list can replace it.
79
80enum class Kind { Factory, Queue, File, StatusArray };
81
82const char* kind_name(Kind k) {
83 switch (k) {
84 case Kind::Factory: return "factory";
85 case Kind::Queue: return "queue";
86 case Kind::File: return "file";
87 case Kind::StatusArray: return "status array";
88 }
89 return "?";
90}
91
92// System interfaces: the COM base range {xxxxxxxx-0000-0000-C000-000000000046} (IClassFactory, IMarshal,
93// IStdMarshalInfo, IExternalConnection, IMultiQI, IClientSecurity, IServerSecurity, IRpcOptions, IMarshal2,
94// IWeakReferenceSource, IDispatch, IPersist, ...) and these others.
95constexpr GUID kSystemInterfaceIds[] = {
96 {0x94ea2b94, 0xe9cc, 0x49e0, {0xc0, 0xff, 0xee, 0x64, 0xca, 0x8f, 0x5b, 0x90}}, // IAgileObject
97 {0xecc8691b, 0xc1db, 0x4dc0, {0x85, 0x5e, 0x65, 0xf6, 0xc5, 0x51, 0xaf, 0x49}}, // INoMarshal
98 {0x1c733a30, 0x2a1c, 0x11ce, {0xad, 0xe5, 0x00, 0xaa, 0x00, 0x44, 0x77, 0x3d}}, // ICallFactory
99 {0xaf86e2e0, 0xb12d, 0x4c6a, {0x9c, 0x5a, 0xd7, 0xaa, 0x65, 0x10, 0x1e, 0x90}}, // IInspectable
100 {0xdf0b3d60, 0x548f, 0x101b, {0x8e, 0x65, 0x08, 0x00, 0x2b, 0x2b, 0xd1, 0x19}}, // ISupportErrorInfo
101 {0xb196b283, 0xbab4, 0x101a, {0xb6, 0x9c, 0x00, 0xaa, 0x00, 0x34, 0x1d, 0x07}}, // IProvideClassInfo
102 {0xb196b284, 0xbab4, 0x101a, {0xb6, 0x9c, 0x00, 0xaa, 0x00, 0x34, 0x1d, 0x07}}, // IConnectionPointContainer
103 {0xfc4801a3, 0x2ba9, 0x11cf, {0xa2, 0x29, 0x00, 0xaa, 0x00, 0x3d, 0x73, 0x52}}, // IObjectWithSite
104};
105
106bool system_interface(const GUID& g) {
107 static const uint8_t kComBase[8] = {0xc0, 0, 0, 0, 0, 0, 0, 0x46};
108 if (g.Data2 == 0 && g.Data3 == 0 && std::memcmp(g.Data4, kComBase, 8) == 0) return true;
109 for (const GUID& s : kSystemInterfaceIds)
110 if (same_guid(g, s)) return true;
111 return false;
112}
113
114// The ids declared for a kind: the PC IDStorageStatusArray id, whose interface has the console one's shape (console
115// D3D12 binaries reuse the PC SDK's ids). No other X interface id is known.
116bool declared(const GUID& g, Kind kind) {
117 for (const GUID& id : kStatusArrayIds)
118 if (same_guid(g, id)) return kind == Kind::StatusArray;
119 return false;
120}
121
122bool declared_for_any(const GUID& g) {
123 for (const GUID& id : kStatusArrayIds)
124 if (same_guid(g, id)) return true;
125 return false;
126}
127
128class IidPolicy {
129public:
130 bool accept_creating(REFIID riid, Kind kind, const char* caller) {
131 if (same_guid(riid, __uuidof(IUnknown)) || declared(riid, kind)) return true;
132 if (system_interface(riid)) return refuse(riid, caller, "a system COM interface");
133 if (declared_for_any(riid)) return refuse(riid, caller, "an id declared for another kind of object");
134 for (const GUID& pc : kPcInterfaceIds)
135 if (same_guid(riid, pc))
136 return refuse(riid, caller, "a PC DirectStorage interface; only the console ABI is served");
137 std::lock_guard lock(mutex_);
138 for (const auto& [id, k] : learned_)
139 if (same_guid(id, riid)) {
140 if (k == kind) return true;
141 return refuse(riid, caller, std::string("seen before as a ") + kind_name(k) + " interface");
142 }
143 learned_.push_back({riid, kind});
144 log_once("learn" + guid_text(riid), std::string(caller) + " asked for " + guid_text(riid) + ": serving the " +
145 kind_name(kind) + " interface");
146 return true;
147 }
148
149 bool accept_query(REFIID riid, Kind kind, const char* caller) {
150 if (same_guid(riid, __uuidof(IUnknown)) || declared(riid, kind)) return true;
151 {
152 std::lock_guard lock(mutex_);
153 for (const auto& [id, k] : learned_)
154 if (same_guid(id, riid) && k == kind) return true;
155 }
156 return refuse(riid, caller, std::string("not an id a ") + kind_name(kind) + " was created with");
157 }
158
159private:
160 static bool refuse(REFIID riid, const char* caller, const std::string& why) {
161 log_once(std::string("refuse") + caller + guid_text(riid),
162 std::string(caller) + " asked for " + guid_text(riid) + ": " + why + " (E_NOINTERFACE)");
163 return false;
164 }
165
166 std::mutex mutex_;
167 std::vector<std::pair<GUID, Kind>> learned_;
168};
169
170IidPolicy& iid_policy() {
171 static auto* p = new IidPolicy;
172 return *p;
173}
174
175// A bad argument to a factory or queue method, logged once per method and kind: a wrong vtable guess for the console
176// interfaces would show up here first, as arguments that make no sense for the method.
177HRESULT bad_call(const char* method, HRESULT hr, const char* what) {
178 log_once(std::string("bad") + method + what,
179 std::string(method) + ": " + what + " (" + hr_text(hr) +
180 "; logged once; a wrong vtable slot guess would show up like this)");
181 return hr;
182}
183
184// ---- Statistics (IDStorageFactoryX1::GetStats) --------------------------------------------------------------------
185
186struct Stats {
187 std::mutex mutex;
188 DSTORAGE_STATS s{};
189 uint32_t live_queues = 0; // all priorities; SetStagingBufferSize is refused while queues or files exist
190};
191
192Stats& stats() {
193 static auto* s = new Stats;
194 return *s;
195}
196
197DSTORAGE_PRIORITY_STATS& priority_stats(DSTORAGE_STATS& s, DSTORAGE_PRIORITY p) {
198 switch (p) {
199 case DSTORAGE_PRIORITY_LOW: return s.LowPriorityStats;
200 case DSTORAGE_PRIORITY_HIGH: return s.HighPriorityStats;
201 case DSTORAGE_PRIORITY_REALTIME: return s.RealtimePriorityStats;
202 default: return s.NormalPriorityStats;
203 }
204}
205
206void count_error() {
207 std::lock_guard lock(stats().mutex);
208 ++stats().s.ErrorCount;
209}
210
211// ---- Live objects ---------------------------------------------------------------------------------------------------
212//
213// A request names its file and a status entry its array by pointer. Only objects this shim made and that are still
214// alive are used; anything else is an error in the request, never a call through a stranger's vtable.
215
216std::mutex& live_mutex() {
217 static auto* m = new std::mutex;
218 return *m;
219}
220// One set per kind, so a status array passed as a file (or the other way round) is not found.
221std::unordered_set<const void*>& live_files() {
222 static auto* s = new std::unordered_set<const void*>;
223 return *s;
224}
225std::unordered_set<const void*>& live_status_arrays() {
226 static auto* s = new std::unordered_set<const void*>;
227 return *s;
228}
229
230// AddRef only if the count has not reached zero (an object being released is not revived).
231bool add_ref_if_live(std::atomic<ULONG>& refs) {
232 ULONG r = refs.load();
233 while (r != 0)
234 if (refs.compare_exchange_weak(r, r + 1)) return true;
235 return false;
236}
237
238// ---- Status arrays ------------------------------------------------------------------------------------------------
239
240class StatusArray final : public IDStorageStatusArrayX {
241public:
242 StatusArray(uint32_t capacity, std::unique_ptr<std::atomic<HRESULT>[]> entries)
243 : capacity_(capacity), entries_(std::move(entries)) {
244 for (uint32_t i = 0; i < capacity_; ++i) entries_[i].store(S_OK, std::memory_order_relaxed);
245 std::lock_guard lock(live_mutex());
246 live_status_arrays().insert(static_cast<IDStorageStatusArrayX*>(this));
247 }
248
249 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override {
250 if (!ppv) return E_POINTER;
251 *ppv = nullptr;
252 if (!iid_policy().accept_query(riid, Kind::StatusArray, "IDStorageStatusArrayX::QueryInterface"))
253 return E_NOINTERFACE;
254 AddRef();
255 *ppv = static_cast<IDStorageStatusArrayX*>(this);
256 return S_OK;
257 }
258 ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; }
259 ULONG STDMETHODCALLTYPE Release() override {
260 ULONG r;
261 {
262 std::lock_guard lock(live_mutex());
263 r = --refs_;
264 if (r == 0) live_status_arrays().erase(static_cast<IDStorageStatusArrayX*>(this));
265 }
266 if (r == 0) delete this;
267 return r;
268 }
269
270 // IsComplete is GetHResult(index) != E_PENDING (the reference says so); an index past the array is not pending.
271 bool STDMETHODCALLTYPE IsComplete(UINT32 index) override { return GetHResult(index) != E_PENDING; }
272 HRESULT STDMETHODCALLTYPE GetHResult(UINT32 index) override {
273 if (index >= capacity_) return E_DSTORAGE_INDEX_BOUND;
274 return entries_[index].load(std::memory_order_acquire);
275 }
276
277 uint32_t capacity() const { return capacity_; }
278 void set_pending(uint32_t index) { entries_[index].store(E_PENDING, std::memory_order_release); }
279 void complete(uint32_t index, HRESULT hr) { entries_[index].store(hr, std::memory_order_release); }
280 std::atomic<ULONG>& refs() { return refs_; }
281
282private:
283 std::atomic<ULONG> refs_{1};
284 const uint32_t capacity_;
285 std::unique_ptr<std::atomic<HRESULT>[]> entries_;
286};
287
288// ---- Files --------------------------------------------------------------------------------------------------------
289
290class File final : public IDStorageFileX {
291public:
292 File(HANDLE handle, std::wstring path) : handle_(handle), path_(std::move(path)) {
293 {
294 std::lock_guard lock(live_mutex());
295 live_files().insert(static_cast<IDStorageFileX*>(this));
296 }
297 std::lock_guard lock(stats().mutex);
298 auto& s = stats().s;
299 ++s.CurrentOpenFileCount;
300 ++s.CumulativeOpenFileCount;
301 s.MaxOpenFileCount = std::max(s.MaxOpenFileCount, s.CurrentOpenFileCount);
302 }
303 ~File() {
304 Close();
305 std::lock_guard lock(stats().mutex);
306 --stats().s.CurrentOpenFileCount;
307 }
308
309 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override {
310 if (!ppv) return E_POINTER;
311 *ppv = nullptr;
312 if (!iid_policy().accept_query(riid, Kind::File, "IDStorageFileX::QueryInterface")) return E_NOINTERFACE;
313 AddRef();
314 *ppv = static_cast<IDStorageFileX*>(this);
315 return S_OK;
316 }
317 ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; }
318 ULONG STDMETHODCALLTYPE Release() override {
319 ULONG r;
320 {
321 std::lock_guard lock(live_mutex());
322 r = --refs_;
323 if (r == 0) live_files().erase(static_cast<IDStorageFileX*>(this));
324 }
325 if (r == 0) delete this;
326 return r;
327 }
328
329 // Waits for the submitted requests that read this file, then closes the handle. A request submitted later fails
330 // with E_DSTORAGE_FILE_NOT_OPEN. Waiting only for submitted requests keeps a Close from blocking forever on a
331 // request that sits unsubmitted in a queue with auto-submit disabled.
332 void STDMETHODCALLTYPE Close() override {
333 std::unique_lock lock(mutex_);
334 closed_ = true;
335 idle_.wait(lock, [&] { return pending_ == 0; });
336 if (handle_ != INVALID_HANDLE_VALUE) {
337 CloseHandle(handle_);
338 handle_ = INVALID_HANDLE_VALUE;
339 }
340 }
341
342 // A new handle the caller closes (GENERIC_READ, FILE_SHARE_READ, as the reference describes it). ReOpenFile,
343 // not DuplicateHandle: a duplicate shares the file position with the shim's own reads, so the title's ReadFile
344 // through it would start wherever the worker's last read ended.
345 HANDLE STDMETHODCALLTYPE GetHandle() override {
346 std::lock_guard lock(mutex_);
347 if (closed_ || handle_ == INVALID_HANDLE_VALUE) {
348 SetLastError(ERROR_INVALID_HANDLE);
349 return INVALID_HANDLE_VALUE;
350 }
351 return ReOpenFile(handle_, GENERIC_READ, FILE_SHARE_READ, 0);
352 }
353
354 // Called when a request naming this file is submitted. False once the file is closed.
355 bool add_pending() {
356 std::lock_guard lock(mutex_);
357 if (closed_) return false;
358 ++pending_;
359 return true;
360 }
361 void finish_pending() {
362 std::lock_guard lock(mutex_);
363 if (--pending_ == 0) idle_.notify_all();
364 }
365 // Valid while the caller holds a pending count: Close does not close the handle before it drops to zero.
366 HANDLE handle() const { return handle_; }
367 const std::wstring& path() const { return path_; }
368 std::atomic<ULONG>& refs() { return refs_; }
369
370private:
371 std::atomic<ULONG> refs_{1};
372 std::mutex mutex_;
373 std::condition_variable idle_;
374 HANDLE handle_;
375 const std::wstring path_;
376 uint32_t pending_ = 0;
377 bool closed_ = false;
378};
379
380StatusArray* live_status_array(IDStorageStatusArrayX* p) {
381 std::lock_guard lock(live_mutex());
382 if (!p || !live_status_arrays().count(p)) return nullptr;
383 auto* a = static_cast<StatusArray*>(p);
384 return add_ref_if_live(a->refs()) ? a : nullptr;
385}
386
387File* live_file(IDStorageFileX* p) {
388 std::lock_guard lock(live_mutex());
389 if (!p || !live_files().count(p)) return nullptr;
390 auto* f = static_cast<File*>(p);
391 return add_ref_if_live(f->refs()) ? f : nullptr;
392}
393
394// ---- Reads --------------------------------------------------------------------------------------------------------
395
396// memmove that turns an access violation into an error instead of ending the process. No C++ objects here: a
397// function with __try cannot have any that need unwinding.
398bool guarded_move(void* destination, const void* source, size_t size) {
399 __try {
400 std::memmove(destination, source, size);
401 return true;
402 } __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER
403 : EXCEPTION_CONTINUE_SEARCH) {
404 return false;
405 }
406}
407
408HRESULT read_error(DWORD error) {
409 switch (error) {
410 case ERROR_NOACCESS:
411 case ERROR_INVALID_USER_BUFFER: return E_DSTORAGE_ACCESS_VIOLATION;
412 case ERROR_HANDLE_EOF: return E_DSTORAGE_END_OF_FILE;
413 default: return HRESULT_FROM_WIN32(error);
414 }
415}
416
417// Reads exactly "size" bytes at "offset" of a synchronous handle into "destination".
418HRESULT read_file_range(HANDLE handle, uint64_t offset, void* destination, uint32_t size) {
419 LARGE_INTEGER length{};
420 if (!GetFileSizeEx(handle, &length)) return HRESULT_FROM_WIN32(GetLastError());
421 const uint64_t file_size = static_cast<uint64_t>(length.QuadPart);
422 if (offset > file_size || size > file_size - offset) return E_DSTORAGE_END_OF_FILE;
423 auto* out = static_cast<uint8_t*>(destination);
424 uint32_t done = 0;
425 while (done < size) {
426 OVERLAPPED at{};
427 const uint64_t position = offset + done;
428 at.Offset = static_cast<DWORD>(position);
429 at.OffsetHigh = static_cast<DWORD>(position >> 32);
430 DWORD got = 0;
431 if (!ReadFile(handle, out + done, size - done, &got, &at)) return read_error(GetLastError());
432 if (got == 0) return E_DSTORAGE_END_OF_FILE; // the file shrank since the size check
433 done += got;
434 }
435 return S_OK;
436}
437
438// ---- Queues -------------------------------------------------------------------------------------------------------
439
440struct Entry {
441 enum class Type { Request, Status, Signal, Event } type = Type::Request;
442 DSTORAGE_REQUEST request{};
443 File* file = nullptr; // a reference, for a file request naming a live file
444 bool file_counted = false; // the file's pending count was raised at submit
445 bool cancelled = false; // CancelRequestsWithTag matched it before it started
446 HRESULT enqueue_error = S_OK; // found at enqueue: reported when the entry is reached, in order
447 StatusArray* status = nullptr; // a reference
448 IDStorageStatusArrayX* status_as_given = nullptr;
449 uint32_t index = 0;
450 ID3D12Fence* fence = nullptr; // a reference
451 uint64_t value = 0;
452 HANDLE event = nullptr; // a duplicate the entry owns
453};
454
455class Queue final : public IDStorageQueueX2 {
456public:
457 explicit Queue(const DSTORAGE_QUEUE_DESC1& desc) : desc_(desc) {
458 error_event_ = CreateEventW(nullptr, TRUE, FALSE, nullptr);
459 clear_record_locked();
460 std::lock_guard lock(stats().mutex);
461 auto& p = priority_stats(stats().s, desc_.Priority);
462 ++p.CurrentQueueCount;
463 ++p.CumulativeQueueCount;
464 p.MaxQueueCount = std::max(p.MaxQueueCount, p.CurrentQueueCount);
465 ++stats().live_queues;
466 }
467 // Separate from the constructor so a failure to start the thread can be reported.
468 bool start() {
469 if (!error_event_) return false;
470 try {
471 worker_ = std::thread([this] { run(); });
472 } catch (...) {
473 return false;
474 }
475 return true;
476 }
477 ~Queue() {
478 Close();
479 if (error_event_) CloseHandle(error_event_);
480 std::lock_guard lock(stats().mutex);
481 --priority_stats(stats().s, desc_.Priority).CurrentQueueCount;
482 --stats().live_queues;
483 }
484
485 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override {
486 if (!ppv) return E_POINTER;
487 *ppv = nullptr;
488 if (!iid_policy().accept_query(riid, Kind::Queue, "IDStorageQueueX::QueryInterface")) return E_NOINTERFACE;
489 AddRef();
490 *ppv = static_cast<IDStorageQueueX2*>(this);
491 return S_OK;
492 }
493 ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; }
494 // The last Release closes the queue, which runs everything enqueued first.
495 ULONG STDMETHODCALLTYPE Release() override {
496 const ULONG r = --refs_;
497 if (r == 0) delete this;
498 return r;
499 }
500
501 void STDMETHODCALLTYPE EnqueueRequest(const DSTORAGE_REQUEST* request) override {
502 Entry e;
503 e.type = Entry::Type::Request;
504 if (!request) {
505 e.enqueue_error = bad_call("IDStorageQueueX::EnqueueRequest", E_INVALIDARG, "null request");
506 } else {
507 e.request = *request; // the title may reuse its structure as soon as this returns
508 const uint64_t o = e.request.Options.AsUINT64;
509 if (options::source_type(o) == DSTORAGE_REQUEST_SOURCE_FILE &&
510 desc_.SourceType == DSTORAGE_REQUEST_SOURCE_FILE && e.request.File) {
511 e.file = live_file(e.request.File);
512 if (!e.file) e.enqueue_error = E_DSTORAGE_INVALID_FILE_HANDLE;
513 }
514 std::lock_guard lock(stats().mutex);
515 auto& p = priority_stats(stats().s, desc_.Priority);
516 ++p.TotalRequestCount;
517 p.TotalRequestSourceByteCount += request->SourceSize;
518 p.TotalRequestDestinationByteCount += request->DestinationSize;
519 }
520 enqueue(std::move(e));
521 }
522
523 void STDMETHODCALLTYPE EnqueueStatus(IDStorageStatusArrayX* status_array, UINT32 index) override {
524 Entry e;
525 e.type = Entry::Type::Status;
526 e.status_as_given = status_array;
527 e.index = index;
528 e.status = live_status_array(status_array);
529 if (!e.status) {
530 e.enqueue_error = E_DSTORAGE_INVALID_STATUS_ARRAY;
531 } else if (index >= e.status->capacity()) {
532 e.enqueue_error = E_DSTORAGE_INDEX_BOUND;
533 } else {
534 e.status->set_pending(index); // polling after this call sees E_PENDING until the entry is reached
535 }
536 {
537 std::lock_guard lock(stats().mutex);
538 ++priority_stats(stats().s, desc_.Priority).TotalStatusCount;
539 }
540 enqueue(std::move(e));
541 }
542
543 void STDMETHODCALLTYPE EnqueueSignal(ID3D12Fence* fence, UINT64 value) override {
544 Entry e;
545 e.type = Entry::Type::Signal;
546 e.fence = fence;
547 e.value = value;
548 if (fence) {
549 fence->AddRef();
550 } else {
551 e.enqueue_error = E_DSTORAGE_INVALID_FENCE;
552 }
553 {
554 std::lock_guard lock(stats().mutex);
555 ++priority_stats(stats().s, desc_.Priority).TotalFenceCount;
556 }
557 enqueue(std::move(e));
558 }
559
560 // The handle is duplicated here and the duplicate closed once it has been set (or dropped), so an event the
561 // title closes, and whose handle value is then reused for another object, is never the one set.
562 void STDMETHODCALLTYPE EnqueueSetEvent(HANDLE handle) override {
563 Entry e;
564 e.type = Entry::Type::Event;
565 if (!handle) {
566 e.enqueue_error = bad_call("IDStorageQueueX1::EnqueueSetEvent", HRESULT_FROM_WIN32(ERROR_INVALID_HANDLE),
567 "null event handle");
568 } else if (!DuplicateHandle(GetCurrentProcess(), handle, GetCurrentProcess(), &e.event, 0, FALSE,
569 DUPLICATE_SAME_ACCESS)) {
570 e.event = nullptr;
571 e.enqueue_error = HRESULT_FROM_WIN32(GetLastError());
572 }
573 enqueue(std::move(e));
574 }
575
576 void STDMETHODCALLTYPE Submit() override {
577 std::lock_guard lock(mutex_);
578 submit_locked();
579 }
580
581 // Marks the requests enqueued before this call that have not started. A cancelled request completes as a success
582 // without being read (the overview: the title may no longer use its result).
583 void STDMETHODCALLTYPE CancelRequestsWithTag(UINT64 mask, UINT64 value) override {
584 std::lock_guard lock(mutex_);
585 for (Entry& e : entries_)
586 if (e.type == Entry::Type::Request && (e.request.CancellationTag & mask) == value) e.cancelled = true;
587 }
588
589 // Submits what is enqueued, waits until the worker has run all of it and stops the worker. Later enqueues are
590 // dropped and recorded as E_DSTORAGE_QUEUE_CLOSED.
591 void STDMETHODCALLTYPE Close() override {
592 std::lock_guard close_lock(close_mutex_);
593 {
594 std::unique_lock lock(mutex_);
595 if (closed_) return;
596 closing_ = true;
597 submit_locked();
598 space_.notify_all(); // an enqueue waiting for space gives up (the queue is closing)
599 idle_.wait(lock, [&] { return entries_.empty() && !in_flight_; });
600 closed_ = true;
601 work_.notify_all();
602 }
603 if (worker_.joinable()) worker_.join();
604 }
605
606 HANDLE STDMETHODCALLTYPE GetErrorEvent() override {
607 HANDLE dup = nullptr;
608 if (!error_event_ || !DuplicateHandle(GetCurrentProcess(), error_event_, GetCurrentProcess(), &dup, 0, FALSE,
609 DUPLICATE_SAME_ACCESS))
610 return nullptr;
611 return dup; // the reference says the title closes it
612 }
613
614 void STDMETHODCALLTYPE RetrieveErrorRecord(DSTORAGE_ERROR_RECORD* record) override {
615 if (!record) {
616 bad_call("IDStorageQueueX::RetrieveErrorRecord", E_POINTER, "null record");
617 return;
618 }
619 std::lock_guard lock(error_mutex_);
620 *record = record_;
621 clear_record_locked();
622 if (error_event_) ResetEvent(error_event_);
623 }
624
625 void STDMETHODCALLTYPE Query(DSTORAGE_QUEUE_INFO* info) override {
626 if (!info) {
627 bad_call("IDStorageQueueX::Query", E_POINTER, "null info");
628 return;
629 }
630 DSTORAGE_QUEUE_INFO1 full{};
631 Query1(&full);
632 info->Desc.SourceType = full.Desc.SourceType;
633 info->Desc.Capacity = full.Desc.Capacity;
634 info->Desc.Priority = full.Desc.Priority;
635 info->Desc.Name = full.Desc.Name;
636 info->EmptySlotCount = full.EmptySlotCount;
637 info->RequestCountUntilAutoSubmit = full.RequestCountUntilAutoSubmit;
638 }
639
640 // An empty queue has capacity - 1 empty slots (one slot tells empty from full). The automatic submit happens when
641 // the entries enqueued since the last submit reach half the capacity; with it disabled the count is 0.
642 void STDMETHODCALLTYPE Query1(DSTORAGE_QUEUE_INFO1* info) override {
643 if (!info) {
644 bad_call("IDStorageQueueX2::Query1", E_POINTER, "null info");
645 return;
646 }
647 std::lock_guard lock(mutex_);
648 info->Desc = desc_;
649 info->EmptySlotCount = static_cast<UINT16>(usable() - used_locked());
650 const size_t unsubmitted = entries_.size() - submitted_;
651 info->RequestCountUntilAutoSubmit =
652 auto_submit() ? static_cast<UINT16>(half() > unsubmitted ? half() - unsubmitted : 0) : 0;
653 }
654
655private:
656 size_t usable() const { return desc_.Capacity - 1u; }
657 size_t half() const { return desc_.Capacity / 2u; }
658 bool auto_submit() const { return !desc_.Options.AutoSubmitDisabled; }
659 size_t used_locked() const { return entries_.size() + (in_flight_ ? 1 : 0); }
660
661 void enqueue(Entry&& e) {
662 {
663 std::unique_lock lock(mutex_);
664 // A full queue waits for the worker to free a slot. With auto-submit on, half the queue is always
665 // submitted by then; with it off, only a Submit from another thread frees one (as the reference warns).
666 space_.wait(lock, [&] { return closing_ || used_locked() < usable(); });
667 if (!closing_) {
668 entries_.push_back(std::move(e));
669 if (auto_submit() && entries_.size() - submitted_ >= half()) submit_locked();
670 return;
671 }
672 }
673 DSTORAGE_ERROR_FIRST_FAILURE f{};
674 f.HResult = E_DSTORAGE_QUEUE_CLOSED;
675 describe(e, f);
676 record_failure(f);
677 log_once("closed", "an entry was enqueued on a closed queue (E_DSTORAGE_QUEUE_CLOSED); it never completes");
678 release_references(e);
679 }
680
681 void submit_locked() {
682 for (size_t i = submitted_; i < entries_.size(); ++i) {
683 Entry& e = entries_[i];
684 if (e.file) e.file_counted = e.file->add_pending();
685 }
686 if (entries_.size() > submitted_) {
687 submitted_ = entries_.size();
688 work_.notify_one();
689 }
690 }
691
692 void run() {
693 for (;;) {
694 Entry e;
695 {
696 std::unique_lock lock(mutex_);
697 work_.wait(lock, [&] { return submitted_ > 0 || closed_; });
698 if (submitted_ == 0) return; // closed and drained
699 e = std::move(entries_.front());
700 entries_.pop_front();
701 --submitted_;
702 in_flight_ = true;
703 }
704 process(e);
705 release_references(e);
706 {
707 std::lock_guard lock(mutex_);
708 in_flight_ = false;
709 space_.notify_all();
710 if (entries_.empty()) idle_.notify_all();
711 }
712 }
713 }
714
715 // Runs on the worker. since_notify_ is the first failure since the last status entry or fence signal: the
716 // HRESULT a status entry reports.
717 void process(Entry& e) {
718 HRESULT hr = e.enqueue_error;
719 switch (e.type) {
720 case Entry::Type::Request:
721 // A cancelled request is a success whatever else is wrong with it (the GDK: not counted as a failure).
722 if (e.cancelled) {
723 hr = S_OK;
724 } else if (SUCCEEDED(hr)) {
725 hr = execute_request(e);
726 }
727 if (e.file && e.file_counted) e.file->finish_pending();
728 if (FAILED(hr) && SUCCEEDED(since_notify_)) since_notify_ = hr;
729 break;
730 case Entry::Type::Status:
731 if (SUCCEEDED(hr)) {
732 e.status->complete(e.index, since_notify_);
733 since_notify_ = S_OK;
734 }
735 break;
736 case Entry::Type::Signal:
737 if (SUCCEEDED(hr)) hr = e.fence->Signal(e.value);
738 since_notify_ = S_OK;
739 break;
740 case Entry::Type::Event:
741 if (SUCCEEDED(hr) && !SetEvent(e.event)) hr = HRESULT_FROM_WIN32(GetLastError());
742 break;
743 }
744 if (FAILED(hr)) {
745 DSTORAGE_ERROR_FIRST_FAILURE f{};
746 f.HResult = hr;
747 describe(e, f);
748 record_failure(f);
749 }
750 }
751
752 HRESULT execute_request(const Entry& e) {
753 const DSTORAGE_REQUEST& r = e.request;
754 const uint64_t o = r.Options.AsUINT64;
755 if (o & options::kReservedMask) return E_DSTORAGE_RESERVED_FIELDS;
756 if (options::source_type(o) != desc_.SourceType) return E_DSTORAGE_INVALID_SOURCE_TYPE;
757 if (options::bcpack(o) > DSTORAGE_BCPACK_MODE_BC7) return E_DSTORAGE_INVALID_BCPACK_MODE;
758 if (options::swizzle(o) > DSTORAGE_SWIZZLE_MODE_4K_12K_4K_12K) return E_DSTORAGE_INVALID_SWIZZLE_MODE;
759 if (options::zlib(o) || options::bcpack(o) != 0 || options::swizzle(o) != 0) {
760 log_once("decompress", "zlib, BCPack and swizzle requests are not implemented yet (E_NOTIMPL)");
761 return E_NOTIMPL;
762 }
763 if (o & (options::kDestinationPages | options::kSourcePages)) {
764 log_once("pages", "physical-page requests are not implemented yet (E_NOTIMPL)");
765 return E_NOTIMPL;
766 }
767 if (r.IntermediateSize != 0) return E_DSTORAGE_INVALID_INTERMEDIATE_SIZE; // only zlib + BCPack use it
768 if (r.DestinationSize != r.SourceSize) return E_DSTORAGE_INVALID_DESTINATION_SIZE;
769 const bool memory = desc_.SourceType == DSTORAGE_REQUEST_SOURCE_MEMORY;
770 const uint64_t total = static_cast<uint64_t>(r.DestinationSize) + (memory ? r.SourceSize : 0u);
771 if (total > kMaxRequestBytes) return E_DSTORAGE_REQUEST_TOO_LARGE;
772 if (!r.Destination) return E_INVALIDARG;
773 if (memory) {
774 if (!r.Source) return E_INVALIDARG;
775 } else {
776 if (!r.File) return E_INVALIDARG;
777 if (!e.file_counted) return E_DSTORAGE_FILE_NOT_OPEN;
778 }
779 if (r.SourceSize == 0) return S_OK; // nothing to move; the reference does not say this fails
780 if (memory) return guarded_move(r.Destination, r.Source, r.SourceSize) ? S_OK : E_DSTORAGE_ACCESS_VIOLATION;
781 return read_file_range(e.file->handle(), r.FileOffset, r.Destination, r.SourceSize);
782 }
783
784 void describe(const Entry& e, DSTORAGE_ERROR_FIRST_FAILURE& f) const {
785 switch (e.type) {
786 case Entry::Type::Request: {
787 f.CommandType = DSTORAGE_COMMAND_TYPE_REQUEST;
788 auto& q = f.Request;
789 const DSTORAGE_REQUEST& r = e.request;
790 q.Options = r.Options;
791 q.Destination = r.Destination;
792 q.DestinationSize = r.DestinationSize;
793 q.SourceSize = r.SourceSize;
794 q.CancellationTag = r.CancellationTag;
795 if (options::source_type(r.Options.AsUINT64) == DSTORAGE_REQUEST_SOURCE_MEMORY) {
796 q.Source = r.Source;
797 } else {
798 q.FileOffset = r.FileOffset;
799 if (e.file) wcsncpy_s(q.Filename, e.file->path().c_str(), _TRUNCATE);
800 }
801 // The reference says the name stays readable until the request completes.
802 if (r.Name)
803 for (size_t i = 0; i + 1 < kRequestMaxName && r.Name[i]; ++i) q.Name[i] = r.Name[i];
804 break;
805 }
806 case Entry::Type::Status:
807 f.CommandType = DSTORAGE_COMMAND_TYPE_STATUS;
808 f.Status.StatusArray = e.status_as_given;
809 f.Status.Index = e.index;
810 break;
811 case Entry::Type::Signal:
812 f.CommandType = DSTORAGE_COMMAND_TYPE_SIGNAL;
813 f.Signal.Fence = e.fence;
814 f.Signal.Value = e.value;
815 break;
816 case Entry::Type::Event:
817 f.CommandType = kCommandTypeEvent;
818 break;
819 }
820 }
821
822 void record_failure(const DSTORAGE_ERROR_FIRST_FAILURE& f) {
823 count_error();
824 {
825 std::lock_guard lock(error_mutex_);
826 if (record_.FailureCount++ == 0) record_.FirstFailure = f;
827 if (error_event_) SetEvent(error_event_);
828 }
829 log_once("fail" + hr_text(f.HResult) + std::to_string(f.CommandType),
830 "an entry failed with " + hr_text(f.HResult) + " (command type " + std::to_string(f.CommandType) +
831 "; logged once per code)");
832 }
833
834 void clear_record_locked() {
835 record_ = DSTORAGE_ERROR_RECORD{};
836 record_.FirstFailure.CommandType = DSTORAGE_COMMAND_TYPE_NONE;
837 }
838
839 static void release_references(Entry& e) {
840 if (e.file) e.file->Release();
841 if (e.status) e.status->Release();
842 if (e.fence) e.fence->Release();
843 if (e.event) CloseHandle(e.event);
844 e.event = nullptr;
845 e.file = nullptr;
846 e.status = nullptr;
847 e.fence = nullptr;
848 }
849
850 std::atomic<ULONG> refs_{1};
851 const DSTORAGE_QUEUE_DESC1 desc_;
852 std::mutex close_mutex_; // one Close at a time
853 std::mutex mutex_; // entries_, submitted_, in_flight_, closing_, closed_
854 std::condition_variable work_, space_, idle_;
855 std::deque<Entry> entries_;
856 size_t submitted_ = 0; // the first submitted_ entries are submitted
857 bool in_flight_ = false;
858 bool closing_ = false;
859 bool closed_ = false;
860 std::thread worker_;
861 HRESULT since_notify_ = S_OK; // worker only
862 std::mutex error_mutex_;
863 DSTORAGE_ERROR_RECORD record_{};
864 HANDLE error_event_ = nullptr;
865};
866
867// ---- The factory ----------------------------------------------------------------------------------------------------
868
869HRESULT validate_queue_desc(const DSTORAGE_QUEUE_DESC1& d) {
870 if (d.SourceType != DSTORAGE_REQUEST_SOURCE_FILE && d.SourceType != DSTORAGE_REQUEST_SOURCE_MEMORY)
871 return E_DSTORAGE_INVALID_SOURCE_TYPE;
872 if (d.Capacity < kMinQueueCapacity || d.Capacity > kMaxQueueCapacity) return E_DSTORAGE_INVALID_QUEUE_CAPACITY;
873 if (d.Priority < DSTORAGE_PRIORITY_FIRST || d.Priority > DSTORAGE_PRIORITY_LAST)
874 return E_DSTORAGE_INVALID_QUEUE_PRIORITY;
875 if (d.SourceType == DSTORAGE_REQUEST_SOURCE_MEMORY && d.Priority != DSTORAGE_PRIORITY_REALTIME)
876 return E_DSTORAGE_INVALID_MEMORY_QUEUE_PRIORITY;
877 if (d.Options.Reserved) return E_DSTORAGE_RESERVED_FIELDS;
878 return S_OK;
879}
880
881using CreateFileWFn = HANDLE(WINAPI*)(LPCWSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE);
882
883// The title's own CreateFileW: the GAME: mapping and overlay when file_system.cpp is linked, else the host's.
884CreateFileWFn create_file_w() {
885 if (void* fn = rt::shims::find("kernel32.dll", "CreateFileW")) return reinterpret_cast<CreateFileWFn>(fn);
886 return &::CreateFileW;
887}
888
889class Factory final : public IDStorageFactoryX2 {
890public:
891 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override {
892 if (!ppv) return E_POINTER;
893 *ppv = nullptr;
894 if (!iid_policy().accept_query(riid, Kind::Factory, "IDStorageFactoryX::QueryInterface")) return E_NOINTERFACE;
895 AddRef();
896 *ppv = static_cast<IDStorageFactoryX2*>(this);
897 return S_OK;
898 }
899 ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; }
900 // One factory for the process; its count never drops below one, so it is never freed.
901 ULONG STDMETHODCALLTYPE Release() override {
902 ULONG r = refs_.load();
903 while (r > 1 && !refs_.compare_exchange_weak(r, r - 1)) {}
904 return r > 1 ? r - 1 : 1;
905 }
906
907 HRESULT STDMETHODCALLTYPE CreateQueue(const DSTORAGE_QUEUE_DESC* desc, REFIID riid, void** ppv) override {
908 if (!ppv) return bad_call("IDStorageFactoryX::CreateQueue", E_POINTER, "null ppv");
909 *ppv = nullptr;
910 if (!desc) return bad_call("IDStorageFactoryX::CreateQueue", E_INVALIDARG, "null desc");
911 DSTORAGE_QUEUE_DESC1 d{};
912 d.SourceType = desc->SourceType;
913 d.Capacity = desc->Capacity;
914 d.Priority = desc->Priority;
915 d.Name = desc->Name;
916 return create_queue(d, riid, ppv, "IDStorageFactoryX::CreateQueue");
917 }
918
919 HRESULT STDMETHODCALLTYPE CreateQueue1(const DSTORAGE_QUEUE_DESC1* desc, REFIID riid, void** ppv) override {
920 if (!ppv) return bad_call("IDStorageFactoryX2::CreateQueue1", E_POINTER, "null ppv");
921 *ppv = nullptr;
922 if (!desc) return bad_call("IDStorageFactoryX2::CreateQueue1", E_INVALIDARG, "null desc");
923 return create_queue(*desc, riid, ppv, "IDStorageFactoryX2::CreateQueue1");
924 }
925
926 HRESULT STDMETHODCALLTYPE OpenFile(const WCHAR* path, REFIID riid, void** ppv) override {
927 if (!ppv) return bad_call("IDStorageFactoryX::OpenFile", E_POINTER, "null ppv");
928 *ppv = nullptr;
929 if (!path || !*path) return bad_call("IDStorageFactoryX::OpenFile", E_INVALIDARG, "null or empty path");
930 if (!iid_policy().accept_creating(riid, Kind::File, "IDStorageFactoryX::OpenFile")) return E_NOINTERFACE;
931 const HANDLE h = create_file_w()(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
932 FILE_ATTRIBUTE_NORMAL, nullptr);
933 if (h == INVALID_HANDLE_VALUE) {
934 const DWORD error = GetLastError();
935 return HRESULT_FROM_WIN32(error ? error : ERROR_FILE_NOT_FOUND);
936 }
937 File* f = new (std::nothrow) File(h, path);
938 if (!f) {
939 CloseHandle(h);
940 return E_OUTOFMEMORY;
941 }
942 *ppv = static_cast<IDStorageFileX*>(f);
943 return S_OK;
944 }
945
946 HRESULT STDMETHODCALLTYPE CreateStatusArray(UINT32 capacity, PCSTR, REFIID riid, void** ppv) override {
947 if (!ppv) return bad_call("IDStorageFactoryX::CreateStatusArray", E_POINTER, "null ppv");
948 *ppv = nullptr;
949 if (capacity == 0) return bad_call("IDStorageFactoryX::CreateStatusArray", E_INVALIDARG, "capacity 0");
950 if (!iid_policy().accept_creating(riid, Kind::StatusArray, "IDStorageFactoryX::CreateStatusArray"))
951 return E_NOINTERFACE;
952 std::unique_ptr<std::atomic<HRESULT>[]> entries(new (std::nothrow) std::atomic<HRESULT>[capacity]);
953 if (!entries) return E_OUTOFMEMORY;
954 auto* a = new (std::nothrow) StatusArray(capacity, std::move(entries));
955 if (!a) return E_OUTOFMEMORY;
956 *ppv = static_cast<IDStorageStatusArrayX*>(a);
957 return S_OK;
958 }
959
960 // DirectStorage's own worker work would be pinned to these cores on the console. The mask names console cores,
961 // so it is stored and not applied to the host's.
962 HRESULT STDMETHODCALLTYPE SetCpuAffinity(UINT64 affinity) override {
963 cpu_affinity_.store(affinity);
964 return S_OK;
965 }
966 void STDMETHODCALLTYPE SetDebugFlags(UINT32 flags) override { debug_flags_.store(flags); }
967
968 HRESULT STDMETHODCALLTYPE SetStagingBufferSize(UINT32 size) override {
969 if (std::find(std::begin(kStagingBufferSizes), std::end(kStagingBufferSizes), size) ==
970 std::end(kStagingBufferSizes))
971 return bad_call("IDStorageFactoryX::SetStagingBufferSize", E_DSTORAGE_INVALID_STAGING_BUFFER_SIZE,
972 "not one of 0, 16, 20, 24, 28 or 32 MiB");
973 std::lock_guard lock(stats().mutex);
974 if (stats().live_queues || stats().s.CurrentOpenFileCount) return E_DSTORAGE_STAGING_BUFFER_LOCKED;
975 staging_size_ = size; // there is no staging buffer here; the size is only kept
976 return S_OK;
977 }
978
979 void STDMETHODCALLTYPE GetStats(DSTORAGE_STATS* out) override {
980 if (!out) {
981 bad_call("IDStorageFactoryX1::GetStats", E_POINTER, "null stats");
982 return;
983 }
984 std::lock_guard lock(stats().mutex);
985 *out = stats().s;
986 }
987
988private:
989 HRESULT create_queue(const DSTORAGE_QUEUE_DESC1& desc, REFIID riid, void** ppv, const char* caller) {
990 if (const HRESULT hr = validate_queue_desc(desc); FAILED(hr)) return bad_call(caller, hr, "invalid queue desc");
991 if (!iid_policy().accept_creating(riid, Kind::Queue, caller)) return E_NOINTERFACE;
992 auto* q = new (std::nothrow) Queue(desc);
993 if (!q) return E_OUTOFMEMORY;
994 if (!q->start()) {
995 q->Release();
996 return E_OUTOFMEMORY;
997 }
998 *ppv = static_cast<IDStorageQueueX2*>(q);
999 return S_OK;
1000 }
1001
1002 std::atomic<ULONG> refs_{1};
1003 std::atomic<uint64_t> cpu_affinity_{~0ull};
1004 std::atomic<uint32_t> debug_flags_{0};
1005 uint32_t staging_size_ = 32u << 20; // under stats().mutex
1006};
1007
1008Factory& factory() {
1009 static auto* f = new Factory;
1010 return *f;
1011}
1012
1013HRESULT WINAPI dstorage_get_factory(REFIID riid, void** ppv) {
1014 if (!ppv) return bad_call("DStorageGetFactory", E_POINTER, "null ppv");
1015 *ppv = nullptr;
1016 if (!iid_policy().accept_creating(riid, Kind::Factory, "DStorageGetFactory")) return E_NOINTERFACE;
1017 Factory& f = factory();
1018 f.AddRef();
1019 *ppv = static_cast<IDStorageFactoryX2*>(&f);
1020 return S_OK;
1021}
1022
1023} // namespace
1024
1025// The console module names; docs/directstorage.md has the evidence and the confidence for each.
1026SHIM_TABLE(dstorage,
1027 {"dstorage_xs.dll", "DStorageGetFactory", reinterpret_cast<void*>(&dstorage_get_factory)},
1028 {"xcrdapi.dll", "DStorageGetFactory", reinterpret_cast<void*>(&dstorage_get_factory)},
1029 {"dstorage.dll", "DStorageGetFactory", reinterpret_cast<void*>(&dstorage_get_factory)},
1030);
diff --git a/runtime/shims/dstorage_xs_abi.h b/runtime/shims/dstorage_xs_abi.h
new file mode 100644
index 000000000..854f8dbf9
--- /dev/null
+++ b/runtime/shims/dstorage_xs_abi.h
@@ -0,0 +1,378 @@
1// Xbox DirectStorage ABI: the console API (dstorage_xs.h on the console) a title calls through DStorageGetFactory.
2//
3// These are Leonida's own declarations. Names, member order and types follow the public GDK reference
4// (learn.microsoft.com/gaming/gdk/docs/reference/system/dstorage); docs/directstorage.md has the evidence for which
5// DLL serves it and how sure each part is. No Microsoft header is copied.
6//
7// VERIFY (docs/directstorage.md "What is not public"):
8// - Vtable order. The reference lists methods alphabetically; the order below is the PC dstorage.h order for the
9// methods both APIs share, with the console-only ones (SetCpuAffinity, GetStats, CreateQueue1, GetHandle,
10// Query1) where the GDK overview lists them. Reorder a declaration here and every object follows.
11// - Interface ids. The X interfaces' ids are not public. The one declared id is the PC IDStorageStatusArray's, whose
12// interface has the same shape (console D3D12 binaries reuse PC SDK ids); dstorage.cpp's creating calls learn and
13// log the others. The other PC ids are declared only so they can be refused.
14// - The capacity bounds, DSTORAGE_REQUEST_MAX_NAME and the E_DSTORAGE_* values are the PC header's.
15#pragma once
16#include <windows.h>
17#include <unknwn.h>
18
19#include <cstddef>
20#include <cstdint>
21
22struct ID3D12Fence; // d3d12.h; the shim calls Signal through it
23
24namespace dsx {
25
26#pragma warning(push)
27#pragma warning(disable : 4201) // nameless struct/union: the reference declares the members that way
28
29// ---- Constants and enumerations -----------------------------------------------------------------------------------
30
31constexpr uint16_t kMinQueueCapacity = 0x80; // DSTORAGE_MIN_QUEUE_CAPACITY (PC value)
32constexpr uint16_t kMaxQueueCapacity = 0x2000; // DSTORAGE_MAX_QUEUE_CAPACITY (PC value)
33constexpr size_t kRequestMaxName = 64; // DSTORAGE_REQUEST_MAX_NAME (PC value)
34constexpr uint64_t kMaxRequestBytes = 1ull << 30; // DSTORAGE_MAX_REQUEST_SIZE: source + destination
35constexpr uint32_t kMax4kPageDestinationSize = 32u << 20; // DSTORAGE_MAX_4K_PAGE_DESTINATION_SIZE
36
37enum DSTORAGE_PRIORITY : int8_t {
38 DSTORAGE_PRIORITY_LOW = -1,
39 DSTORAGE_PRIORITY_NORMAL = 0,
40 DSTORAGE_PRIORITY_HIGH = 1,
41 DSTORAGE_PRIORITY_REALTIME = 2,
42 DSTORAGE_PRIORITY_FIRST = DSTORAGE_PRIORITY_LOW,
43 DSTORAGE_PRIORITY_LAST = DSTORAGE_PRIORITY_REALTIME,
44 DSTORAGE_PRIORITY_COUNT = 4,
45};
46
47enum DSTORAGE_REQUEST_SOURCE_TYPE : uint64_t {
48 DSTORAGE_REQUEST_SOURCE_FILE = 0,
49 DSTORAGE_REQUEST_SOURCE_MEMORY = 1,
50};
51
52enum DSTORAGE_BCPACK_MODE : uint64_t {
53 DSTORAGE_BCPACK_MODE_NONE = 0,
54 DSTORAGE_BCPACK_MODE_BC1 = 1,
55 DSTORAGE_BCPACK_MODE_BC2 = 2,
56 DSTORAGE_BCPACK_MODE_BC3 = 3,
57 DSTORAGE_BCPACK_MODE_BC4 = 4,
58 DSTORAGE_BCPACK_MODE_BC5 = 5,
59 DSTORAGE_BCPACK_MODE_BC6H = 6,
60 DSTORAGE_BCPACK_MODE_BC7 = 7,
61};
62
63enum DSTORAGE_SWIZZLE_MODE : uint64_t {
64 DSTORAGE_SWIZZLE_MODE_NONE = 0,
65 DSTORAGE_SWIZZLE_MODE_4K_4K_8K = 1,
66 DSTORAGE_SWIZZLE_MODE_4K_4K_24K = 2,
67 DSTORAGE_SWIZZLE_MODE_4K_12K_4K_4K_8K = 3,
68 DSTORAGE_SWIZZLE_MODE_4K_12K_4K_12K = 4,
69};
70
71enum DSTORAGE_COMMAND_TYPE : int32_t {
72 DSTORAGE_COMMAND_TYPE_NONE = -1,
73 DSTORAGE_COMMAND_TYPE_REQUEST = 0,
74 DSTORAGE_COMMAND_TYPE_STATUS = 1,
75 DSTORAGE_COMMAND_TYPE_SIGNAL = 2,
76};
77// Not in the console enum: the PC API's DSTORAGE_COMMAND_TYPE_EVENT, used here for a failed EnqueueSetEvent.
78constexpr DSTORAGE_COMMAND_TYPE kCommandTypeEvent = static_cast<DSTORAGE_COMMAND_TYPE>(3);
79
80enum DSTORAGE_DEBUG : uint32_t {
81 DSTORAGE_DEBUG_NONE = 0x00,
82 DSTORAGE_DEBUG_SHOW_ERRORS = 0x01,
83 DSTORAGE_DEBUG_BREAK_ON_ERROR = 0x02,
84 DSTORAGE_DEBUG_RECORD_OBJECT_NAMES = 0x04,
85};
86
87// The staging-buffer sizes the GDK overview lists as valid (its enumeration page is not public).
88constexpr uint32_t kStagingBufferSizes[] = {0, 16u << 20, 20u << 20, 24u << 20, 28u << 20, 32u << 20};
89
90// ---- Errors (FACILITY_GAME, the PC dstorageerr.h values) ----------------------------------------------------------
91
92constexpr HRESULT E_DSTORAGE_INVALID_QUEUE_CAPACITY = static_cast<HRESULT>(0x89240003L);
93constexpr HRESULT E_DSTORAGE_END_OF_FILE = static_cast<HRESULT>(0x89240007L);
94constexpr HRESULT E_DSTORAGE_REQUEST_TOO_LARGE = static_cast<HRESULT>(0x89240008L);
95constexpr HRESULT E_DSTORAGE_ACCESS_VIOLATION = static_cast<HRESULT>(0x89240009L);
96constexpr HRESULT E_DSTORAGE_FILE_NOT_OPEN = static_cast<HRESULT>(0x8924000BL);
97constexpr HRESULT E_DSTORAGE_RESERVED_FIELDS = static_cast<HRESULT>(0x8924000CL);
98constexpr HRESULT E_DSTORAGE_INVALID_BCPACK_MODE = static_cast<HRESULT>(0x8924000DL);
99constexpr HRESULT E_DSTORAGE_INVALID_SWIZZLE_MODE = static_cast<HRESULT>(0x8924000EL);
100constexpr HRESULT E_DSTORAGE_INVALID_DESTINATION_SIZE = static_cast<HRESULT>(0x8924000FL);
101constexpr HRESULT E_DSTORAGE_QUEUE_CLOSED = static_cast<HRESULT>(0x89240010L);
102constexpr HRESULT E_DSTORAGE_INVALID_QUEUE_PRIORITY = static_cast<HRESULT>(0x89240013L);
103constexpr HRESULT E_DSTORAGE_INDEX_BOUND = static_cast<HRESULT>(0x89240015L);
104constexpr HRESULT E_DSTORAGE_INVALID_FILE_HANDLE = static_cast<HRESULT>(0x89240017L);
105constexpr HRESULT E_DSTORAGE_INVALID_FILE_OFFSET = static_cast<HRESULT>(0x8924001AL);
106constexpr HRESULT E_DSTORAGE_INVALID_SOURCE_TYPE = static_cast<HRESULT>(0x8924001BL);
107constexpr HRESULT E_DSTORAGE_INVALID_INTERMEDIATE_SIZE = static_cast<HRESULT>(0x8924001CL);
108constexpr HRESULT E_DSTORAGE_STAGING_BUFFER_LOCKED = static_cast<HRESULT>(0x8924001FL);
109constexpr HRESULT E_DSTORAGE_INVALID_STAGING_BUFFER_SIZE = static_cast<HRESULT>(0x89240020L);
110constexpr HRESULT E_DSTORAGE_INVALID_FENCE = static_cast<HRESULT>(0x89240022L);
111constexpr HRESULT E_DSTORAGE_INVALID_STATUS_ARRAY = static_cast<HRESULT>(0x89240023L);
112constexpr HRESULT E_DSTORAGE_INVALID_MEMORY_QUEUE_PRIORITY = static_cast<HRESULT>(0x89240024L);
113
114// ---- Structures ---------------------------------------------------------------------------------------------------
115
116// DSTORAGE_REQUEST_OPTIONS as the reference declares it. The shim reads AsUINT64 through the bit positions below
117// (MSVC allocates bit-fields from bit 0 up); dstorage_test checks that the two agree.
118union DSTORAGE_REQUEST_OPTIONS {
119 struct {
120 uint64_t ZlibDecompress : 1;
121 DSTORAGE_BCPACK_MODE BcpackMode : 4;
122 DSTORAGE_SWIZZLE_MODE SwizzleMode : 16;
123 uint64_t DestinationIsPhysicalPages : 1;
124 DSTORAGE_REQUEST_SOURCE_TYPE SourceType : 1;
125 uint64_t SourceIsPhysicalPages : 1;
126 uint64_t Reserved : 40;
127 };
128 uint64_t AsUINT64;
129};
130static_assert(sizeof(DSTORAGE_REQUEST_OPTIONS) == 8);
131
132namespace options {
133constexpr uint64_t kZlib = 1ull << 0;
134constexpr unsigned kBcpackShift = 1;
135constexpr uint64_t kBcpackMask = 0xFull << kBcpackShift;
136constexpr unsigned kSwizzleShift = 5;
137constexpr uint64_t kSwizzleMask = 0xFFFFull << kSwizzleShift;
138constexpr uint64_t kDestinationPages = 1ull << 21;
139constexpr uint64_t kSourceMemory = 1ull << 22; // SourceType == DSTORAGE_REQUEST_SOURCE_MEMORY
140constexpr uint64_t kSourcePages = 1ull << 23;
141constexpr uint64_t kReservedMask = ~((1ull << 24) - 1);
142
143constexpr bool zlib(uint64_t o) { return (o & kZlib) != 0; }
144constexpr uint64_t bcpack(uint64_t o) { return (o & kBcpackMask) >> kBcpackShift; }
145constexpr uint64_t swizzle(uint64_t o) { return (o & kSwizzleMask) >> kSwizzleShift; }
146constexpr DSTORAGE_REQUEST_SOURCE_TYPE source_type(uint64_t o) {
147 return (o & kSourceMemory) ? DSTORAGE_REQUEST_SOURCE_MEMORY : DSTORAGE_REQUEST_SOURCE_FILE;
148}
149} // namespace options
150
151struct IDStorageFileX;
152struct IDStorageStatusArrayX;
153
154struct DSTORAGE_REQUEST {
155 DSTORAGE_REQUEST_OPTIONS Options;
156 union {
157 void* Destination;
158 struct {
159 PULONG_PTR DestinationPageArray;
160 UINT16 DestinationPageOffset;
161 };
162 };
163 UINT32 DestinationSize;
164 union {
165 struct {
166 IDStorageFileX* File;
167 UINT64 FileOffset;
168 };
169 const void* Source;
170 struct {
171 PULONG_PTR SourcePageArray;
172 UINT16 SourcePageOffset;
173 };
174 };
175 UINT32 SourceSize;
176 UINT32 IntermediateSize;
177 UINT64 CancellationTag;
178 const CHAR* Name;
179};
180static_assert(offsetof(DSTORAGE_REQUEST, Destination) == 8 && offsetof(DSTORAGE_REQUEST, DestinationPageOffset) == 16);
181static_assert(offsetof(DSTORAGE_REQUEST, DestinationSize) == 24 && offsetof(DSTORAGE_REQUEST, File) == 32);
182static_assert(offsetof(DSTORAGE_REQUEST, FileOffset) == 40 && offsetof(DSTORAGE_REQUEST, Source) == 32);
183static_assert(offsetof(DSTORAGE_REQUEST, SourcePageOffset) == 40 && offsetof(DSTORAGE_REQUEST, SourceSize) == 48);
184static_assert(offsetof(DSTORAGE_REQUEST, IntermediateSize) == 52 && offsetof(DSTORAGE_REQUEST, CancellationTag) == 56);
185static_assert(offsetof(DSTORAGE_REQUEST, Name) == 64 && sizeof(DSTORAGE_REQUEST) == 72);
186
187struct DSTORAGE_QUEUE_DESC {
188 DSTORAGE_REQUEST_SOURCE_TYPE SourceType;
189 UINT16 Capacity;
190 DSTORAGE_PRIORITY Priority;
191 const CHAR* Name;
192};
193static_assert(offsetof(DSTORAGE_QUEUE_DESC, Capacity) == 8 && offsetof(DSTORAGE_QUEUE_DESC, Priority) == 10);
194static_assert(offsetof(DSTORAGE_QUEUE_DESC, Name) == 16 && sizeof(DSTORAGE_QUEUE_DESC) == 24);
195
196union DSTORAGE_QUEUE_OPTIONS {
197 struct {
198 uint64_t AutoSubmitDisabled : 1;
199 uint64_t Reserved : 63;
200 };
201 uint64_t AsUINT64;
202};
203static_assert(sizeof(DSTORAGE_QUEUE_OPTIONS) == 8);
204
205struct DSTORAGE_QUEUE_DESC1 {
206 DSTORAGE_REQUEST_SOURCE_TYPE SourceType;
207 UINT16 Capacity;
208 DSTORAGE_PRIORITY Priority;
209 const CHAR* Name;
210 DSTORAGE_QUEUE_OPTIONS Options;
211};
212static_assert(offsetof(DSTORAGE_QUEUE_DESC1, Options) == 24 && sizeof(DSTORAGE_QUEUE_DESC1) == 32);
213
214struct DSTORAGE_QUEUE_INFO {
215 DSTORAGE_QUEUE_DESC Desc;
216 UINT16 EmptySlotCount;
217 UINT16 RequestCountUntilAutoSubmit;
218};
219static_assert(offsetof(DSTORAGE_QUEUE_INFO, EmptySlotCount) == 24 && sizeof(DSTORAGE_QUEUE_INFO) == 32);
220
221struct DSTORAGE_QUEUE_INFO1 {
222 DSTORAGE_QUEUE_DESC1 Desc;
223 UINT16 EmptySlotCount;
224 UINT16 RequestCountUntilAutoSubmit;
225};
226static_assert(offsetof(DSTORAGE_QUEUE_INFO1, EmptySlotCount) == 32 && sizeof(DSTORAGE_QUEUE_INFO1) == 40);
227
228// The reference declares the three failure kinds as unnamed structs inside DSTORAGE_ERROR_RECORD; they are named
229// here (Leonida's names) so the shim can fill them. The layout is the same.
230struct DSTORAGE_ERROR_REQUEST {
231 DSTORAGE_REQUEST_OPTIONS Options;
232 void* Destination;
233 UINT32 DestinationSize;
234 WCHAR Filename[MAX_PATH];
235 UINT64 FileOffset;
236 const void* Source;
237 UINT32 SourceSize;
238 UINT64 CancellationTag;
239 CHAR Name[kRequestMaxName];
240};
241struct DSTORAGE_ERROR_STATUS {
242 IDStorageStatusArrayX* StatusArray;
243 UINT32 Index;
244};
245struct DSTORAGE_ERROR_SIGNAL {
246 ID3D12Fence* Fence;
247 UINT64 Value;
248};
249struct DSTORAGE_ERROR_FIRST_FAILURE {
250 HRESULT HResult;
251 DSTORAGE_COMMAND_TYPE CommandType;
252 union {
253 DSTORAGE_ERROR_REQUEST Request;
254 DSTORAGE_ERROR_STATUS Status;
255 DSTORAGE_ERROR_SIGNAL Signal;
256 };
257};
258struct DSTORAGE_ERROR_RECORD {
259 UINT32 FailureCount;
260 DSTORAGE_ERROR_FIRST_FAILURE FirstFailure;
261};
262static_assert(offsetof(DSTORAGE_ERROR_RECORD, FirstFailure) == 8);
263static_assert(offsetof(DSTORAGE_ERROR_FIRST_FAILURE, Request) == 8);
264static_assert(offsetof(DSTORAGE_ERROR_REQUEST, Filename) == 20 && offsetof(DSTORAGE_ERROR_REQUEST, FileOffset) == 544);
265static_assert(offsetof(DSTORAGE_ERROR_REQUEST, Name) == 576 && sizeof(DSTORAGE_ERROR_REQUEST) == 640);
266static_assert(sizeof(DSTORAGE_ERROR_RECORD) == 656);
267
268struct DSTORAGE_PRIORITY_STATS {
269 UINT32 CurrentQueueCount;
270 UINT32 MaxQueueCount;
271 UINT32 CumulativeQueueCount;
272 UINT32 TotalStatusCount;
273 UINT32 TotalFenceCount;
274 UINT32 PendingRequestCount;
275 UINT32 TotalRequestCount;
276 UINT64 TotalRequestSourceByteCount;
277 UINT64 TotalRequestDestinationByteCount;
278};
279static_assert(sizeof(DSTORAGE_PRIORITY_STATS) == 48);
280
281struct DSTORAGE_STATS {
282 DSTORAGE_PRIORITY_STATS LowPriorityStats;
283 DSTORAGE_PRIORITY_STATS NormalPriorityStats;
284 DSTORAGE_PRIORITY_STATS HighPriorityStats;
285 DSTORAGE_PRIORITY_STATS RealtimePriorityStats;
286 UINT8 CurrentOpenVirtualDiskCount;
287 UINT8 MaxOpenVirtualDiskCount;
288 UINT32 CumulativeOpenVirtualDiskCount;
289 UINT32 PendingStorageRequestCount;
290 UINT32 TotalStorageRequestCount;
291 UINT32 StorageRetries;
292 UINT32 StorageErrors;
293 UINT32 PendingDecompressionRequestCount;
294 UINT32 TotalDecompressionRequestCount;
295 UINT32 DecompressionErrors;
296 UINT32 StagingBufferStallCount;
297 UINT32 CurrentOpenFileCount;
298 UINT32 MaxOpenFileCount;
299 UINT32 CumulativeOpenFileCount;
300 UINT32 CurrentTitleMemoryUsageBytes;
301 UINT32 MaxTitleMemoryUsageBytes;
302 UINT32 ErrorCount;
303};
304
305#pragma warning(pop)
306
307// ---- Interfaces, in the vtable order chosen above ---------------------------------------------------------------
308
309struct IDStorageStatusArrayX : IUnknown {
310 virtual bool STDMETHODCALLTYPE IsComplete(UINT32 index) = 0;
311 virtual HRESULT STDMETHODCALLTYPE GetHResult(UINT32 index) = 0;
312};
313
314struct IDStorageFileX : IUnknown {
315 virtual void STDMETHODCALLTYPE Close() = 0;
316 virtual HANDLE STDMETHODCALLTYPE GetHandle() = 0;
317};
318
319struct IDStorageQueueX : IUnknown {
320 virtual void STDMETHODCALLTYPE EnqueueRequest(const DSTORAGE_REQUEST* request) = 0;
321 virtual void STDMETHODCALLTYPE EnqueueStatus(IDStorageStatusArrayX* status_array, UINT32 index) = 0;
322 virtual void STDMETHODCALLTYPE EnqueueSignal(ID3D12Fence* fence, UINT64 value) = 0;
323 virtual void STDMETHODCALLTYPE Submit() = 0;
324 virtual void STDMETHODCALLTYPE CancelRequestsWithTag(UINT64 mask, UINT64 value) = 0;
325 virtual void STDMETHODCALLTYPE Close() = 0;
326 virtual HANDLE STDMETHODCALLTYPE GetErrorEvent() = 0;
327 virtual void STDMETHODCALLTYPE RetrieveErrorRecord(DSTORAGE_ERROR_RECORD* record) = 0;
328 virtual void STDMETHODCALLTYPE Query(DSTORAGE_QUEUE_INFO* info) = 0;
329};
330
331struct IDStorageQueueX1 : IDStorageQueueX {
332 virtual void STDMETHODCALLTYPE EnqueueSetEvent(HANDLE handle) = 0;
333};
334
335struct IDStorageQueueX2 : IDStorageQueueX1 {
336 virtual void STDMETHODCALLTYPE Query1(DSTORAGE_QUEUE_INFO1* info) = 0;
337};
338
339struct IDStorageFactoryX : IUnknown {
340 virtual HRESULT STDMETHODCALLTYPE CreateQueue(const DSTORAGE_QUEUE_DESC* desc, REFIID riid, void** ppv) = 0;
341 virtual HRESULT STDMETHODCALLTYPE OpenFile(const WCHAR* path, REFIID riid, void** ppv) = 0;
342 virtual HRESULT STDMETHODCALLTYPE CreateStatusArray(UINT32 capacity, PCSTR name, REFIID riid, void** ppv) = 0;
343 virtual HRESULT STDMETHODCALLTYPE SetCpuAffinity(UINT64 affinity) = 0;
344 virtual void STDMETHODCALLTYPE SetDebugFlags(UINT32 flags) = 0;
345 virtual HRESULT STDMETHODCALLTYPE SetStagingBufferSize(UINT32 size) = 0;
346};
347
348struct IDStorageFactoryX1 : IDStorageFactoryX {
349 virtual void STDMETHODCALLTYPE GetStats(DSTORAGE_STATS* stats) = 0;
350};
351
352struct IDStorageFactoryX2 : IDStorageFactoryX1 {
353 virtual HRESULT STDMETHODCALLTYPE CreateQueue1(const DSTORAGE_QUEUE_DESC1* desc, REFIID riid, void** ppv) = 0;
354};
355
356using DStorageGetFactoryFn = HRESULT(WINAPI*)(REFIID riid, void** ppv);
357
358// ---- Interface ids -------------------------------------------------------------------------------------------------
359
360// Accepted for a status array: IDStorageStatusArray (PC dstorage.h 1.3.0), same methods in the same order.
361constexpr GUID kStatusArrayIds[] = {
362 {0x82397587, 0x7cd5, 0x453b, {0xa0, 0x2e, 0x31, 0x37, 0x9b, 0xd6, 0x46, 0x56}},
363};
364
365// The other PC DirectStorage ids (dstorage.h 1.3.0), refused: their objects have another shape.
366constexpr GUID kPcInterfaceIds[] = {
367 {0x6924ea0c, 0xc3cd, 0x4826, {0xb1, 0x0a, 0xf6, 0x4f, 0x4e, 0xd9, 0x27, 0xc1}}, // IDStorageFactory
368 {0x5de95e7b, 0x955a, 0x4868, {0xa7, 0x3c, 0x24, 0x3b, 0x29, 0xf4, 0xb8, 0xda}}, // IDStorageFile
369 {0xcfdbd83f, 0x9e06, 0x4fda, {0x8e, 0xa5, 0x69, 0x04, 0x21, 0x37, 0xf4, 0x9b}}, // IDStorageQueue
370 {0xdd2f482c, 0x5eff, 0x41e8, {0x9c, 0x9e, 0xd2, 0x37, 0x4b, 0x27, 0x81, 0x28}}, // IDStorageQueue1
371 {0xb1c9d643, 0x3a49, 0x44a2, {0xb4, 0x6f, 0x65, 0x36, 0x49, 0x47, 0x0d, 0x18}}, // IDStorageQueue2
372 {0xdeb54c52, 0xeca8, 0x46b3, {0x82, 0xa7, 0x03, 0x1b, 0x72, 0x26, 0x26, 0x53}}, // IDStorageQueue3
373 {0x97179b2f, 0x2c21, 0x49ca, {0x82, 0x91, 0x4e, 0x1b, 0xf4, 0xa1, 0x60, 0xdf}}, // ...CustomDecompressionQueue
374 {0x0d47c6c9, 0xe61a, 0x4706, {0x93, 0xb4, 0x68, 0xbf, 0xe3, 0xf4, 0xaa, 0x4a}}, // ...CustomDecompressionQueue1
375 {0x84ef5121, 0x9b43, 0x4d03, {0xb5, 0xc1, 0xcc, 0x34, 0x60, 0x6b, 0x26, 0x2d}}, // IDStorageCompressionCodec
376};
377
378} // namespace dsx
diff --git a/runtime/shims/registry.cpp b/runtime/shims/registry.cpp
index 37ff540c5..047645401 100644
--- a/runtime/shims/registry.cpp
+++ b/runtime/shims/registry.cpp
@@ -80,7 +80,10 @@ std::vector<Lookup> g_lookups;
80// xaudio2_9.dll XAudio2Create: HRESULT (learn.microsoft.com/windows/win32/api/xaudio2/ 80// xaudio2_9.dll XAudio2Create: HRESULT (learn.microsoft.com/windows/win32/api/xaudio2/
81// xaudio2_9redist.dll nf-xaudio2-xaudio2create). xaudio2_9.dll is the console name (docs/d3d12_vulkan.md §7). 81// xaudio2_9redist.dll nf-xaudio2-xaudio2create). xaudio2_9.dll is the console name (docs/d3d12_vulkan.md §7).
82// dstorage.dll DStorageGetFactory: HRESULT (learn.microsoft.com/windows/win32/api/dstorage/ 82// dstorage.dll DStorageGetFactory: HRESULT (learn.microsoft.com/windows/win32/api/dstorage/
83// dstorage_xs.dll nf-dstorage-dstoragegetfactory). dstorage_xs.dll is the console name. 83// dstorage_xs.dll nf-dstorage-dstoragegetfactory, and the GDK's gaming/gdk/docs/reference/system/dstorage/
84// xcrdapi.dll functions/dstoragegetfactory). dstorage_xs.dll is the console name; xcrdapi.dll is a
85// console module the title may import it from (docs/directstorage.md). dstorage.cpp serves
86// it; the class is kept for a build without that shim.
84const char* const kNotHResult[] = { 87const char* const kNotHResult[] = {
85 "XAsyncCancel", "XAsyncComplete", 88 "XAsyncCancel", "XAsyncComplete",
86 "XTaskQueueCloseHandle", "XTaskQueueDispatch", "XTaskQueueGetCurrentProcessTaskQueue", 89 "XTaskQueueCloseHandle", "XTaskQueueDispatch", "XTaskQueueGetCurrentProcessTaskQueue",
@@ -111,7 +114,7 @@ ReturnClass classify(const std::string& dll, const std::string& name) {
111 if (name == "XAudio2Create") return ReturnClass::HResult; 114 if (name == "XAudio2Create") return ReturnClass::HResult;
112 } else if (dll == "gameinput.dll") { 115 } else if (dll == "gameinput.dll") {
113 if (name == "GameInputCreate") return ReturnClass::HResult; 116 if (name == "GameInputCreate") return ReturnClass::HResult;
114 } else if (dll == "dstorage.dll" || dll == "dstorage_xs.dll") { 117 } else if (dll == "dstorage.dll" || dll == "dstorage_xs.dll" || dll == "xcrdapi.dll") {
115 if (name == "DStorageGetFactory") return ReturnClass::HResult; 118 if (name == "DStorageGetFactory") return ReturnClass::HResult;
116 } else if (dll == "xgameruntime.dll") { 119 } else if (dll == "xgameruntime.dll") {
117 if (name == "XGameRuntimeInitialize" || name == "XGameEventWrite") return ReturnClass::HResult; 120 if (name == "XGameRuntimeInitialize" || name == "XGameEventWrite") return ReturnClass::HResult;