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:
authorMumogg <104529023+Mumogg@users.noreply.github.com>2026-11-23 20:23:21 -0600
committerMumogg <104529023+Mumogg@users.noreply.github.com>2026-11-23 20:23:21 -0600
commit2d7be48dec529446e0ead3393e2b3acabb29ff64 (patch)
treee33ffbd80a396f79ea4842fbd3e45d7f145df73e /runtime/shims/dstorage.cpp
parent9ec34cdff41b19d7671bc260e5f40dc69790d905 (diff)
runtime: restore the console DirectStorage shim (DStorageGetFactory) on main
The merge that brought the mirrored pull requests into main (6dece9231) left the DirectStorage shim out, noting that it "needs the typed-error zlib inflate". The shim's commits (f87d05fdd, ac1843da2, 00551ba00, by mariuslozo-boop and Kelebek) are ancestors of main, but its files are not in the tree, so the retail executable's XCRDAPI.dll!DStorageGetFactory import is unimplemented (issue #47, stop 5 of docs/retail_boot_chain.md). - shims/dstorage.cpp, shims/dstorage_xs_abi.h, test/dstorage_test.cpp and docs/directstorage.md are back as those commits left them. - leonida::zlib_inflate reports why it failed through an optional ZlibError* (header, data, checksum, limit), which the shim turns into its E_DSTORAGE_ZLIB_* codes. This is the same interface the shim was written against, added to main's current table-driven inflater; callers that pass no pointer behave as before. - registry.cpp classes xcrdapi.dll!DStorageGetFactory as an HRESULT import, the retail spelling #47 found missing. - CMake and scripts/build_runtime.ps1 build the shim into gta6rt, and CMake builds and registers dstorage_test. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01HxBQf4pXH8PWpC5oZsM4bt
Diffstat (limited to 'runtime/shims/dstorage.cpp')
-rw-r--r--runtime/shims/dstorage.cpp1125
1 files changed, 1125 insertions, 0 deletions
diff --git a/runtime/shims/dstorage.cpp b/runtime/shims/dstorage.cpp
new file mode 100644
index 000000000..81abaea3d
--- /dev/null
+++ b/runtime/shims/dstorage.cpp
@@ -0,0 +1,1125 @@
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// - A zlib request (ZlibDecompress alone) reads its source into a staging buffer, inflates it on the worker with
12// the runtime's RFC 1950 inflater (leonida::zlib_inflate, src/shader_library.h) and copies the result to the
13// destination only when it is exactly DestinationSize bytes; a stream that fails leaves the destination as it was.
14// - BCPack, swizzle and physical-page requests fail with E_NOTIMPL for now (later PRs: they become stages between
15// the read and the destination write, BCPack after the inflate).
16// Nothing here goes online or touches the GPU.
17#include <windows.h>
18#include <d3d12.h>
19
20#include <algorithm>
21#include <atomic>
22#include <condition_variable>
23#include <cstdio>
24#include <cstring>
25#include <deque>
26#include <memory>
27#include <mutex>
28#include <new>
29#include <set>
30#include <string>
31#include <thread>
32#include <unordered_set>
33#include <vector>
34
35#include "../src/shader_library.h" // leonida::zlib_inflate
36#include "dstorage_xs_abi.h"
37#include "shims.h"
38
39using namespace dsx;
40
41namespace {
42
43// ---- Logging ------------------------------------------------------------------------------------------------------
44
45// Process-lifetime state is allocated once and never freed: a worker thread may still run while statics are destroyed
46// at exit.
47std::mutex& log_mutex() {
48 static auto* m = new std::mutex;
49 return *m;
50}
51
52void log_once(const std::string& key, const std::string& line) {
53 static auto* seen = new std::set<std::string>;
54 std::lock_guard lock(log_mutex());
55 if (!seen->insert(key).second) return;
56 std::fprintf(stderr, "[rt] dstorage: %s\n", line.c_str());
57}
58
59std::string guid_text(const GUID& g) {
60 char b[48];
61 std::snprintf(b, sizeof b, "{%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}", g.Data1, g.Data2, g.Data3,
62 g.Data4[0], g.Data4[1], g.Data4[2], g.Data4[3], g.Data4[4], g.Data4[5], g.Data4[6], g.Data4[7]);
63 return b;
64}
65
66bool same_guid(const GUID& a, const GUID& b) { return std::memcmp(&a, &b, sizeof(GUID)) == 0; }
67
68std::string hr_text(HRESULT hr) {
69 char b[16];
70 std::snprintf(b, sizeof b, "0x%08lx", static_cast<unsigned long>(hr));
71 return b;
72}
73
74// ---- Interface ids ------------------------------------------------------------------------------------------------
75//
76// The X interfaces' ids are not public. A creating call (DStorageGetFactory, CreateQueue*, OpenFile,
77// CreateStatusArray) accepts an id it has not seen for the kind of object it hands out and logs it the first time, so
78// the first boot records the console's ids. It refuses an id seen for another kind, a PC DirectStorage id of another
79// shape, and the system COM interfaces (IMarshal, IAgileObject, ...), which a DirectStorage object never implements.
80// QueryInterface is stricter (docs/d3d12_vulkan.md: an unknown id is E_NOINTERFACE): it accepts IUnknown, the
81// declared ids (dstorage_xs_abi.h) and the ids a creating call accepted for that kind, and logs anything else. This is
82// a policy, not a fact; it lives here so a measured id list can replace it.
83
84enum class Kind { Factory, Queue, File, StatusArray };
85
86const char* kind_name(Kind k) {
87 switch (k) {
88 case Kind::Factory: return "factory";
89 case Kind::Queue: return "queue";
90 case Kind::File: return "file";
91 case Kind::StatusArray: return "status array";
92 }
93 return "?";
94}
95
96// System interfaces: the COM base range {xxxxxxxx-0000-0000-C000-000000000046} (IClassFactory, IMarshal,
97// IStdMarshalInfo, IExternalConnection, IMultiQI, IClientSecurity, IServerSecurity, IRpcOptions, IMarshal2,
98// IWeakReferenceSource, IDispatch, IPersist, ...) and these others.
99constexpr GUID kSystemInterfaceIds[] = {
100 {0x94ea2b94, 0xe9cc, 0x49e0, {0xc0, 0xff, 0xee, 0x64, 0xca, 0x8f, 0x5b, 0x90}}, // IAgileObject
101 {0xecc8691b, 0xc1db, 0x4dc0, {0x85, 0x5e, 0x65, 0xf6, 0xc5, 0x51, 0xaf, 0x49}}, // INoMarshal
102 {0x1c733a30, 0x2a1c, 0x11ce, {0xad, 0xe5, 0x00, 0xaa, 0x00, 0x44, 0x77, 0x3d}}, // ICallFactory
103 {0xaf86e2e0, 0xb12d, 0x4c6a, {0x9c, 0x5a, 0xd7, 0xaa, 0x65, 0x10, 0x1e, 0x90}}, // IInspectable
104 {0xdf0b3d60, 0x548f, 0x101b, {0x8e, 0x65, 0x08, 0x00, 0x2b, 0x2b, 0xd1, 0x19}}, // ISupportErrorInfo
105 {0xb196b283, 0xbab4, 0x101a, {0xb6, 0x9c, 0x00, 0xaa, 0x00, 0x34, 0x1d, 0x07}}, // IProvideClassInfo
106 {0xb196b284, 0xbab4, 0x101a, {0xb6, 0x9c, 0x00, 0xaa, 0x00, 0x34, 0x1d, 0x07}}, // IConnectionPointContainer
107 {0xfc4801a3, 0x2ba9, 0x11cf, {0xa2, 0x29, 0x00, 0xaa, 0x00, 0x3d, 0x73, 0x52}}, // IObjectWithSite
108};
109
110bool system_interface(const GUID& g) {
111 static const uint8_t kComBase[8] = {0xc0, 0, 0, 0, 0, 0, 0, 0x46};
112 if (g.Data2 == 0 && g.Data3 == 0 && std::memcmp(g.Data4, kComBase, 8) == 0) return true;
113 for (const GUID& s : kSystemInterfaceIds)
114 if (same_guid(g, s)) return true;
115 return false;
116}
117
118// The ids declared for a kind: the PC IDStorageStatusArray id, whose interface has the console one's shape (console
119// D3D12 binaries reuse the PC SDK's ids). No other X interface id is known.
120bool declared(const GUID& g, Kind kind) {
121 for (const GUID& id : kStatusArrayIds)
122 if (same_guid(g, id)) return kind == Kind::StatusArray;
123 return false;
124}
125
126bool declared_for_any(const GUID& g) {
127 for (const GUID& id : kStatusArrayIds)
128 if (same_guid(g, id)) return true;
129 return false;
130}
131
132class IidPolicy {
133public:
134 bool accept_creating(REFIID riid, Kind kind, const char* caller) {
135 if (same_guid(riid, __uuidof(IUnknown)) || declared(riid, kind)) return true;
136 if (system_interface(riid)) return refuse(riid, caller, "a system COM interface");
137 if (declared_for_any(riid)) return refuse(riid, caller, "an id declared for another kind of object");
138 for (const GUID& pc : kPcInterfaceIds)
139 if (same_guid(riid, pc))
140 return refuse(riid, caller, "a PC DirectStorage interface; only the console ABI is served");
141 std::lock_guard lock(mutex_);
142 for (const auto& [id, k] : learned_)
143 if (same_guid(id, riid)) {
144 if (k == kind) return true;
145 return refuse(riid, caller, std::string("seen before as a ") + kind_name(k) + " interface");
146 }
147 learned_.push_back({riid, kind});
148 log_once("learn" + guid_text(riid), std::string(caller) + " asked for " + guid_text(riid) + ": serving the " +
149 kind_name(kind) + " interface");
150 return true;
151 }
152
153 bool accept_query(REFIID riid, Kind kind, const char* caller) {
154 if (same_guid(riid, __uuidof(IUnknown)) || declared(riid, kind)) return true;
155 {
156 std::lock_guard lock(mutex_);
157 for (const auto& [id, k] : learned_)
158 if (same_guid(id, riid) && k == kind) return true;
159 }
160 return refuse(riid, caller, std::string("not an id a ") + kind_name(kind) + " was created with");
161 }
162
163private:
164 static bool refuse(REFIID riid, const char* caller, const std::string& why) {
165 log_once(std::string("refuse") + caller + guid_text(riid),
166 std::string(caller) + " asked for " + guid_text(riid) + ": " + why + " (E_NOINTERFACE)");
167 return false;
168 }
169
170 std::mutex mutex_;
171 std::vector<std::pair<GUID, Kind>> learned_;
172};
173
174IidPolicy& iid_policy() {
175 static auto* p = new IidPolicy;
176 return *p;
177}
178
179// A bad argument to a factory or queue method, logged once per method and kind: a wrong vtable guess for the console
180// interfaces would show up here first, as arguments that make no sense for the method.
181HRESULT bad_call(const char* method, HRESULT hr, const char* what) {
182 log_once(std::string("bad") + method + what,
183 std::string(method) + ": " + what + " (" + hr_text(hr) +
184 "; logged once; a wrong vtable slot guess would show up like this)");
185 return hr;
186}
187
188// ---- Statistics (IDStorageFactoryX1::GetStats) --------------------------------------------------------------------
189
190struct Stats {
191 std::mutex mutex;
192 DSTORAGE_STATS s{};
193 uint32_t live_queues = 0; // all priorities; SetStagingBufferSize is refused while queues or files exist
194};
195
196Stats& stats() {
197 static auto* s = new Stats;
198 return *s;
199}
200
201DSTORAGE_PRIORITY_STATS& priority_stats(DSTORAGE_STATS& s, DSTORAGE_PRIORITY p) {
202 switch (p) {
203 case DSTORAGE_PRIORITY_LOW: return s.LowPriorityStats;
204 case DSTORAGE_PRIORITY_HIGH: return s.HighPriorityStats;
205 case DSTORAGE_PRIORITY_REALTIME: return s.RealtimePriorityStats;
206 default: return s.NormalPriorityStats;
207 }
208}
209
210void count_error() {
211 std::lock_guard lock(stats().mutex);
212 ++stats().s.ErrorCount;
213}
214
215// ---- Live objects ---------------------------------------------------------------------------------------------------
216//
217// A request names its file and a status entry its array by pointer. Only objects this shim made and that are still
218// alive are used; anything else is an error in the request, never a call through a stranger's vtable.
219
220std::mutex& live_mutex() {
221 static auto* m = new std::mutex;
222 return *m;
223}
224// One set per kind, so a status array passed as a file (or the other way round) is not found.
225std::unordered_set<const void*>& live_files() {
226 static auto* s = new std::unordered_set<const void*>;
227 return *s;
228}
229std::unordered_set<const void*>& live_status_arrays() {
230 static auto* s = new std::unordered_set<const void*>;
231 return *s;
232}
233
234// AddRef only if the count has not reached zero (an object being released is not revived).
235bool add_ref_if_live(std::atomic<ULONG>& refs) {
236 ULONG r = refs.load();
237 while (r != 0)
238 if (refs.compare_exchange_weak(r, r + 1)) return true;
239 return false;
240}
241
242// ---- Status arrays ------------------------------------------------------------------------------------------------
243
244class StatusArray final : public IDStorageStatusArrayX {
245public:
246 StatusArray(uint32_t capacity, std::unique_ptr<std::atomic<HRESULT>[]> entries)
247 : capacity_(capacity), entries_(std::move(entries)) {
248 for (uint32_t i = 0; i < capacity_; ++i) entries_[i].store(S_OK, std::memory_order_relaxed);
249 std::lock_guard lock(live_mutex());
250 live_status_arrays().insert(static_cast<IDStorageStatusArrayX*>(this));
251 }
252
253 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override {
254 if (!ppv) return E_POINTER;
255 *ppv = nullptr;
256 if (!iid_policy().accept_query(riid, Kind::StatusArray, "IDStorageStatusArrayX::QueryInterface"))
257 return E_NOINTERFACE;
258 AddRef();
259 *ppv = static_cast<IDStorageStatusArrayX*>(this);
260 return S_OK;
261 }
262 ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; }
263 ULONG STDMETHODCALLTYPE Release() override {
264 ULONG r;
265 {
266 std::lock_guard lock(live_mutex());
267 r = --refs_;
268 if (r == 0) live_status_arrays().erase(static_cast<IDStorageStatusArrayX*>(this));
269 }
270 if (r == 0) delete this;
271 return r;
272 }
273
274 // IsComplete is GetHResult(index) != E_PENDING (the reference says so); an index past the array is not pending.
275 bool STDMETHODCALLTYPE IsComplete(UINT32 index) override { return GetHResult(index) != E_PENDING; }
276 HRESULT STDMETHODCALLTYPE GetHResult(UINT32 index) override {
277 if (index >= capacity_) return E_DSTORAGE_INDEX_BOUND;
278 return entries_[index].load(std::memory_order_acquire);
279 }
280
281 uint32_t capacity() const { return capacity_; }
282 void set_pending(uint32_t index) { entries_[index].store(E_PENDING, std::memory_order_release); }
283 void complete(uint32_t index, HRESULT hr) { entries_[index].store(hr, std::memory_order_release); }
284 std::atomic<ULONG>& refs() { return refs_; }
285
286private:
287 std::atomic<ULONG> refs_{1};
288 const uint32_t capacity_;
289 std::unique_ptr<std::atomic<HRESULT>[]> entries_;
290};
291
292// ---- Files --------------------------------------------------------------------------------------------------------
293
294class File final : public IDStorageFileX {
295public:
296 File(HANDLE handle, std::wstring path) : handle_(handle), path_(std::move(path)) {
297 {
298 std::lock_guard lock(live_mutex());
299 live_files().insert(static_cast<IDStorageFileX*>(this));
300 }
301 std::lock_guard lock(stats().mutex);
302 auto& s = stats().s;
303 ++s.CurrentOpenFileCount;
304 ++s.CumulativeOpenFileCount;
305 s.MaxOpenFileCount = std::max(s.MaxOpenFileCount, s.CurrentOpenFileCount);
306 }
307 ~File() {
308 Close();
309 std::lock_guard lock(stats().mutex);
310 --stats().s.CurrentOpenFileCount;
311 }
312
313 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override {
314 if (!ppv) return E_POINTER;
315 *ppv = nullptr;
316 if (!iid_policy().accept_query(riid, Kind::File, "IDStorageFileX::QueryInterface")) return E_NOINTERFACE;
317 AddRef();
318 *ppv = static_cast<IDStorageFileX*>(this);
319 return S_OK;
320 }
321 ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; }
322 ULONG STDMETHODCALLTYPE Release() override {
323 ULONG r;
324 {
325 std::lock_guard lock(live_mutex());
326 r = --refs_;
327 if (r == 0) live_files().erase(static_cast<IDStorageFileX*>(this));
328 }
329 if (r == 0) delete this;
330 return r;
331 }
332
333 // Waits for the submitted requests that read this file, then closes the handle. A request submitted later fails
334 // with E_DSTORAGE_FILE_NOT_OPEN. Waiting only for submitted requests keeps a Close from blocking forever on a
335 // request that sits unsubmitted in a queue with auto-submit disabled.
336 void STDMETHODCALLTYPE Close() override {
337 std::unique_lock lock(mutex_);
338 closed_ = true;
339 idle_.wait(lock, [&] { return pending_ == 0; });
340 if (handle_ != INVALID_HANDLE_VALUE) {
341 CloseHandle(handle_);
342 handle_ = INVALID_HANDLE_VALUE;
343 }
344 }
345
346 // A new handle the caller closes (GENERIC_READ, FILE_SHARE_READ, as the reference describes it). ReOpenFile,
347 // not DuplicateHandle: a duplicate shares the file position with the shim's own reads, so the title's ReadFile
348 // through it would start wherever the worker's last read ended.
349 HANDLE STDMETHODCALLTYPE GetHandle() override {
350 std::lock_guard lock(mutex_);
351 if (closed_ || handle_ == INVALID_HANDLE_VALUE) {
352 SetLastError(ERROR_INVALID_HANDLE);
353 return INVALID_HANDLE_VALUE;
354 }
355 return ReOpenFile(handle_, GENERIC_READ, FILE_SHARE_READ, 0);
356 }
357
358 // Called when a request naming this file is submitted. False once the file is closed.
359 bool add_pending() {
360 std::lock_guard lock(mutex_);
361 if (closed_) return false;
362 ++pending_;
363 return true;
364 }
365 void finish_pending() {
366 std::lock_guard lock(mutex_);
367 if (--pending_ == 0) idle_.notify_all();
368 }
369 // Valid while the caller holds a pending count: Close does not close the handle before it drops to zero.
370 HANDLE handle() const { return handle_; }
371 const std::wstring& path() const { return path_; }
372 std::atomic<ULONG>& refs() { return refs_; }
373
374private:
375 std::atomic<ULONG> refs_{1};
376 std::mutex mutex_;
377 std::condition_variable idle_;
378 HANDLE handle_;
379 const std::wstring path_;
380 uint32_t pending_ = 0;
381 bool closed_ = false;
382};
383
384StatusArray* live_status_array(IDStorageStatusArrayX* p) {
385 std::lock_guard lock(live_mutex());
386 if (!p || !live_status_arrays().count(p)) return nullptr;
387 auto* a = static_cast<StatusArray*>(p);
388 return add_ref_if_live(a->refs()) ? a : nullptr;
389}
390
391File* live_file(IDStorageFileX* p) {
392 std::lock_guard lock(live_mutex());
393 if (!p || !live_files().count(p)) return nullptr;
394 auto* f = static_cast<File*>(p);
395 return add_ref_if_live(f->refs()) ? f : nullptr;
396}
397
398// ---- Reads --------------------------------------------------------------------------------------------------------
399
400// memmove that turns an access violation into an error instead of ending the process. No C++ objects here: a
401// function with __try cannot have any that need unwinding.
402bool guarded_move(void* destination, const void* source, size_t size) {
403 __try {
404 std::memmove(destination, source, size);
405 return true;
406 } __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER
407 : EXCEPTION_CONTINUE_SEARCH) {
408 return false;
409 }
410}
411
412HRESULT read_error(DWORD error) {
413 switch (error) {
414 case ERROR_NOACCESS:
415 case ERROR_INVALID_USER_BUFFER: return E_DSTORAGE_ACCESS_VIOLATION;
416 case ERROR_HANDLE_EOF: return E_DSTORAGE_END_OF_FILE;
417 default: return HRESULT_FROM_WIN32(error);
418 }
419}
420
421// Reads exactly "size" bytes at "offset" of a synchronous handle into "destination".
422HRESULT read_file_range(HANDLE handle, uint64_t offset, void* destination, uint32_t size) {
423 LARGE_INTEGER length{};
424 if (!GetFileSizeEx(handle, &length)) return HRESULT_FROM_WIN32(GetLastError());
425 const uint64_t file_size = static_cast<uint64_t>(length.QuadPart);
426 if (offset > file_size || size > file_size - offset) return E_DSTORAGE_END_OF_FILE;
427 auto* out = static_cast<uint8_t*>(destination);
428 uint32_t done = 0;
429 while (done < size) {
430 OVERLAPPED at{};
431 const uint64_t position = offset + done;
432 at.Offset = static_cast<DWORD>(position);
433 at.OffsetHigh = static_cast<DWORD>(position >> 32);
434 DWORD got = 0;
435 if (!ReadFile(handle, out + done, size - done, &got, &at)) return read_error(GetLastError());
436 if (got == 0) return E_DSTORAGE_END_OF_FILE; // the file shrank since the size check
437 done += got;
438 }
439 return S_OK;
440}
441
442// ---- Queues -------------------------------------------------------------------------------------------------------
443
444struct Entry {
445 enum class Type { Request, Status, Signal, Event } type = Type::Request;
446 DSTORAGE_REQUEST request{};
447 File* file = nullptr; // a reference, for a file request naming a live file
448 bool file_counted = false; // the file's pending count was raised at submit
449 bool cancelled = false; // CancelRequestsWithTag matched it before it started
450 bool counted = false; // a request the title passed: counted in the statistics when it is submitted
451 HRESULT enqueue_error = S_OK; // found at enqueue: reported when the entry is reached, in order
452 StatusArray* status = nullptr; // a reference
453 IDStorageStatusArrayX* status_as_given = nullptr;
454 uint32_t index = 0;
455 ID3D12Fence* fence = nullptr; // a reference
456 uint64_t value = 0;
457 HANDLE event = nullptr; // a duplicate the entry owns
458};
459
460class Queue final : public IDStorageQueueX2 {
461public:
462 explicit Queue(const DSTORAGE_QUEUE_DESC1& desc) : desc_(desc) {
463 error_event_ = CreateEventW(nullptr, TRUE, FALSE, nullptr);
464 clear_record_locked();
465 std::lock_guard lock(stats().mutex);
466 auto& p = priority_stats(stats().s, desc_.Priority);
467 ++p.CurrentQueueCount;
468 ++p.CumulativeQueueCount;
469 p.MaxQueueCount = std::max(p.MaxQueueCount, p.CurrentQueueCount);
470 ++stats().live_queues;
471 }
472 // Separate from the constructor so a failure to start the thread can be reported.
473 bool start() {
474 if (!error_event_) return false;
475 try {
476 worker_ = std::thread([this] { run(); });
477 } catch (...) {
478 return false;
479 }
480 return true;
481 }
482 ~Queue() {
483 Close();
484 if (error_event_) CloseHandle(error_event_);
485 std::lock_guard lock(stats().mutex);
486 --priority_stats(stats().s, desc_.Priority).CurrentQueueCount;
487 --stats().live_queues;
488 }
489
490 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override {
491 if (!ppv) return E_POINTER;
492 *ppv = nullptr;
493 if (!iid_policy().accept_query(riid, Kind::Queue, "IDStorageQueueX::QueryInterface")) return E_NOINTERFACE;
494 AddRef();
495 *ppv = static_cast<IDStorageQueueX2*>(this);
496 return S_OK;
497 }
498 ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; }
499 // The last Release closes the queue, which runs everything enqueued first.
500 ULONG STDMETHODCALLTYPE Release() override {
501 const ULONG r = --refs_;
502 if (r == 0) delete this;
503 return r;
504 }
505
506 void STDMETHODCALLTYPE EnqueueRequest(const DSTORAGE_REQUEST* request) override {
507 Entry e;
508 e.type = Entry::Type::Request;
509 if (!request) {
510 e.enqueue_error = bad_call("IDStorageQueueX::EnqueueRequest", E_INVALIDARG, "null request");
511 } else {
512 e.request = *request; // the title may reuse its structure as soon as this returns
513 const uint64_t o = e.request.Options.AsUINT64;
514 if (options::source_type(o) == DSTORAGE_REQUEST_SOURCE_FILE &&
515 desc_.SourceType == DSTORAGE_REQUEST_SOURCE_FILE && e.request.File) {
516 e.file = live_file(e.request.File);
517 if (!e.file) e.enqueue_error = E_DSTORAGE_INVALID_FILE_HANDLE;
518 }
519 e.counted = true; // TotalRequestCount is "submitted requests" (DSTORAGE_PRIORITY_STATS): see submit_locked
520 }
521 enqueue(std::move(e));
522 }
523
524 void STDMETHODCALLTYPE EnqueueStatus(IDStorageStatusArrayX* status_array, UINT32 index) override {
525 Entry e;
526 e.type = Entry::Type::Status;
527 e.status_as_given = status_array;
528 e.index = index;
529 e.status = live_status_array(status_array);
530 if (!e.status) {
531 e.enqueue_error = E_DSTORAGE_INVALID_STATUS_ARRAY;
532 } else if (index >= e.status->capacity()) {
533 e.enqueue_error = E_DSTORAGE_INDEX_BOUND;
534 } else {
535 e.status->set_pending(index); // polling after this call sees E_PENDING until the entry is reached
536 }
537 {
538 std::lock_guard lock(stats().mutex);
539 ++priority_stats(stats().s, desc_.Priority).TotalStatusCount;
540 }
541 enqueue(std::move(e));
542 }
543
544 void STDMETHODCALLTYPE EnqueueSignal(ID3D12Fence* fence, UINT64 value) override {
545 Entry e;
546 e.type = Entry::Type::Signal;
547 e.fence = fence;
548 e.value = value;
549 if (fence) {
550 fence->AddRef();
551 } else {
552 e.enqueue_error = E_DSTORAGE_INVALID_FENCE;
553 }
554 {
555 std::lock_guard lock(stats().mutex);
556 ++priority_stats(stats().s, desc_.Priority).TotalFenceCount;
557 }
558 enqueue(std::move(e));
559 }
560
561 // The handle is duplicated here and the duplicate closed once it has been set (or dropped), so an event the
562 // title closes, and whose handle value is then reused for another object, is never the one set.
563 void STDMETHODCALLTYPE EnqueueSetEvent(HANDLE handle) override {
564 Entry e;
565 e.type = Entry::Type::Event;
566 if (!handle) {
567 e.enqueue_error = bad_call("IDStorageQueueX1::EnqueueSetEvent", HRESULT_FROM_WIN32(ERROR_INVALID_HANDLE),
568 "null event handle");
569 } else if (!DuplicateHandle(GetCurrentProcess(), handle, GetCurrentProcess(), &e.event, 0, FALSE,
570 DUPLICATE_SAME_ACCESS)) {
571 e.event = nullptr;
572 e.enqueue_error = HRESULT_FROM_WIN32(GetLastError());
573 }
574 enqueue(std::move(e));
575 }
576
577 void STDMETHODCALLTYPE Submit() override {
578 std::lock_guard lock(mutex_);
579 submit_locked();
580 }
581
582 // Marks the requests enqueued before this call that have not started. A cancelled request completes as a success
583 // without being read (the overview: the title may no longer use its result).
584 void STDMETHODCALLTYPE CancelRequestsWithTag(UINT64 mask, UINT64 value) override {
585 std::lock_guard lock(mutex_);
586 for (Entry& e : entries_)
587 if (e.type == Entry::Type::Request && (e.request.CancellationTag & mask) == value) e.cancelled = true;
588 }
589
590 // Submits what is enqueued, waits until the worker has run all of it and stops the worker. Later enqueues are
591 // dropped and recorded as E_DSTORAGE_QUEUE_CLOSED.
592 void STDMETHODCALLTYPE Close() override {
593 std::lock_guard close_lock(close_mutex_);
594 {
595 std::unique_lock lock(mutex_);
596 if (closed_) return;
597 closing_ = true;
598 submit_locked();
599 space_.notify_all(); // an enqueue waiting for space gives up (the queue is closing)
600 idle_.wait(lock, [&] { return entries_.empty() && !in_flight_; });
601 closed_ = true;
602 work_.notify_all();
603 }
604 if (worker_.joinable()) worker_.join();
605 }
606
607 HANDLE STDMETHODCALLTYPE GetErrorEvent() override {
608 HANDLE dup = nullptr;
609 if (!error_event_ || !DuplicateHandle(GetCurrentProcess(), error_event_, GetCurrentProcess(), &dup, 0, FALSE,
610 DUPLICATE_SAME_ACCESS))
611 return nullptr;
612 return dup; // the reference says the title closes it
613 }
614
615 void STDMETHODCALLTYPE RetrieveErrorRecord(DSTORAGE_ERROR_RECORD* record) override {
616 if (!record) {
617 bad_call("IDStorageQueueX::RetrieveErrorRecord", E_POINTER, "null record");
618 return;
619 }
620 std::lock_guard lock(error_mutex_);
621 *record = record_;
622 clear_record_locked();
623 if (error_event_) ResetEvent(error_event_);
624 }
625
626 void STDMETHODCALLTYPE Query(DSTORAGE_QUEUE_INFO* info) override {
627 if (!info) {
628 bad_call("IDStorageQueueX::Query", E_POINTER, "null info");
629 return;
630 }
631 DSTORAGE_QUEUE_INFO1 full{};
632 Query1(&full);
633 info->Desc.SourceType = full.Desc.SourceType;
634 info->Desc.Capacity = full.Desc.Capacity;
635 info->Desc.Priority = full.Desc.Priority;
636 info->Desc.Name = full.Desc.Name;
637 info->EmptySlotCount = full.EmptySlotCount;
638 info->RequestCountUntilAutoSubmit = full.RequestCountUntilAutoSubmit;
639 }
640
641 // An empty queue has capacity - 1 empty slots (one slot tells empty from full). The automatic submit happens when
642 // the entries enqueued since the last submit reach half the capacity; with it disabled the count is 0.
643 void STDMETHODCALLTYPE Query1(DSTORAGE_QUEUE_INFO1* info) override {
644 if (!info) {
645 bad_call("IDStorageQueueX2::Query1", E_POINTER, "null info");
646 return;
647 }
648 std::lock_guard lock(mutex_);
649 info->Desc = desc_;
650 info->EmptySlotCount = static_cast<UINT16>(usable() - used_locked());
651 const size_t unsubmitted = entries_.size() - submitted_;
652 info->RequestCountUntilAutoSubmit =
653 auto_submit() ? static_cast<UINT16>(half() > unsubmitted ? half() - unsubmitted : 0) : 0;
654 }
655
656private:
657 size_t usable() const { return desc_.Capacity - 1u; }
658 size_t half() const { return desc_.Capacity / 2u; }
659 bool auto_submit() const { return !desc_.Options.AutoSubmitDisabled; }
660 size_t used_locked() const { return entries_.size() + (in_flight_ ? 1 : 0); }
661
662 void enqueue(Entry&& e) {
663 {
664 std::unique_lock lock(mutex_);
665 // A full queue waits for the worker to free a slot. With auto-submit on, half the queue is always
666 // submitted by then; with it off, only a Submit from another thread frees one (as the reference warns).
667 space_.wait(lock, [&] { return closing_ || used_locked() < usable(); });
668 if (!closing_) {
669 entries_.push_back(std::move(e));
670 if (auto_submit() && entries_.size() - submitted_ >= half()) submit_locked();
671 return;
672 }
673 }
674 DSTORAGE_ERROR_FIRST_FAILURE f{};
675 f.HResult = E_DSTORAGE_QUEUE_CLOSED;
676 describe(e, f);
677 record_failure(f);
678 log_once("closed", "an entry was enqueued on a closed queue (E_DSTORAGE_QUEUE_CLOSED); it never completes");
679 release_references(e);
680 }
681
682 void submit_locked() {
683 uint32_t requests = 0;
684 uint64_t source_bytes = 0, destination_bytes = 0;
685 for (size_t i = submitted_; i < entries_.size(); ++i) {
686 Entry& e = entries_[i];
687 if (e.file) e.file_counted = e.file->add_pending();
688 if (e.counted) {
689 ++requests;
690 source_bytes += e.request.SourceSize;
691 destination_bytes += e.request.DestinationSize;
692 }
693 }
694 if (requests) {
695 std::lock_guard stats_lock(stats().mutex);
696 auto& p = priority_stats(stats().s, desc_.Priority);
697 p.TotalRequestCount += requests;
698 p.TotalRequestSourceByteCount += source_bytes;
699 p.TotalRequestDestinationByteCount += destination_bytes;
700 }
701 if (entries_.size() > submitted_) {
702 submitted_ = entries_.size();
703 work_.notify_one();
704 }
705 }
706
707 void run() {
708 for (;;) {
709 Entry e;
710 {
711 std::unique_lock lock(mutex_);
712 work_.wait(lock, [&] { return submitted_ > 0 || closed_; });
713 if (submitted_ == 0) return; // closed and drained
714 e = std::move(entries_.front());
715 entries_.pop_front();
716 --submitted_;
717 in_flight_ = true;
718 }
719 process(e);
720 release_references(e);
721 {
722 std::lock_guard lock(mutex_);
723 in_flight_ = false;
724 space_.notify_all();
725 if (entries_.empty()) idle_.notify_all();
726 }
727 }
728 }
729
730 // Runs on the worker. since_notify_ is the first failure since the last status entry or fence signal: the
731 // HRESULT a status entry reports.
732 void process(Entry& e) {
733 HRESULT hr = e.enqueue_error;
734 switch (e.type) {
735 case Entry::Type::Request:
736 // A cancelled request is a success whatever else is wrong with it (the GDK: not counted as a failure).
737 if (e.cancelled) {
738 hr = S_OK;
739 } else if (SUCCEEDED(hr)) {
740 // Pending: processing has started and not completed (DSTORAGE_PRIORITY_STATS).
741 set_pending(+1);
742 hr = execute_request(e);
743 set_pending(-1);
744 }
745 if (e.file && e.file_counted) e.file->finish_pending();
746 if (FAILED(hr) && SUCCEEDED(since_notify_)) since_notify_ = hr;
747 break;
748 case Entry::Type::Status:
749 if (SUCCEEDED(hr)) {
750 e.status->complete(e.index, since_notify_);
751 since_notify_ = S_OK;
752 }
753 break;
754 case Entry::Type::Signal:
755 if (SUCCEEDED(hr)) hr = e.fence->Signal(e.value);
756 since_notify_ = S_OK;
757 break;
758 case Entry::Type::Event:
759 if (SUCCEEDED(hr) && !SetEvent(e.event)) hr = HRESULT_FROM_WIN32(GetLastError());
760 break;
761 }
762 if (FAILED(hr)) {
763 DSTORAGE_ERROR_FIRST_FAILURE f{};
764 f.HResult = hr;
765 describe(e, f);
766 record_failure(f);
767 }
768 }
769
770 HRESULT execute_request(const Entry& e) {
771 const DSTORAGE_REQUEST& r = e.request;
772 const uint64_t o = r.Options.AsUINT64;
773 if (o & options::kReservedMask) return E_DSTORAGE_RESERVED_FIELDS;
774 if (options::source_type(o) != desc_.SourceType) return E_DSTORAGE_INVALID_SOURCE_TYPE;
775 if (options::bcpack(o) > DSTORAGE_BCPACK_MODE_BC7) return E_DSTORAGE_INVALID_BCPACK_MODE;
776 if (options::swizzle(o) > DSTORAGE_SWIZZLE_MODE_4K_12K_4K_12K) return E_DSTORAGE_INVALID_SWIZZLE_MODE;
777 if (options::bcpack(o) != 0 || options::swizzle(o) != 0) {
778 log_once("decompress", "BCPack and swizzle requests are not implemented yet (E_NOTIMPL)");
779 return E_NOTIMPL;
780 }
781 if (o & (options::kDestinationPages | options::kSourcePages)) {
782 log_once("pages", "physical-page requests are not implemented yet (E_NOTIMPL)");
783 return E_NOTIMPL;
784 }
785 const bool zlib = options::zlib(o);
786 // IntermediateSize is the BCPack data's size between the inflate and the BCPack decode (DSTORAGE_REQUEST), so
787 // it is 0 for every request that gets here (BCPack is refused above).
788 if (r.IntermediateSize != 0) return E_DSTORAGE_INVALID_INTERMEDIATE_SIZE;
789 // E_DSTORAGE_INVALID_DESTINATION_SIZE: without decompression DestinationSize must equal the source's length,
790 // with it it must be larger (dstorageerr.h's description; DSTORAGE_REQUEST says the same of DestinationSize).
791 if (zlib ? r.DestinationSize <= r.SourceSize : r.DestinationSize != r.SourceSize)
792 return E_DSTORAGE_INVALID_DESTINATION_SIZE;
793 const bool memory = desc_.SourceType == DSTORAGE_REQUEST_SOURCE_MEMORY;
794 const uint64_t total = static_cast<uint64_t>(r.DestinationSize) + (memory ? r.SourceSize : 0u);
795 if (total > kMaxRequestBytes) return E_DSTORAGE_REQUEST_TOO_LARGE;
796 // DSTORAGE_REQUEST: a buffer over 32 MiB is allowed only with 64 KiB or 2 MiB pages, which are not implemented
797 // yet (refused above). The source is never larger than the destination here (the same size without zlib,
798 // smaller with it), so this covers both buffers, and bounds the staging buffers of a zlib request too.
799 if (r.DestinationSize > kMax4kPageDestinationSize) return E_DSTORAGE_REQUEST_TOO_LARGE;
800 // DSTORAGE_REQUEST: with ZlibDecompress the file offset must be 16-byte aligned.
801 if (zlib && !memory && r.FileOffset % 16 != 0) return E_DSTORAGE_INVALID_FILE_OFFSET;
802 if (!r.Destination) return E_INVALIDARG;
803 if (memory) {
804 if (!r.Source) return E_INVALIDARG;
805 } else {
806 if (!r.File) return E_INVALIDARG;
807 if (!e.file_counted) return E_DSTORAGE_FILE_NOT_OPEN;
808 }
809 if (zlib) return inflate_request(e, memory);
810 if (r.SourceSize == 0) return S_OK; // nothing to move; the reference does not say this fails
811 if (memory) return guarded_move(r.Destination, r.Source, r.SourceSize) ? S_OK : E_DSTORAGE_ACCESS_VIOLATION;
812 return read_file_range(e.file->handle(), r.FileOffset, r.Destination, r.SourceSize);
813 }
814
815 // A zlib request whose checks have passed: the source (SourceSize bytes of the file or of memory) goes into a
816 // staging buffer, inflates there, and only a result of exactly DestinationSize bytes is copied to the destination.
817 // So a failed stream leaves the destination as it was, and a memory source that overlaps its destination is safe.
818 // Both buffers are at most 32 MiB (execute_request). The stream is RFC 1950: the two header bytes, the deflate
819 // data, the Adler-32 of the result; bytes after the Adler-32 are not read. A failure is the matching
820 // dstorageerr.h code: a bad header (not deflate, a window over 32 KiB, a bad check value or a preset dictionary)
821 // E_DSTORAGE_ZLIB_BAD_HEADER, bad or truncated deflate data E_DSTORAGE_ZLIB_BAD_DATA, an Adler-32 mismatch
822 // E_DSTORAGE_ZLIB_PARITY_FAIL, and a stream that inflates to more or fewer bytes than DestinationSize
823 // E_DSTORAGE_DECOMPRESSION_ERROR (no code names a size mismatch; this is the header's generic one).
824 HRESULT inflate_request(const Entry& e, bool memory) {
825 const DSTORAGE_REQUEST& r = e.request;
826 std::vector<uint8_t> source, result;
827 try {
828 source.resize(r.SourceSize);
829 result.reserve(r.DestinationSize);
830 } catch (const std::bad_alloc&) {
831 return E_OUTOFMEMORY;
832 }
833 if (r.SourceSize != 0) {
834 if (memory) {
835 if (!guarded_move(source.data(), r.Source, r.SourceSize)) return E_DSTORAGE_ACCESS_VIOLATION;
836 } else if (const HRESULT hr = read_file_range(e.file->handle(), r.FileOffset, source.data(), r.SourceSize);
837 FAILED(hr)) {
838 return hr;
839 }
840 }
841 log_once("zlib", "zlib requests are inflated on the CPU (RFC 1950, leonida::zlib_inflate)");
842 set_decompression_pending(+1);
843 leonida::ZlibError why = leonida::ZlibError::none;
844 const bool inflated = leonida::zlib_inflate(source, result, r.DestinationSize, &why);
845 set_decompression_pending(-1);
846 HRESULT hr = S_OK;
847 if (!inflated) {
848 switch (why) {
849 case leonida::ZlibError::header: hr = E_DSTORAGE_ZLIB_BAD_HEADER; break;
850 case leonida::ZlibError::checksum: hr = E_DSTORAGE_ZLIB_PARITY_FAIL; break;
851 case leonida::ZlibError::limit: hr = E_DSTORAGE_DECOMPRESSION_ERROR; break; // longer than the destination
852 default: hr = E_DSTORAGE_ZLIB_BAD_DATA; break;
853 }
854 } else if (result.size() != r.DestinationSize) {
855 hr = E_DSTORAGE_DECOMPRESSION_ERROR; // shorter than the destination
856 }
857 if (FAILED(hr)) {
858 std::lock_guard lock(stats().mutex);
859 ++stats().s.DecompressionErrors;
860 return hr;
861 }
862 return guarded_move(r.Destination, result.data(), result.size()) ? S_OK : E_DSTORAGE_ACCESS_VIOLATION;
863 }
864
865 void set_pending(int delta) {
866 std::lock_guard lock(stats().mutex);
867 priority_stats(stats().s, desc_.Priority).PendingRequestCount += static_cast<uint32_t>(delta);
868 }
869
870 // PendingDecompressionRequestCount is the zlib requests being inflated; TotalDecompressionRequestCount counts each
871 // one that reached its inflate (its source was read), DecompressionErrors those whose stream then failed.
872 static void set_decompression_pending(int delta) {
873 std::lock_guard lock(stats().mutex);
874 auto& s = stats().s;
875 s.PendingDecompressionRequestCount += static_cast<uint32_t>(delta);
876 if (delta > 0) ++s.TotalDecompressionRequestCount;
877 }
878
879 void describe(const Entry& e, DSTORAGE_ERROR_FIRST_FAILURE& f) const {
880 switch (e.type) {
881 case Entry::Type::Request: {
882 f.CommandType = DSTORAGE_COMMAND_TYPE_REQUEST;
883 auto& q = f.Request;
884 const DSTORAGE_REQUEST& r = e.request;
885 q.Options = r.Options;
886 q.Destination = r.Destination;
887 q.DestinationSize = r.DestinationSize;
888 q.SourceSize = r.SourceSize;
889 q.CancellationTag = r.CancellationTag;
890 if (options::source_type(r.Options.AsUINT64) == DSTORAGE_REQUEST_SOURCE_MEMORY) {
891 q.Source = r.Source;
892 } else {
893 q.FileOffset = r.FileOffset;
894 if (e.file) wcsncpy_s(q.Filename, e.file->path().c_str(), _TRUNCATE);
895 }
896 // The reference says the name stays readable until the request completes.
897 if (r.Name)
898 for (size_t i = 0; i + 1 < kRequestMaxName && r.Name[i]; ++i) q.Name[i] = r.Name[i];
899 break;
900 }
901 case Entry::Type::Status:
902 f.CommandType = DSTORAGE_COMMAND_TYPE_STATUS;
903 f.Status.StatusArray = e.status_as_given;
904 f.Status.Index = e.index;
905 break;
906 case Entry::Type::Signal:
907 f.CommandType = DSTORAGE_COMMAND_TYPE_SIGNAL;
908 f.Signal.Fence = e.fence;
909 f.Signal.Value = e.value;
910 break;
911 case Entry::Type::Event:
912 f.CommandType = kCommandTypeEvent;
913 break;
914 }
915 }
916
917 void record_failure(const DSTORAGE_ERROR_FIRST_FAILURE& f) {
918 count_error();
919 {
920 std::lock_guard lock(error_mutex_);
921 if (record_.FailureCount++ == 0) record_.FirstFailure = f;
922 if (error_event_) SetEvent(error_event_);
923 }
924 log_once("fail" + hr_text(f.HResult) + std::to_string(f.CommandType),
925 "an entry failed with " + hr_text(f.HResult) + " (command type " + std::to_string(f.CommandType) +
926 "; logged once per code)");
927 }
928
929 void clear_record_locked() {
930 record_ = DSTORAGE_ERROR_RECORD{};
931 record_.FirstFailure.CommandType = DSTORAGE_COMMAND_TYPE_NONE;
932 }
933
934 static void release_references(Entry& e) {
935 if (e.file) e.file->Release();
936 if (e.status) e.status->Release();
937 if (e.fence) e.fence->Release();
938 if (e.event) CloseHandle(e.event);
939 e.event = nullptr;
940 e.file = nullptr;
941 e.status = nullptr;
942 e.fence = nullptr;
943 }
944
945 std::atomic<ULONG> refs_{1};
946 const DSTORAGE_QUEUE_DESC1 desc_;
947 std::mutex close_mutex_; // one Close at a time
948 std::mutex mutex_; // entries_, submitted_, in_flight_, closing_, closed_
949 std::condition_variable work_, space_, idle_;
950 std::deque<Entry> entries_;
951 size_t submitted_ = 0; // the first submitted_ entries are submitted
952 bool in_flight_ = false;
953 bool closing_ = false;
954 bool closed_ = false;
955 std::thread worker_;
956 HRESULT since_notify_ = S_OK; // worker only
957 std::mutex error_mutex_;
958 DSTORAGE_ERROR_RECORD record_{};
959 HANDLE error_event_ = nullptr;
960};
961
962// ---- The factory ----------------------------------------------------------------------------------------------------
963
964HRESULT validate_queue_desc(const DSTORAGE_QUEUE_DESC1& d) {
965 if (d.SourceType != DSTORAGE_REQUEST_SOURCE_FILE && d.SourceType != DSTORAGE_REQUEST_SOURCE_MEMORY)
966 return E_DSTORAGE_INVALID_SOURCE_TYPE;
967 if (d.Capacity < kMinQueueCapacity || d.Capacity > kMaxQueueCapacity) return E_DSTORAGE_INVALID_QUEUE_CAPACITY;
968 if (d.Priority < DSTORAGE_PRIORITY_FIRST || d.Priority > DSTORAGE_PRIORITY_LAST)
969 return E_DSTORAGE_INVALID_QUEUE_PRIORITY;
970 if (d.SourceType == DSTORAGE_REQUEST_SOURCE_MEMORY && d.Priority != DSTORAGE_PRIORITY_REALTIME)
971 return E_DSTORAGE_INVALID_MEMORY_QUEUE_PRIORITY;
972 if (d.Options.Reserved) return E_DSTORAGE_RESERVED_FIELDS;
973 return S_OK;
974}
975
976using CreateFileWFn = HANDLE(WINAPI*)(LPCWSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE);
977
978// The title's own CreateFileW: the GAME: mapping and overlay when file_system.cpp is linked, else the host's.
979CreateFileWFn create_file_w() {
980 if (void* fn = rt::shims::find("kernel32.dll", "CreateFileW")) return reinterpret_cast<CreateFileWFn>(fn);
981 return &::CreateFileW;
982}
983
984class Factory final : public IDStorageFactoryX2 {
985public:
986 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override {
987 if (!ppv) return E_POINTER;
988 *ppv = nullptr;
989 if (!iid_policy().accept_query(riid, Kind::Factory, "IDStorageFactoryX::QueryInterface")) return E_NOINTERFACE;
990 AddRef();
991 *ppv = static_cast<IDStorageFactoryX2*>(this);
992 return S_OK;
993 }
994 ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; }
995 // One factory for the process; its count never drops below one, so it is never freed.
996 ULONG STDMETHODCALLTYPE Release() override {
997 ULONG r = refs_.load();
998 while (r > 1 && !refs_.compare_exchange_weak(r, r - 1)) {}
999 return r > 1 ? r - 1 : 1;
1000 }
1001
1002 HRESULT STDMETHODCALLTYPE CreateQueue(const DSTORAGE_QUEUE_DESC* desc, REFIID riid, void** ppv) override {
1003 if (!ppv) return bad_call("IDStorageFactoryX::CreateQueue", E_POINTER, "null ppv");
1004 *ppv = nullptr;
1005 if (!desc) return bad_call("IDStorageFactoryX::CreateQueue", E_INVALIDARG, "null desc");
1006 DSTORAGE_QUEUE_DESC1 d{};
1007 d.SourceType = desc->SourceType;
1008 d.Capacity = desc->Capacity;
1009 d.Priority = desc->Priority;
1010 d.Name = desc->Name;
1011 return create_queue(d, riid, ppv, "IDStorageFactoryX::CreateQueue");
1012 }
1013
1014 HRESULT STDMETHODCALLTYPE CreateQueue1(const DSTORAGE_QUEUE_DESC1* desc, REFIID riid, void** ppv) override {
1015 if (!ppv) return bad_call("IDStorageFactoryX2::CreateQueue1", E_POINTER, "null ppv");
1016 *ppv = nullptr;
1017 if (!desc) return bad_call("IDStorageFactoryX2::CreateQueue1", E_INVALIDARG, "null desc");
1018 return create_queue(*desc, riid, ppv, "IDStorageFactoryX2::CreateQueue1");
1019 }
1020
1021 HRESULT STDMETHODCALLTYPE OpenFile(const WCHAR* path, REFIID riid, void** ppv) override {
1022 if (!ppv) return bad_call("IDStorageFactoryX::OpenFile", E_POINTER, "null ppv");
1023 *ppv = nullptr;
1024 if (!path || !*path) return bad_call("IDStorageFactoryX::OpenFile", E_INVALIDARG, "null or empty path");
1025 if (!iid_policy().accept_creating(riid, Kind::File, "IDStorageFactoryX::OpenFile")) return E_NOINTERFACE;
1026 const HANDLE h = create_file_w()(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
1027 FILE_ATTRIBUTE_NORMAL, nullptr);
1028 if (h == INVALID_HANDLE_VALUE) {
1029 const DWORD error = GetLastError();
1030 return HRESULT_FROM_WIN32(error ? error : ERROR_FILE_NOT_FOUND);
1031 }
1032 File* f = new (std::nothrow) File(h, path);
1033 if (!f) {
1034 CloseHandle(h);
1035 return E_OUTOFMEMORY;
1036 }
1037 *ppv = static_cast<IDStorageFileX*>(f);
1038 return S_OK;
1039 }
1040
1041 HRESULT STDMETHODCALLTYPE CreateStatusArray(UINT32 capacity, PCSTR, REFIID riid, void** ppv) override {
1042 if (!ppv) return bad_call("IDStorageFactoryX::CreateStatusArray", E_POINTER, "null ppv");
1043 *ppv = nullptr;
1044 if (capacity == 0) return bad_call("IDStorageFactoryX::CreateStatusArray", E_INVALIDARG, "capacity 0");
1045 if (!iid_policy().accept_creating(riid, Kind::StatusArray, "IDStorageFactoryX::CreateStatusArray"))
1046 return E_NOINTERFACE;
1047 std::unique_ptr<std::atomic<HRESULT>[]> entries(new (std::nothrow) std::atomic<HRESULT>[capacity]);
1048 if (!entries) return E_OUTOFMEMORY;
1049 auto* a = new (std::nothrow) StatusArray(capacity, std::move(entries));
1050 if (!a) return E_OUTOFMEMORY;
1051 *ppv = static_cast<IDStorageStatusArrayX*>(a);
1052 return S_OK;
1053 }
1054
1055 // DirectStorage's own worker work would be pinned to these cores on the console. The mask names console cores,
1056 // so it is stored and not applied to the host's.
1057 HRESULT STDMETHODCALLTYPE SetCpuAffinity(UINT64 affinity) override {
1058 cpu_affinity_.store(affinity);
1059 return S_OK;
1060 }
1061 void STDMETHODCALLTYPE SetDebugFlags(UINT32 flags) override { debug_flags_.store(flags); }
1062
1063 HRESULT STDMETHODCALLTYPE SetStagingBufferSize(UINT32 size) override {
1064 if (std::find(std::begin(kStagingBufferSizes), std::end(kStagingBufferSizes), size) ==
1065 std::end(kStagingBufferSizes))
1066 return bad_call("IDStorageFactoryX::SetStagingBufferSize", E_DSTORAGE_INVALID_STAGING_BUFFER_SIZE,
1067 "not one of 0, 16, 20, 24, 28 or 32 MiB");
1068 std::lock_guard lock(stats().mutex);
1069 if (stats().live_queues || stats().s.CurrentOpenFileCount) return E_DSTORAGE_STAGING_BUFFER_LOCKED;
1070 staging_size_ = size; // there is no staging buffer here; the size is only kept
1071 return S_OK;
1072 }
1073
1074 void STDMETHODCALLTYPE GetStats(DSTORAGE_STATS* out) override {
1075 if (!out) {
1076 bad_call("IDStorageFactoryX1::GetStats", E_POINTER, "null stats");
1077 return;
1078 }
1079 std::lock_guard lock(stats().mutex);
1080 *out = stats().s;
1081 }
1082
1083private:
1084 HRESULT create_queue(const DSTORAGE_QUEUE_DESC1& desc, REFIID riid, void** ppv, const char* caller) {
1085 if (const HRESULT hr = validate_queue_desc(desc); FAILED(hr)) return bad_call(caller, hr, "invalid queue desc");
1086 if (!iid_policy().accept_creating(riid, Kind::Queue, caller)) return E_NOINTERFACE;
1087 auto* q = new (std::nothrow) Queue(desc);
1088 if (!q) return E_OUTOFMEMORY;
1089 if (!q->start()) {
1090 q->Release();
1091 return E_OUTOFMEMORY;
1092 }
1093 *ppv = static_cast<IDStorageQueueX2*>(q);
1094 return S_OK;
1095 }
1096
1097 std::atomic<ULONG> refs_{1};
1098 std::atomic<uint64_t> cpu_affinity_{~0ull};
1099 std::atomic<uint32_t> debug_flags_{0};
1100 uint32_t staging_size_ = 32u << 20; // under stats().mutex
1101};
1102
1103Factory& factory() {
1104 static auto* f = new Factory;
1105 return *f;
1106}
1107
1108HRESULT WINAPI dstorage_get_factory(REFIID riid, void** ppv) {
1109 if (!ppv) return bad_call("DStorageGetFactory", E_POINTER, "null ppv");
1110 *ppv = nullptr;
1111 if (!iid_policy().accept_creating(riid, Kind::Factory, "DStorageGetFactory")) return E_NOINTERFACE;
1112 Factory& f = factory();
1113 f.AddRef();
1114 *ppv = static_cast<IDStorageFactoryX2*>(&f);
1115 return S_OK;
1116}
1117
1118} // namespace
1119
1120// The console module names; docs/directstorage.md has the evidence and the confidence for each.
1121SHIM_TABLE(dstorage,
1122 {"dstorage_xs.dll", "DStorageGetFactory", reinterpret_cast<void*>(&dstorage_get_factory)},
1123 {"xcrdapi.dll", "DStorageGetFactory", reinterpret_cast<void*>(&dstorage_get_factory)},
1124 {"dstorage.dll", "DStorageGetFactory", reinterpret_cast<void*>(&dstorage_get_factory)},
1125);