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:
Diffstat (limited to 'runtime/shims/dstorage.cpp')
-rw-r--r--runtime/shims/dstorage.cpp516
1 files changed, 421 insertions, 95 deletions
diff --git a/runtime/shims/dstorage.cpp b/runtime/shims/dstorage.cpp
index 0f8345689..7f4cef9d9 100644
--- a/runtime/shims/dstorage.cpp
+++ b/runtime/shims/dstorage.cpp
@@ -5,20 +5,19 @@
5// for those names, the console ABI and what each method does here. In short: 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 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. 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 8// - Each queue publishes 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 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. 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 11// - Compressed requests stage RFC 1950 inflate, BCPack BC block reconstruction and DirectStorage
12// the runtime's RFC 1950 inflater (leonida::zlib_inflate, src/shader_library.h) and copies the result to the 12// macro-unshuffle before publishing the destination. Physical page numbers resolve in xmem at execution.
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. 13// Nothing here goes online or touches the GPU.
17#include <windows.h> 14#include <windows.h>
18#include <d3d12.h> 15#include <d3d12.h>
19 16
20#include <algorithm> 17#include <algorithm>
21#include <atomic> 18#include <atomic>
19#include <chrono>
20#include <map>
22#include <condition_variable> 21#include <condition_variable>
23#include <cstdio> 22#include <cstdio>
24#include <cstring> 23#include <cstring>
@@ -33,7 +32,15 @@
33#include <vector> 32#include <vector>
34 33
35#include "../src/shader_library.h" // leonida::zlib_inflate 34#include "../src/shader_library.h" // leonida::zlib_inflate
35#include "../src/title_page_watch.h" // title_gpu_views, title_texel_writes, kernel_writes
36#include "../src/bcpack.h"
37#include "../src/shader_directory.h"
38#include "../src/dstorage_swizzle.h"
39#include "../src/dstorage_trace.h"
36#include "dstorage_xs_abi.h" 40#include "dstorage_xs_abi.h"
41#include "dstorage_staging.h"
42#include "startup_trace.h"
43#include "xmem.h"
37#include "shims.h" 44#include "shims.h"
38 45
39using namespace dsx; 46using namespace dsx;
@@ -431,8 +438,66 @@ HRESULT read_error(DWORD error) {
431 } 438 }
432} 439}
433 440
434// Reads exactly "size" bytes at "offset" of a synchronous handle into "destination". 441bool extended_enabled() {
435HRESULT read_file_range(HANDLE handle, uint64_t offset, void* destination, uint32_t size) { 442 static const bool enabled = [] {
443 char value[2]{};
444 return GetEnvironmentVariableA("LEONIDA_DSTORAGE_EXTENDED", value, sizeof value) != 1 || value[0] != '0';
445 }();
446 return enabled;
447}
448
449// Calibrated predictor values stay in a local sidecar. Absent or invalid files retain the built-in codec policy.
450const leonida::bcpack::Calibration* bcpack_history() {
451 static const auto profile = []() -> std::unique_ptr<leonida::bcpack::Calibration> {
452 std::wstring explicit_path(32768, L'\0');
453 const DWORD n = GetEnvironmentVariableW(L"LEONIDA_DSTORAGE_HISTORY", explicit_path.data(), DWORD(explicit_path.size()));
454 if (n >= explicit_path.size()) return {};
455 std::filesystem::path path;
456 if (n) {
457 explicit_path.resize(n);
458 if (explicit_path == L"0") return {};
459 path = explicit_path;
460 } else {
461 auto shaders = leonida::shader_paths::configured();
462 if (shaders.empty()) return {};
463 if (!shaders.has_filename()) shaders = shaders.parent_path();
464 path = shaders.parent_path() / "bcpack" / "history.bcph";
465 }
466 FILE* raw = nullptr;
467 if (_wfopen_s(&raw, path.c_str(), L"rb") || !raw) {
468 log_once("history-open", "could not open the local BCPack predictor profile");
469 return {};
470 }
471 std::unique_ptr<FILE, decltype(&std::fclose)> file(raw, &std::fclose);
472 auto table = std::make_unique<leonida::bcpack::Calibration>();
473 char magic[8];
474 if (std::fread(magic, 1, sizeof magic, raw) != sizeof magic || std::memcmp(magic, "BCPHIST1", 8) ||
475 std::fread(table.get(), 1, sizeof *table, raw) != sizeof *table || std::fgetc(raw) != EOF || std::ferror(raw)) {
476 log_once("history-format", "invalid local BCPack predictor profile");
477 return {};
478 }
479 unsigned bc6_ep = 0, bc6_ix = 0, bc7_ep = 0, bc7_ix = 0;
480 for (const auto& row : table->bc6) {
481 bc6_ep += row.ep_class != 0;
482 bc6_ix += row.ix_class != 0;
483 }
484 for (const auto& row : table->bc7) {
485 bc7_ep += unsigned(std::count_if(row.ep_bits.begin(), row.ep_bits.end(), [](auto v) {return v != 0;}));
486 bc7_ix += unsigned(std::count_if(row.ix_bits.begin(), row.ix_bits.end(), [](auto v) {return v != 0;}));
487 }
488 log_once("history-ok", std::string("loaded ") + (n ? "explicit" : "default") + " BCPack profile; BC6H endpoint/index rows " +
489 std::to_string(bc6_ep) + "/256 " + std::to_string(bc6_ix) + "/256; BC7 endpoint/index fields " +
490 std::to_string(bc7_ep) + "/6144 " + std::to_string(bc7_ix) + "/8192");
491 return table;
492 }();
493 return profile.get();
494}
495
496// Reads exactly "size" bytes at "offset" of a synchronous handle into "destination". Through kernel_writes, as the
497// title's own reads: the destination is title memory, which a kernel write cannot fault in (pages the D3D12 layer
498// keeps read-only, xmem pages that wait for their first touch), title_page_watch.h.
499enum class ReadTarget { Title, Staging };
500HRESULT read_file_range(HANDLE handle, uint64_t offset, void* destination, uint32_t size, ReadTarget target) {
436 LARGE_INTEGER length{}; 501 LARGE_INTEGER length{};
437 if (!GetFileSizeEx(handle, &length)) return HRESULT_FROM_WIN32(GetLastError()); 502 if (!GetFileSizeEx(handle, &length)) return HRESULT_FROM_WIN32(GetLastError());
438 const uint64_t file_size = static_cast<uint64_t>(length.QuadPart); 503 const uint64_t file_size = static_cast<uint64_t>(length.QuadPart);
@@ -445,7 +510,13 @@ HRESULT read_file_range(HANDLE handle, uint64_t offset, void* destination, uint3
445 at.Offset = static_cast<DWORD>(position); 510 at.Offset = static_cast<DWORD>(position);
446 at.OffsetHigh = static_cast<DWORD>(position >> 32); 511 at.OffsetHigh = static_cast<DWORD>(position >> 32);
447 DWORD got = 0; 512 DWORD got = 0;
448 if (!ReadFile(handle, out + done, size - done, &got, &at)) { 513 // A private vector cannot be mapped or write-protected by the title.
514 const auto read = [&] {
515 return target == ReadTarget::Title
516 ? leonida::kernel_writes::read_file(handle, out + done, size - done, &got, &at)
517 : ::ReadFile(handle, out + done, size - done, &got, &at);
518 };
519 if (!read()) {
449 const DWORD error = GetLastError(); 520 const DWORD error = GetLastError();
450 if (error != ERROR_NOACCESS) return read_error(error); 521 if (error != ERROR_NOACCESS) return read_error(error);
451 // Destination pages not committed yet (see touch_pages): commit them from user mode and read again once. 522 // Destination pages not committed yet (see touch_pages): commit them from user mode and read again once.
@@ -453,7 +524,7 @@ HRESULT read_file_range(HANDLE handle, uint64_t offset, void* destination, uint3
453 at = OVERLAPPED{}; 524 at = OVERLAPPED{};
454 at.Offset = static_cast<DWORD>(position); 525 at.Offset = static_cast<DWORD>(position);
455 at.OffsetHigh = static_cast<DWORD>(position >> 32); 526 at.OffsetHigh = static_cast<DWORD>(position >> 32);
456 if (!ReadFile(handle, out + done, size - done, &got, &at)) return read_error(GetLastError()); 527 if (!read()) return read_error(GetLastError());
457 } 528 }
458 if (got == 0) return E_DSTORAGE_END_OF_FILE; // the file shrank since the size check 529 if (got == 0) return E_DSTORAGE_END_OF_FILE; // the file shrank since the size check
459 done += got; 530 done += got;
@@ -463,7 +534,21 @@ HRESULT read_file_range(HANDLE handle, uint64_t offset, void* destination, uint3
463 534
464// ---- Queues ------------------------------------------------------------------------------------------------------- 535// ---- Queues -------------------------------------------------------------------------------------------------------
465 536
537// Only sampled when request tracing is enabled. Times include work done by the file/decode worker.
538struct Timing {
539 using Clock = std::chrono::steady_clock;
540 long long read{}, inflate{}, bcpack{}, copy{}, unshuffle{};
541 static Clock::time_point start() {
542 return leonida::dstorage::trace_enabled() ? Clock::now() : Clock::time_point{};
543 }
544 static long long elapsed(Clock::time_point begin) {
545 return leonida::dstorage::trace_enabled()
546 ? std::chrono::duration_cast<std::chrono::microseconds>(Clock::now() - begin).count() : 0;
547 }
548};
466struct Entry { 549struct Entry {
550 Timing timing;
551 const char* reason = "none";
467 enum class Type { Request, Status, Signal, Event } type = Type::Request; 552 enum class Type { Request, Status, Signal, Event } type = Type::Request;
468 DSTORAGE_REQUEST request{}; 553 DSTORAGE_REQUEST request{};
469 File* file = nullptr; // a reference, for a file request naming a live file 554 File* file = nullptr; // a reference, for a file request naming a live file
@@ -494,6 +579,10 @@ public:
494 // Separate from the constructor so a failure to start the thread can be reported. 579 // Separate from the constructor so a failure to start the thread can be reported.
495 bool start() { 580 bool start() {
496 if (!error_event_) return false; 581 if (!error_event_) return false;
582 wchar_t workers[4]{};
583 const DWORD n = GetEnvironmentVariableW(L"LEONIDA_DSTORAGE_WORKERS", workers, 4);
584 if (!(n == 1 && (workers[0] == L'1' || workers[0] == L'0')))
585 preparation_work_ = CreateThreadpoolWork(prepare_in_background, this, nullptr);
497 try { 586 try {
498 worker_ = std::thread([this] { run(); }); 587 worker_ = std::thread([this] { run(); });
499 } catch (...) { 588 } catch (...) {
@@ -503,6 +592,7 @@ public:
503 } 592 }
504 ~Queue() { 593 ~Queue() {
505 Close(); 594 Close();
595 if (preparation_work_) CloseThreadpoolWork(preparation_work_);
506 if (error_event_) CloseHandle(error_event_); 596 if (error_event_) CloseHandle(error_event_);
507 std::lock_guard lock(stats().mutex); 597 std::lock_guard lock(stats().mutex);
508 --priority_stats(stats().s, desc_.Priority).CurrentQueueCount; 598 --priority_stats(stats().s, desc_.Priority).CurrentQueueCount;
@@ -679,7 +769,7 @@ private:
679 size_t usable() const { return desc_.Capacity - 1u; } 769 size_t usable() const { return desc_.Capacity - 1u; }
680 size_t half() const { return desc_.Capacity / 2u; } 770 size_t half() const { return desc_.Capacity / 2u; }
681 bool auto_submit() const { return !desc_.Options.AutoSubmitDisabled; } 771 bool auto_submit() const { return !desc_.Options.AutoSubmitDisabled; }
682 size_t used_locked() const { return entries_.size() + (in_flight_ ? 1 : 0); } 772 size_t used_locked() const { return entries_.size() + in_flight_; }
683 773
684 void enqueue(Entry&& e) { 774 void enqueue(Entry&& e) {
685 { 775 {
@@ -726,23 +816,67 @@ private:
726 } 816 }
727 } 817 }
728 818
819 struct Prepared {
820 Entry& entry;
821 HRESULT result = S_OK;
822 std::vector<uint8_t> bytes;
823 };
824 // Each queue publishes in order. Only an adjacent pair of file transforms can
825 // overlap. Memory inputs, direct reads, page resolution and notifications remain barriers.
826 static bool can_prepare(const Entry& e) {
827 const auto& r = e.request;
828 const auto o = r.Options.AsUINT64;
829 constexpr uint64_t budget = 16ull << 20;
830 return e.type == Entry::Type::Request && !e.cancelled && SUCCEEDED(e.enqueue_error) && e.file &&
831 (options::zlib(o) || options::bcpack(o) || options::swizzle(o)) &&
832 leonida::dstorage::staging_bytes(r) <= budget;
833 }
834
835 static void CALLBACK prepare_in_background(PTP_CALLBACK_INSTANCE, void* context, PTP_WORK) {
836 auto& q = *static_cast<Queue*>(context);
837 q.set_pending(+1);
838 auto& job = *q.helper_job_;
839 job.result = q.validate_request(job.entry);
840 if (SUCCEEDED(job.result)) job.result = q.prepare(job.entry, job.bytes);
841 else job.entry.reason = "request-validation";
842 }
843
729 void run() { 844 void run() {
730 for (;;) { 845 for (;;) {
731 Entry e; 846 Entry head, next;
847 leonida::dstorage::StagingPool::Lease reservation(leonida::dstorage::staging_pool());
848 Prepared prepared{next, S_OK, {}};
849 bool paired = false;
732 { 850 {
733 std::unique_lock lock(mutex_); 851 std::unique_lock lock(mutex_);
734 work_.wait(lock, [&] { return submitted_ > 0 || closed_; }); 852 work_.wait(lock, [&] { return submitted_ > 0 || closed_; });
735 if (submitted_ == 0) return; // closed and drained 853 if (submitted_ == 0) return;
736 e = std::move(entries_.front()); 854 head = std::move(entries_.front());
737 entries_.pop_front(); 855 entries_.pop_front();
738 --submitted_; 856 --submitted_;
739 in_flight_ = true; 857 paired = preparation_work_ && submitted_ && can_prepare(head) && can_prepare(entries_.front()) &&
858 reservation.try_pair(leonida::dstorage::staging_bytes(head.request) +
859 leonida::dstorage::staging_bytes(entries_.front().request));
860 if (paired) {
861 next = std::move(entries_.front());
862 entries_.pop_front();
863 --submitted_;
864 helper_job_ = &prepared;
865 SubmitThreadpoolWork(preparation_work_);
866 }
867 in_flight_ = paired ? 2 : 1;
868 }
869 process(head, nullptr, paired);
870 release_references(head);
871 if (paired) {
872 WaitForThreadpoolWorkCallbacks(preparation_work_, FALSE);
873 process(next, &prepared);
874 release_references(next);
875 helper_job_ = nullptr;
740 } 876 }
741 process(e);
742 release_references(e);
743 { 877 {
744 std::lock_guard lock(mutex_); 878 std::lock_guard lock(mutex_);
745 in_flight_ = false; 879 in_flight_ = 0;
746 space_.notify_all(); 880 space_.notify_all();
747 if (entries_.empty()) idle_.notify_all(); 881 if (entries_.empty()) idle_.notify_all();
748 } 882 }
@@ -751,8 +885,11 @@ private:
751 885
752 // Runs on the worker. since_notify_ is the first failure since the last status entry or fence signal: the 886 // Runs on the worker. since_notify_ is the first failure since the last status entry or fence signal: the
753 // HRESULT a status entry reports. 887 // HRESULT a status entry reports.
754 void process(Entry& e) { 888 void process(Entry& e, Prepared* prepared, bool pair_reserved = false) {
755 HRESULT hr = e.enqueue_error; 889 HRESULT hr = e.enqueue_error;
890 if (FAILED(hr)) e.reason = "enqueue";
891 const auto begin = Timing::start();
892 long long notify_us = 0;
756 switch (e.type) { 893 switch (e.type) {
757 case Entry::Type::Request: 894 case Entry::Type::Request:
758 // A cancelled request is a success whatever else is wrong with it (the GDK: not counted as a failure). 895 // A cancelled request is a success whatever else is wrong with it (the GDK: not counted as a failure).
@@ -760,27 +897,85 @@ private:
760 hr = S_OK; 897 hr = S_OK;
761 } else if (SUCCEEDED(hr)) { 898 } else if (SUCCEEDED(hr)) {
762 // Pending: processing has started and not completed (DSTORAGE_PRIORITY_STATS). 899 // Pending: processing has started and not completed (DSTORAGE_PRIORITY_STATS).
763 set_pending(+1); 900 if (prepared) {
764 hr = execute_request(e); 901 hr = prepared->result;
902 if (SUCCEEDED(hr)) hr = publish(e, prepared->bytes);
903 } else {
904 set_pending(+1);
905 hr = execute_request(e, pair_reserved);
906 }
765 set_pending(-1); 907 set_pending(-1);
766 } 908 }
909 if (FAILED(hr) || leonida::dstorage::trace_enabled()) {
910 const auto& r = e.request;
911 const auto o = r.Options.AsUINT64;
912 const bool pages = (o & options::kDestinationPages) != 0;
913 std::fprintf(stderr, "[rt] ds-request queue=%p options=%llx zlib=%d bc=%llu sw=%llu "
914 "dest=%s address=%p file=%ls offset=%llu src=%u mid=%u dst=%u cancelled=%d hr=%08lx "
915 "tick_ms=%llu page_offset=%u read_us=%lld inflate_us=%lld bc_us=%lld copy_us=%lld sw_us=%lld paired=%d reason=%s priority=%d\n",
916 static_cast<void*>(this), o, int(options::zlib(o)), options::bcpack(o),
917 options::swizzle(o), pages ? "pages" : "buffer", r.Destination,
918 e.file ? e.file->path().c_str() : L"-", e.file ? r.FileOffset : 0ull,
919 r.SourceSize, r.IntermediateSize, r.DestinationSize, int(e.cancelled),
920 static_cast<unsigned long>(hr), GetTickCount64(),
921 pages ? unsigned(r.DestinationPageOffset) : 0u, e.timing.read, e.timing.inflate,
922 e.timing.bcpack, e.timing.copy, e.timing.unshuffle, int(prepared != nullptr), e.reason, int(desc_.Priority));
923 if (hr == E_DSTORAGE_ACCESS_VIOLATION) {
924 const void* cpu = pages ? r.DestinationPageArray : cpu_destination(r);
925 MEMORY_BASIC_INFORMATION info{};
926 VirtualQuery(cpu, &info, sizeof(info));
927 std::fprintf(stderr, "[rt] ds-access queue=%p dest=%p cpu=%p paired=%llx base=%p "
928 "region=%zu state=%lx protect=%lx type=%lx\n", static_cast<void*>(this),
929 r.Destination, cpu, static_cast<unsigned long long>(pages ? 0 :
930 leonida::title_gpu_views::other_view(reinterpret_cast<uintptr_t>(cpu))),
931 info.BaseAddress, info.RegionSize, info.State, info.Protect, info.Type);
932 }
933 // Put failures on the same clock as title faults, even if another queue is active.
934 if (FAILED(hr) && rt::startup_trace::enabled()) {
935 rt::startup_trace::event("dstorage_failure",
936 "\"queue\":" + rt::startup_trace::quote(rt::startup_trace::hex(reinterpret_cast<uintptr_t>(this))) +
937 ",\"hr\":" + rt::startup_trace::quote(hr_text(hr)) +
938 ",\"options\":" + rt::startup_trace::quote(rt::startup_trace::hex(o)) +
939 ",\"offset\":" + std::to_string(e.file ? r.FileOffset : 0ull) +
940 ",\"source_size\":" + std::to_string(r.SourceSize) +
941 ",\"destination_size\":" + std::to_string(r.DestinationSize));
942 }
943 }
767 if (e.file && e.file_counted) e.file->finish_pending(); 944 if (e.file && e.file_counted) e.file->finish_pending();
768 if (FAILED(hr) && SUCCEEDED(since_notify_)) since_notify_ = hr; 945 if (FAILED(hr) && SUCCEEDED(since_notify_)) since_notify_ = hr;
769 break; 946 break;
770 case Entry::Type::Status: 947 case Entry::Type::Status: {
948 const auto result = FAILED(hr) ? hr : since_notify_;
771 if (SUCCEEDED(hr)) { 949 if (SUCCEEDED(hr)) {
772 e.status->complete(e.index, since_notify_); 950 e.status->complete(e.index, result);
773 since_notify_ = S_OK; 951 since_notify_ = S_OK;
774 } 952 }
953 notify_us = Timing::elapsed(begin);
954 if (leonida::dstorage::trace_enabled())
955 std::fprintf(stderr, "[rt] ds-status queue=%p array=%p slot=%u hr=%08lx\n",
956 static_cast<void*>(this), static_cast<void*>(e.status), e.index,
957 static_cast<unsigned long>(result));
775 break; 958 break;
959 }
776 case Entry::Type::Signal: 960 case Entry::Type::Signal:
777 if (SUCCEEDED(hr)) hr = e.fence->Signal(e.value); 961 if (SUCCEEDED(hr)) hr = e.fence->Signal(e.value);
962 notify_us = Timing::elapsed(begin);
963 if (leonida::dstorage::trace_enabled())
964 std::fprintf(stderr, "[rt] ds-signal queue=%p value=%llu hr=%08lx\n", static_cast<void*>(this),
965 e.value, static_cast<unsigned long>(hr));
778 since_notify_ = S_OK; 966 since_notify_ = S_OK;
779 break; 967 break;
780 case Entry::Type::Event: 968 case Entry::Type::Event:
781 if (SUCCEEDED(hr) && !SetEvent(e.event)) hr = HRESULT_FROM_WIN32(GetLastError()); 969 if (SUCCEEDED(hr) && !SetEvent(e.event)) hr = HRESULT_FROM_WIN32(GetLastError());
970 notify_us = Timing::elapsed(begin);
971 if (leonida::dstorage::trace_enabled())
972 std::fprintf(stderr, "[rt] ds-event queue=%p hr=%08lx\n", static_cast<void*>(this),
973 static_cast<unsigned long>(hr));
782 break; 974 break;
783 } 975 }
976 if (e.type != Entry::Type::Request && leonida::dstorage::trace_enabled())
977 std::fprintf(stderr, "[rt] ds-notify queue=%p type=%u us=%lld\n", static_cast<void*>(this),
978 static_cast<unsigned>(e.type), notify_us);
784 if (FAILED(hr)) { 979 if (FAILED(hr)) {
785 DSTORAGE_ERROR_FIRST_FAILURE f{}; 980 DSTORAGE_ERROR_FIRST_FAILURE f{};
786 f.HResult = hr; 981 f.HResult = hr;
@@ -789,38 +984,36 @@ private:
789 } 984 }
790 } 985 }
791 986
792 HRESULT execute_request(const Entry& e) { 987 HRESULT validate_request(const Entry& e) const {
793 const DSTORAGE_REQUEST& r = e.request; 988 const DSTORAGE_REQUEST& r = e.request;
794 const uint64_t o = r.Options.AsUINT64; 989 const uint64_t o = r.Options.AsUINT64;
795 if (o & options::kReservedMask) return E_DSTORAGE_RESERVED_FIELDS; 990 if (o & options::kReservedMask) return E_DSTORAGE_RESERVED_FIELDS;
796 if (options::source_type(o) != desc_.SourceType) return E_DSTORAGE_INVALID_SOURCE_TYPE; 991 if (options::source_type(o) != desc_.SourceType) return E_DSTORAGE_INVALID_SOURCE_TYPE;
797 if (options::bcpack(o) > DSTORAGE_BCPACK_MODE_BC7) return E_DSTORAGE_INVALID_BCPACK_MODE; 992 if (options::bcpack(o) > DSTORAGE_BCPACK_MODE_BC7) return E_DSTORAGE_INVALID_BCPACK_MODE;
798 if (options::swizzle(o) > DSTORAGE_SWIZZLE_MODE_4K_12K_4K_12K) return E_DSTORAGE_INVALID_SWIZZLE_MODE; 993 if (options::swizzle(o) > DSTORAGE_SWIZZLE_MODE_4K_12K_4K_12K) return E_DSTORAGE_INVALID_SWIZZLE_MODE;
799 if (options::bcpack(o) != 0 || options::swizzle(o) != 0) { 994 const unsigned bc = unsigned(options::bcpack(o)), sw = unsigned(options::swizzle(o));
800 log_once("decompress", "BCPack and swizzle requests are not implemented yet (E_NOTIMPL)"); 995 const bool pages = o & (options::kDestinationPages | options::kSourcePages);
801 return E_NOTIMPL; 996 if ((bc || sw || pages) && !extended_enabled()) return E_NOTIMPL;
802 } 997 if (bc == DSTORAGE_BCPACK_MODE_BC2) {
803 if (o & (options::kDestinationPages | options::kSourcePages)) { 998 log_once("bc2", "BC2 has no known BCPack block decoder (E_NOTIMPL)");
804 log_once("pages", "physical-page requests are not implemented yet (E_NOTIMPL)");
805 return E_NOTIMPL; 999 return E_NOTIMPL;
806 } 1000 }
807 const bool zlib = options::zlib(o); 1001 const bool zlib = options::zlib(o);
808 // IntermediateSize is the BCPack data's size between the inflate and the BCPack decode (DSTORAGE_REQUEST), so 1002 if ((zlib && bc) != (r.IntermediateSize != 0) || r.IntermediateSize > kMaxRequestBytes)
809 // it is 0 for every request that gets here (BCPack is refused above). 1003 return E_DSTORAGE_INVALID_INTERMEDIATE_SIZE;
810 if (r.IntermediateSize != 0) return E_DSTORAGE_INVALID_INTERMEDIATE_SIZE; 1004 if (zlib || bc) {
811 // E_DSTORAGE_INVALID_DESTINATION_SIZE: without decompression DestinationSize must equal the source's length, 1005 if (r.DestinationSize <= r.SourceSize) return E_DSTORAGE_INVALID_DESTINATION_SIZE;
812 // with it it must be larger (dstorageerr.h's description; DSTORAGE_REQUEST says the same of DestinationSize). 1006 } else if (r.DestinationSize != r.SourceSize) return E_DSTORAGE_INVALID_DESTINATION_SIZE;
813 if (zlib ? r.DestinationSize <= r.SourceSize : r.DestinationSize != r.SourceSize) 1007 if (bc && r.DestinationSize % ((bc == 1 || bc == 4) ? 8 : 16)) return E_DSTORAGE_INVALID_DESTINATION_SIZE;
814 return E_DSTORAGE_INVALID_DESTINATION_SIZE; 1008 if (sw && r.DestinationSize % leonida::dstorage::group_size(sw)) return E_DSTORAGE_INVALID_DESTINATION_SIZE;
815 const bool memory = desc_.SourceType == DSTORAGE_REQUEST_SOURCE_MEMORY; 1009 const bool memory = desc_.SourceType == DSTORAGE_REQUEST_SOURCE_MEMORY;
1010 if (!memory && (o & options::kSourcePages)) return E_DSTORAGE_INVALID_SOURCE_TYPE;
816 const uint64_t total = static_cast<uint64_t>(r.DestinationSize) + (memory ? r.SourceSize : 0u); 1011 const uint64_t total = static_cast<uint64_t>(r.DestinationSize) + (memory ? r.SourceSize : 0u);
817 if (total > kMaxRequestBytes) return E_DSTORAGE_REQUEST_TOO_LARGE; 1012 if (total > kMaxRequestBytes ||
818 // DSTORAGE_REQUEST: a buffer over 32 MiB is allowed only with 64 KiB or 2 MiB pages, which are not implemented 1013 (r.DestinationSize > kMax4kPageDestinationSize && !(o & options::kDestinationPages)) ||
819 // yet (refused above). The source is never larger than the destination here (the same size without zlib, 1014 (memory && r.SourceSize > kMax4kPageDestinationSize && !(o & options::kSourcePages)))
820 // smaller with it), so this covers both buffers, and bounds the staging buffers of a zlib request too. 1015 return E_DSTORAGE_REQUEST_TOO_LARGE;
821 if (r.DestinationSize > kMax4kPageDestinationSize) return E_DSTORAGE_REQUEST_TOO_LARGE; 1016 if ((zlib || bc) && !memory && r.FileOffset % 16 != 0) return E_DSTORAGE_INVALID_FILE_OFFSET;
822 // DSTORAGE_REQUEST: with ZlibDecompress the file offset must be 16-byte aligned.
823 if (zlib && !memory && r.FileOffset % 16 != 0) return E_DSTORAGE_INVALID_FILE_OFFSET;
824 if (!r.Destination) return E_INVALIDARG; 1017 if (!r.Destination) return E_INVALIDARG;
825 if (memory) { 1018 if (memory) {
826 if (!r.Source) return E_INVALIDARG; 1019 if (!r.Source) return E_INVALIDARG;
@@ -828,68 +1021,192 @@ private:
828 if (!r.File) return E_INVALIDARG; 1021 if (!r.File) return E_INVALIDARG;
829 if (!e.file_counted) return E_DSTORAGE_FILE_NOT_OPEN; 1022 if (!e.file_counted) return E_DSTORAGE_FILE_NOT_OPEN;
830 } 1023 }
831 if (zlib) return inflate_request(e, memory); 1024 return S_OK;
1025 }
1026
1027 HRESULT execute_request(Entry& e, bool pair_reserved) {
1028 const HRESULT valid = validate_request(e);
1029 if (FAILED(valid)) { e.reason = "request-validation"; return valid; }
1030 const auto& r = e.request;
1031 const auto o = r.Options.AsUINT64;
1032 const bool memory = desc_.SourceType == DSTORAGE_REQUEST_SOURCE_MEMORY;
1033 if ((o & (options::kDestinationPages | options::kSourcePages)) || options::zlib(o) ||
1034 options::bcpack(o) || options::swizzle(o)) {
1035 leonida::dstorage::StagingPool::Lease reservation(leonida::dstorage::staging_pool());
1036 if (!pair_reserved) reservation.acquire(leonida::dstorage::staging_bytes(r));
1037 std::vector<uint8_t> data;
1038 const auto hr = prepare(e, data);
1039 return FAILED(hr) ? hr : publish(e, data);
1040 }
832 if (r.SourceSize == 0) return S_OK; // nothing to move; the reference does not say this fails 1041 if (r.SourceSize == 0) return S_OK; // nothing to move; the reference does not say this fails
833 if (memory) return guarded_move(r.Destination, r.Source, r.SourceSize) ? S_OK : E_DSTORAGE_ACCESS_VIOLATION; 1042 void* const destination = cpu_destination(r);
834 return read_file_range(e.file->handle(), r.FileOffset, r.Destination, r.SourceSize); 1043 if (memory) {
835 } 1044 const auto begin = Timing::start();
836 1045 const auto hr = written(r, guarded_move(destination, r.Source, r.SourceSize) ? S_OK : E_DSTORAGE_ACCESS_VIOLATION);
837 // A zlib request whose checks have passed: the source (SourceSize bytes of the file or of memory) goes into a 1046 e.timing.copy = Timing::elapsed(begin);
838 // staging buffer, inflates there, and only a result of exactly DestinationSize bytes is copied to the destination. 1047 if (FAILED(hr)) e.reason = "copy";
839 // So a failed stream leaves the destination as it was, and a memory source that overlaps its destination is safe. 1048 return hr;
840 // Both buffers are at most 32 MiB (execute_request). The stream is RFC 1950: the two header bytes, the deflate 1049 }
841 // data, the Adler-32 of the result; bytes after the Adler-32 are not read. A failure is the matching 1050 if (extended_enabled() && !rt::xmem::commit_physical_range(destination, r.DestinationSize)) {
842 // dstorageerr.h code: a bad header (not deflate, a window over 32 KiB, a bad check value or a preset dictionary) 1051 e.reason = "destination-commit";
843 // E_DSTORAGE_ZLIB_BAD_HEADER, bad or truncated deflate data E_DSTORAGE_ZLIB_BAD_DATA, an Adler-32 mismatch 1052 return E_DSTORAGE_ACCESS_VIOLATION;
844 // E_DSTORAGE_ZLIB_PARITY_FAIL, and a stream that inflates to more or fewer bytes than DestinationSize 1053 }
845 // E_DSTORAGE_DECOMPRESSION_ERROR (no code names a size mismatch; this is the header's generic one). 1054 const auto begin = Timing::start();
846 HRESULT inflate_request(const Entry& e, bool memory) { 1055 const auto hr = read_file_range(e.file->handle(), r.FileOffset, destination, r.SourceSize, ReadTarget::Title);
847 const DSTORAGE_REQUEST& r = e.request; 1056 e.timing.read = Timing::elapsed(begin);
848 std::vector<uint8_t> source, result; 1057 if (FAILED(hr)) e.reason = "file-read";
849 try { 1058 return written(r, hr);
850 source.resize(r.SourceSize); 1059 }
851 result.reserve(r.DestinationSize); 1060
852 } catch (const std::bad_alloc&) { 1061 // Where the CPU writes a request's destination: the title hands its stream pool's GPU-only alias range as the
853 return E_OUTOFMEMORY; 1062 // destination of streamed texture data (gfxgeom notes, section 2), which only the GPU maps; its CPU view holds the
1063 // same pages (src/title_page_watch.h, title_gpu_views).
1064 static void* cpu_destination(const DSTORAGE_REQUEST& r) {
1065 return reinterpret_cast<void*>(leonida::title_gpu_views::to_cpu(reinterpret_cast<uintptr_t>(r.Destination)));
1066 }
1067 // A request that wrote its destination tells the D3D12 layer, whose images of textures in that memory are filled
1068 // from it (title_texel_writes).
1069 static HRESULT written(const DSTORAGE_REQUEST& r, HRESULT hr) {
1070 if (SUCCEEDED(hr)) leonida::title_texel_writes::note(cpu_destination(r), r.DestinationSize);
1071 return hr;
1072 }
1073
1074 // The caller may populate or remap the physical page list between enqueue and Submit.
1075 // Snapshot page numbers on the worker before taking xmem's allocation/map lock.
1076 static HRESULT page_transfer(const ULONG_PTR* pages, uint16_t offset, std::span<uint8_t> buffer, bool write) {
1077 if (buffer.empty()) return S_OK;
1078 std::vector<uint64_t> numbers(1 + (buffer.size() - 1 + offset) / 65536);
1079 if (!guarded_move(numbers.data(), pages, numbers.size() * sizeof(numbers[0])))
1080 return E_DSTORAGE_ACCESS_VIOLATION;
1081 if (rt::xmem::transfer_physical(numbers, offset, buffer, write)) return S_OK;
1082 return HRESULT_FROM_WIN32(GetLastError());
1083 }
1084
1085 static HRESULT inflate(const std::vector<uint8_t>& src, std::vector<uint8_t>& out, size_t size) {
1086 leonida::ZlibError why{};
1087 static const bool bulk = [] {
1088 wchar_t value[2]{};
1089 return GetEnvironmentVariableW(L"LEONIDA_DSTORAGE_FAST_INFLATE", value, 2) != 1 || value[0] != L'0';
1090 }();
1091 out.reserve(size);
1092 if (leonida::zlib_inflate(src, out, size, &why, bulk))
1093 return out.size() == size ? S_OK : E_DSTORAGE_DECOMPRESSION_ERROR;
1094 switch (why) {
1095 case leonida::ZlibError::header: return E_DSTORAGE_ZLIB_BAD_HEADER;
1096 case leonida::ZlibError::checksum: return E_DSTORAGE_ZLIB_PARITY_FAIL;
1097 case leonida::ZlibError::limit: return E_DSTORAGE_DECOMPRESSION_ERROR;
1098 default: return E_DSTORAGE_ZLIB_BAD_DATA;
1099 }
1100 }
1101
1102 static HRESULT decode_stages(Entry& e, unsigned bc, unsigned sw, std::vector<uint8_t>& data) {
1103 const auto& r = e.request;
1104 if (options::zlib(r.Options.AsUINT64)) {
1105 std::vector<uint8_t> scratch;
1106 static const bool reported = (log_once("zlib", "zlib requests use CPU inflate (RFC 1950)"), true);
1107 (void)reported;
1108 const auto begin = Timing::start();
1109 const auto hr = inflate(data, scratch, bc ? r.IntermediateSize : r.DestinationSize);
1110 e.timing.inflate = Timing::elapsed(begin);
1111 if (FAILED(hr)) { e.reason = "inflate"; return hr; }
1112 data = std::move(scratch);
854 } 1113 }
855 if (r.SourceSize != 0) { 1114 if (bc) {
856 if (memory) { 1115 std::vector<uint8_t> scratch(r.DestinationSize);
857 if (!guarded_move(source.data(), r.Source, r.SourceSize)) return E_DSTORAGE_ACCESS_VIOLATION; 1116 static const bool allow_fitted = [] {
858 } else if (const HRESULT hr = read_file_range(e.file->handle(), r.FileOffset, source.data(), r.SourceSize); 1117 char value[2]{};
859 FAILED(hr)) { 1118 return GetEnvironmentVariableA("LEONIDA_DSTORAGE_FITTED", value, sizeof value) != 1 || value[0] != '0';
1119 }();
1120 const auto begin = Timing::start();
1121 static const bool fast_entropy = [] {
1122 char value[2]{};
1123 return GetEnvironmentVariableA("LEONIDA_DSTORAGE_FAST_BCPACK", value, sizeof value) != 1 || value[0] != '0';
1124 }();
1125 const char* failure = nullptr;
1126 const auto quality = leonida::bcpack::decode(bc, data, scratch, allow_fitted, bc >= 6 ? bcpack_history() : nullptr, &failure, fast_entropy);
1127 e.timing.bcpack = Timing::elapsed(begin);
1128 if (quality == leonida::bcpack::Quality::failed) { e.reason = failure; return E_DSTORAGE_DECOMPRESSION_ERROR; }
1129 if (quality == leonida::bcpack::Quality::fitted) {
1130 static const bool reported = (log_once("fitted", "using fitted BCPack predictors"), true);
1131 (void)reported;
1132 if (leonida::dstorage::trace_enabled())
1133 std::fprintf(stderr, "[rt] ds-fitted bc=%u bytes=%u\n", bc, r.DestinationSize);
1134 }
1135 data = std::move(scratch);
1136 }
1137 if (sw) {
1138 std::vector<uint8_t> scratch(r.DestinationSize);
1139 const auto begin = Timing::start();
1140 if (!leonida::dstorage::unshuffle(sw, data, scratch)) return E_DSTORAGE_INVALID_DESTINATION_SIZE;
1141 e.timing.unshuffle = Timing::elapsed(begin);
1142 data = std::move(scratch);
1143 }
1144 return S_OK;
1145 }
1146
1147 HRESULT prepare(Entry& e, std::vector<uint8_t>& data) try {
1148 const auto& r = e.request;
1149 const auto o = r.Options.AsUINT64;
1150 const bool memory = desc_.SourceType == DSTORAGE_REQUEST_SOURCE_MEMORY;
1151 const auto bc = unsigned(options::bcpack(o)), sw = unsigned(options::swizzle(o));
1152 data.resize(r.SourceSize);
1153 HRESULT hr = S_OK;
1154 const auto read_begin = Timing::start();
1155 if (!memory) hr = read_file_range(e.file->handle(), r.FileOffset, data.data(), r.SourceSize, ReadTarget::Staging);
1156 else if (o & options::kSourcePages) hr = page_transfer(r.SourcePageArray, r.SourcePageOffset, data, false);
1157 else if (!data.empty() && !guarded_move(data.data(), r.Source, data.size())) hr = E_DSTORAGE_ACCESS_VIOLATION;
1158 e.timing.read = Timing::elapsed(read_begin);
1159 if (FAILED(hr)) { e.reason = "read"; return hr; }
1160 if (bc || sw || options::zlib(o)) {
1161 set_decompression_pending(+1);
1162 try {
1163 hr = decode_stages(e, bc, sw, data);
1164 } catch (const std::bad_alloc&) {
1165 hr = E_OUTOFMEMORY;
1166 }
1167 set_decompression_pending(-1);
1168 if (FAILED(hr)) {
1169 std::lock_guard lock(stats().mutex);
1170 ++stats().s.DecompressionErrors;
860 return hr; 1171 return hr;
861 } 1172 }
862 } 1173 }
863 log_once("zlib", "zlib requests are inflated on the CPU (RFC 1950, leonida::zlib_inflate)"); 1174 return S_OK;
864 set_decompression_pending(+1); 1175 } catch (const std::bad_alloc&) { return E_OUTOFMEMORY; }
865 leonida::ZlibError why = leonida::ZlibError::none; 1176
866 const bool inflated = leonida::zlib_inflate(source, result, r.DestinationSize, &why); 1177 HRESULT publish(Entry& e, std::vector<uint8_t>& data) try {
867 set_decompression_pending(-1); 1178 const auto& r = e.request;
1179 const auto o = r.Options.AsUINT64;
1180 const auto bc = options::bcpack(o), sw = options::swizzle(o);
868 HRESULT hr = S_OK; 1181 HRESULT hr = S_OK;
869 if (!inflated) { 1182 const auto copy_begin = Timing::start();
870 switch (why) { 1183 if (o & options::kDestinationPages) hr = page_transfer(r.DestinationPageArray, r.DestinationPageOffset, data, true);
871 case leonida::ZlibError::header: hr = E_DSTORAGE_ZLIB_BAD_HEADER; break; 1184 else if (!data.empty()) {
872 case leonida::ZlibError::checksum: hr = E_DSTORAGE_ZLIB_PARITY_FAIL; break; 1185 void* const dest = cpu_destination(r);
873 case leonida::ZlibError::limit: hr = E_DSTORAGE_DECOMPRESSION_ERROR; break; // longer than the destination 1186 if (extended_enabled() && !rt::xmem::commit_physical_range(dest, data.size())) {
874 default: hr = E_DSTORAGE_ZLIB_BAD_DATA; break; 1187 e.reason = "destination-commit";
1188 return E_DSTORAGE_ACCESS_VIOLATION;
875 } 1189 }
876 } else if (result.size() != r.DestinationSize) { 1190 hr = written(r, guarded_move(dest, data.data(), data.size()) ? S_OK : E_DSTORAGE_ACCESS_VIOLATION);
877 hr = E_DSTORAGE_DECOMPRESSION_ERROR; // shorter than the destination
878 } 1191 }
879 if (FAILED(hr)) { 1192 e.timing.copy = Timing::elapsed(copy_begin);
880 std::lock_guard lock(stats().mutex); 1193 if (FAILED(hr)) e.reason = "publish";
881 ++stats().s.DecompressionErrors; 1194 if (leonida::dstorage::trace_enabled() && SUCCEEDED(hr) && (bc || sw || (o & options::kDestinationPages) ||
882 return hr; 1195 leonida::title_gpu_views::other_view(reinterpret_cast<uintptr_t>(r.Destination)))) {
1196 std::fprintf(stderr, "[rt] ds-write queue=%p dest=%p cpu=%p options=%llx bytes=%zu nonzero=%d\n",
1197 static_cast<void*>(this), r.Destination, (o & options::kDestinationPages) ? nullptr : cpu_destination(r),
1198 o, data.size(),
1199 int(std::any_of(data.begin(), data.end(), [](uint8_t byte) { return byte != 0; })));
883 } 1200 }
884 return guarded_move(r.Destination, result.data(), result.size()) ? S_OK : E_DSTORAGE_ACCESS_VIOLATION; 1201 return hr;
885 } 1202 } catch (const std::bad_alloc&) { return E_OUTOFMEMORY; }
886 1203
887 void set_pending(int delta) { 1204 void set_pending(int delta) {
888 std::lock_guard lock(stats().mutex); 1205 std::lock_guard lock(stats().mutex);
889 priority_stats(stats().s, desc_.Priority).PendingRequestCount += static_cast<uint32_t>(delta); 1206 priority_stats(stats().s, desc_.Priority).PendingRequestCount += static_cast<uint32_t>(delta);
890 } 1207 }
891 1208
892 // PendingDecompressionRequestCount is the zlib requests being inflated; TotalDecompressionRequestCount counts each 1209 // PendingDecompressionRequestCount covers the current decode pipeline; TotalDecompressionRequestCount counts each
893 // one that reached its inflate (its source was read), DecompressionErrors those whose stream then failed. 1210 // one that reached its inflate (its source was read), DecompressionErrors those whose stream then failed.
894 static void set_decompression_pending(int delta) { 1211 static void set_decompression_pending(int delta) {
895 std::lock_guard lock(stats().mutex); 1212 std::lock_guard lock(stats().mutex);
@@ -943,9 +1260,16 @@ private:
943 if (record_.FailureCount++ == 0) record_.FirstFailure = f; 1260 if (record_.FailureCount++ == 0) record_.FirstFailure = f;
944 if (error_event_) SetEvent(error_event_); 1261 if (error_event_) SetEvent(error_event_);
945 } 1262 }
946 log_once("fail" + hr_text(f.HResult) + std::to_string(f.CommandType), 1263 static auto* counts = new std::map<HRESULT, uint64_t>;
947 "an entry failed with " + hr_text(f.HResult) + " (command type " + std::to_string(f.CommandType) + 1264 std::lock_guard lock(log_mutex());
948 "; logged once per code)"); 1265 const auto count = ++(*counts)[f.HResult];
1266 // The boot digest groups identical lines. Keep one invariant line per HRESULT and
1267 // report the cumulative value separately so a truncated run is still countable.
1268 std::fprintf(stderr, "[rt] dstorage: an entry failed with 0x%08lx (facility=%lx code=%lx)\n"
1269 "[rt] ds-error-count hr=%08lx count=%llu command=%u\n",
1270 static_cast<unsigned long>(f.HResult), static_cast<unsigned long>(HRESULT_FACILITY(f.HResult)),
1271 static_cast<unsigned long>(HRESULT_CODE(f.HResult)), static_cast<unsigned long>(f.HResult),
1272 static_cast<unsigned long long>(count), unsigned(f.CommandType));
949 } 1273 }
950 1274
951 void clear_record_locked() { 1275 void clear_record_locked() {
@@ -971,10 +1295,12 @@ private:
971 std::condition_variable work_, space_, idle_; 1295 std::condition_variable work_, space_, idle_;
972 std::deque<Entry> entries_; 1296 std::deque<Entry> entries_;
973 size_t submitted_ = 0; // the first submitted_ entries are submitted 1297 size_t submitted_ = 0; // the first submitted_ entries are submitted
974 bool in_flight_ = false; 1298 size_t in_flight_ = 0;
975 bool closing_ = false; 1299 bool closing_ = false;
976 bool closed_ = false; 1300 bool closed_ = false;
977 std::thread worker_; 1301 std::thread worker_;
1302 PTP_WORK preparation_work_ = nullptr;
1303 Prepared* helper_job_ = nullptr; // Lives on the publisher stack through the callback and ordered write.
978 HRESULT since_notify_ = S_OK; // worker only 1304 HRESULT since_notify_ = S_OK; // worker only
979 std::mutex error_mutex_; 1305 std::mutex error_mutex_;
980 DSTORAGE_ERROR_RECORD record_{}; 1306 DSTORAGE_ERROR_RECORD record_{};