upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/shims/dstorage.cpp
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/dstorage.cpp
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/dstorage.cpp')
-rw-r--r--runtime/shims/dstorage.cpp1030
1 files changed, 1030 insertions, 0 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);