diff options
Diffstat (limited to 'runtime/shims/d3d12_vulkan_device.cpp')
| -rw-r--r-- | runtime/shims/d3d12_vulkan_device.cpp | 4155 |
1 files changed, 3878 insertions, 277 deletions
diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index c5f72eb27..1fb36401e 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp | |||
| @@ -12,6 +12,8 @@ | |||
| 12 | #include "d3d12_com.h" | 12 | #include "d3d12_com.h" |
| 13 | #include "d3d12_compile_exit.h" | 13 | #include "d3d12_compile_exit.h" |
| 14 | #include "d3d12_pipeline_compile.h" | 14 | #include "d3d12_pipeline_compile.h" |
| 15 | #include "d3d12_precompile.h" | ||
| 16 | #include "d3d12_compile_helper.h" | ||
| 15 | #include "d3d12_pipeline_checkpoint.h" | 17 | #include "d3d12_pipeline_checkpoint.h" |
| 16 | #include "d3d12_feature_compat.h" | 18 | #include "d3d12_feature_compat.h" |
| 17 | 19 | ||
| @@ -46,6 +48,9 @@ | |||
| 46 | #include "../src/pipeline_profile.h" | 48 | #include "../src/pipeline_profile.h" |
| 47 | #include "../src/submit_phases.h" | 49 | #include "../src/submit_phases.h" |
| 48 | #include "../src/pipeline_cache_store.h" | 50 | #include "../src/pipeline_cache_store.h" |
| 51 | #include "../src/pipeline_cache_journal.h" | ||
| 52 | #include "../src/large_module_gate.h" | ||
| 53 | #include "../src/dev_status.h" | ||
| 49 | #include "../src/conservative_raster.h" | 54 | #include "../src/conservative_raster.h" |
| 50 | #include "../src/resource_detile.h" | 55 | #include "../src/resource_detile.h" |
| 51 | #include "../src/console_texture_layout.h" | 56 | #include "../src/console_texture_layout.h" |
| @@ -60,6 +65,7 @@ | |||
| 60 | #include "../src/spirv_f16_halves.h" | 65 | #include "../src/spirv_f16_halves.h" |
| 61 | #include "../src/spirv_stores.h" | 66 | #include "../src/spirv_stores.h" |
| 62 | #include "../src/title_va_alias.h" | 67 | #include "../src/title_va_alias.h" |
| 68 | #include "../src/console_heap_vsharp_slots.h" | ||
| 63 | #include "../src/title_window_plan.h" | 69 | #include "../src/title_window_plan.h" |
| 64 | #include "../src/vulkan_present.h" | 70 | #include "../src/vulkan_present.h" |
| 65 | #include "../src/vulkan_device_filter.h" | 71 | #include "../src/vulkan_device_filter.h" |
| @@ -70,6 +76,7 @@ | |||
| 70 | #include "../src/local_diagnostics.h" | 76 | #include "../src/local_diagnostics.h" |
| 71 | #include "../src/mem_probe.h" // LOCAL DIAGNOSTIC | 77 | #include "../src/mem_probe.h" // LOCAL DIAGNOSTIC |
| 72 | #include "../src/vulkan_aftermath.h" | 78 | #include "../src/vulkan_aftermath.h" |
| 79 | #include "../src/console_heap_gpu.h" | ||
| 73 | 80 | ||
| 74 | #include <vulkan/vulkan_win32.h> | 81 | #include <vulkan/vulkan_win32.h> |
| 75 | #ifdef _MSC_VER | 82 | #ifdef _MSC_VER |
| @@ -89,6 +96,7 @@ | |||
| 89 | #include <fstream> | 96 | #include <fstream> |
| 90 | #include <iterator> | 97 | #include <iterator> |
| 91 | #include <map> | 98 | #include <map> |
| 99 | #include <unordered_map> | ||
| 92 | #include <cstring> | 100 | #include <cstring> |
| 93 | #include <memory> | 101 | #include <memory> |
| 94 | #include <mutex> | 102 | #include <mutex> |
| @@ -97,11 +105,13 @@ | |||
| 97 | #include <optional> | 105 | #include <optional> |
| 98 | #include <set> | 106 | #include <set> |
| 99 | #include <deque> | 107 | #include <deque> |
| 108 | #include <unordered_map> | ||
| 100 | #include <unordered_set> | 109 | #include <unordered_set> |
| 101 | #include <shared_mutex> | 110 | #include <shared_mutex> |
| 102 | #include <string> | 111 | #include <string> |
| 103 | #include <type_traits> | 112 | #include <type_traits> |
| 104 | #include <cwchar> | 113 | #include <cwchar> |
| 114 | #include <intrin.h> | ||
| 105 | #include <smmintrin.h> | 115 | #include <smmintrin.h> |
| 106 | #include <vector> | 116 | #include <vector> |
| 107 | 117 | ||
| @@ -252,6 +262,13 @@ inline std::uint64_t hashed_bytes(std::uint64_t bytes, bool every_byte = false) | |||
| 252 | return bytes <= (256u << 10) || every_byte ? bytes : bytes / 32 + 64; | 262 | return bytes <= (256u << 10) || every_byte ? bytes : bytes / 32 + 64; |
| 253 | } | 263 | } |
| 254 | 264 | ||
| 265 | bool async_texture_refresh() { | ||
| 266 | static const bool enabled = [] { | ||
| 267 | const char* v = std::getenv("LEONIDA_TEXTURE_REFRESH_ASYNC"); | ||
| 268 | return v && std::strcmp(v, "1") == 0; | ||
| 269 | }(); | ||
| 270 | return enabled; | ||
| 271 | } | ||
| 255 | // Set while this thread is inside the title-texture registry (it holds title_texture_mutex): a staged copy it makes | 272 | // Set while this thread is inside the title-texture registry (it holds title_texture_mutex): a staged copy it makes |
| 256 | // submits through a queue, whose before-submission refresh must then not take the registry again. | 273 | // submits through a queue, whose before-submission refresh must then not take the registry again. |
| 257 | thread_local bool t_in_title_textures = false; | 274 | thread_local bool t_in_title_textures = false; |
| @@ -324,6 +341,13 @@ class ShadowPages { | |||
| 324 | public: | 341 | public: |
| 325 | static constexpr std::uintptr_t kPage = 0x1000; | 342 | static constexpr std::uintptr_t kPage = 0x1000; |
| 326 | static constexpr std::uintptr_t kBlock = 0x10000; // what one write fault makes writable again | 343 | static constexpr std::uintptr_t kBlock = 0x10000; // what one write fault makes writable again |
| 344 | // LEONIDA_SHADOW_GPU (DeviceState::gpu_copy_shadow): takes a copy of [from, from + bytes) to `to` for the GPU, or | ||
| 345 | // returns false and the CPU copies it. Set once by the device. | ||
| 346 | using GpuCopy = bool (*)(void* context, std::uint8_t* to, const std::uint8_t* from, std::size_t bytes); | ||
| 347 | static inline GpuCopy gpu_copy = nullptr; | ||
| 348 | static inline void* gpu_copy_context = nullptr; | ||
| 349 | // Bytes this tracker's refreshes handed to gpu_copy so far. | ||
| 350 | std::uint64_t gpu_bytes() const { return gpu_bytes_; } | ||
| 327 | 351 | ||
| 328 | ShadowPages(const std::uint8_t* pages, std::uint8_t* shadow, std::size_t size, bool watch) : watch_(watch) { | 352 | ShadowPages(const std::uint8_t* pages, std::uint8_t* shadow, std::size_t size, bool watch) : watch_(watch) { |
| 329 | begin_ = reinterpret_cast<std::uintptr_t>(pages); | 353 | begin_ = reinterpret_cast<std::uintptr_t>(pages); |
| @@ -384,6 +408,8 @@ public: | |||
| 384 | // Brings every target up to date with the pages. Returns the bytes copied into them. With copy_aliased false, pages | 408 | // Brings every target up to date with the pages. Returns the bytes copied into them. With copy_aliased false, pages |
| 385 | // xmem maps at another address too are left as they are this time (DeviceState::refresh_shadows throttles them). | 409 | // xmem maps at another address too are left as they are this time (DeviceState::refresh_shadows throttles them). |
| 386 | std::size_t refresh(bool copy_aliased = true) { | 410 | std::size_t refresh(bool copy_aliased = true) { |
| 411 | const auto walk_start = std::chrono::steady_clock::now(); | ||
| 412 | pieces_ = {}; | ||
| 387 | copy_aliased_ = copy_aliased; | 413 | copy_aliased_ = copy_aliased; |
| 388 | jobs_.clear(); | 414 | jobs_.clear(); |
| 389 | zeroed_.clear(); | 415 | zeroed_.clear(); |
| @@ -524,11 +550,15 @@ public: | |||
| 524 | switch (how) { | 550 | switch (how) { |
| 525 | case Watch::clean: break; // write-watched, not written since it was copied | 551 | case Watch::clean: break; // write-watched, not written since it was copied |
| 526 | case Watch::written: // write-watched: written since, or not known yet | 552 | case Watch::written: // write-watched: written since, or not known yet |
| 553 | // A page this tracker made read-only is opened first: dropping kProtected alone left it | ||
| 554 | // read-only with no owner, so the next write could fault. | ||
| 555 | unguard_ours(i, j); | ||
| 527 | for (std::size_t k = i; k < j; ++k) | 556 | for (std::size_t k = i; k < j; ++k) |
| 528 | state_[k] = std::uint8_t((state_[k] & ~(kZero | kProtected)) | kClean); | 557 | state_[k] = std::uint8_t((state_[k] & ~(kZero | kProtected)) | kClean); |
| 529 | add_job(i, j, streaming, Copy::write_watched); | 558 | add_job(i, j, streaming, Copy::write_watched); |
| 530 | break; | 559 | break; |
| 531 | case Watch::open: // write-watched, but pinned for a kernel write: copied until the pin ends | 560 | case Watch::open: // write-watched, but pinned for a kernel write: copied until the pin ends |
| 561 | unguard_ours(i, j); | ||
| 532 | for (std::size_t k = i; k < j; ++k) state_[k] &= ~(kZero | kProtected | kClean); | 562 | for (std::size_t k = i; k < j; ++k) state_[k] &= ~(kZero | kProtected | kClean); |
| 533 | add_job(i, j, streaming, Copy::write_watched); | 563 | add_job(i, j, streaming, Copy::write_watched); |
| 534 | break; | 564 | break; |
| @@ -543,6 +573,7 @@ public: | |||
| 543 | } | 573 | } |
| 544 | break; | 574 | break; |
| 545 | case Kind::unwatched: | 575 | case Kind::unwatched: |
| 576 | unguard_ours(i0, i1); // as above: never drop kProtected over a page still read-only for us | ||
| 546 | for (std::size_t i = i0; i < i1; ++i) state_[i] &= kAliased | kPinned | kWatched; | 577 | for (std::size_t i = i0; i < i1; ++i) state_[i] &= kAliased | kPinned | kWatched; |
| 547 | add_job(i0, i1, streaming, Copy::copy_on_write); | 578 | add_job(i0, i1, streaming, Copy::copy_on_write); |
| 548 | break; | 579 | break; |
| @@ -558,15 +589,55 @@ public: | |||
| 558 | log_once("slot-133 shadow: VirtualProtect refused to watch the title's pages for writes, so they are " | 589 | log_once("slot-133 shadow: VirtualProtect refused to watch the title's pages for writes, so they are " |
| 559 | "copied at every submission; error", | 590 | "copied at every submission; error", |
| 560 | int(protect_error)); | 591 | int(protect_error)); |
| 561 | // The copies run without the lock: a write that faults meanwhile is let through and copied next time. | 592 | // The copies run without the lock: a write that faults meanwhile is let through and copied next time. Pages |
| 593 | // copied because they are aliased go to the GPU when LEONIDA_SHADOW_GPU set gpu_copy and it takes them. | ||
| 594 | // LEONIDA_SHADOW_JOIN=1: pieces of one job that go on where the one before ended, in the pages and in the copy | ||
| 595 | // both, are one copy (one GPU region, one gpu_copy call); one the GPU refuses is copied by the CPU whole. | ||
| 596 | static const bool join = [] { | ||
| 597 | char value[4] = {}; | ||
| 598 | return GetEnvironmentVariableA("LEONIDA_SHADOW_JOIN", value, sizeof(value)) == 1 && value[0] == '1'; | ||
| 599 | }(); | ||
| 600 | const auto copy_start = std::chrono::steady_clock::now(); | ||
| 601 | pieces_.walk_ms = std::chrono::duration<double, std::milli>(copy_start - walk_start).count(); | ||
| 562 | std::size_t copied = 0; | 602 | std::size_t copied = 0; |
| 563 | for (const Job& job : jobs_) | 603 | for (const Job& job : jobs_) { |
| 604 | std::uint8_t* run_dst = nullptr; | ||
| 605 | const std::uint8_t* run_src = nullptr; | ||
| 606 | std::size_t run_bytes = 0; | ||
| 607 | const auto flush = [&] { | ||
| 608 | if (!run_bytes) return; | ||
| 609 | ++pieces_.calls; | ||
| 610 | if (job.aliased && gpu_copy) ++pieces_.gpu_calls; | ||
| 611 | if (job.aliased && gpu_copy && gpu_copy(gpu_copy_context, run_dst, run_src, run_bytes)) | ||
| 612 | gpu_bytes_ += run_bytes; | ||
| 613 | else | ||
| 614 | copy_run(run_dst, run_src, run_bytes, job.streaming); | ||
| 615 | run_bytes = 0; | ||
| 616 | }; | ||
| 564 | for_each_target(begin_ + job.offset, begin_ + job.offset + job.bytes, | 617 | for_each_target(begin_ + job.offset, begin_ + job.offset + job.bytes, |
| 565 | [&](const Target& t, std::uintptr_t from, std::uintptr_t to) { | 618 | [&](const Target& t, std::uintptr_t from, std::uintptr_t to) { |
| 566 | copy_run(t.shadow + (from - t.begin), reinterpret_cast<const std::uint8_t*>(from), | 619 | std::uint8_t* dst = t.shadow + (from - t.begin); |
| 567 | to - from, job.streaming); | 620 | const auto* src = reinterpret_cast<const std::uint8_t*>(from); |
| 568 | copied += to - from; | 621 | const std::size_t n = to - from; |
| 622 | ++pieces_.pieces; | ||
| 623 | pieces_.short_pieces += n < kPage; | ||
| 624 | const bool follows = run_bytes && run_dst + run_bytes == dst && run_src + run_bytes == src; | ||
| 625 | pieces_.joinable += follows; | ||
| 626 | if (join && follows) { | ||
| 627 | run_bytes += n; | ||
| 628 | } else { | ||
| 629 | flush(); | ||
| 630 | run_dst = dst; | ||
| 631 | run_src = src; | ||
| 632 | run_bytes = n; | ||
| 633 | if (!join) flush(); | ||
| 634 | } | ||
| 635 | copied += n; | ||
| 569 | }); | 636 | }); |
| 637 | flush(); | ||
| 638 | } | ||
| 639 | pieces_.copy_ms = | ||
| 640 | std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - copy_start).count(); | ||
| 570 | refresh_queries_ = queries; | 641 | refresh_queries_ = queries; |
| 571 | return copied; | 642 | return copied; |
| 572 | } | 643 | } |
| @@ -761,6 +832,15 @@ public: | |||
| 761 | // read-only pages that are not this tracker's, copy-on-write pages, write-watched pages found written. | 832 | // read-only pages that are not this tracker's, copy-on-write pages, write-watched pages found written. |
| 762 | enum class Copy { guarded, unguarded, aliased, pinned, read_only, copy_on_write, write_watched, count }; | 833 | enum class Copy { guarded, unguarded, aliased, pinned, read_only, copy_on_write, write_watched, count }; |
| 763 | const std::array<std::uint64_t, unsigned(Copy::count)>& copy_bytes() const { return copy_bytes_; } | 834 | const std::array<std::uint64_t, unsigned(Copy::count)>& copy_bytes() const { return copy_bytes_; } |
| 835 | // The last refresh()'s copies as pieces (one per job and target: a slot-133 buffer is a few KiB, so a run of | ||
| 836 | // pages over many of them is many pieces), those under 4 KiB, those that go on where the one before ended in both | ||
| 837 | // the title's pages and the copy (VItoriaBr's JOIN_COPIES case), the copy calls made after LEONIDA_SHADOW_JOIN | ||
| 838 | // joined those, and the milliseconds of the walk (queries, guards, under the lock) and of the copies. | ||
| 839 | struct Pieces { | ||
| 840 | std::uint64_t pieces = 0, short_pieces = 0, joinable = 0, calls = 0, gpu_calls = 0; | ||
| 841 | double walk_ms = 0, copy_ms = 0; | ||
| 842 | }; | ||
| 843 | const Pieces& pieces() const { return pieces_; } | ||
| 764 | 844 | ||
| 765 | private: | 845 | private: |
| 766 | // How a committed, readable page is watched: by the kernel (clean, written or, pinned or aliased, open) or by | 846 | // How a committed, readable page is watched: by the kernel (clean, written or, pinned or aliased, open) or by |
| @@ -905,6 +985,7 @@ private: | |||
| 905 | struct Job { | 985 | struct Job { |
| 906 | std::size_t offset, bytes; // from begin_ | 986 | std::size_t offset, bytes; // from begin_ |
| 907 | bool streaming; | 987 | bool streaming; |
| 988 | bool aliased; // copied because xmem maps the pages elsewhere too (Copy::aliased) | ||
| 908 | }; | 989 | }; |
| 909 | struct Target { | 990 | struct Target { |
| 910 | std::uintptr_t begin, end; // the title's bytes | 991 | std::uintptr_t begin, end; // the title's bytes |
| @@ -933,12 +1014,13 @@ private: | |||
| 933 | void add_job(std::size_t i, std::size_t j, bool streaming, Copy why) { | 1014 | void add_job(std::size_t i, std::size_t j, bool streaming, Copy why) { |
| 934 | const auto [offset, bytes] = span_of(i, j); | 1015 | const auto [offset, bytes] = span_of(i, j); |
| 935 | copy_bytes_[unsigned(why)] += bytes; | 1016 | copy_bytes_[unsigned(why)] += bytes; |
| 936 | if (!jobs_.empty() && jobs_.back().streaming == streaming && | 1017 | const bool aliased = why == Copy::aliased; |
| 1018 | if (!jobs_.empty() && jobs_.back().streaming == streaming && jobs_.back().aliased == aliased && | ||
| 937 | jobs_.back().offset + jobs_.back().bytes == offset) { | 1019 | jobs_.back().offset + jobs_.back().bytes == offset) { |
| 938 | jobs_.back().bytes += bytes; | 1020 | jobs_.back().bytes += bytes; |
| 939 | return; | 1021 | return; |
| 940 | } | 1022 | } |
| 941 | jobs_.push_back({offset, bytes, streaming}); | 1023 | jobs_.push_back({offset, bytes, streaming, aliased}); |
| 942 | } | 1024 | } |
| 943 | 1025 | ||
| 944 | // The targets sorted by start, the bytes they hold, and reach_[k], the furthest end among targets_[0..k]: the | 1026 | // The targets sorted by start, the bytes they hold, and reach_[k], the furthest end among targets_[0..k]: the |
| @@ -989,6 +1071,18 @@ private: | |||
| 989 | ++refresh_protects_; | 1071 | ++refresh_protects_; |
| 990 | } | 1072 | } |
| 991 | 1073 | ||
| 1074 | // With the lock held: before pages [i, j) stop counting as ours (kProtected), the ones this tracker made read-only | ||
| 1075 | // are given back their write access, so no page stays read-only with no guard to answer its writes. | ||
| 1076 | void unguard_ours(std::size_t i, std::size_t j) { | ||
| 1077 | for (std::size_t k = i; k < j; ++k) | ||
| 1078 | if (state_[k] & kProtected) { | ||
| 1079 | ++unguarded_on_drop_; | ||
| 1080 | reopen_locked(first_ + i * kPage, first_ + j * kPage); | ||
| 1081 | return; | ||
| 1082 | } | ||
| 1083 | } | ||
| 1084 | std::uint64_t unguarded_on_drop_ = 0; // times unguard_ours found pages of ours to reopen (diagnostic) | ||
| 1085 | |||
| 992 | // With the lock held: the pages in [from, to) this tracker made read-only are read-write again. | 1086 | // With the lock held: the pages in [from, to) this tracker made read-only are read-write again. |
| 993 | void reopen_locked(std::uintptr_t from, std::uintptr_t to) { | 1087 | void reopen_locked(std::uintptr_t from, std::uintptr_t to) { |
| 994 | for (std::uintptr_t at = from; at < to;) { | 1088 | for (std::uintptr_t at = from; at < to;) { |
| @@ -1042,6 +1136,8 @@ private: | |||
| 1042 | DWORD protect_error_ = 0; // a VirtualProtect refusal of this refresh(), logged after it | 1136 | DWORD protect_error_ = 0; // a VirtualProtect refusal of this refresh(), logged after it |
| 1043 | std::array<std::uint64_t, unsigned(Copy::count)> copy_bytes_{}; // refresh() only, likewise | 1137 | std::array<std::uint64_t, unsigned(Copy::count)> copy_bytes_{}; // refresh() only, likewise |
| 1044 | bool copy_aliased_ = true; // likewise | 1138 | bool copy_aliased_ = true; // likewise |
| 1139 | std::uint64_t gpu_bytes_ = 0; | ||
| 1140 | Pieces pieces_; // refresh() only, likewise | ||
| 1045 | std::uint64_t refresh_queries_ = 0; | 1141 | std::uint64_t refresh_queries_ = 0; |
| 1046 | std::uint64_t refresh_protects_ = 0; // VirtualProtect calls of the last refresh() | 1142 | std::uint64_t refresh_protects_ = 0; // VirtualProtect calls of the last refresh() |
| 1047 | bool refresh_walked_all_ = false; // the last refresh() queried every page (the title memory map changed) | 1143 | bool refresh_walked_all_ = false; // the last refresh() queried every page (the title memory map changed) |
| @@ -1075,6 +1171,49 @@ leonida::host_heap::vector<ShadowPages*>& shadow_pages_list() { | |||
| 1075 | // pages at every submission (title_page_aliases), so the guard to look for is the faulting address's own. When none | 1171 | // pages at every submission (title_page_aliases), so the guard to look for is the faulting address's own. When none |
| 1076 | // answers for it (each guard reopens only what it protected), xmem makes the page writable again if its window is | 1172 | // answers for it (each guard reopens only what it protected), xmem makes the page writable again if its window is |
| 1077 | // (kernel_writes' unguarder): a read-only page nobody reopens would fault that write, and every later one, for good. | 1173 | // (kernel_writes' unguarder): a read-only page nobody reopens would fault that write, and every later one, for good. |
| 1174 | // A title write into a committed, private, read-only page of title memory that no guard owns (the geometry watch, | ||
| 1175 | // the slot-133 shadows and the kernel-write unguarder all declined it): a guard of ours left behind, since the title | ||
| 1176 | // never writes memory it made read-only itself on the console. Said for the first 32 pages, with whether a shadow's | ||
| 1177 | // range still covers the page (its bookkeeping then calls the page unguarded). LEONIDA_STRAY_RO_HEAL=1: the page is | ||
| 1178 | // made writable again and the write retried, so the title goes on (a shadow may then miss that page's next writes: | ||
| 1179 | // the GPU copy may be stale for one frame). | ||
| 1180 | bool stray_read_only(EXCEPTION_POINTERS* info, std::uintptr_t address) { | ||
| 1181 | MEMORY_BASIC_INFORMATION m{}; | ||
| 1182 | if (!VirtualQuery(reinterpret_cast<const void*>(address), &m, sizeof m)) return false; | ||
| 1183 | if (m.State != MEM_COMMIT || m.Type != MEM_PRIVATE || (m.Protect & 0xff) != PAGE_READONLY) return false; | ||
| 1184 | std::uint64_t lo = 0, hi = 0; | ||
| 1185 | if (!leonida::title_va_aliases().title_memory(address, lo, hi)) return false; | ||
| 1186 | static const bool heal = [] { | ||
| 1187 | const char* v = std::getenv("LEONIDA_STRAY_RO_HEAL"); | ||
| 1188 | return v && *v == '1'; | ||
| 1189 | }(); | ||
| 1190 | unsigned covering = 0; | ||
| 1191 | AcquireSRWLockShared(&g_shadow_pages_lock); | ||
| 1192 | for (ShadowPages* pages : shadow_pages_list()) covering += pages->contains(address); | ||
| 1193 | ReleaseSRWLockShared(&g_shadow_pages_lock); | ||
| 1194 | static std::atomic<unsigned> told{0}, healed{0}; | ||
| 1195 | const std::uintptr_t page = address & ~std::uintptr_t(0xfff); | ||
| 1196 | bool ok = false; | ||
| 1197 | if (heal) { | ||
| 1198 | DWORD old = 0; | ||
| 1199 | ok = VirtualProtect(reinterpret_cast<void*>(page), 0x1000, (m.Protect & ~DWORD(0xff)) | PAGE_READWRITE, &old) != 0; | ||
| 1200 | if (ok) healed.fetch_add(1, std::memory_order_relaxed); | ||
| 1201 | } | ||
| 1202 | if (told.fetch_add(1, std::memory_order_relaxed) < 32) { | ||
| 1203 | const auto rip = info && info->ContextRecord ? info->ContextRecord->Rip : 0; | ||
| 1204 | std::fprintf(stderr, "[rt] d3d12: stray read-only title page 0x%llx (write to 0x%llx from rip 0x%llx; " | ||
| 1205 | "allocation 0x%llx, protect 0x%lx): no guard owns it, %u shadow range(s) cover it; %s " | ||
| 1206 | "(%u healed so far)\n", | ||
| 1207 | static_cast<unsigned long long>(page), static_cast<unsigned long long>(address), | ||
| 1208 | static_cast<unsigned long long>(rip), static_cast<unsigned long long>( | ||
| 1209 | reinterpret_cast<std::uintptr_t>(m.AllocationBase)), | ||
| 1210 | static_cast<unsigned long>(m.Protect), covering, | ||
| 1211 | !heal ? "left to fault (LEONIDA_STRAY_RO_HEAL=1 makes it writable)" : ok ? "made writable" : "could not be made writable", | ||
| 1212 | healed.load(std::memory_order_relaxed)); | ||
| 1213 | } | ||
| 1214 | return ok; | ||
| 1215 | } | ||
| 1216 | |||
| 1078 | LONG CALLBACK shadow_write_fault(EXCEPTION_POINTERS* info) { | 1217 | LONG CALLBACK shadow_write_fault(EXCEPTION_POINTERS* info) { |
| 1079 | const EXCEPTION_RECORD* record = info ? info->ExceptionRecord : nullptr; | 1218 | const EXCEPTION_RECORD* record = info ? info->ExceptionRecord : nullptr; |
| 1080 | if (!record || record->ExceptionCode != EXCEPTION_ACCESS_VIOLATION || record->NumberParameters < 2 || | 1219 | if (!record || record->ExceptionCode != EXCEPTION_ACCESS_VIOLATION || record->NumberParameters < 2 || |
| @@ -1097,6 +1236,7 @@ LONG CALLBACK shadow_write_fault(EXCEPTION_POINTERS* info) { | |||
| 1097 | if (!retry) | 1236 | if (!retry) |
| 1098 | if (const auto unguard = leonida::kernel_writes::state().unguarder.load(std::memory_order_acquire)) | 1237 | if (const auto unguard = leonida::kernel_writes::state().unguarder.load(std::memory_order_acquire)) |
| 1099 | retry = unguard(address, address + 1); | 1238 | retry = unguard(address, address + 1); |
| 1239 | if (!retry) retry = stray_read_only(info, address); | ||
| 1100 | return retry ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_CONTINUE_SEARCH; | 1240 | return retry ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_CONTINUE_SEARCH; |
| 1101 | } | 1241 | } |
| 1102 | 1242 | ||
| @@ -1114,6 +1254,15 @@ void open_shadow_pages(std::uintptr_t from, std::uintptr_t to) { | |||
| 1114 | ReleaseSRWLockShared(&g_shadow_pages_lock); | 1254 | ReleaseSRWLockShared(&g_shadow_pages_lock); |
| 1115 | } | 1255 | } |
| 1116 | 1256 | ||
| 1257 | // fsdraw's backing hook: whether a slot-133 shadow keeps the GPU copy of a title VA (LEONIDA_FSDRAW_PROBE only). | ||
| 1258 | const char* fsdraw_backing(std::uint64_t title_va) { | ||
| 1259 | unsigned covering = 0; | ||
| 1260 | AcquireSRWLockShared(&g_shadow_pages_lock); | ||
| 1261 | for (ShadowPages* pages : shadow_pages_list()) covering += pages->contains(std::uintptr_t(title_va)); | ||
| 1262 | ReleaseSRWLockShared(&g_shadow_pages_lock); | ||
| 1263 | return covering ? "a slot-133 shadow" : "an alias with no slot-133 shadow (window, geometry view or import)"; | ||
| 1264 | } | ||
| 1265 | |||
| 1117 | // Installs the handler once. false: it couldn't be, and shadows copy every page at every submission. | 1266 | // Installs the handler once. false: it couldn't be, and shadows copy every page at every submission. |
| 1118 | bool watch_shadow_writes() { | 1267 | bool watch_shadow_writes() { |
| 1119 | static const bool installed = [] { | 1268 | static const bool installed = [] { |
| @@ -1238,6 +1387,36 @@ std::filesystem::path pipeline_cache_session_path() { | |||
| 1238 | return path; | 1387 | return path; |
| 1239 | } | 1388 | } |
| 1240 | 1389 | ||
| 1390 | std::size_t pipeline_cache_save_limit(); | ||
| 1391 | |||
| 1392 | // LOCAL FIX (pipeline journal, pipeline_cache_journal.h): where each compute pipeline's own cache file goes, beside | ||
| 1393 | // the session file (so LEONIDA_PIPELINE_CACHE_DIR moves it too). Empty, and no journal, with LEONIDA_PIPELINE_JOURNAL=0 | ||
| 1394 | // or LEONIDA_PIPELINE_CACHE_BYTES=0. | ||
| 1395 | const leonida::pipeline_journal::Roots& pipeline_journal_roots() { | ||
| 1396 | static const auto roots = []() -> leonida::pipeline_journal::Roots { | ||
| 1397 | wchar_t value[2]{}; | ||
| 1398 | if (GetEnvironmentVariableW(L"LEONIDA_PIPELINE_JOURNAL", value, 2) == 1 && value[0] == L'0') | ||
| 1399 | return {}; | ||
| 1400 | if (!pipeline_cache_save_limit()) return {}; | ||
| 1401 | std::filesystem::path path = pipeline_cache_path(); | ||
| 1402 | if (!path.empty()) path.replace_filename(L"pipeline_cache.d"); | ||
| 1403 | std::wstring seed(32768, L'\0'); | ||
| 1404 | const DWORD n = GetEnvironmentVariableW(L"LEONIDA_PIPELINE_JOURNAL_SEED_DIR", seed.data(), | ||
| 1405 | static_cast<DWORD>(seed.size())); | ||
| 1406 | if (n >= seed.size()) return {}; | ||
| 1407 | seed.resize(n); | ||
| 1408 | auto result = leonida::pipeline_journal::resolve_roots(path, seed); | ||
| 1409 | if (!seed.empty() && result.writable.empty()) | ||
| 1410 | std::fprintf(stderr, "[rt] d3d12: invalid or overlapping compute journal directories; journal disabled\n"); | ||
| 1411 | return result; | ||
| 1412 | }(); | ||
| 1413 | return roots; | ||
| 1414 | } | ||
| 1415 | |||
| 1416 | const std::filesystem::path& pipeline_journal_dir() { | ||
| 1417 | return pipeline_journal_roots().writable; | ||
| 1418 | } | ||
| 1419 | |||
| 1241 | // LEONIDA_PIPELINE_CACHE_BYTES, in bytes; 0 turns the session file off. One line for a value that is not a number. | 1420 | // LEONIDA_PIPELINE_CACHE_BYTES, in bytes; 0 turns the session file off. One line for a value that is not a number. |
| 1242 | std::size_t pipeline_cache_save_limit() { | 1421 | std::size_t pipeline_cache_save_limit() { |
| 1243 | char text[32] = {}; | 1422 | char text[32] = {}; |
| @@ -1320,16 +1499,16 @@ VkPipelineCache create_seeded_pipeline_cache(PFN_vkCreatePipelineCache create_ca | |||
| 1320 | // and the session file cannot be handed over as one VkPipelineCacheCreateInfo -- Vulkan reads a single blob -- so the | 1499 | // and the session file cannot be handed over as one VkPipelineCacheCreateInfo -- Vulkan reads a single blob -- so the |
| 1321 | // session cache is created on its own and merged in. A missing, foreign or corrupt session file leaves the cache as | 1500 | // session cache is created on its own and merged in. A missing, foreign or corrupt session file leaves the cache as |
| 1322 | // it was, and so does a driver that does not expose vkMergePipelineCaches. | 1501 | // it was, and so does a driver that does not expose vkMergePipelineCaches. |
| 1323 | void merge_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache, | 1502 | bool merge_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache, |
| 1324 | const leonida::cached_pso::Identity& identity) { | 1503 | const leonida::cached_pso::Identity& identity) { |
| 1325 | if (!cache || !vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache || !vk.vkMergePipelineCaches) return; | 1504 | if (!cache || !vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache || !vk.vkMergePipelineCaches) return false; |
| 1326 | if (!pipeline_cache_save_limit()) return; // LEONIDA_PIPELINE_CACHE_BYTES=0 turns the session file off | 1505 | if (!pipeline_cache_save_limit()) return false; // LEONIDA_PIPELINE_CACHE_BYTES=0 turns the session file off |
| 1327 | const auto start = compile_us(); | 1506 | const auto start = compile_us(); |
| 1328 | const PipelineCacheSeed seed(pipeline_cache_session_path()); | 1507 | const PipelineCacheSeed seed(pipeline_cache_session_path()); |
| 1329 | if (!seed.data()) return; | 1508 | if (!seed.data()) return false; |
| 1330 | if (!seed.compatible(identity)) { | 1509 | if (!seed.compatible(identity)) { |
| 1331 | std::fprintf(stderr, "[rt] d3d12: pipeline_cache.session.bin does not match this Vulkan device\n"); | 1510 | std::fprintf(stderr, "[rt] d3d12: pipeline_cache.session.bin does not match this Vulkan device\n"); |
| 1332 | return; | 1511 | return false; |
| 1333 | } | 1512 | } |
| 1334 | const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, nullptr, 0, seed.size(), | 1513 | const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, nullptr, 0, seed.size(), |
| 1335 | seed.data()}; | 1514 | seed.data()}; |
| @@ -1337,7 +1516,7 @@ void merge_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDe | |||
| 1337 | VkPipelineCache session = VK_NULL_HANDLE; | 1516 | VkPipelineCache session = VK_NULL_HANDLE; |
| 1338 | if (vk.vkCreatePipelineCache(device, &create, nullptr, &session) != VK_SUCCESS) { | 1517 | if (vk.vkCreatePipelineCache(device, &create, nullptr, &session) != VK_SUCCESS) { |
| 1339 | std::fprintf(stderr, "[rt] d3d12: Vulkan declined pipeline_cache.session.bin\n"); | 1518 | std::fprintf(stderr, "[rt] d3d12: Vulkan declined pipeline_cache.session.bin\n"); |
| 1340 | return; | 1519 | return false; |
| 1341 | } | 1520 | } |
| 1342 | const auto created = compile_us(); | 1521 | const auto created = compile_us(); |
| 1343 | const VkResult result = vk.vkMergePipelineCaches(device, cache, 1, &session); | 1522 | const VkResult result = vk.vkMergePipelineCaches(device, cache, 1, &session); |
| @@ -1351,6 +1530,7 @@ void merge_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDe | |||
| 1351 | else | 1530 | else |
| 1352 | std::fprintf(stderr, "[rt] d3d12: vkMergePipelineCaches on pipeline_cache.session.bin returned %d; ignored\n", | 1531 | std::fprintf(stderr, "[rt] d3d12: vkMergePipelineCaches on pipeline_cache.session.bin returned %d; ignored\n", |
| 1353 | static_cast<int>(result)); | 1532 | static_cast<int>(result)); |
| 1533 | return result == VK_SUCCESS; | ||
| 1354 | } | 1534 | } |
| 1355 | 1535 | ||
| 1356 | // LEONIDA_SKIP_COMPUTE=<part of a name>[,<part>...]: compute programs whose library name contains one of the parts are | 1536 | // LEONIDA_SKIP_COMPUTE=<part of a name>[,<part>...]: compute programs whose library name contains one of the parts are |
| @@ -1402,14 +1582,39 @@ bool console_format_stand_ins() { | |||
| 1402 | return on; | 1582 | return on; |
| 1403 | } | 1583 | } |
| 1404 | 1584 | ||
| 1405 | // A driver's compiler needs hundreds of MiB for a very large module; several at once exhausted host memory. Compute modules | 1585 | // A driver's compiler needs hundreds of MiB for a very large module; several at once exhausted host memory. Large are |
| 1406 | // over 128 KiB compile one at a time (LEONIDA_SERIAL_BIG_COMPILES=0: as many as are asked for). | 1586 | // compute modules over 128 KiB and graphics pipelines of PipelineCompiles::large_spirv_bytes or more. They compile side by |
| 1407 | bool serial_big_compile(std::size_t spirv_bytes) { | 1587 | // side while their estimates fit the memory that is free (big_compile_gate). LEONIDA_SERIAL_BIG_COMPILES=1: one at a time, |
| 1408 | static const bool serial = [] { | 1588 | // as before there was a budget (graphics: one after another in each submission). 0: as many as are asked for. |
| 1589 | enum class BigCompiles { budget, serial, unlimited }; | ||
| 1590 | BigCompiles big_compiles() { | ||
| 1591 | static const BigCompiles mode = [] { | ||
| 1409 | wchar_t v[2]{}; | 1592 | wchar_t v[2]{}; |
| 1410 | return !(GetEnvironmentVariableW(L"LEONIDA_SERIAL_BIG_COMPILES", v, 2) == 1 && v[0] == L'0'); | 1593 | const DWORD n = GetEnvironmentVariableW(L"LEONIDA_SERIAL_BIG_COMPILES", v, 2); |
| 1594 | if (n == 0) return BigCompiles::budget; | ||
| 1595 | return n == 1 && v[0] == L'0' ? BigCompiles::unlimited : BigCompiles::serial; | ||
| 1596 | }(); | ||
| 1597 | return mode; | ||
| 1598 | } | ||
| 1599 | bool big_compute(std::size_t spirv_bytes) { return spirv_bytes > 128 * 1024; } | ||
| 1600 | |||
| 1601 | // Where large compiles wait for memory: one for the process, as the memory is the machine's. Never destroyed: static | ||
| 1602 | // destruction must not race the compile worker. | ||
| 1603 | leonida::LargeModuleGate& big_compile_gate() { | ||
| 1604 | static auto* const gate = [] { | ||
| 1605 | char text[32]{}; | ||
| 1606 | std::size_t length = 0; | ||
| 1607 | const bool present = getenv_s(&length, text, "LEONIDA_BIG_COMPILE_BUDGET_MB") == 0 && length > 1; | ||
| 1608 | const auto setting = leonida::large_compile_budget(present ? text : ""); | ||
| 1609 | if (!setting.valid) | ||
| 1610 | std::fprintf(stderr, "[rt] d3d12: LEONIDA_BIG_COMPILE_BUDGET_MB=%s is not a number; not used\n", text); | ||
| 1611 | auto budget = [fixed = setting.fixed] { return fixed ? *fixed : leonida::large_compile_budget_bytes(); }; | ||
| 1612 | std::fprintf(stderr, "[rt] d3d12: large pipelines compile side by side within %llu MiB (%s)\n", | ||
| 1613 | static_cast<unsigned long long>(budget() >> 20), | ||
| 1614 | setting.fixed ? "LEONIDA_BIG_COMPILE_BUDGET_MB" : "3/4 of the memory free now"); | ||
| 1615 | return new leonida::LargeModuleGate(std::move(budget)); | ||
| 1411 | }(); | 1616 | }(); |
| 1412 | return serial && spirv_bytes > 128 * 1024; | 1617 | return *gate; |
| 1413 | } | 1618 | } |
| 1414 | 1619 | ||
| 1415 | bool startup_cache_checkpoints_enabled() { | 1620 | bool startup_cache_checkpoints_enabled() { |
| @@ -1422,7 +1627,7 @@ bool startup_cache_checkpoints_enabled() { | |||
| 1422 | 1627 | ||
| 1423 | // Writes the session cache at a startup checkpoint or during device teardown. The size cap applies to either write. | 1628 | // Writes the session cache at a startup checkpoint or during device teardown. The size cap applies to either write. |
| 1424 | void save_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache, | 1629 | void save_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache, |
| 1425 | bool checkpoint = false) { | 1630 | bool checkpoint = false, const char* op = nullptr) { |
| 1426 | if (!cache || !vk.vkGetPipelineCacheData) return; | 1631 | if (!cache || !vk.vkGetPipelineCacheData) return; |
| 1427 | auto limit = pipeline_cache_save_limit(); | 1632 | auto limit = pipeline_cache_save_limit(); |
| 1428 | // The output is an opaque Vulkan blob. A prefix is not an incremental cache. | 1633 | // The output is an opaque Vulkan blob. A prefix is not an incremental cache. |
| @@ -1453,7 +1658,7 @@ void save_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDev | |||
| 1453 | written <= size && staging.publish(path, written); | 1658 | written <= size && staging.publish(path, written); |
| 1454 | if (trace_pipeline_compile()) | 1659 | if (trace_pipeline_compile()) |
| 1455 | std::fprintf(stderr, "[rt] pipeline-cache op=%s bytes=%zu query_us=%lld fill_us=%lld publish_us=%lld ok=%d result=%d\n", | 1660 | std::fprintf(stderr, "[rt] pipeline-cache op=%s bytes=%zu query_us=%lld fill_us=%lld publish_us=%lld ok=%d result=%d\n", |
| 1456 | checkpoint ? "checkpoint" : "teardown", written, queried-start, filled-queried, | 1661 | op ? op : checkpoint ? "checkpoint" : "teardown", written, queried-start, filled-queried, |
| 1457 | compile_us()-filled, int(ok), int(result)); | 1662 | compile_us()-filled, int(ok), int(result)); |
| 1458 | if (ok) std::fprintf(stderr, "[rt] d3d12: wrote %zu bytes to pipeline_cache.session.bin\n", written); | 1663 | if (ok) std::fprintf(stderr, "[rt] d3d12: wrote %zu bytes to pipeline_cache.session.bin\n", written); |
| 1459 | else std::fprintf(stderr, "[rt] d3d12: pipeline cache snapshot incomplete (%d); previous session retained\n", int(result)); | 1664 | else std::fprintf(stderr, "[rt] d3d12: pipeline cache snapshot incomplete (%d); previous session retained\n", int(result)); |
| @@ -1875,6 +2080,18 @@ public: | |||
| 1875 | if (va >= r.console_va && va - r.console_va < r.bytes) return r.shader_va + (va - r.console_va); | 2080 | if (va >= r.console_va && va - r.console_va < r.bytes) return r.shader_va + (va - r.console_va); |
| 1876 | return va; | 2081 | return va; |
| 1877 | } | 2082 | } |
| 2083 | // The console heap holding `va`: its console VA and size. False when no console heap with a copy holds it. | ||
| 2084 | bool range_of(std::uint64_t va, std::uint64_t& console_va, std::uint64_t& bytes) const { | ||
| 2085 | if (!count_.load(std::memory_order_acquire)) return false; | ||
| 2086 | std::shared_lock lock(mutex_); | ||
| 2087 | for (const Range& r : ranges_) | ||
| 2088 | if (va >= r.console_va && va - r.console_va < r.bytes) { | ||
| 2089 | console_va = r.console_va; | ||
| 2090 | bytes = r.bytes; | ||
| 2091 | return true; | ||
| 2092 | } | ||
| 2093 | return false; | ||
| 2094 | } | ||
| 1878 | 2095 | ||
| 1879 | private: | 2096 | private: |
| 1880 | struct Range { | 2097 | struct Range { |
| @@ -1904,13 +2121,69 @@ bool console_heap_shadow_enabled() { | |||
| 1904 | // What a T# the title wrote itself into a console descriptor heap came to (bind_title_image, after Resource). | 2121 | // What a T# the title wrote itself into a console descriptor heap came to (bind_title_image, after Resource). |
| 1905 | // not_tsharp: words with an image TYPE that do not decode as a T#: data, not a descriptor (the retail heap's last | 2122 | // not_tsharp: words with an image TYPE that do not decode as a T#: data, not a descriptor (the retail heap's last |
| 1906 | // 27 MiB are also the slot-133 pool, whose buffers sit there; T14 in ref/GAP-ANALYSIS-2.md). | 2123 | // 27 MiB are also the slot-133 pool, whose buffers sit there; T14 in ref/GAP-ANALYSIS-2.md). |
| 1907 | enum class TitleImage { known, bound, unknown, refused, not_tsharp }; | 2124 | // TitleImage is defined in d3d12_com.h. |
| 1908 | class Resource; | 2125 | class Resource; |
| 1909 | struct DeviceState; | 2126 | struct DeviceState; |
| 1910 | // `why`, when given, says what refused a T#: the first refusals are logged with their words (scan_console_slots). | 2127 | // `why`, when given, says what refused a T#: the first refusals are logged with their words (scan_console_slots). |
| 1911 | TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWords& words, const char** why = nullptr); | 2128 | TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWords& words, const char** why = nullptr); |
| 1912 | struct TitleTexture; // a texture the title keeps in its own memory (TitleTexture, after Resource) | 2129 | struct TitleTexture; // a texture the title keeps in its own memory (TitleTexture, after Resource) |
| 1913 | 2130 | ||
| 2131 | // The first refused T#s of each reason, with where they sit in the heap and their words, and counts of the | ||
| 2132 | // distinct slots refused overall and per reason (a slot is scanned again every pass over the heap). | ||
| 2133 | struct UnboundTsharpTracker { | ||
| 2134 | std::mutex mutex; | ||
| 2135 | std::set<std::size_t> total_slots; | ||
| 2136 | std::map<std::string, std::set<std::size_t>> slots_by_reason; | ||
| 2137 | std::map<std::string, std::uint64_t> counts_by_reason; | ||
| 2138 | std::map<std::string, unsigned> logged; | ||
| 2139 | std::uint64_t total_refusals = 0; | ||
| 2140 | |||
| 2141 | void note(std::uint64_t heap_va, std::size_t offset, const leonida::gfx10::ImageWords& words, const char* why) { | ||
| 2142 | std::lock_guard lock(mutex); | ||
| 2143 | const std::string reason = why ? why : "?"; | ||
| 2144 | ++total_refusals; | ||
| 2145 | ++counts_by_reason[reason]; | ||
| 2146 | if (total_slots.size() >= 262144) return; // enough to say how many | ||
| 2147 | const bool fresh_overall = total_slots.insert(offset).second; | ||
| 2148 | const bool fresh_reason = slots_by_reason[reason].insert(offset).second; | ||
| 2149 | unsigned& n = logged[reason]; | ||
| 2150 | if ((!fresh_overall && !fresh_reason) || n >= 6) return; | ||
| 2151 | ++n; | ||
| 2152 | std::fprintf(stderr, | ||
| 2153 | "[rt] d3d12: unbound T# in console heap 0x%llx at +0x%zx (%zu distinct slots so far, %zu for '%s'): %s: " | ||
| 2154 | "%08x %08x %08x %08x %08x %08x %08x %08x\n", | ||
| 2155 | static_cast<unsigned long long>(heap_va), offset, total_slots.size(), | ||
| 2156 | slots_by_reason[reason].size(), reason.c_str(), reason.c_str(), words[0], | ||
| 2157 | words[1], words[2], words[3], words[4], words[5], words[6], words[7]); | ||
| 2158 | } | ||
| 2159 | |||
| 2160 | UnboundTsharpStats stats() { | ||
| 2161 | std::lock_guard lock(mutex); | ||
| 2162 | UnboundTsharpStats s; | ||
| 2163 | s.total_distinct_slots = total_slots.size(); | ||
| 2164 | s.total_refusals = total_refusals; | ||
| 2165 | for (const auto& [reason, slots] : slots_by_reason) { | ||
| 2166 | s.by_reason[reason].distinct_slots = slots.size(); | ||
| 2167 | s.by_reason[reason].total_refusals = counts_by_reason[reason]; | ||
| 2168 | } | ||
| 2169 | return s; | ||
| 2170 | } | ||
| 2171 | |||
| 2172 | void reset() { | ||
| 2173 | std::lock_guard lock(mutex); | ||
| 2174 | total_slots.clear(); | ||
| 2175 | slots_by_reason.clear(); | ||
| 2176 | counts_by_reason.clear(); | ||
| 2177 | logged.clear(); | ||
| 2178 | total_refusals = 0; | ||
| 2179 | } | ||
| 2180 | }; | ||
| 2181 | |||
| 2182 | UnboundTsharpTracker& unbound_tsharp_tracker() { | ||
| 2183 | static UnboundTsharpTracker tracker; | ||
| 2184 | return tracker; | ||
| 2185 | } | ||
| 2186 | |||
| 1914 | // What a device's children need from it, kept apart from the COM class so children can hold a plain pointer. | 2187 | // What a device's children need from it, kept apart from the COM class so children can hold a plain pointer. |
| 1915 | class Resource; | 2188 | class Resource; |
| 1916 | struct DeviceState { | 2189 | struct DeviceState { |
| @@ -1962,6 +2235,18 @@ struct DeviceState { | |||
| 1962 | leonida::cached_pso::Identity pso_identity; // what GetCachedBlob records and CachedPSO is checked against | 2235 | leonida::cached_pso::Identity pso_identity; // what GetCachedBlob records and CachedPSO is checked against |
| 1963 | std::once_flag pipeline_cache_once; | 2236 | std::once_flag pipeline_cache_once; |
| 1964 | VkPipelineCache pipeline_cache_handle = VK_NULL_HANDLE; | 2237 | VkPipelineCache pipeline_cache_handle = VK_NULL_HANDLE; |
| 2238 | // The shared cache started from a file (the offline seed or an earlier session): a compute pipeline the journal | ||
| 2239 | // has no file for may still be in it (build_compute asks it first, when it can ask without a compile). | ||
| 2240 | bool pipeline_cache_seeded = false; | ||
| 2241 | std::atomic<unsigned> journal_hits{0}, journal_writes{0}, journal_shared_hits{0}; | ||
| 2242 | std::atomic<std::uint64_t> journal_bytes{0}; // on disk: counted at the cache's creation, then added to | ||
| 2243 | std::uint64_t journal_budget = leonida::pipeline_journal::default_budget; | ||
| 2244 | // Ask the shared cache first, with FAIL_ON_PIPELINE_COMPILE_REQUIRED, while the driver honours it. | ||
| 2245 | // LEONIDA_PIPELINE_JOURNAL_ASK_SHARED=0: never. | ||
| 2246 | std::atomic<bool> journal_ask_shared{[] { | ||
| 2247 | wchar_t value[2]{}; | ||
| 2248 | return !(GetEnvironmentVariableW(L"LEONIDA_PIPELINE_JOURNAL_ASK_SHARED", value, 2) == 1 && value[0] == L'0'); | ||
| 2249 | }()}; | ||
| 1965 | std::atomic<ULONGLONG> next_checkpoint{GetTickCount64() + 120000}; | 2250 | std::atomic<ULONGLONG> next_checkpoint{GetTickCount64() + 120000}; |
| 1966 | std::atomic<unsigned> active_compiles{0}; | 2251 | std::atomic<unsigned> active_compiles{0}; |
| 1967 | 2252 | ||
| @@ -1970,20 +2255,45 @@ struct DeviceState { | |||
| 1970 | const auto& vk = context->vk; | 2255 | const auto& vk = context->vk; |
| 1971 | if (!vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache) return; | 2256 | if (!vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache) return; |
| 1972 | if (pipeline_cache_save_limit()) clean_stale_cache_files(pipeline_cache_session_path()); | 2257 | if (pipeline_cache_save_limit()) clean_stale_cache_files(pipeline_cache_session_path()); |
| 1973 | pipeline_cache_handle = create_seeded_pipeline_cache(vk.vkCreatePipelineCache, info.device, pso_identity); | 2258 | // A build host (precompile, compile helper) journals every pipeline: no seed, no session file. |
| 2259 | if (!compile_helper::build_host) | ||
| 2260 | pipeline_cache_handle = create_seeded_pipeline_cache(vk.vkCreatePipelineCache, info.device, pso_identity); | ||
| 1974 | if (pipeline_cache_handle) { | 2261 | if (pipeline_cache_handle) { |
| 2262 | pipeline_cache_seeded = true; | ||
| 1975 | merge_session_pipeline_cache(vk, info.device, pipeline_cache_handle, pso_identity); | 2263 | merge_session_pipeline_cache(vk, info.device, pipeline_cache_handle, pso_identity); |
| 1976 | } else if (pipeline_cache_save_limit() && direct_session_cache()) { | 2264 | } else if (pipeline_cache_save_limit() && direct_session_cache() && !compile_helper::build_host) { |
| 1977 | // With no offline seed the session file can initialize the actual cache directly. | 2265 | // With no offline seed the session file can initialize the actual cache directly. |
| 1978 | pipeline_cache_handle = create_seeded_pipeline_cache(vk.vkCreatePipelineCache, info.device, pso_identity, true); | 2266 | pipeline_cache_handle = create_seeded_pipeline_cache(vk.vkCreatePipelineCache, info.device, pso_identity, true); |
| 2267 | pipeline_cache_seeded = pipeline_cache_handle != VK_NULL_HANDLE; | ||
| 1979 | } | 2268 | } |
| 1980 | if (!pipeline_cache_handle) { | 2269 | if (!pipeline_cache_handle) { |
| 1981 | const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; | 2270 | const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; |
| 1982 | if (vk.vkCreatePipelineCache(info.device, &create, nullptr, &pipeline_cache_handle) != VK_SUCCESS) | 2271 | if (vk.vkCreatePipelineCache(info.device, &create, nullptr, &pipeline_cache_handle) != VK_SUCCESS) |
| 1983 | pipeline_cache_handle = VK_NULL_HANDLE; | 2272 | pipeline_cache_handle = VK_NULL_HANDLE; |
| 1984 | else if (!direct_session_cache()) | 2273 | else if (!direct_session_cache() && !compile_helper::build_host) |
| 1985 | merge_session_pipeline_cache(vk, info.device, pipeline_cache_handle, pso_identity); | 2274 | pipeline_cache_seeded = merge_session_pipeline_cache(vk, info.device, pipeline_cache_handle, pso_identity); |
| 1986 | } | 2275 | } |
| 2276 | if (!pipeline_journal_dir().empty()) { | ||
| 2277 | char text[32] = {}; | ||
| 2278 | size_t length = 0; | ||
| 2279 | if (getenv_s(&length, text, "LEONIDA_PIPELINE_JOURNAL_BYTES") == 0 && length > 1) { | ||
| 2280 | const auto budget = leonida::pipeline_cache_store::parse_save_limit(text); | ||
| 2281 | if (budget.valid) journal_budget = budget.bytes; | ||
| 2282 | } | ||
| 2283 | // Old staging files out, and the least recently used files when over the budget: translator | ||
| 2284 | // regenerations leave files no build names any more. | ||
| 2285 | const auto tidy = leonida::pipeline_journal::tidy(pipeline_journal_dir(), journal_budget); | ||
| 2286 | journal_bytes = tidy.bytes; | ||
| 2287 | if (tidy.evicted || tidy.swept) | ||
| 2288 | std::fprintf(stderr, "[rt] d3d12: pipeline journal: removed %zu least recently used file(s) over " | ||
| 2289 | "the %llu-byte budget and %zu stale staging file(s); %zu file(s), %llu bytes " | ||
| 2290 | "left\n", tidy.evicted, static_cast<unsigned long long>(journal_budget), | ||
| 2291 | tidy.swept, tidy.entries, static_cast<unsigned long long>(tidy.bytes)); | ||
| 2292 | } | ||
| 2293 | if (!pipeline_journal_dir().empty()) | ||
| 2294 | std::fprintf(stderr, "[rt] d3d12: compute pipelines are journaled one file each in %ls\n", | ||
| 2295 | pipeline_journal_dir().c_str()); | ||
| 2296 | if (compile_helper::enabled() && !pipeline_journal_dir().empty()) compile_helper::Client::instance().prestart(); | ||
| 1987 | }); | 2297 | }); |
| 1988 | // Without EXTERNALLY_SYNCHRONIZED_BIT the driver synchronizes concurrent pipeline creation using this cache. | 2298 | // Without EXTERNALLY_SYNCHRONIZED_BIT the driver synchronizes concurrent pipeline creation using this cache. |
| 1989 | return pipeline_cache_handle; | 2299 | return pipeline_cache_handle; |
| @@ -2059,6 +2369,7 @@ struct DeviceState { | |||
| 2059 | std::uint64_t shadow_asks = 0; // GetWriteWatch calls, likewise | 2369 | std::uint64_t shadow_asks = 0; // GetWriteWatch calls, likewise |
| 2060 | std::uint64_t shadow_written = 0; // write-watched pages they found written, likewise | 2370 | std::uint64_t shadow_written = 0; // write-watched pages they found written, likewise |
| 2061 | std::array<std::uint64_t, unsigned(ShadowPages::Copy::count)> shadow_copy_bytes{}; // by cause, likewise | 2371 | std::array<std::uint64_t, unsigned(ShadowPages::Copy::count)> shadow_copy_bytes{}; // by cause, likewise |
| 2372 | ShadowPages::Pieces shadow_pieces; // summed over the refreshes since the last log line | ||
| 2062 | std::chrono::steady_clock::time_point shadow_alias_time{}; // the last refresh that copied aliased pages | 2373 | std::chrono::steady_clock::time_point shadow_alias_time{}; // the last refresh that copied aliased pages |
| 2063 | double shadow_ms = 0; // spent since the last log line | 2374 | double shadow_ms = 0; // spent since the last log line |
| 2064 | double shadow_max_ms = 0; // the longest refresh since the last log line | 2375 | double shadow_max_ms = 0; // the longest refresh since the last log line |
| @@ -2146,6 +2457,14 @@ struct DeviceState { | |||
| 2146 | shadow_asks += s->refresh_asks(); | 2457 | shadow_asks += s->refresh_asks(); |
| 2147 | shadow_written += s->refresh_written(); | 2458 | shadow_written += s->refresh_written(); |
| 2148 | for (unsigned k = 0; k < shadow_copy_bytes.size(); ++k) shadow_copy_bytes[k] += s->copy_bytes()[k]; | 2459 | for (unsigned k = 0; k < shadow_copy_bytes.size(); ++k) shadow_copy_bytes[k] += s->copy_bytes()[k]; |
| 2460 | const ShadowPages::Pieces& p = s->pieces(); | ||
| 2461 | shadow_pieces.pieces += p.pieces; | ||
| 2462 | shadow_pieces.short_pieces += p.short_pieces; | ||
| 2463 | shadow_pieces.joinable += p.joinable; | ||
| 2464 | shadow_pieces.calls += p.calls; | ||
| 2465 | shadow_pieces.gpu_calls += p.gpu_calls; | ||
| 2466 | shadow_pieces.walk_ms += p.walk_ms; | ||
| 2467 | shadow_pieces.copy_ms += p.copy_ms; | ||
| 2149 | } | 2468 | } |
| 2150 | const auto now = clock::now(); | 2469 | const auto now = clock::now(); |
| 2151 | const double ms = std::chrono::duration<double, std::milli>(now - start).count(); | 2470 | const double ms = std::chrono::duration<double, std::milli>(now - start).count(); |
| @@ -2181,6 +2500,15 @@ struct DeviceState { | |||
| 2181 | kib(ShadowPages::Copy::guarded), kib(ShadowPages::Copy::unguarded), kib(ShadowPages::Copy::aliased), | 2500 | kib(ShadowPages::Copy::guarded), kib(ShadowPages::Copy::unguarded), kib(ShadowPages::Copy::aliased), |
| 2182 | kib(ShadowPages::Copy::pinned), kib(ShadowPages::Copy::read_only), | 2501 | kib(ShadowPages::Copy::pinned), kib(ShadowPages::Copy::read_only), |
| 2183 | kib(ShadowPages::Copy::copy_on_write), kib(ShadowPages::Copy::write_watched)); | 2502 | kib(ShadowPages::Copy::copy_on_write), kib(ShadowPages::Copy::write_watched)); |
| 2503 | std::fprintf(stderr, | ||
| 2504 | "[rt] d3d12: slot-133 shadow copies as pieces, a refresh: %.1f pieces (%.1f under 4 KiB, %.1f going on " | ||
| 2505 | "where the one before ended), %.1f copy calls (%.1f offered to the GPU); walk %.3f ms, copies %.3f " | ||
| 2506 | "ms\n", | ||
| 2507 | double(shadow_pieces.pieces) / count, double(shadow_pieces.short_pieces) / count, | ||
| 2508 | double(shadow_pieces.joinable) / count, double(shadow_pieces.calls) / count, | ||
| 2509 | double(shadow_pieces.gpu_calls) / count, shadow_pieces.walk_ms / count, | ||
| 2510 | shadow_pieces.copy_ms / count); | ||
| 2511 | shadow_pieces = {}; | ||
| 2184 | shadow_copy_bytes = {}; | 2512 | shadow_copy_bytes = {}; |
| 2185 | shadow_logged = shadow_submissions; | 2513 | shadow_logged = shadow_submissions; |
| 2186 | shadow_log_time = now; | 2514 | shadow_log_time = now; |
| @@ -2196,6 +2524,9 @@ struct DeviceState { | |||
| 2196 | // defined after TitleTexture. | 2524 | // defined after TitleTexture. |
| 2197 | std::mutex title_texture_mutex; | 2525 | std::mutex title_texture_mutex; |
| 2198 | std::map<std::uint64_t, std::shared_ptr<TitleTexture>> title_textures; | 2526 | std::map<std::uint64_t, std::shared_ptr<TitleTexture>> title_textures; |
| 2527 | leonida::TitleTextureRangeIndex texture_ranges; | ||
| 2528 | std::map<std::uint64_t, std::shared_ptr<TitleTexture>> mapped_title_textures; | ||
| 2529 | void index_texture(const TitleTexture& t); | ||
| 2199 | void title_texture_mapped(const void* resource, std::uint64_t address); | 2530 | void title_texture_mapped(const void* resource, std::uint64_t address); |
| 2200 | void title_texture_unmapped(const void* resource, std::uint64_t address); // the title wrote texels | 2531 | void title_texture_unmapped(const void* resource, std::uint64_t address); // the title wrote texels |
| 2201 | void title_texture_gone(const void* resource, std::uint64_t address); | 2532 | void title_texture_gone(const void* resource, std::uint64_t address); |
| @@ -2226,6 +2557,7 @@ struct DeviceState { | |||
| 2226 | static constexpr std::uint64_t kPoolExtentMax = 1ull << 20; | 2557 | static constexpr std::uint64_t kPoolExtentMax = 1ull << 20; |
| 2227 | std::mutex title_window_mutex; // taken before shadow_mutex, never under it | 2558 | std::mutex title_window_mutex; // taken before shadow_mutex, never under it |
| 2228 | rt::d3d12::TitleBufferWindows external_windows; | 2559 | rt::d3d12::TitleBufferWindows external_windows; |
| 2560 | std::atomic<bool> external_window_made{false}; // a window lies outside the arena: device_reachable looks there | ||
| 2229 | std::vector<TitleWindow> title_windows; | 2561 | std::vector<TitleWindow> title_windows; |
| 2230 | std::atomic<std::size_t> title_window_count{0}; // title_windows.size(), read without the mutex | 2562 | std::atomic<std::size_t> title_window_count{0}; // title_windows.size(), read without the mutex |
| 2231 | std::uint64_t title_window_bytes = 0; | 2563 | std::uint64_t title_window_bytes = 0; |
| @@ -2245,6 +2577,45 @@ struct DeviceState { | |||
| 2245 | std::uint64_t unbacked_requests = 0; // title addresses no backing could be made for (zero-size views) | 2577 | std::uint64_t unbacked_requests = 0; // title addresses no backing could be made for (zero-size views) |
| 2246 | 2578 | ||
| 2247 | rt::d3d12::GeometryViews geometry; | 2579 | rt::d3d12::GeometryViews geometry; |
| 2580 | // A retired geometry view: its alias ranges go, and so does every answer made through it without one | ||
| 2581 | // (vsharp_address and placed views take geometry_va() directly), by its CPU and its GPU-twin address. | ||
| 2582 | static void forget_geometry_alias(std::uintptr_t source, std::size_t size, VkDeviceSize va) { | ||
| 2583 | auto& aliases = leonida::title_va_aliases(); | ||
| 2584 | aliases.remove(source, va); | ||
| 2585 | aliases.forget_copy(source, size, va); | ||
| 2586 | if (const auto twin = leonida::title_gpu_views::other_view(source)) { | ||
| 2587 | aliases.remove(twin, va); | ||
| 2588 | aliases.forget_copy(twin, size, va); | ||
| 2589 | } | ||
| 2590 | } | ||
| 2591 | // Before the submission's console heap slots are translated (refresh_shadows): a view retired here is answered | ||
| 2592 | // by nothing from now on. It is freed only after every replay in progress has recorded its submissions and those | ||
| 2593 | // have completed (GeometryViews::kAfterExecutes, execute_end): this submission's own lists, recorded before, and | ||
| 2594 | // another queue's replay that translated its slots before this retirement may still name it. A ticket read here | ||
| 2595 | // would be one short of this submission, which records its own only after before_execute_ (and with an idle GPU | ||
| 2596 | // the view would be reaped in this very call). | ||
| 2597 | void drain_geometry_releases() { | ||
| 2598 | if (!context || !geometry.has_pending_reclaim()) return; | ||
| 2599 | const std::uint64_t completed_ticket = geometry.has_retired() ? context->completed_retire_ticket() : 0; | ||
| 2600 | geometry.drain_released(*this, rt::d3d12::GeometryViews::kAfterExecutes, completed_ticket, | ||
| 2601 | forget_geometry_alias); | ||
| 2602 | } | ||
| 2603 | // ExecuteCommandLists replays in progress, for GeometryViews::kAfterExecutes (see drain_geometry_releases). | ||
| 2604 | static std::vector<std::uint64_t>& geometry_execute_serials() { | ||
| 2605 | thread_local std::vector<std::uint64_t> serials; | ||
| 2606 | return serials; | ||
| 2607 | } | ||
| 2608 | void geometry_execute_begin() { | ||
| 2609 | if (!geometry.cap()) return; | ||
| 2610 | geometry_execute_serials().push_back(geometry.execute_begin()); | ||
| 2611 | } | ||
| 2612 | void geometry_execute_end() { | ||
| 2613 | auto& serials = geometry_execute_serials(); | ||
| 2614 | if (!geometry.cap() || serials.empty()) return; | ||
| 2615 | const std::uint64_t serial = serials.back(); | ||
| 2616 | serials.pop_back(); | ||
| 2617 | geometry.execute_end(serial, [this] { return context->submitted_retire_ticket(); }); | ||
| 2618 | } | ||
| 2248 | static rt::d3d12::GeometryCopy copy_geometry(std::uint8_t* to, const std::uint8_t* from, std::size_t size) { | 2619 | static rt::d3d12::GeometryCopy copy_geometry(std::uint8_t* to, const std::uint8_t* from, std::size_t size) { |
| 2249 | using Result = rt::d3d12::GeometryCopy; | 2620 | using Result = rt::d3d12::GeometryCopy; |
| 2250 | if (!leonida::texture_memory_readable(reinterpret_cast<std::uintptr_t>(from), size)) return Result::unreadable; | 2621 | if (!leonida::texture_memory_readable(reinterpret_cast<std::uintptr_t>(from), size)) return Result::unreadable; |
| @@ -2334,7 +2705,9 @@ struct DeviceState { | |||
| 2334 | std::uint8_t* mapped{}; | 2705 | std::uint8_t* mapped{}; |
| 2335 | if (arena_allocate(size, kTitleWindowAlign, offset, arena_buffer)) { | 2706 | if (arena_allocate(size, kTitleWindowAlign, offset, arena_buffer)) { |
| 2336 | mapped = arena.mapped + offset; | 2707 | mapped = arena.mapped + offset; |
| 2337 | } else if (!stream_windows() || !external_windows.allocate(*this, size, offset, mapped)) { | 2708 | } else if (stream_windows() && external_windows.allocate(*this, size, offset, mapped)) { |
| 2709 | external_window_made.store(true, std::memory_order_release); | ||
| 2710 | } else { | ||
| 2338 | ++title_window_refusals; | 2711 | ++title_window_refusals; |
| 2339 | log_once("GPU address arena full (raise LEONIDA_ARENA_MB): title memory has no window; window KiB:", | 2712 | log_once("GPU address arena full (raise LEONIDA_ARENA_MB): title memory has no window; window KiB:", |
| 2340 | int(std::min<std::uint64_t>(size >> 10, INT_MAX))); | 2713 | int(std::min<std::uint64_t>(size >> 10, INT_MAX))); |
| @@ -2411,8 +2784,10 @@ struct DeviceState { | |||
| 2411 | if (aliases.shader_va(extent.start) == extent.start) aliases.add(extent.start, extent.size, shader); | 2784 | if (aliases.shader_va(extent.start) == extent.start) aliases.add(extent.start, extent.size, shader); |
| 2412 | } else { | 2785 | } else { |
| 2413 | bool geometry_copy = false; | 2786 | bool geometry_copy = false; |
| 2414 | if (geometry.cap() && watch_shadow_writes() && !context->knows_buffer_va(extent.start, extent.size)) | 2787 | if (geometry.cap() && watch_shadow_writes() && !context->knows_buffer_va(extent.start, extent.size)) { |
| 2415 | shader = geometry.resolve(*this, extent.start, extent.size, copy_geometry), geometry_copy = shader != 0; | 2788 | shader = geometry.resolve(*this, extent.start, extent.size, copy_geometry); |
| 2789 | geometry_copy = shader != 0; | ||
| 2790 | } | ||
| 2416 | if (!shader) shader = make_title_window(extent.start, extent.size); | 2791 | if (!shader) shader = make_title_window(extent.start, extent.size); |
| 2417 | if (!shader) { | 2792 | if (!shader) { |
| 2418 | out = 0; | 2793 | out = 0; |
| @@ -2437,8 +2812,52 @@ struct DeviceState { | |||
| 2437 | return true; | 2812 | return true; |
| 2438 | } | 2813 | } |
| 2439 | 2814 | ||
| 2815 | // Whether a shader that forms heap_base + `va` reaches memory of the device's: the arena, a registered buffer (an | ||
| 2816 | // upload or readback heap, an import, by its VA), a geometry copy, a title window outside the arena, or the copy | ||
| 2817 | // of any title range (an address the layer already wrote for the title). A raw title address is none of these. | ||
| 2818 | // A V#'s base is 48 bits and translated shaders sign-extend it (Gen.host_addr), so a wrapped one is also tried | ||
| 2819 | // with its upper bits set. `buffers_checked`: the caller already asked the buffer index about `va` itself (the | ||
| 2820 | // resolver does). Cheapest first; title_window_mutex only once a window outside the arena exists, and never | ||
| 2821 | // called with it held. | ||
| 2822 | bool device_reachable(std::uint64_t va, bool buffers_checked = false) { | ||
| 2823 | if (va < arena.size) return true; | ||
| 2824 | const bool wrapped = va < (1ull << 48) && (va >> 47); | ||
| 2825 | const std::uint64_t candidates[2] = {va, wrapped ? va | ~((1ull << 48) - 1) : va}; | ||
| 2826 | auto& aliases = leonida::title_va_aliases(); | ||
| 2827 | for (int i = 0; i < (wrapped ? 2 : 1); ++i) { | ||
| 2828 | const std::uint64_t at = candidates[i]; | ||
| 2829 | if (aliases.shader_side(at)) return true; | ||
| 2830 | std::uint64_t host = 0, room = 0; | ||
| 2831 | if (geometry.cap() && geometry.lookup(arena.address + at, host, room)) return true; | ||
| 2832 | if (external_window_made.load(std::memory_order_acquire)) { | ||
| 2833 | std::lock_guard lock(title_window_mutex); | ||
| 2834 | if (external_windows.lookup(arena.address + at, host, room)) return true; | ||
| 2835 | } | ||
| 2836 | if (context && !(i == 0 && buffers_checked) && context->knows_buffer_va(at)) return true; | ||
| 2837 | } | ||
| 2838 | return false; | ||
| 2839 | } | ||
| 2840 | |||
| 2841 | // One line per kind (and then at 2, 4, 8... of it): an address outside the title's memory that names nothing of | ||
| 2842 | // the device's, written as a zero-size view (a V#) or 0 (a root view) instead of a raw address. | ||
| 2843 | void note_unmapped(std::uint64_t va, std::uint64_t bytes) { | ||
| 2844 | static std::atomic<std::uint64_t> seen{0}; | ||
| 2845 | const std::uint64_t n = seen.fetch_add(1, std::memory_order_relaxed) + 1; | ||
| 2846 | if (n != 1 && (n & (n - 1))) return; | ||
| 2847 | std::fprintf(stderr, | ||
| 2848 | "[rt] d3d12: address 0x%llx (%llu bytes) is neither the title's memory nor any allocation of the " | ||
| 2849 | "device's: the view is written with no base and no records (loads 0, stores dropped); %llu so " | ||
| 2850 | "far\n", | ||
| 2851 | static_cast<unsigned long long>(va), static_cast<unsigned long long>(bytes), | ||
| 2852 | static_cast<unsigned long long>(n)); | ||
| 2853 | } | ||
| 2854 | |||
| 2440 | // Called through title_va_aliases().resolve for an address with no copy yet. False: not the title's memory. | 2855 | // Called through title_va_aliases().resolve for an address with no copy yet. False: not the title's memory. |
| 2441 | // True: it is, and `out` is its shader VA, 0 when no backing could be made (never the raw address). | 2856 | // True: it is, and `out` is its shader VA, 0 when no backing could be made (never the raw address). An address |
| 2857 | // past the arena that is not the title's memory either gets 0 too when nothing of the device's is there | ||
| 2858 | // (device_reachable): heap_base + such an address is no allocation, and a shader that reads or writes through it | ||
| 2859 | // takes an MMU fault (measured with Aftermath at world start: compute reads ~4 GiB and ~10 GiB above anything | ||
| 2860 | // allocated). | ||
| 2442 | bool resolve_title_memory(std::uint64_t va, std::uint64_t bytes, std::uint64_t& out) { | 2861 | bool resolve_title_memory(std::uint64_t va, std::uint64_t bytes, std::uint64_t& out) { |
| 2443 | out = va; | 2862 | out = va; |
| 2444 | if (!arena.mapped || !context) return false; | 2863 | if (!arena.mapped || !context) return false; |
| @@ -2781,10 +3200,6 @@ struct DeviceState { | |||
| 2781 | --it; | 3200 | --it; |
| 2782 | return addr < it->second && (addr-it->first) % kDescriptorSize == 0; | 3201 | return addr < it->second && (addr-it->first) % kDescriptorSize == 0; |
| 2783 | } | 3202 | } |
| 2784 | // The shader-visible CBV/SRV/UAV heaps (arena offset -> end), for the scan of bound tables before a submission. | ||
| 2785 | std::mutex cbv_heap_mutex; | ||
| 2786 | std::map<VkDeviceSize, VkDeviceSize> cbv_heaps; | ||
| 2787 | |||
| 2788 | // The buffer V#s of the table at `table_va` whose base is in the title's own memory get the address of a copy, | 3203 | // The buffer V#s of the table at `table_va` whose base is in the title's own memory get the address of a copy, |
| 2789 | // written in place: the title wrote them itself (or copied them), so no Create*View saw them. Images (T#s) and | 3204 | // written in place: the title wrote them itself (or copied them), so no Create*View saw them. Images (T#s) and |
| 2790 | // null slots are skipped; so is a V# already in the arena, so a rewritten one is left alone next time. | 3205 | // null slots are skipped; so is a V# already in the arena, so a rewritten one is left alone next time. |
| @@ -2807,20 +3222,99 @@ struct DeviceState { | |||
| 2807 | // Slots the title wrote in its own backing of this heap, if it gave the heap one. | 3222 | // Slots the title wrote in its own backing of this heap, if it gave the heap one. |
| 2808 | aliases.pull_descriptors(arena.mapped + table_va, std::size_t(end - table_va)); | 3223 | aliases.pull_descriptors(arena.mapped + table_va, std::size_t(end - table_va)); |
| 2809 | if (sampler) return; // S# words describe sampling state. They have no buffer address to translate. | 3224 | if (sampler) return; // S# words describe sampling state. They have no buffer address to translate. |
| 2810 | // Each slot's V# and the counter V# in its second half, as a console heap's GPU copy (fix_vsharp): a base in | 3225 | for (VkDeviceSize at = table_va; at + 16 <= end; at += kDescriptorSize) { |
| 2811 | // the title's memory is rebased, one nothing backs becomes zero-size instead of a GPU fault at heap_base plus | 3226 | auto* words = reinterpret_cast<std::uint32_t*>(arena.mapped + at); |
| 2812 | // that address. | 3227 | if (words[3] >> 30) continue; |
| 2813 | for (VkDeviceSize at = table_va; at + kDescriptorSize <= end; at += kDescriptorSize) { | 3228 | if (retry_nulled_table_slot(at, words, aliases)) continue; |
| 2814 | auto* const w = reinterpret_cast<std::uint32_t*>(arena.mapped + at); | 3229 | const std::uint32_t original[3] = {words[0], words[1], words[2]}; |
| 2815 | fix_vsharp(w, VsharpPath::table); | 3230 | bool unbacked = false; |
| 2816 | fix_vsharp(w + 4, VsharpPath::table); | 3231 | if (!rebase_title_vsharp(words, aliases, true, &unbacked) && unbacked) { |
| 2817 | } | 3232 | // Title memory no window or geometry copy could back, or an address nothing backs: no base and no |
| 3233 | // records, so a shader's load returns 0 and its store is dropped rather than written at heap_base + | ||
| 3234 | // the raw address. The words are kept to look at again (retry_nulled_table_slot). The null form is the | ||
| 3235 | // one a zero-size view has (base 0, no records): base 0 is the arena's zero page, which reads 0. | ||
| 3236 | words[0] = 0; | ||
| 3237 | words[1] &= 0xFFFF0000u; | ||
| 3238 | words[2] = 0; | ||
| 3239 | note_nulled_table_slot(at, original, words[3]); | ||
| 3240 | } | ||
| 3241 | // The slot's second V# is a UAV counter (raw, 4 bytes, in the descriptor's upper 16 bytes): a store to it | ||
| 3242 | // at heap_base + a raw title address loses the device just as one through the buffer V# does. Nothing | ||
| 3243 | // retries it - a counter whose backing arrives later stays with no records until the title rewrites it. | ||
| 3244 | if (at + kDescriptorSize <= end) fix_vsharp(words + 4, VsharpPath::table); | ||
| 3245 | } | ||
| 3246 | } | ||
| 3247 | |||
| 3248 | // The table slots scan_title_table wrote null in place (the layer's heaps have no separate GPU copy), by arena | ||
| 3249 | // offset, with the words the title gave them: at each later scan that still finds the null form there, the | ||
| 3250 | // original is tried again, kNulledTableTries times at most, so a V# whose buffer or copy comes after the | ||
| 3251 | // descriptor gets its base back. A slot the title rewrote meanwhile is forgotten and scanned as new. At most | ||
| 3252 | // kNulledTableSlots are kept (past that a nulled slot stays null until rewritten). The null form is base 0 with no | ||
| 3253 | // records, as a zero-size view has; a slot holding it is recognised by the rest of the words the title gave it, | ||
| 3254 | // so a view Create*View wrote (also base 0) is only retried when its other words match a nulled slot's exactly. | ||
| 3255 | struct NulledTableSlot { | ||
| 3256 | std::uint32_t words[4]; | ||
| 3257 | std::uint32_t tries; | ||
| 3258 | }; | ||
| 3259 | static constexpr std::size_t kNulledTableSlots = 65536; | ||
| 3260 | static constexpr std::uint32_t kNulledTableTries = 16; | ||
| 3261 | std::mutex nulled_table_mutex; | ||
| 3262 | std::unordered_map<VkDeviceSize, NulledTableSlot> nulled_table_slots; | ||
| 3263 | std::atomic<std::size_t> nulled_table_count{0}; | ||
| 3264 | |||
| 3265 | void note_nulled_table_slot(VkDeviceSize at, const std::uint32_t (&original)[3], std::uint32_t word3) { | ||
| 3266 | std::lock_guard lock(nulled_table_mutex); | ||
| 3267 | if (nulled_table_slots.size() >= kNulledTableSlots) return; | ||
| 3268 | nulled_table_slots[at] = {{original[0], original[1], original[2], word3}, 0}; | ||
| 3269 | nulled_table_count.store(nulled_table_slots.size(), std::memory_order_relaxed); | ||
| 3270 | } | ||
| 3271 | |||
| 3272 | // A heap's arena range is released: what was noted in it is no longer anybody's slot. | ||
| 3273 | void forget_nulled_table_slots(VkDeviceSize offset, VkDeviceSize bytes) { | ||
| 3274 | if (!nulled_table_count.load(std::memory_order_relaxed)) return; | ||
| 3275 | std::lock_guard lock(nulled_table_mutex); | ||
| 3276 | std::erase_if(nulled_table_slots, [&](const auto& e) { return e.first - offset < bytes; }); | ||
| 3277 | nulled_table_count.store(nulled_table_slots.size(), std::memory_order_relaxed); | ||
| 3278 | } | ||
| 3279 | |||
| 3280 | // True when `at` is a slot this scan nulled earlier and still holds that null form: tried again (and restored | ||
| 3281 | // when its address is backed now), so the caller moves on. | ||
| 3282 | bool retry_nulled_table_slot(VkDeviceSize at, std::uint32_t* words, leonida::TitleVaAliases& aliases) { | ||
| 3283 | if (!nulled_table_count.load(std::memory_order_relaxed)) return false; | ||
| 3284 | NulledTableSlot entry{}; | ||
| 3285 | { | ||
| 3286 | std::lock_guard lock(nulled_table_mutex); | ||
| 3287 | const auto it = nulled_table_slots.find(at); | ||
| 3288 | if (it == nulled_table_slots.end()) return false; | ||
| 3289 | entry = it->second; | ||
| 3290 | // entry.words[2] != 0: a view the title wrote with zero records is not one this scan nulled. | ||
| 3291 | const bool still_null = words[0] == 0 && words[2] == 0 && entry.words[2] != 0 && | ||
| 3292 | words[3] == entry.words[3] && words[1] == (entry.words[1] & 0xFFFF0000u); | ||
| 3293 | if (!still_null || ++it->second.tries > kNulledTableTries) { | ||
| 3294 | nulled_table_slots.erase(it); | ||
| 3295 | nulled_table_count.store(nulled_table_slots.size(), std::memory_order_relaxed); | ||
| 3296 | return still_null; // rewritten by the title: scanned as new; out of tries: left null | ||
| 3297 | } | ||
| 3298 | } | ||
| 3299 | std::uint32_t retry[4] = {entry.words[0], entry.words[1], entry.words[2], words[3]}; | ||
| 3300 | bool unbacked = false; | ||
| 3301 | const bool rebased = rebase_title_vsharp(retry, aliases, true, &unbacked); | ||
| 3302 | if (!rebased && unbacked) return true; // still nothing behind it: stays null, looked at again next scan | ||
| 3303 | words[0] = retry[0]; | ||
| 3304 | words[1] = retry[1]; | ||
| 3305 | words[2] = retry[2]; | ||
| 3306 | std::lock_guard lock(nulled_table_mutex); | ||
| 3307 | nulled_table_slots.erase(at); | ||
| 3308 | nulled_table_count.store(nulled_table_slots.size(), std::memory_order_relaxed); | ||
| 3309 | return true; | ||
| 2818 | } | 3310 | } |
| 2819 | 3311 | ||
| 2820 | // A buffer V# (its first four dwords at `w`) whose base is in the title's own memory gets the console VA of a GPU | 3312 | // A buffer V# (its first four dwords at `w`) whose base is in the title's own memory gets the console VA of a GPU |
| 2821 | // copy of that memory, in place. False for anything else: a null slot, an image, a V# already in the arena, or | 3313 | // copy of that memory, in place. False for anything else: a null slot, an image, a V# already in the arena, or |
| 2822 | // memory no copy could be made of. | 3314 | // memory no copy could be made of. `unbacked` (when given) is set for the last case: title memory with neither a |
| 2823 | bool rebase_title_vsharp(std::uint32_t* w, leonida::TitleVaAliases& aliases, bool make_window = true) { | 3315 | // window nor a geometry copy behind it, which the caller writes as a zero-size range. |
| 3316 | bool rebase_title_vsharp(std::uint32_t* w, leonida::TitleVaAliases& aliases, bool make_window = true, | ||
| 3317 | bool* unbacked = nullptr) { | ||
| 2824 | const std::uint32_t w0 = w[0], w1 = w[1], w2 = w[2], w3 = w[3]; | 3318 | const std::uint32_t w0 = w[0], w1 = w[1], w2 = w[2], w3 = w[3]; |
| 2825 | if (!(w0 | w1 | w2 | w3) || (w3 >> 30)) return false; // null, or not a buffer V# (TYPE, dword 3 bits 30-31) | 3319 | if (!(w0 | w1 | w2 | w3) || (w3 >> 30)) return false; // null, or not a buffer V# (TYPE, dword 3 bits 30-31) |
| 2826 | const std::uint64_t base = std::uint64_t(w0) | (std::uint64_t(w1 & 0xFFFFu) << 32); | 3320 | const std::uint64_t base = std::uint64_t(w0) | (std::uint64_t(w1 & 0xFFFFu) << 32); |
| @@ -2828,6 +3322,14 @@ struct DeviceState { | |||
| 2828 | if (base < arena.size || (geometry.cap() && geometry.lookup(arena.address + base, host, remaining))) return false; | 3322 | if (base < arena.size || (geometry.cap() && geometry.lookup(arena.address + base, host, remaining))) return false; |
| 2829 | const std::uint32_t stride = (w1 >> 16) & 0x3FFFu; | 3323 | const std::uint32_t stride = (w1 >> 16) & 0x3FFFu; |
| 2830 | const std::uint64_t span = std::uint64_t(w2) * (stride ? stride : 1); | 3324 | const std::uint64_t span = std::uint64_t(w2) * (stride ? stride : 1); |
| 3325 | // A V# the layer wrote for one of its own buffers that the driver put below the arena (an upload buffer in | ||
| 3326 | // ReBAR memory, say): the low 48 bits of a negative offset, which the shaders read sign-extended | ||
| 3327 | // (vsharp_address). Not the title's memory: left as it is, never nulled. | ||
| 3328 | if (base & (1ull << 47)) { | ||
| 3329 | std::lock_guard lock(backing_mutex); | ||
| 3330 | if (gpu_backings.covers(arena.address + (base | ~((1ull << 48) - 1)), std::max<std::uint64_t>(span, 1))) | ||
| 3331 | return false; | ||
| 3332 | } | ||
| 2831 | std::uint64_t to{}; | 3333 | std::uint64_t to{}; |
| 2832 | if (geometry.cap()) { | 3334 | if (geometry.cap()) { |
| 2833 | const leonida::gfx10::BufferWords words{w0, w1, w2, w3}; | 3335 | const leonida::gfx10::BufferWords words{w0, w1, w2, w3}; |
| @@ -2851,22 +3353,57 @@ struct DeviceState { | |||
| 2851 | if (!to) to = make_window ? aliases.resolve(base, span, leonida::TitleVaAliases::table_view) | 3353 | if (!to) to = make_window ? aliases.resolve(base, span, leonida::TitleVaAliases::table_view) |
| 2852 | : aliases.shader_va(base, span); | 3354 | : aliases.shader_va(base, span); |
| 2853 | 3355 | ||
| 2854 | if (to == base || (to >> 48)) return false; | 3356 | // to == 0: the title's memory, and neither a window nor a geometry copy could back it, or an address that is |
| 3357 | // nobody's (resolve_title_memory). to == base: no copy was asked for (a heap scan only looks existing ones up) | ||
| 3358 | // or the address is left as it is; that holds only when the device can reach it (a raw title address, or one | ||
| 3359 | // past every allocation, cannot be). A copy whose VA does not fit the V#'s 48 bits (an import below heap_base, | ||
| 3360 | // off by default) cannot be named here either, and the raw base is no better. False in each case, and | ||
| 3361 | // `unbacked` tells the caller to write it with no records instead of leaving a base a shader would add | ||
| 3362 | // heap_base to. | ||
| 3363 | if (!to || to == base || (to >> 48)) { | ||
| 3364 | // The resolver (make_window) answers 0 for an address the device cannot reach, so a base it left as it | ||
| 3365 | // is needs no second look; a heap scan only looked existing copies up and asks here. | ||
| 3366 | if (unbacked) *unbacked = !to || (to >> 48) || (!make_window && !device_reachable(base)); | ||
| 3367 | return false; | ||
| 3368 | } | ||
| 2855 | w[0] = std::uint32_t(to); | 3369 | w[0] = std::uint32_t(to); |
| 2856 | w[1] = (w1 & 0xFFFF0000u) | std::uint32_t((to >> 32) & 0xFFFFu); | 3370 | w[1] = (w1 & 0xFFFF0000u) | std::uint32_t((to >> 32) & 0xFFFFu); |
| 2857 | return true; | 3371 | return true; |
| 2858 | } | 3372 | } |
| 2859 | 3373 | ||
| 2860 | // Indexed by actual Vulkan address, never by a placed buffer's CPU address. | 3374 | // Indexed by actual Vulkan address, never by a placed buffer's CPU address. |
| 3375 | static bool filter_heap_releases() { | ||
| 3376 | static const bool on = [] { | ||
| 3377 | const auto* v = std::getenv("LEONIDA_CONSOLE_RELEASE_FILTER"); | ||
| 3378 | return v && std::strcmp(v, "1") == 0; | ||
| 3379 | }(); | ||
| 3380 | return on; | ||
| 3381 | } | ||
| 3382 | leonida::DescriptorRangeChanges backing_changes; | ||
| 2861 | std::atomic<uint64_t> released_backings{}; | 3383 | std::atomic<uint64_t> released_backings{}; |
| 3384 | std::atomic<uint64_t> backing_generation{}; // every add and release | ||
| 2862 | std::mutex backing_mutex; | 3385 | std::mutex backing_mutex; |
| 2863 | leonida::BufferVaIndex<uint64_t> gpu_backings; | 3386 | leonida::BufferVaIndex<uint64_t> gpu_backings; |
| 3387 | // A title-window or geometry-copy block was destroyed (TitleBufferWindows::destroy_block; its GPU work completed): | ||
| 3388 | // as for a released backing, the backed table cuts it and the key entries and heap slots answering into it go at | ||
| 3389 | // the next refresh, so no table names the freed memory. | ||
| 3390 | void title_block_gone(VkDeviceAddress address, VkDeviceSize bytes) { | ||
| 3391 | std::lock_guard lock(backing_mutex); | ||
| 3392 | if (filter_heap_releases()) backing_changes.record(address, bytes); | ||
| 3393 | backing_generation.fetch_add(1, std::memory_order_relaxed); | ||
| 3394 | released_backings.fetch_add(1, std::memory_order_release); | ||
| 3395 | if (heap_gpu) released_ranges.emplace_back(address - arena.address, bytes); | ||
| 3396 | } | ||
| 2864 | void backing(VkDeviceAddress address, uint64_t bytes, uint64_t id, bool add) { | 3397 | void backing(VkDeviceAddress address, uint64_t bytes, uint64_t id, bool add) { |
| 2865 | std::lock_guard lock(backing_mutex); | 3398 | std::lock_guard lock(backing_mutex); |
| 3399 | if (filter_heap_releases()) backing_changes.record(address, bytes); | ||
| 3400 | backing_generation.fetch_add(1, std::memory_order_relaxed); | ||
| 2866 | if (add) gpu_backings.insert(address, bytes, id); | 3401 | if (add) gpu_backings.insert(address, bytes, id); |
| 2867 | else { | 3402 | else { |
| 2868 | gpu_backings.erase(address, id); | 3403 | gpu_backings.erase(address, id); |
| 2869 | released_backings.fetch_add(1, std::memory_order_release); | 3404 | released_backings.fetch_add(1, std::memory_order_release); |
| 3405 | // LEONIDA_CONSOLE_HEAP_GPU: the key entries answering into it go at the next refresh. | ||
| 3406 | if (heap_gpu) released_ranges.emplace_back(address - arena.address, bytes); | ||
| 2870 | } | 3407 | } |
| 2871 | } | 3408 | } |
| 2872 | 3409 | ||
| @@ -2898,30 +3435,35 @@ struct DeviceState { | |||
| 2898 | uint64_t host{}, room{}; | 3435 | uint64_t host{}, room{}; |
| 2899 | return geometry.cap() && geometry.lookup(bda, host, room) && room >= bytes; | 3436 | return geometry.cap() && geometry.lookup(bda, host, room) && room >= bytes; |
| 2900 | }; | 3437 | }; |
| 3438 | const auto path = [this](unsigned p) { vsharp_paths[p].fetch_add(1, std::memory_order_relaxed); }; | ||
| 2901 | uint64_t to{}, room{}; | 3439 | uint64_t to{}, room{}; |
| 2902 | if (aliases.range_of(base, to, room)) { | 3440 | if (aliases.range_of(base, to, room)) { |
| 2903 | if (!to || room < bytes || !backed(to)) return 0; | 3441 | if (!to || room < bytes || !backed(to)) return path(1), 0; |
| 2904 | aliases.note_translation(kind); | 3442 | aliases.note_translation(kind); |
| 2905 | return to; | 3443 | return path(0), to; |
| 2906 | } | 3444 | } |
| 2907 | // An already rewritten descriptor carries only the low 48 bits. | 3445 | // An already rewritten descriptor carries only the low 48 bits. |
| 2908 | uint64_t offset = base; | 3446 | uint64_t offset = base; |
| 2909 | if (signed_vsharp_offsets() && base <= mask && (base & (1ull << 47))) offset |= ~mask; | 3447 | if (signed_vsharp_offsets() && base <= mask && (base & (1ull << 47))) offset |= ~mask; |
| 2910 | if (backed(offset)) return offset; | 3448 | if (backed(offset)) return path(2), offset; |
| 2911 | // Read the other way: bit 47 as a sign, for a below-arena buffer's V# the layer wrote itself. | 3449 | // Read the other way: bit 47 as a sign, for a below-arena buffer's V# the layer wrote itself. |
| 2912 | if (offset == base && base <= mask && (base & (1ull << 47)) && backed(base | ~mask)) return base | ~mask; | 3450 | if (offset == base && base <= mask && (base & (1ull << 47)) && backed(base | ~mask)) return base | ~mask; |
| 2913 | if (try_geometry) { | 3451 | if (try_geometry) { |
| 2914 | to = geometry_va(base, bytes, false); | 3452 | to = geometry_va(base, bytes, false); |
| 2915 | if (to && encodable(to)) return to; | 3453 | if (to && encodable(to)) return path(3), to; |
| 2916 | } | 3454 | } |
| 2917 | uint64_t lo{}, hi{}; | 3455 | uint64_t lo{}, hi{}; |
| 2918 | if (make_window && aliases.title_memory(base, lo, hi) && bytes <= hi - base) { | 3456 | if (make_window && aliases.title_memory(base, lo, hi) && bytes <= hi - base) { |
| 2919 | to = aliases.resolve(base, bytes, kind); | 3457 | to = aliases.resolve(base, bytes, kind); |
| 2920 | uint64_t mapped{}; | 3458 | uint64_t mapped{}; |
| 2921 | if (to && aliases.range_of(base, mapped, room) && mapped == to && room >= bytes && backed(to)) return to; | 3459 | if (to && aliases.range_of(base, mapped, room) && mapped == to && room >= bytes && backed(to)) |
| 3460 | return path(4), to; | ||
| 2922 | } | 3461 | } |
| 2923 | return 0; | 3462 | return path(5), 0; |
| 2924 | } | 3463 | } |
| 3464 | // vsharp_address's outcomes (diagnostics): alias hit, alias refused, arena VA, geometry copy, window, none. | ||
| 3465 | static constexpr unsigned kVsharpPathCount = 6; | ||
| 3466 | std::array<std::atomic<std::uint64_t>, kVsharpPathCount> vsharp_paths{}; | ||
| 2925 | 3467 | ||
| 2926 | VsharpResult fix_vsharp(uint32_t* w, VsharpPath path) { | 3468 | VsharpResult fix_vsharp(uint32_t* w, VsharpPath path) { |
| 2927 | if ((w[3] >> 30) || !w[2]) return VsharpResult::unchanged; // image, empty slot or raw pointer | 3469 | if ((w[3] >> 30) || !w[2]) return VsharpResult::unchanged; // image, empty slot or raw pointer |
| @@ -3086,6 +3628,7 @@ struct DeviceState { | |||
| 3086 | static_cast<unsigned long long>(arena.blocks.free_bytes() >> 10)); | 3628 | static_cast<unsigned long long>(arena.blocks.free_bytes() >> 10)); |
| 3087 | return false; | 3629 | return false; |
| 3088 | } | 3630 | } |
| 3631 | // The V# writers look this range up by device address (vsharp_address): an allocation registers its backing. | ||
| 3089 | backing(arena.address + out, bytes, out, true); | 3632 | backing(arena.address + out, bytes, out, true); |
| 3090 | ++arena.allocations; | 3633 | ++arena.allocations; |
| 3091 | arena.in_use += bytes; | 3634 | arena.in_use += bytes; |
| @@ -3107,21 +3650,29 @@ struct DeviceState { | |||
| 3107 | (unsigned long long)va, (unsigned long long)bytes); | 3650 | (unsigned long long)va, (unsigned long long)bytes); |
| 3108 | } | 3651 | } |
| 3109 | 3652 | ||
| 3110 | // Printed once at device release, so a run reports the size the arena needs. | 3653 | // Printed once at device release, so a run reports the size the arena needs; the arena line also about once a |
| 3654 | // minute with a console heap's log (report_arena_peak), since a run cut short never releases its device. | ||
| 3111 | void report_arena() { | 3655 | void report_arena() { |
| 3656 | report_arena_peak(); | ||
| 3657 | report_title_memory(); | ||
| 3658 | } | ||
| 3659 | void report_arena_peak() { | ||
| 3112 | std::lock_guard lock(arena.mutex); | 3660 | std::lock_guard lock(arena.mutex); |
| 3113 | if (!arena.size) return; | 3661 | if (!arena.size) return; |
| 3114 | const double mib = 1.0 / (1 << 20); | 3662 | const double mib = 1.0 / (1 << 20); |
| 3115 | std::fprintf(stderr, | 3663 | std::fprintf(stderr, |
| 3116 | "[rt] d3d12: GPU address arena: peak end %.1f of %.1f MiB (%.1f%%), peak live %.1f MiB " | 3664 | "[rt] d3d12: GPU address arena: peak end %.1f of %.1f MiB (%.1f%%), peak live %.1f MiB " |
| 3117 | "(buffers %.1f, descriptor heaps %.1f, shaders %.1f, heaps %.1f), %llu allocations, %llu refused; " | 3665 | "(buffers %.1f, descriptor heaps %.1f of which null guards %.1f now, shaders %.1f, heaps %.1f), %llu " |
| 3118 | "%zu free blocks (largest %.1f MiB, %.1f MiB free)\n", | 3666 | "allocations, %llu refused; %zu free blocks (largest %.1f MiB, %.1f MiB free)\n", |
| 3119 | arena.peak_end * mib, arena.size * mib, 100.0 * double(arena.peak_end) / double(arena.size), | 3667 | arena.peak_end * mib, arena.size * mib, 100.0 * double(arena.peak_end) / double(arena.size), |
| 3120 | arena.peak_in_use * mib, arena.use_peak[arena_buffer] * mib, | 3668 | arena.peak_in_use * mib, arena.use_peak[arena_buffer] * mib, |
| 3121 | arena.use_peak[arena_descriptor_heap] * mib, arena.use_peak[arena_shader] * mib, | 3669 | arena.use_peak[arena_descriptor_heap] * mib, |
| 3670 | double(arena_guard_bytes.load(std::memory_order_relaxed)) * mib, arena.use_peak[arena_shader] * mib, | ||
| 3122 | arena.use_peak[arena_heap] * mib, | 3671 | arena.use_peak[arena_heap] * mib, |
| 3123 | (unsigned long long)arena.allocations, (unsigned long long)arena.failures, arena.blocks.count(), | 3672 | (unsigned long long)arena.allocations, (unsigned long long)arena.failures, arena.blocks.count(), |
| 3124 | arena.blocks.largest().size * mib, arena.blocks.free_bytes() * mib); | 3673 | arena.blocks.largest().size * mib, arena.blocks.free_bytes() * mib); |
| 3674 | } | ||
| 3675 | void report_title_memory() { | ||
| 3125 | { | 3676 | { |
| 3126 | std::lock_guard windows(title_window_mutex); | 3677 | std::lock_guard windows(title_window_mutex); |
| 3127 | const auto geometry_spans = std::count_if(pool_spans.begin(), pool_spans.end(), | 3678 | const auto geometry_spans = std::count_if(pool_spans.begin(), pool_spans.end(), |
| @@ -3149,6 +3700,8 @@ struct DeviceState { | |||
| 3149 | backing(arena.address + offset, bytes, offset, false); | 3700 | backing(arena.address + offset, bytes, offset, false); |
| 3150 | arena.in_use -= bytes; | 3701 | arena.in_use -= bytes; |
| 3151 | arena.use_in_use[use] -= bytes; | 3702 | arena.use_in_use[use] -= bytes; |
| 3703 | // A heap copy re-fixes its slots when a backing has gone (released_backings): the range is no view's. | ||
| 3704 | backing(arena.address + offset, bytes, offset, false); | ||
| 3152 | } | 3705 | } |
| 3153 | if (fault != leonida::ArenaBlocks::Fault::none && arena_report_due()) { | 3706 | if (fault != leonida::ArenaBlocks::Fault::none && arena_report_due()) { |
| 3154 | std::fprintf(stderr, | 3707 | std::fprintf(stderr, |
| @@ -3160,6 +3713,7 @@ struct DeviceState { | |||
| 3160 | static_cast<unsigned long long>(arena.blocks.free_bytes() >> 10), | 3713 | static_cast<unsigned long long>(arena.blocks.free_bytes() >> 10), |
| 3161 | static_cast<unsigned long long>(arena.blocks.faults())); | 3714 | static_cast<unsigned long long>(arena.blocks.faults())); |
| 3162 | arena_report_suppressed("arena releases"); | 3715 | arena_report_suppressed("arena releases"); |
| 3716 | |||
| 3163 | } | 3717 | } |
| 3164 | check_arena("a release"); | 3718 | check_arena("a release"); |
| 3165 | } | 3719 | } |
| @@ -3195,8 +3749,8 @@ struct DeviceState { | |||
| 3195 | std::uint64_t console_va = 0; | 3749 | std::uint64_t console_va = 0; |
| 3196 | VkDeviceSize bytes = 0; | 3750 | VkDeviceSize bytes = 0; |
| 3197 | std::uint64_t shader_va = 0; // where shaders read it | 3751 | std::uint64_t shader_va = 0; // where shaders read it |
| 3198 | VkDeviceSize guard = 0; | 3752 | VkDeviceSize guard = 0; // null bytes after the GPU copy (heap_guard_bytes/heap_guard_for), its allocation |
| 3199 | bool resource_heap = false; | 3753 | bool resource_heap = false; // a CBV/SRV/UAV heap; a sampler heap's S#s are copied as written |
| 3200 | bool imported = false; | 3754 | bool imported = false; |
| 3201 | std::uint8_t* copy = nullptr; // writable GPU mirror of the console heap | 3755 | std::uint8_t* copy = nullptr; // writable GPU mirror of the console heap |
| 3202 | // Keep large scratch allocations out of the low addresses the title can use for its heap. | 3756 | // Keep large scratch allocations out of the low addresses the title can use for its heap. |
| @@ -3208,17 +3762,25 @@ struct DeviceState { | |||
| 3208 | VkDeviceMemory memory = VK_NULL_HANDLE; | 3762 | VkDeviceMemory memory = VK_NULL_HANDLE; |
| 3209 | std::uint64_t pin = 0; // the imported pages' leonida::kernel_writes pin while `memory` lives | 3763 | std::uint64_t pin = 0; // the imported pages' leonida::kernel_writes pin while `memory` lives |
| 3210 | std::size_t scan_at = 0; // the next slot the T# scan reads | 3764 | std::size_t scan_at = 0; // the next slot the T# scan reads |
| 3211 | uint64_t checked_generation{}, alias_generation{}; | 3765 | uint64_t checked_generation{}, alias_generation{}, backing_cursor{}, alias_cursor{}; |
| 3766 | uint64_t release_sweeps{}, release_candidates{}, release_fixes{}, release_rebases{}, release_full{}; | ||
| 3212 | // copy | 3767 | // copy |
| 3213 | bool identity = false; | 3768 | bool identity = false; |
| 3214 | ShadowPagesPtr pages; | 3769 | ShadowPagesPtr pages; |
| 3215 | std::vector<std::uint8_t> mirror; // the title's bytes as the tracker last copied them | 3770 | std::vector<std::uint8_t> mirror; // the title's bytes as the tracker last copied them |
| 3216 | std::vector<std::uint8_t> made; // the title's bytes each arena slot was last made from | 3771 | std::vector<std::uint8_t> made; // the title's bytes each arena slot was last made from |
| 3217 | std::vector<std::uint8_t> retry; // per slot: not settled yet (fix_console_slot), in `retries` | 3772 | std::vector<std::uint8_t> retry; // per slot: not settled yet (fix_console_slot), in `retries` |
| 3773 | leonida::ConsoleHeapVsharpSlots live_vsharps; // slots whose GPU copy holds a live buffer V# | ||
| 3218 | std::vector<std::uint32_t> retries; | 3774 | std::vector<std::uint32_t> retries; |
| 3219 | std::set<std::uint32_t> empty_slots; | 3775 | std::set<std::uint32_t> empty_slots; |
| 3220 | std::uint32_t next_empty = 0; | 3776 | std::uint32_t next_empty = 0; |
| 3221 | std::size_t retry_at = 0; // where retry_console_slots goes on | 3777 | std::size_t retry_at = 0; // where retry_console_slots goes on |
| 3778 | // V#s naming an address nothing backs that is not the title's memory: null in the copy, and looked at again a | ||
| 3779 | // few times (kUnmappedTries, at most kUnmappedRetrySlots a submission) in case their buffer is made after the | ||
| 3780 | // descriptor. | ||
| 3781 | std::vector<std::uint8_t> unmapped_tries; // per slot: 0, or the looks so far (it is in `unmapped`) | ||
| 3782 | std::vector<std::uint32_t> unmapped; | ||
| 3783 | std::size_t unmapped_at = 0; | ||
| 3222 | // fix_console_slots' budget, for the current refresh, and the slots it nulled since the last log line | 3784 | // fix_console_slots' budget, for the current refresh, and the slots it nulled since the last log line |
| 3223 | std::chrono::steady_clock::time_point fix_start{}; | 3785 | std::chrono::steady_clock::time_point fix_start{}; |
| 3224 | bool fix_over = false; | 3786 | bool fix_over = false; |
| @@ -3229,11 +3791,52 @@ struct DeviceState { | |||
| 3229 | // Since the last log line. | 3791 | // Since the last log line. |
| 3230 | std::uint64_t copied = 0, vsharps = 0, unbacked = 0, retried = 0; | 3792 | std::uint64_t copied = 0, vsharps = 0, unbacked = 0, retried = 0; |
| 3231 | std::uint64_t images[5] = {}; // by TitleImage | 3793 | std::uint64_t images[5] = {}; // by TitleImage |
| 3794 | std::map<std::string, std::uint64_t> refused_reasons; | ||
| 3232 | double ms = 0, pages_ms = 0, fix_ms = 0, retry_ms = 0; // ms: all; the others its parts | 3795 | double ms = 0, pages_ms = 0, fix_ms = 0, retry_ms = 0; // ms: all; the others its parts |
| 3796 | // Changed slots by class (before the fix budget), since the last log line: all-zero, V# pair, T#, other | ||
| 3797 | // words; V# halves whose 16 bytes were seen before (a direct-mapped memo of 65536 keys, so a lower bound of | ||
| 3798 | // how often an exact-key translation would be found again); rescans after a backing release and their cost. | ||
| 3799 | std::uint64_t changed[4] = {}, vsharp_halves = 0, vsharp_repeats = 0; | ||
| 3800 | std::uint64_t rescans = 0, rescanned = 0; | ||
| 3801 | double rescan_ms = 0; | ||
| 3802 | std::vector<std::array<std::uint32_t, 4>> seen_keys; | ||
| 3803 | // LEONIDA_CONSOLE_HEAP_GPU (DeviceState::attach_console_heap_gpu): the translation pass's index of this heap | ||
| 3804 | // (-1: fixed on the CPU), the import of `input` the pass reads, the slots holding a V# pair (translated again | ||
| 3805 | // when a backing goes), and the slots queued for the pass since the last log line. | ||
| 3806 | int gpu = -1; | ||
| 3807 | VkBuffer input_buffer = VK_NULL_HANDLE; | ||
| 3808 | VkDeviceMemory input_memory = VK_NULL_HANDLE; | ||
| 3809 | std::vector<std::uint64_t> vsharp_bits; | ||
| 3810 | std::uint64_t gpu_queued = 0; | ||
| 3811 | std::uint32_t gpu_high = 0; // one past the highest slot the title has written (a rescan's range) | ||
| 3233 | }; | 3812 | }; |
| 3234 | std::mutex console_heap_mutex; // taken before title_window_mutex, shadow_mutex and descriptor_mutex | 3813 | std::mutex console_heap_mutex; // taken before title_window_mutex, shadow_mutex and descriptor_mutex |
| 3235 | std::vector<std::unique_ptr<ConsoleHeap>> console_heaps; | 3814 | std::vector<std::unique_ptr<ConsoleHeap>> console_heaps; |
| 3236 | 3815 | ||
| 3816 | // Null slots after a shader-visible resource heap's GPU copy. A directly indexed heap is read at | ||
| 3817 | // heap VA + index * 32 with the index from data (docs/d3d12_vulkan.md section 3.4), and nothing bounds it: an | ||
| 3818 | // index past the heap read whatever the arena held after it, and a buffer V# made of those bytes sent loads and | ||
| 3819 | // stores to heap_base + garbage (GPU MMU faults at world start). With the guard such an index reads a null | ||
| 3820 | // descriptor instead (loads 0, stores dropped). As VIctory does for its host heaps (crates/victory-shader/src/emit | ||
| 3821 | // "Heap indices": at least 2^21 slots, those past the title's own null). | ||
| 3822 | // Two shapes: `heap_guard_bytes` is the fixed reach a directly indexed heap is given (2^21 slots, bounded so the | ||
| 3823 | // heap and its guard stay inside a 32-bit shader offset, LEONIDA_HEAP_GUARD_MB overrides), and `heap_guard_for` | ||
| 3824 | // is the per-heap guard a console heap's copy takes - as large as the heap, at least 1 MiB, at most | ||
| 3825 | // `heap_guard_cap()` (64 MiB by default, 0: no guard). Either comes out of the arena every default-heap buffer is | ||
| 3826 | // placed in; a heap the arena has no room for with its guard is made without one (logged). | ||
| 3827 | static constexpr VkDeviceSize kHeapGuardFloor = VkDeviceSize(1) << 20; | ||
| 3828 | static VkDeviceSize heap_guard_cap() { | ||
| 3829 | static const VkDeviceSize bytes = [] { | ||
| 3830 | constexpr VkDeviceSize fallback = VkDeviceSize(64) << 20; | ||
| 3831 | char text[16] = {}; | ||
| 3832 | const DWORD n = GetEnvironmentVariableA("LEONIDA_HEAP_GUARD_MB", text, sizeof(text)); | ||
| 3833 | if (n == 0 || n >= sizeof(text)) return fallback; | ||
| 3834 | for (DWORD i = 0; i < n; ++i) | ||
| 3835 | if (text[i] < '0' || text[i] > '9') return fallback; // "-1" and the like: the default | ||
| 3836 | return VkDeviceSize(std::min<unsigned long long>(std::strtoull(text, nullptr, 10), 1024)) << 20; | ||
| 3837 | }(); | ||
| 3838 | return bytes; | ||
| 3839 | } | ||
| 3237 | static constexpr VkDeviceSize kHeapIndexReach = VkDeviceSize(1) << 26; // 2^21 slots of 32 bytes | 3840 | static constexpr VkDeviceSize kHeapIndexReach = VkDeviceSize(1) << 26; // 2^21 slots of 32 bytes |
| 3238 | static VkDeviceSize heap_guard_bytes() { | 3841 | static VkDeviceSize heap_guard_bytes() { |
| 3239 | static const VkDeviceSize bytes = [] { | 3842 | static const VkDeviceSize bytes = [] { |
| @@ -3244,6 +3847,17 @@ struct DeviceState { | |||
| 3244 | }(); | 3847 | }(); |
| 3245 | return bytes; | 3848 | return bytes; |
| 3246 | } | 3849 | } |
| 3850 | // The null bytes after a heap of `bytes`: as many as the heap, at least `floor`, at most heap_guard_cap(); grown so | ||
| 3851 | // heap and guard together end on a multiple of `align`. 0 with no cap. | ||
| 3852 | static VkDeviceSize heap_guard_for(VkDeviceSize bytes, VkDeviceSize floor, VkDeviceSize align) { | ||
| 3853 | const VkDeviceSize cap = heap_guard_cap(); | ||
| 3854 | if (!cap || !bytes) return 0; | ||
| 3855 | VkDeviceSize guard = std::min(std::max(bytes, floor), cap); | ||
| 3856 | if (align > 1) guard = (bytes + guard + align - 1) / align * align - bytes; | ||
| 3857 | return guard; | ||
| 3858 | } | ||
| 3859 | std::atomic<std::uint64_t> arena_guard_bytes{0}; // the heap guards in the arena now (report_arena) | ||
| 3860 | |||
| 3247 | 3861 | ||
| 3248 | // [start, start + bytes) of the arena, exactly. False when any of it is taken or past the arena. | 3862 | // [start, start + bytes) of the arena, exactly. False when any of it is taken or past the arena. |
| 3249 | bool arena_allocate_at(VkDeviceSize start, VkDeviceSize bytes, ArenaUse use) { | 3863 | bool arena_allocate_at(VkDeviceSize start, VkDeviceSize bytes, ArenaUse use) { |
| @@ -3261,17 +3875,34 @@ struct DeviceState { | |||
| 3261 | } | 3875 | } |
| 3262 | 3876 | ||
| 3263 | // Slot `slot` of a heap copy, as the title wrote it, fixed up as described above. True when it is settled: not a | 3877 | // Slot `slot` of a heap copy, as the title wrote it, fixed up as described above. True when it is settled: not a |
| 3264 | // T# whose texture is still to come, nor a V# into the title's memory that got no copy. | 3878 | // T# whose texture is still to come, nor a V# into the title's memory that got no copy. `unmapped` (when given) is |
| 3265 | bool fix_console_slot(ConsoleHeap& heap, std::size_t slot) { | 3879 | // set for a V# written null because its base is neither the title's memory nor anything of the device's: settled, |
| 3880 | // but its buffer may still be made (the round-robin probe in refresh_console_heap). A sampler heap holds S#s: | ||
| 3881 | // copied as written. | ||
| 3882 | bool fix_console_slot(ConsoleHeap& heap, std::size_t slot, bool* unmapped = nullptr) { | ||
| 3266 | std::uint32_t w[kDescriptorSize / 4]; | 3883 | std::uint32_t w[kDescriptorSize / 4]; |
| 3267 | std::memcpy(w, heap.previous + slot * kDescriptorSize, kDescriptorSize); | 3884 | std::memcpy(w, heap.previous + slot * kDescriptorSize, kDescriptorSize); |
| 3268 | bool settled = true, empty = false; | 3885 | bool settled = true, empty = false; |
| 3269 | if (!(w[3] >> 30)) { | 3886 | if (unmapped) *unmapped = false; |
| 3270 | const auto path = heap.scratch ? VsharpPath::scratch : VsharpPath::shadow; | 3887 | const VsharpPath path = heap.scratch ? VsharpPath::scratch : VsharpPath::shadow; |
| 3271 | const auto result = fix_vsharp(w, path); | 3888 | if (!heap.resource_heap || !(w[0] | w[1] | w[2] | w[3])) { |
| 3272 | const auto counter = fix_vsharp(w + 4, path); | 3889 | // A sampler heap holds S#s (copied as written); an all-zero slot stays null. |
| 3890 | } else if (!(w[3] >> 30)) { | ||
| 3891 | // A buffer V#: rewritten to the address its bytes are backed at (fix_vsharp: the console shadow, or the | ||
| 3892 | // console scratch an imported heap rewrites). A base nothing backs is written with no base and no records, | ||
| 3893 | // settled, and left for the bounded round-robin probe in refresh_console_heap in case its buffer is made | ||
| 3894 | // after the descriptor. | ||
| 3895 | const VsharpResult result = fix_vsharp(w, path); | ||
| 3273 | if (result == VsharpResult::rebased) ++heap.vsharps; | 3896 | if (result == VsharpResult::rebased) ++heap.vsharps; |
| 3274 | if (result == VsharpResult::empty || counter == VsharpResult::empty) { | 3897 | if (result == VsharpResult::empty) { |
| 3898 | // Only the GPU copy changes; the title's bytes (heap.previous) stay as written. | ||
| 3899 | ++heap.unbacked; | ||
| 3900 | empty = true; | ||
| 3901 | } | ||
| 3902 | // The slot's second V# is a UAV counter (raw, 4 bytes, in the descriptor's upper 16 bytes): a store to it at | ||
| 3903 | // heap_base + a raw title address loses the device just as one through the buffer V# does. A counter with | ||
| 3904 | // no backing is nulled and left to retry_console_slots. | ||
| 3905 | if (fix_vsharp(w + 4, path) == VsharpResult::empty) { | ||
| 3275 | ++heap.unbacked; | 3906 | ++heap.unbacked; |
| 3276 | empty = true; | 3907 | empty = true; |
| 3277 | } | 3908 | } |
| @@ -3281,12 +3912,19 @@ struct DeviceState { | |||
| 3281 | if (leonida::gfx10::is_image(words)) { | 3912 | if (leonida::gfx10::is_image(words)) { |
| 3282 | const char* why = nullptr; | 3913 | const char* why = nullptr; |
| 3283 | const TitleImage result = bind_title_image(*this, words, &why); | 3914 | const TitleImage result = bind_title_image(*this, words, &why); |
| 3284 | if (result == TitleImage::unknown || result == TitleImage::refused) | 3915 | if (result == TitleImage::unknown || result == TitleImage::refused) { |
| 3285 | note_refused_tsharp(heap, slot * kDescriptorSize, words, why); | 3916 | note_refused_tsharp(heap, slot * kDescriptorSize, words, why); |
| 3917 | if (result == TitleImage::refused) | ||
| 3918 | ++heap.refused_reasons[why ? why : "?"]; | ||
| 3919 | } | ||
| 3286 | ++heap.images[unsigned(result)]; | 3920 | ++heap.images[unsigned(result)]; |
| 3287 | settled = result != TitleImage::unknown && result != TitleImage::refused; | 3921 | settled = result != TitleImage::unknown && result != TitleImage::refused; |
| 3288 | if (result == TitleImage::not_tsharp) std::memset(w, 0, 16); | 3922 | if (result == TitleImage::not_tsharp) std::memset(w, 0, 16); |
| 3289 | } else { | 3923 | } else { |
| 3924 | // Neither a buffer V# (TYPE is not 0) nor a T# the layer can decode: data the title keeps in the slot. | ||
| 3925 | // No image is found by these words (the bindless lookup misses, as for a null T#), but a shader that | ||
| 3926 | // takes the slot as a V# (an index from data, or one past what the title filled) adds heap_base to | ||
| 3927 | // words that name nothing: in the GPU copy the slot is null, and left to retry_console_slots. | ||
| 3290 | ++heap.images[unsigned(TitleImage::not_tsharp)]; | 3928 | ++heap.images[unsigned(TitleImage::not_tsharp)]; |
| 3291 | std::memset(w, 0, 16); | 3929 | std::memset(w, 0, 16); |
| 3292 | } | 3930 | } |
| @@ -3294,9 +3932,38 @@ struct DeviceState { | |||
| 3294 | if (empty) heap.empty_slots.insert(std::uint32_t(slot)); | 3932 | if (empty) heap.empty_slots.insert(std::uint32_t(slot)); |
| 3295 | else if (!heap.empty_slots.empty()) heap.empty_slots.erase(std::uint32_t(slot)); | 3933 | else if (!heap.empty_slots.empty()) heap.empty_slots.erase(std::uint32_t(slot)); |
| 3296 | std::memcpy(heap.copy + slot * kDescriptorSize, w, kDescriptorSize); | 3934 | std::memcpy(heap.copy + slot * kDescriptorSize, w, kDescriptorSize); |
| 3935 | heap.live_vsharps.set(slot, leonida::ConsoleHeapVsharpSlots::is_live_vsharp(w)); | ||
| 3297 | return settled; | 3936 | return settled; |
| 3298 | } | 3937 | } |
| 3299 | 3938 | ||
| 3939 | // Diagnostics only: the class of a changed slot, and whether its V# halves were seen before (ConsoleHeap::changed). | ||
| 3940 | static void note_changed_slot(ConsoleHeap& heap, const std::uint8_t* bytes) { | ||
| 3941 | std::uint32_t w[8]; | ||
| 3942 | std::memcpy(w, bytes, sizeof(w)); | ||
| 3943 | if (!(w[0] | w[1] | w[2] | w[3] | w[4] | w[5] | w[6] | w[7])) { | ||
| 3944 | ++heap.changed[0]; | ||
| 3945 | return; | ||
| 3946 | } | ||
| 3947 | if (w[3] >> 30) { | ||
| 3948 | leonida::gfx10::ImageWords words; | ||
| 3949 | std::memcpy(words.data(), w, sizeof(words)); | ||
| 3950 | ++heap.changed[leonida::gfx10::is_image(words) ? 2 : 3]; | ||
| 3951 | return; | ||
| 3952 | } | ||
| 3953 | ++heap.changed[1]; | ||
| 3954 | if (heap.seen_keys.empty()) heap.seen_keys.resize(65536); | ||
| 3955 | for (int half = 0; half < 2; ++half) { | ||
| 3956 | const std::uint32_t* k = w + 4 * half; | ||
| 3957 | if (!k[2]) continue; // no records: nothing to translate | ||
| 3958 | ++heap.vsharp_halves; | ||
| 3959 | std::uint32_t h = 2166136261u; | ||
| 3960 | for (int i = 0; i < 4; ++i) h = (h ^ k[i]) * 16777619u; | ||
| 3961 | auto& entry = heap.seen_keys[h & 0xffffu]; | ||
| 3962 | if (entry[0] == k[0] && entry[1] == k[1] && entry[2] == k[2] && entry[3] == k[3]) ++heap.vsharp_repeats; | ||
| 3963 | else entry = {k[0], k[1], k[2], k[3]}; | ||
| 3964 | } | ||
| 3965 | } | ||
| 3966 | |||
| 3300 | // The slots on [offset, offset + bytes) of a heap copy's mirror, just brought up to date: each that differs from | 3967 | // The slots on [offset, offset + bytes) of a heap copy's mirror, just brought up to date: each that differs from |
| 3301 | // what its arena slot was made from is written there and fixed up. | 3968 | // what its arena slot was made from is written there and fixed up. |
| 3302 | // LEONIDA_CONSOLE_FIX_US limits the fixing in one submission (0, the default: no limit). Past it a changed slot is | 3969 | // LEONIDA_CONSOLE_FIX_US limits the fixing in one submission (0, the default: no limit). Past it a changed slot is |
| @@ -3320,11 +3987,14 @@ struct DeviceState { | |||
| 3320 | const std::size_t slot = at / kDescriptorSize; | 3987 | const std::size_t slot = at / kDescriptorSize; |
| 3321 | if (!std::memcmp(heap.previous + at, heap.input + at, kDescriptorSize)) continue; | 3988 | if (!std::memcmp(heap.previous + at, heap.input + at, kDescriptorSize)) continue; |
| 3322 | std::memcpy(heap.previous + at, heap.input + at, kDescriptorSize); | 3989 | std::memcpy(heap.previous + at, heap.input + at, kDescriptorSize); |
| 3990 | if (heap.unmapped_tries[slot]) heap.unmapped_tries[slot] = 1; // new words: their looks start over | ||
| 3991 | note_changed_slot(heap, heap.previous + at); | ||
| 3323 | if (budget_us && !heap.fix_over && !(++heap.fix_count & 15) && | 3992 | if (budget_us && !heap.fix_over && !(++heap.fix_count & 15) && |
| 3324 | std::chrono::steady_clock::now() - heap.fix_start >= std::chrono::microseconds(budget_us)) | 3993 | std::chrono::steady_clock::now() - heap.fix_start >= std::chrono::microseconds(budget_us)) |
| 3325 | heap.fix_over = true; | 3994 | heap.fix_over = true; |
| 3326 | if (heap.fix_over) { | 3995 | if (heap.fix_over) { |
| 3327 | std::memset(heap.copy + at, 0, kDescriptorSize); | 3996 | std::memset(heap.copy + at, 0, kDescriptorSize); |
| 3997 | heap.live_vsharps.clear(slot); | ||
| 3328 | ++heap.deferred_fixes; | 3998 | ++heap.deferred_fixes; |
| 3329 | if (!heap.retry[slot]) { | 3999 | if (!heap.retry[slot]) { |
| 3330 | heap.retry[slot] = 1; | 4000 | heap.retry[slot] = 1; |
| @@ -3332,13 +4002,49 @@ struct DeviceState { | |||
| 3332 | } | 4002 | } |
| 3333 | continue; | 4003 | continue; |
| 3334 | } | 4004 | } |
| 3335 | if (fix_console_slot(heap, slot)) { | 4005 | bool unmapped = false; |
| 4006 | if (fix_console_slot(heap, slot, &unmapped)) { | ||
| 3336 | heap.retry[slot] = 0; | 4007 | heap.retry[slot] = 0; |
| 3337 | } else if (!heap.retry[slot]) { | 4008 | } else if (!heap.retry[slot]) { |
| 3338 | heap.retry[slot] = 1; | 4009 | heap.retry[slot] = 1; |
| 3339 | heap.retries.push_back(std::uint32_t(slot)); | 4010 | heap.retries.push_back(std::uint32_t(slot)); |
| 3340 | } | 4011 | } |
| 4012 | if (unmapped && !heap.unmapped_tries[slot]) { | ||
| 4013 | heap.unmapped_tries[slot] = 1; | ||
| 4014 | heap.unmapped.push_back(std::uint32_t(slot)); | ||
| 4015 | } | ||
| 4016 | } | ||
| 4017 | } | ||
| 4018 | |||
| 4019 | // The V#s fix_console_slot wrote null because nothing backs their base: looked at again, round robin, at most | ||
| 4020 | // kUnmappedRetrySlots a submission, each kUnmappedTries times at most. A descriptor the title wrote before making | ||
| 4021 | // its buffer (or a buffer another thread registers just after) then gets its base back; one that stays unmapped | ||
| 4022 | // drops out of the list, so data the title keeps in its heap does not cost a lookup at every submission. | ||
| 4023 | static constexpr std::size_t kUnmappedRetrySlots = 2048; | ||
| 4024 | static constexpr std::uint8_t kUnmappedTries = 4; | ||
| 4025 | void retry_unmapped_slots(ConsoleHeap& heap) { | ||
| 4026 | std::size_t i = heap.unmapped_at; | ||
| 4027 | // Each entry once a submission at most: the looks are a submission apart. | ||
| 4028 | const std::size_t visits = std::min(kUnmappedRetrySlots, heap.unmapped.size()); | ||
| 4029 | for (std::size_t visited = 0; visited < visits && !heap.unmapped.empty(); ++visited) { | ||
| 4030 | if (i >= heap.unmapped.size()) i = 0; | ||
| 4031 | const std::uint32_t slot = heap.unmapped[i]; | ||
| 4032 | // Zeroed since (unmapped_tries reset), reachable now, or out of looks: out of the list. | ||
| 4033 | bool done = !heap.unmapped_tries[slot]; | ||
| 4034 | if (!done) { | ||
| 4035 | bool unmapped = false; | ||
| 4036 | fix_console_slot(heap, slot, &unmapped); | ||
| 4037 | done = !unmapped || ++heap.unmapped_tries[slot] > kUnmappedTries; | ||
| 4038 | } | ||
| 4039 | if (done) { | ||
| 4040 | heap.unmapped_tries[slot] = 0; | ||
| 4041 | heap.unmapped[i] = heap.unmapped.back(); | ||
| 4042 | heap.unmapped.pop_back(); | ||
| 4043 | } else { | ||
| 4044 | ++i; | ||
| 4045 | } | ||
| 3341 | } | 4046 | } |
| 4047 | heap.unmapped_at = i; | ||
| 3342 | } | 4048 | } |
| 3343 | 4049 | ||
| 3344 | // The slots of a heap copy not settled yet: fixed again, and kept while they are still not. Round robin, for at | 4050 | // The slots of a heap copy not settled yet: fixed again, and kept while they are still not. Round robin, for at |
| @@ -3375,28 +4081,14 @@ struct DeviceState { | |||
| 3375 | heap.retried += visited; | 4081 | heap.retried += visited; |
| 3376 | } | 4082 | } |
| 3377 | 4083 | ||
| 3378 | // The first refused T#s of each reason, with where they sit in the heap and their words, and a count of the | ||
| 3379 | // distinct slots refused (a slot is scanned again every pass over the heap). | ||
| 3380 | void note_refused_tsharp(ConsoleHeap& heap, std::size_t offset, const leonida::gfx10::ImageWords& words, | 4084 | void note_refused_tsharp(ConsoleHeap& heap, std::size_t offset, const leonida::gfx10::ImageWords& words, |
| 3381 | const char* why) { | 4085 | const char* why) { |
| 3382 | static std::mutex mutex; | 4086 | unbound_tsharp_tracker().note(heap.console_va, offset, words, why); |
| 3383 | static std::map<std::string, unsigned> logged; | ||
| 3384 | static std::set<std::size_t> slots; | ||
| 3385 | std::lock_guard lock(mutex); | ||
| 3386 | if (slots.size() >= 262144) return; // enough to say how many | ||
| 3387 | const bool fresh = slots.insert(offset).second; | ||
| 3388 | unsigned& n = logged[why ? why : "?"]; | ||
| 3389 | if (!fresh || n >= 6) return; | ||
| 3390 | ++n; | ||
| 3391 | std::fprintf(stderr, | ||
| 3392 | "[rt] d3d12: unbound T# in console heap 0x%llx at +0x%zx (%zu distinct slots so far): %s: " | ||
| 3393 | "%08x %08x %08x %08x %08x %08x %08x %08x\n", | ||
| 3394 | static_cast<unsigned long long>(heap.console_va), offset, slots.size(), why ? why : "?", words[0], | ||
| 3395 | words[1], words[2], words[3], words[4], words[5], words[6], words[7]); | ||
| 3396 | } | 4087 | } |
| 3397 | 4088 | ||
| 3398 | void refresh_console_heap(ConsoleHeap& heap) { // console_heap_mutex held | 4089 | void refresh_console_heap(ConsoleHeap& heap) { // console_heap_mutex held |
| 3399 | if (heap.imported) return; // directly imported sampler heap | 4090 | if (heap.imported) return; // directly imported sampler heap |
| 4091 | if (heap.gpu >= 0) return refresh_console_heap_gpu(heap); | ||
| 3400 | using clock = std::chrono::steady_clock; | 4092 | using clock = std::chrono::steady_clock; |
| 3401 | const auto ms = [](clock::time_point a, clock::time_point b) { | 4093 | const auto ms = [](clock::time_point a, clock::time_point b) { |
| 3402 | return std::chrono::duration<double, std::milli>(b - a).count(); | 4094 | return std::chrono::duration<double, std::milli>(b - a).count(); |
| @@ -3409,7 +4101,11 @@ struct DeviceState { | |||
| 3409 | const auto first = std::uint32_t(offset / kDescriptorSize); | 4101 | const auto first = std::uint32_t(offset / kDescriptorSize); |
| 3410 | const auto end = std::uint32_t((offset + bytes) / kDescriptorSize); | 4102 | const auto end = std::uint32_t((offset + bytes) / kDescriptorSize); |
| 3411 | heap.empty_slots.erase(heap.empty_slots.lower_bound(first), heap.empty_slots.lower_bound(end)); | 4103 | heap.empty_slots.erase(heap.empty_slots.lower_bound(first), heap.empty_slots.lower_bound(end)); |
| 3412 | for (auto slot = first; slot < end; ++slot) heap.retry[slot] = 0; | 4104 | for (auto slot = first; slot < end; ++slot) { |
| 4105 | heap.retry[slot] = 0; | ||
| 4106 | heap.unmapped_tries[slot] = 0; | ||
| 4107 | } | ||
| 4108 | heap.live_vsharps.clear_range(first, end); | ||
| 3413 | }); | 4109 | }); |
| 3414 | const auto t1 = clock::now(); | 4110 | const auto t1 = clock::now(); |
| 3415 | heap.fix_start = t1; | 4111 | heap.fix_start = t1; |
| @@ -3421,17 +4117,54 @@ struct DeviceState { | |||
| 3421 | if (heap.resource_heap && (generation != heap.checked_generation || alias_generation != heap.alias_generation)) { | 4117 | if (heap.resource_heap && (generation != heap.checked_generation || alias_generation != heap.alias_generation)) { |
| 3422 | heap.alias_generation = alias_generation; | 4118 | heap.alias_generation = alias_generation; |
| 3423 | heap.checked_generation = generation; | 4119 | heap.checked_generation = generation; |
| 4120 | leonida::DescriptorRanges backing, aliases; | ||
| 4121 | bool filtered = filter_heap_releases(); | ||
| 4122 | if (filtered) { | ||
| 4123 | { | ||
| 4124 | std::lock_guard lock(backing_mutex); | ||
| 4125 | filtered = backing_changes.read(heap.backing_cursor, backing); | ||
| 4126 | } | ||
| 4127 | filtered &= leonida::title_va_aliases().changed_ranges(heap.alias_cursor, aliases); | ||
| 4128 | backing.merge(); | ||
| 4129 | aliases.merge(); | ||
| 4130 | } | ||
| 4131 | ++heap.release_sweeps; | ||
| 4132 | heap.release_full += !filtered; | ||
| 4133 | const auto bda = [&](uint64_t base) { | ||
| 4134 | if (signed_vsharp_offsets() && (base & (1ull << 47))) base |= ~((1ull << 48)-1); | ||
| 4135 | return arena.address + base; | ||
| 4136 | }; | ||
| 4137 | const auto affected = [&](const uint32_t* src, const uint32_t* dst) { | ||
| 4138 | if ((src[3] >> 30) || !src[2]) return false; | ||
| 4139 | const uint64_t base = uint64_t(src[0]) | (uint64_t(src[1] & 0xffff) << 32); | ||
| 4140 | const uint64_t fixed = uint64_t(dst[0]) | (uint64_t(dst[1] & 0xffff) << 32); | ||
| 4141 | const auto stride = (src[1] >> 16) & 0x3fff; | ||
| 4142 | const uint64_t bytes = uint64_t(src[2]) * (stride ? stride : 1); | ||
| 4143 | return aliases.overlaps(base, 1) || backing.overlaps(bda(base), bytes) || | ||
| 4144 | (dst[2] && backing.overlaps(bda(fixed), bytes)); | ||
| 4145 | }; | ||
| 4146 | const auto before = heap.vsharps; | ||
| 4147 | ++heap.rescans; | ||
| 4148 | const auto rescan_start = clock::now(); | ||
| 3424 | // Even an unchanged title slot may name a buffer released since the last submission. | 4149 | // Even an unchanged title slot may name a buffer released since the last submission. |
| 3425 | for (size_t at = 0; at + kDescriptorSize <= heap.bytes; at += kDescriptorSize) { | 4150 | // Walk the host-RAM V# bitset instead of reading every slot of `heap.copy` (which may be uncached WC VRAM). |
| 3426 | auto* w = reinterpret_cast<uint32_t*>(heap.copy + at); | 4151 | heap.live_vsharps.for_each([&](std::size_t slot) { |
| 3427 | if (!(w[3] >> 30) && (w[2] || w[6])) { | 4152 | ++heap.release_candidates; |
| 3428 | const auto slot = at / kDescriptorSize; | 4153 | if (filtered) { |
| 3429 | if (!fix_console_slot(heap, slot) && !heap.retry[slot]) { | 4154 | const auto at = slot * kDescriptorSize; |
| 3430 | heap.retry[slot] = 1; | 4155 | const auto* src = reinterpret_cast<const uint32_t*>(heap.previous + at); |
| 3431 | heap.retries.push_back(uint32_t(slot)); | 4156 | const auto* dst = reinterpret_cast<const uint32_t*>(heap.copy + at); |
| 3432 | } | 4157 | if (!affected(src, dst) && !affected(src + 4, dst + 4)) return; |
| 3433 | } | 4158 | } |
| 3434 | } | 4159 | ++heap.release_fixes; |
| 4160 | ++heap.rescanned; | ||
| 4161 | if (!fix_console_slot(heap, slot) && !heap.retry[slot]) { | ||
| 4162 | heap.retry[slot] = 1; | ||
| 4163 | heap.retries.push_back(uint32_t(slot)); | ||
| 4164 | } | ||
| 4165 | }); | ||
| 4166 | heap.release_rebases += heap.vsharps - before; | ||
| 4167 | heap.rescan_ms += ms(rescan_start, clock::now()); | ||
| 3435 | } | 4168 | } |
| 3436 | const auto t2 = clock::now(); | 4169 | const auto t2 = clock::now(); |
| 3437 | // A settled zero can acquire GPU backing without a CPU map event. Probe at most eight in | 4170 | // A settled zero can acquire GPU backing without a CPU map event. Probe at most eight in |
| @@ -3450,6 +4183,7 @@ struct DeviceState { | |||
| 3450 | } | 4183 | } |
| 3451 | } | 4184 | } |
| 3452 | if (!heap.retries.empty()) retry_console_slots(heap); | 4185 | if (!heap.retries.empty()) retry_console_slots(heap); |
| 4186 | if (!heap.unmapped.empty()) retry_unmapped_slots(heap); | ||
| 3453 | const auto t3 = clock::now(); | 4187 | const auto t3 = clock::now(); |
| 3454 | heap.pages_ms += ms(t0, t1); | 4188 | heap.pages_ms += ms(t0, t1); |
| 3455 | heap.fix_ms += ms(t1, t2); | 4189 | heap.fix_ms += ms(t1, t2); |
| @@ -3459,6 +4193,16 @@ struct DeviceState { | |||
| 3459 | // Before every submission, ahead of the slot-133 shadows. | 4193 | // Before every submission, ahead of the slot-133 shadows. |
| 3460 | void refresh_console_heaps() { | 4194 | void refresh_console_heaps() { |
| 3461 | std::lock_guard lock(console_heap_mutex); | 4195 | std::lock_guard lock(console_heap_mutex); |
| 4196 | const bool heap_pass = heap_gpu && console_heap_gpu_enabled(); | ||
| 4197 | if (heap_pass) console_heap_gpu_begin(); | ||
| 4198 | else if (heap_gpu) heap_gpu->drain(context->completed_retire_ticket(), [](int, std::uint32_t, std::uint32_t) {}, [](int) {}); | ||
| 4199 | struct GpuEnd { // after every heap's slots are queued, however the loop ends | ||
| 4200 | DeviceState& state; | ||
| 4201 | bool on; | ||
| 4202 | ~GpuEnd() { | ||
| 4203 | if (on) state.console_heap_gpu_end(); | ||
| 4204 | } | ||
| 4205 | } gpu_end{*this, heap_pass}; | ||
| 3462 | for (const auto& heap : console_heaps) { | 4206 | for (const auto& heap : console_heaps) { |
| 3463 | const auto start = std::chrono::steady_clock::now(); | 4207 | const auto start = std::chrono::steady_clock::now(); |
| 3464 | refresh_console_heap(*heap); | 4208 | refresh_console_heap(*heap); |
| @@ -3476,8 +4220,8 @@ struct DeviceState { | |||
| 3476 | "in %.3f ms on average (pages %.3f, fixing copied slots %.3f, %llu left to retries past the " | 4220 | "in %.3f ms on average (pages %.3f, fixing copied slots %.3f, %llu left to retries past the " |
| 3477 | "budget, retrying %.3f: %.1f slots a " | 4221 | "budget, retrying %.3f: %.1f slots a " |
| 3478 | "submission, %zu waiting), %llu write faults; %llu title V#s rebased, %llu with no copy given " | 4222 | "submission, %zu waiting), %llu write faults; %llu title V#s rebased, %llu with no copy given " |
| 3479 | "no records, T#s %llu known, %llu bound, %llu naming no texture, %llu refused, %llu words " | 4223 | "no records (%zu naming nothing waiting for another look), T#s %llu known, %llu bound, %llu " |
| 3480 | "that are no T# (data)\n", | 4224 | "naming no texture, %llu refused, %llu words that are no V# or T# (data, null in the copy)\n", |
| 3481 | static_cast<unsigned long long>(heap->console_va), heap->imported ? "imported" : "copy", | 4225 | static_cast<unsigned long long>(heap->console_va), heap->imported ? "imported" : "copy", |
| 3482 | static_cast<unsigned long long>(heap->refreshes), "copied", | 4226 | static_cast<unsigned long long>(heap->refreshes), "copied", |
| 3483 | double(heap->copied) / 1024.0 / count, | 4227 | double(heap->copied) / 1024.0 / count, |
| @@ -3486,17 +4230,60 @@ struct DeviceState { | |||
| 3486 | double(heap->retried) / count, heap->retries.size(), | 4230 | double(heap->retried) / count, heap->retries.size(), |
| 3487 | static_cast<unsigned long long>(heap->pages ? heap->pages->faults() : 0), | 4231 | static_cast<unsigned long long>(heap->pages ? heap->pages->faults() : 0), |
| 3488 | static_cast<unsigned long long>(heap->vsharps), | 4232 | static_cast<unsigned long long>(heap->vsharps), |
| 3489 | static_cast<unsigned long long>(heap->unbacked), | 4233 | static_cast<unsigned long long>(heap->unbacked), heap->empty_slots.size(), |
| 3490 | static_cast<unsigned long long>(heap->images[unsigned(TitleImage::known)]), | 4234 | static_cast<unsigned long long>(heap->images[unsigned(TitleImage::known)]), |
| 3491 | static_cast<unsigned long long>(heap->images[unsigned(TitleImage::bound)]), | 4235 | static_cast<unsigned long long>(heap->images[unsigned(TitleImage::bound)]), |
| 3492 | static_cast<unsigned long long>(heap->images[unsigned(TitleImage::unknown)]), | 4236 | static_cast<unsigned long long>(heap->images[unsigned(TitleImage::unknown)]), |
| 3493 | static_cast<unsigned long long>(heap->images[unsigned(TitleImage::refused)]), | 4237 | static_cast<unsigned long long>(heap->images[unsigned(TitleImage::refused)]), |
| 3494 | static_cast<unsigned long long>(heap->images[unsigned(TitleImage::not_tsharp)])); | 4238 | static_cast<unsigned long long>(heap->images[unsigned(TitleImage::not_tsharp)])); |
| 4239 | if (heap->release_sweeps && filter_heap_releases()) | ||
| 4240 | std::fprintf(stderr, "[rt] CPU release filter: %llu sweeps, %llu live slots, %llu fixes, %llu rebases, %llu full fallbacks\n", | ||
| 4241 | (unsigned long long)heap->release_sweeps, (unsigned long long)heap->release_candidates, | ||
| 4242 | (unsigned long long)heap->release_fixes, (unsigned long long)heap->release_rebases, | ||
| 4243 | (unsigned long long)heap->release_full); | ||
| 4244 | heap->release_sweeps = heap->release_candidates = heap->release_fixes = heap->release_rebases = heap->release_full = 0; | ||
| 4245 | if (heap->resource_heap) { | ||
| 4246 | std::uint64_t paths[kVsharpPathCount]; | ||
| 4247 | for (unsigned i = 0; i < kVsharpPathCount; ++i) | ||
| 4248 | paths[i] = vsharp_paths[i].exchange(0, std::memory_order_relaxed); | ||
| 4249 | std::fprintf(stderr, | ||
| 4250 | "[rt] d3d12: console descriptor heap 0x%llx changed slots per submission: %.1f zero, %.1f " | ||
| 4251 | "V# pairs, %.1f T#s, %.1f other; V# halves %.1f, %.1f%% seen before; rescans %llu (%.1f " | ||
| 4252 | "V# slots and %.3f ms each); V# resolutions since the last line: alias %llu, alias " | ||
| 4253 | "refused %llu, arena %llu, geometry %llu, window %llu, none %llu\n", | ||
| 4254 | static_cast<unsigned long long>(heap->console_va), double(heap->changed[0]) / count, | ||
| 4255 | double(heap->changed[1]) / count, double(heap->changed[2]) / count, | ||
| 4256 | double(heap->changed[3]) / count, double(heap->vsharp_halves) / count, | ||
| 4257 | heap->vsharp_halves ? 100.0 * double(heap->vsharp_repeats) / double(heap->vsharp_halves) | ||
| 4258 | : 0.0, | ||
| 4259 | static_cast<unsigned long long>(heap->rescans), | ||
| 4260 | heap->rescans ? double(heap->rescanned) / double(heap->rescans) : 0.0, | ||
| 4261 | heap->rescans ? heap->rescan_ms / double(heap->rescans) : 0.0, | ||
| 4262 | static_cast<unsigned long long>(paths[0]), static_cast<unsigned long long>(paths[1]), | ||
| 4263 | static_cast<unsigned long long>(paths[2]), static_cast<unsigned long long>(paths[3]), | ||
| 4264 | static_cast<unsigned long long>(paths[4]), static_cast<unsigned long long>(paths[5])); | ||
| 4265 | for (auto& n : heap->changed) n = 0; | ||
| 4266 | heap->vsharp_halves = heap->vsharp_repeats = heap->rescans = heap->rescanned = 0; | ||
| 4267 | heap->rescan_ms = 0; | ||
| 4268 | } | ||
| 4269 | if (heap->gpu >= 0) log_console_heap_gpu(*heap, count); | ||
| 4270 | std::string refused_breakdown; | ||
| 4271 | for (const auto& [reason, count] : heap->refused_reasons) | ||
| 4272 | refused_breakdown += (refused_breakdown.empty() ? "" : "; ") + reason + " " + std::to_string(count); | ||
| 4273 | if (!refused_breakdown.empty()) | ||
| 4274 | std::fprintf(stderr, "[rt] d3d12: console descriptor heap 0x%llx unbound T#s by reason: %s\n", | ||
| 4275 | static_cast<unsigned long long>(heap->console_va), refused_breakdown.c_str()); | ||
| 4276 | heap->refused_reasons.clear(); | ||
| 3495 | heap->copied = heap->vsharps = heap->unbacked = heap->retried = heap->deferred_fixes = 0; | 4277 | heap->copied = heap->vsharps = heap->unbacked = heap->retried = heap->deferred_fixes = 0; |
| 3496 | for (auto& n : heap->images) n = 0; | 4278 | for (auto& n : heap->images) n = 0; |
| 3497 | heap->ms = heap->pages_ms = heap->fix_ms = heap->retry_ms = 0; | 4279 | heap->ms = heap->pages_ms = heap->fix_ms = heap->retry_ms = 0; |
| 4280 | if (start - arena_log_time >= std::chrono::seconds(60)) { | ||
| 4281 | arena_log_time = start; | ||
| 4282 | report_arena_peak(); | ||
| 4283 | } | ||
| 3498 | } | 4284 | } |
| 3499 | } | 4285 | } |
| 4286 | std::chrono::steady_clock::time_point arena_log_time{}; // console_heap_mutex held | ||
| 3500 | 4287 | ||
| 3501 | // The heap's pages imported as host memory (see above): true with `heap` filled in, false when they cannot be | 4288 | // The heap's pages imported as host memory (see above): true with `heap` filled in, false when they cannot be |
| 3502 | // (no VK_EXT_external_memory_host, a page not committed or write-combined, a driver refusal, or a device address | 4289 | // (no VK_EXT_external_memory_host, a page not committed or write-combined, a driver refusal, or a device address |
| @@ -3588,13 +4375,46 @@ struct DeviceState { | |||
| 3588 | heap->bytes = bytes; | 4375 | heap->bytes = bytes; |
| 3589 | // Self-written V#s must be rebased without changing the title's descriptor bytes. | 4376 | // Self-written V#s must be rebased without changing the title's descriptor bytes. |
| 3590 | // A directly indexed heap can lie outside the main arena and still fit in a 32-bit shader offset. | 4377 | // A directly indexed heap can lie outside the main arena and still fit in a 32-bit shader offset. |
| 4378 | // A resource heap's copy is followed by null slots (heap_guard_bytes), rounded so the whole stays 64 KiB | ||
| 4379 | // aligned for an import. | ||
| 3591 | heap->resource_heap = resource_heap; | 4380 | heap->resource_heap = resource_heap; |
| 3592 | // Round the guarded import up to Wine's allocation granularity. | 4381 | // Round the guarded import up to Wine's allocation granularity. |
| 3593 | if (bytes > (1ull << 32)) return false; | 4382 | if (bytes > (1ull << 32)) return false; |
| 3594 | const VkDeviceSize requested = resource_heap ? heap_guard_bytes() : 0; | 4383 | const VkDeviceSize requested = resource_heap ? heap_guard_bytes() : 0; |
| 3595 | const VkDeviceSize guard = requested && bytes + requested <= (1ull << 32) | 4384 | const VkDeviceSize guard = requested && bytes + requested <= (1ull << 32) |
| 3596 | ? ((bytes + requested + 65535) & ~VkDeviceSize(65535)) - bytes : 0; | 4385 | ? ((bytes + requested + 65535) & ~VkDeviceSize(65535)) - bytes : 0; |
| 3597 | if (resource_heap && geometry.cap()) { | 4386 | // LEONIDA_CONSOLE_HEAP_ARENA=1 (with LEONIDA_CONSOLE_HEAP_GPU): the copy and its guard in the arena, which is |
| 4387 | // device-local where the device has it (ReBAR), not in an import of host memory: every draw's descriptor | ||
| 4388 | // fetch and the pass's writes stay on the card. The CPU never writes the copy then (the pass does); [input | | ||
| 4389 | // previous] stay in host memory. No room in the arena: the import, as without the switch. | ||
| 4390 | bool in_arena = false; | ||
| 4391 | if (resource_heap && geometry.cap() && heap_gpu && console_heap_gpu_enabled() && console_heap_arena_enabled() && | ||
| 4392 | bytes <= SIZE_MAX / 2) { | ||
| 4393 | VkDeviceSize offset = 0; | ||
| 4394 | const VkDeviceSize size = bytes + guard; | ||
| 4395 | if (arena_allocate(size, 65536, offset, arena_descriptor_heap)) { | ||
| 4396 | heap->scratch.reset(static_cast<std::uint8_t*>( | ||
| 4397 | VirtualAlloc(nullptr, bytes * 2, MEM_TOP_DOWN | MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE))); | ||
| 4398 | if (heap->scratch) { | ||
| 4399 | heap->input = heap->scratch.get(); | ||
| 4400 | heap->previous = heap->scratch.get() + bytes; | ||
| 4401 | heap->shader_va = offset; | ||
| 4402 | heap->copy = arena.mapped + offset; | ||
| 4403 | heap->guard = guard; | ||
| 4404 | heap->imported = false; | ||
| 4405 | in_arena = true; | ||
| 4406 | std::fprintf(stderr, "[rt] d3d12: LEONIDA_CONSOLE_HEAP_ARENA: console descriptor heap 0x%llx's " | ||
| 4407 | "copy and %llu MiB guard in the arena at 0x%llx (memory type %u)\n", | ||
| 4408 | static_cast<unsigned long long>(console_va), | ||
| 4409 | static_cast<unsigned long long>(guard >> 20), | ||
| 4410 | static_cast<unsigned long long>(offset), unsigned(arena.memory_type)); | ||
| 4411 | } else { | ||
| 4412 | arena_release(offset, size, arena_descriptor_heap); | ||
| 4413 | } | ||
| 4414 | } | ||
| 4415 | } | ||
| 4416 | if (in_arena) { | ||
| 4417 | } else if (resource_heap && geometry.cap()) { | ||
| 3598 | if (bytes > (SIZE_MAX - guard) / 3) return false; | 4418 | if (bytes > (SIZE_MAX - guard) / 3) return false; |
| 3599 | // [copy | guard | input | previous]: the import covers the copy and its guard. | 4419 | // [copy | guard | input | previous]: the import covers the copy and its guard. |
| 3600 | heap->scratch.reset(static_cast<std::uint8_t*>(VirtualAlloc(nullptr, bytes * 3 + guard, MEM_TOP_DOWN | | 4420 | heap->scratch.reset(static_cast<std::uint8_t*>(VirtualAlloc(nullptr, bytes * 3 + guard, MEM_TOP_DOWN | |
| @@ -3649,6 +4469,8 @@ struct DeviceState { | |||
| 3649 | heap->previous = heap->made.data(); | 4469 | heap->previous = heap->made.data(); |
| 3650 | } | 4470 | } |
| 3651 | heap->retry.assign(std::size_t(bytes / kDescriptorSize), 0); | 4471 | heap->retry.assign(std::size_t(bytes / kDescriptorSize), 0); |
| 4472 | heap->live_vsharps.reset(std::size_t(bytes / kDescriptorSize)); | ||
| 4473 | heap->unmapped_tries.assign(std::size_t(bytes / kDescriptorSize), 0); | ||
| 3652 | heap->pages = make_shadow_pages(reinterpret_cast<const std::uint8_t*>(static_cast<std::uintptr_t>(console_va)), | 4474 | heap->pages = make_shadow_pages(reinterpret_cast<const std::uint8_t*>(static_cast<std::uintptr_t>(console_va)), |
| 3653 | heap->input, std::size_t(bytes)); | 4475 | heap->input, std::size_t(bytes)); |
| 3654 | } | 4476 | } |
| @@ -3656,8 +4478,12 @@ struct DeviceState { | |||
| 3656 | if (shader_va != console_va) console_heap_ranges().add(console_va, bytes, shader_va); | 4478 | if (shader_va != console_va) console_heap_ranges().add(console_va, bytes, shader_va); |
| 3657 | const bool imported = heap->imported; | 4479 | const bool imported = heap->imported; |
| 3658 | const VkDeviceSize guarded = heap->guard; | 4480 | const VkDeviceSize guarded = heap->guard; |
| 4481 | arena_guard_bytes.fetch_add(guarded, std::memory_order_relaxed); | ||
| 4482 | if (heap_gpu && console_heap_gpu_enabled() && heap->scratch && resource_heap && !imported) | ||
| 4483 | attach_console_heap_gpu(*heap); | ||
| 3659 | { | 4484 | { |
| 3660 | std::lock_guard lock(console_heap_mutex); | 4485 | std::lock_guard lock(console_heap_mutex); |
| 4486 | if (heap->gpu >= 0) gpu_heaps[std::size_t(heap->gpu)] = heap.get(); | ||
| 3661 | if (!imported) refresh_console_heap(*heap); | 4487 | if (!imported) refresh_console_heap(*heap); |
| 3662 | if (heap->copy) { | 4488 | if (heap->copy) { |
| 3663 | std::unique_lock ranges(console_copy_ranges_mutex); | 4489 | std::unique_lock ranges(console_copy_ranges_mutex); |
| @@ -3666,13 +4492,14 @@ struct DeviceState { | |||
| 3666 | console_heaps.push_back(std::move(heap)); | 4492 | console_heaps.push_back(std::move(heap)); |
| 3667 | } | 4493 | } |
| 3668 | std::fprintf(stderr, | 4494 | std::fprintf(stderr, |
| 3669 | "[rt] d3d12: console descriptor heap 0x%llx (%llu KiB): shaders read it at heap_base + 0x%llx, %s; " | 4495 | "[rt] d3d12: console %s descriptor heap 0x%llx (%llu KiB): shaders read it at heap_base + 0x%llx, " |
| 3670 | "%llu KiB of null slots after it\n", | 4496 | "%s; %llu KiB of null slots after it%s\n", |
| 3671 | static_cast<unsigned long long>(console_va), static_cast<unsigned long long>(bytes >> 10), | 4497 | resource_heap ? "CBV/SRV/UAV" : "sampler", static_cast<unsigned long long>(console_va), |
| 3672 | static_cast<unsigned long long>(shader_va), | 4498 | static_cast<unsigned long long>(bytes >> 10), static_cast<unsigned long long>(shader_va), |
| 3673 | imported ? "the title's pages imported as host memory" | 4499 | imported ? "the title's pages imported as host memory" |
| 3674 | : "a descriptor copy brought up to date before every submission", | 4500 | : "a descriptor copy brought up to date before every submission", |
| 3675 | static_cast<unsigned long long>(guarded >> 10)); | 4501 | static_cast<unsigned long long>(guarded >> 10), |
| 4502 | imported && resource_heap ? " (imported pages have no guard)" : ""); | ||
| 3676 | return true; | 4503 | return true; |
| 3677 | } | 4504 | } |
| 3678 | 4505 | ||
| @@ -3699,9 +4526,21 @@ struct DeviceState { | |||
| 3699 | console_heaps.erase(it); | 4526 | console_heaps.erase(it); |
| 3700 | std::unique_lock ranges(console_copy_ranges_mutex); | 4527 | std::unique_lock ranges(console_copy_ranges_mutex); |
| 3701 | std::erase_if(console_copy_ranges, [console_va](const auto& r) { return r.first == console_va; }); | 4528 | std::erase_if(console_copy_ranges, [console_va](const auto& r) { return r.first == console_va; }); |
| 4529 | if (heap->gpu >= 0) { | ||
| 4530 | heap_gpu->remove_heap(heap->gpu); | ||
| 4531 | gpu_heaps[std::size_t(heap->gpu)] = nullptr; | ||
| 4532 | } | ||
| 3702 | } | 4533 | } |
| 3703 | console_heap_ranges().remove(console_va); | 4534 | console_heap_ranges().remove(console_va); |
| 3704 | heap->pages.reset(); | 4535 | heap->pages.reset(); |
| 4536 | if (heap->gpu >= 0) { | ||
| 4537 | // A pass recorded before remove_heap may still be on its way to the queue, and then reads `input` and | ||
| 4538 | // writes the copy: wait for it to be submitted, then for everything submitted. | ||
| 4539 | while (heap_gpu->uncommitted()) Sleep(0); | ||
| 4540 | context->wait_retire_ticket(context->submitted_retire_ticket()); | ||
| 4541 | if (heap->input_buffer) context->vk.vkDestroyBuffer(info.device, heap->input_buffer, nullptr); | ||
| 4542 | if (heap->input_memory) context->vk.vkFreeMemory(info.device, heap->input_memory, nullptr); | ||
| 4543 | } | ||
| 3705 | if (heap->buffer) { | 4544 | if (heap->buffer) { |
| 3706 | // As for an imported slot-133 buffer: the title may free its pages right after, so the memory goes once | 4545 | // As for an imported slot-133 buffer: the title may free its pages right after, so the memory goes once |
| 3707 | // what was submitted retires, not through the deferred queue. | 4546 | // what was submitted retires, not through the deferred queue. |
| @@ -3712,6 +4551,1110 @@ struct DeviceState { | |||
| 3712 | } else { | 4551 | } else { |
| 3713 | arena_release(heap->shader_va, heap->bytes + heap->guard, arena_descriptor_heap); | 4552 | arena_release(heap->shader_va, heap->bytes + heap->guard, arena_descriptor_heap); |
| 3714 | } | 4553 | } |
| 4554 | arena_guard_bytes.fetch_sub(heap->guard, std::memory_order_relaxed); | ||
| 4555 | } | ||
| 4556 | |||
| 4557 | // ---- LEONIDA_CONSOLE_HEAP_GPU=1: the console heaps' V#s rebased by a compute pass (src/console_heap_gpu.h) ---- | ||
| 4558 | // Before every submission the CPU still finds the changed slots (the heap's ShadowPages, then a compare with the | ||
| 4559 | // bytes each slot was last made from) and registers the T#s, as fix_console_slot does; every changed slot is then | ||
| 4560 | // queued for the pass, which writes it into the copy at the start of the submission (the context's prelude). A | ||
| 4561 | // V# half the pass's tables cannot answer is written with no records and comes back as a miss once its submission | ||
| 4562 | // is done: resolved here with vsharp_address (which may make a geometry copy) within LEONIDA_CONSOLE_GPU_RESOLVE_US | ||
| 4563 | // a refresh (2000 by default), its answer entered in the key table and its slots queued again. Words that got no | ||
| 4564 | // backing are asked again every LEONIDA_CONSOLE_GPU_RETRY_MS (500), on a timer to bound the per-submission cost. | ||
| 4565 | // When a backing or an alias range goes, the key entries that answered into it are dropped and every V# slot of | ||
| 4566 | // the heap is translated again (on the GPU: a list of slot indices). | ||
| 4567 | std::unique_ptr<leonida::ConsoleHeapGpu> heap_gpu; | ||
| 4568 | std::array<ConsoleHeap*, leonida::ConsoleHeapGpu::kMaxHeaps> gpu_heaps{}; // console_heap_mutex | ||
| 4569 | std::vector<std::pair<std::uint64_t, std::uint64_t>> released_ranges; // (shader VA, bytes); backing_mutex | ||
| 4570 | struct GpuKeyHash { | ||
| 4571 | std::size_t operator()(const leonida::ConsoleHeapKeys::Key& k) const { | ||
| 4572 | return leonida::ConsoleHeapKeys::hash(k); | ||
| 4573 | } | ||
| 4574 | }; | ||
| 4575 | // The rest: console_heap_mutex. Unresolved words with the slots that missed on them (heap << 28 | slot), and | ||
| 4576 | // whether the resolver has them. | ||
| 4577 | struct GpuUnresolved { | ||
| 4578 | std::vector<std::uint32_t> slots; | ||
| 4579 | bool asked = false; | ||
| 4580 | }; | ||
| 4581 | std::unordered_map<leonida::ConsoleHeapKeys::Key, GpuUnresolved, GpuKeyHash> gpu_unresolved; | ||
| 4582 | // The resolver: a thread of ours that answers missed words with vsharp_address, off the submitting thread (one | ||
| 4583 | // answer can wait milliseconds for the geometry worker's lock). | ||
| 4584 | // Requests and answers pass under its own mutex; the refresh hands words over and takes answers, never waits. | ||
| 4585 | struct GpuAnswer { | ||
| 4586 | leonida::ConsoleHeapKeys::Key key; | ||
| 4587 | std::uint64_t to, span; | ||
| 4588 | bool retry; | ||
| 4589 | }; | ||
| 4590 | struct GpuResolver { | ||
| 4591 | std::mutex mutex; | ||
| 4592 | std::condition_variable wake; | ||
| 4593 | bool stop = false; | ||
| 4594 | std::vector<std::pair<leonida::ConsoleHeapKeys::Key, bool>> requests; // (words, a retry of no backing) | ||
| 4595 | std::vector<GpuAnswer> answers; | ||
| 4596 | // T#s to register (bind_title_image), the slot's words: the refresh only decodes them. Resolver-only state: | ||
| 4597 | // the words registered recently (not asked again) and those whose texture is still to come (asked again). | ||
| 4598 | std::vector<leonida::gfx10::ImageWords> tsharps; | ||
| 4599 | std::unordered_set<std::uint64_t> registered; | ||
| 4600 | std::deque<std::pair<std::chrono::steady_clock::time_point, leonida::gfx10::ImageWords>> waiting; | ||
| 4601 | std::thread thread; | ||
| 4602 | ~GpuResolver() { halt(); } | ||
| 4603 | void halt() { | ||
| 4604 | { | ||
| 4605 | std::lock_guard lock(mutex); | ||
| 4606 | stop = true; | ||
| 4607 | } | ||
| 4608 | wake.notify_all(); | ||
| 4609 | if (thread.joinable()) thread.join(); | ||
| 4610 | } | ||
| 4611 | }; | ||
| 4612 | std::unique_ptr<GpuResolver> gpu_resolver; | ||
| 4613 | std::array<std::atomic<std::uint64_t>, 5> gpu_tsharps{}; // the resolver's T# registrations, by TitleImage | ||
| 4614 | std::size_t gpu_asked = 0; // requests handed over and not answered yet | ||
| 4615 | struct GpuUnbacked { | ||
| 4616 | std::chrono::steady_clock::time_point at; // when it may be asked again | ||
| 4617 | leonida::ConsoleHeapKeys::Key key; | ||
| 4618 | std::uint32_t tries = 0; // asked again so far: the wait doubles each time, up to 64x retry_ms | ||
| 4619 | }; | ||
| 4620 | std::deque<GpuUnbacked> gpu_unbacked; // words answered "no backing", by when they may be asked again (roughly) | ||
| 4621 | std::unordered_map<leonida::ConsoleHeapKeys::Key, std::uint32_t, GpuKeyHash> gpu_unbacked_tries; // being asked | ||
| 4622 | std::uint64_t gpu_alias_generation = ~0ull; | ||
| 4623 | std::chrono::steady_clock::time_point gpu_ranges_at{}; | ||
| 4624 | std::vector<leonida::ConsoleHeapRange> gpu_ranges; | ||
| 4625 | leonida::ConsoleHeapSpans gpu_backed, gpu_ask; | ||
| 4626 | std::uint64_t gpu_backed_generation = ~0ull, gpu_ask_generation = ~0ull; | ||
| 4627 | std::uint64_t gpu_backed_blocks = ~0ull; // the title-window blocks' layout generations at the last rebuild | ||
| 4628 | std::chrono::steady_clock::time_point gpu_backed_at{}; | ||
| 4629 | std::vector<std::uint32_t> gpu_queue_scratch; | ||
| 4630 | bool gpu_rescan = false, gpu_rescan_after_resolve = false; | ||
| 4631 | std::chrono::steady_clock::time_point gpu_rescan_asked{}; | ||
| 4632 | // LEONIDA_CONSOLE_GPU_FILTER=1 (default: LEONIDA_CONSOLE_RELEASE_FILTER's value): a release, an alias range that | ||
| 4633 | // went or a word answered since asks for a rescan of the slots it touches (the release filter's interval rule, | ||
| 4634 | // 8a22e92c8) instead of every V# slot: the GPU passes over the rest on its device-local metadata. | ||
| 4635 | // gpu_filter_shader: shader-VA spans (released backings, alias copies that went); gpu_filter_title: title VAs | ||
| 4636 | // (words backed since). Overflows and key resets still rescan everything. | ||
| 4637 | static bool gpu_filter_enabled() { | ||
| 4638 | static const bool on = [] { | ||
| 4639 | char text[8] = {}; | ||
| 4640 | if (GetEnvironmentVariableA("LEONIDA_CONSOLE_GPU_FILTER", text, sizeof(text)) && text[0]) | ||
| 4641 | return text[0] == '1'; | ||
| 4642 | return GetEnvironmentVariableA("LEONIDA_CONSOLE_RELEASE_FILTER", text, sizeof(text)) && text[0] == '1'; | ||
| 4643 | }(); | ||
| 4644 | return on; | ||
| 4645 | } | ||
| 4646 | bool gpu_rescan_filtered = false; | ||
| 4647 | leonida::ConsoleHeapSpans gpu_filter_shader, gpu_filter_title; | ||
| 4648 | void request_rescan_after_resolve() { | ||
| 4649 | if (!gpu_rescan_after_resolve) gpu_rescan_asked = std::chrono::steady_clock::now(); | ||
| 4650 | gpu_rescan_after_resolve = true; | ||
| 4651 | } | ||
| 4652 | struct GpuMiss { | ||
| 4653 | leonida::ConsoleHeapKeys::Key key; | ||
| 4654 | std::uint32_t code; // heap << 28 | slot; UINT32_MAX once handled | ||
| 4655 | }; | ||
| 4656 | std::vector<GpuMiss> gpu_miss_scratch; | ||
| 4657 | struct GpuCounts { | ||
| 4658 | std::uint64_t misses = 0, resolved = 0, none = 0, flips = 0, rescans = 0, dropped = 0, released = 0; | ||
| 4659 | std::uint64_t known_misses = 0, put_failed = 0, backed_rebuilds = 0, backed_cuts = 0, key_resets = 0; | ||
| 4660 | std::uint64_t retried = 0, filtered_rescans = 0; | ||
| 4661 | double backed_ms = 0; | ||
| 4662 | double resolve_ms = 0, begin_ms = 0; | ||
| 4663 | double part_ms[5] = {}; // before: alias probes, drain + releases, range table, backed table, ask table | ||
| 4664 | } gpu_counts; | ||
| 4665 | |||
| 4666 | // LEONIDA_SHADOW_GPU=1 copies aliased shadow pages on the GPU at the start of the submission. | ||
| 4667 | // The source uses VK_EXT_external_memory_host to import the mapped title section. An import is | ||
| 4668 | // made per 2 MiB-aligned window of the view, kept while xmem's map journal shows no change over it, and lives until | ||
| 4669 | // the last pass that copies from it retires. Destinations outside the arena, and pages that will not import, are | ||
| 4670 | // copied by the CPU as before. | ||
| 4671 | static bool shadow_gpu_enabled() { | ||
| 4672 | static const bool on = [] { | ||
| 4673 | char value[4] = {}; | ||
| 4674 | return GetEnvironmentVariableA("LEONIDA_SHADOW_GPU", value, sizeof(value)) == 1 && value[0] == '1'; | ||
| 4675 | }(); | ||
| 4676 | return on; | ||
| 4677 | } | ||
| 4678 | struct ShadowImport { | ||
| 4679 | DeviceState* device = nullptr; | ||
| 4680 | std::uintptr_t base = 0; | ||
| 4681 | std::size_t bytes = 0; | ||
| 4682 | VkBuffer buffer = VK_NULL_HANDLE; | ||
| 4683 | VkDeviceMemory memory = VK_NULL_HANDLE; | ||
| 4684 | std::uint64_t generation = 0; // title_memory_map's, when last found unchanged | ||
| 4685 | ~ShadowImport() { | ||
| 4686 | if (buffer) device->context->vk.vkDestroyBuffer(device->info.device, buffer, nullptr); | ||
| 4687 | if (memory) device->context->vk.vkFreeMemory(device->info.device, memory, nullptr); | ||
| 4688 | } | ||
| 4689 | }; | ||
| 4690 | std::mutex shadow_import_mutex; | ||
| 4691 | std::map<std::uintptr_t, std::shared_ptr<ShadowImport>> shadow_imports; // by base | ||
| 4692 | std::uint64_t shadow_import_bytes = 0; | ||
| 4693 | struct ShadowGpuCounts { | ||
| 4694 | std::uint64_t copies = 0, bytes = 0, imports = 0, imported = 0, dropped = 0, refused = 0, outside = 0; | ||
| 4695 | } shadow_gpu_counts; // shadow_import_mutex | ||
| 4696 | |||
| 4697 | static bool shadow_gpu_copy(void* context, std::uint8_t* to, const std::uint8_t* from, std::size_t bytes) { | ||
| 4698 | return static_cast<DeviceState*>(context)->gpu_copy_shadow(to, from, bytes); | ||
| 4699 | } | ||
| 4700 | // Shadows with memory of their own (no room in the arena): their mapping and buffer, for gpu_copy_shadow. | ||
| 4701 | struct CopyTarget { | ||
| 4702 | std::size_t bytes; | ||
| 4703 | VkBuffer buffer; | ||
| 4704 | }; | ||
| 4705 | std::map<const std::uint8_t*, CopyTarget> copy_targets; // shadow_import_mutex | ||
| 4706 | void add_copy_target(const std::uint8_t* mapped, std::size_t bytes, VkBuffer buffer) { | ||
| 4707 | if (!shadow_gpu_enabled() || !mapped || !buffer) return; | ||
| 4708 | std::lock_guard lock(shadow_import_mutex); | ||
| 4709 | copy_targets[mapped] = {bytes, buffer}; | ||
| 4710 | } | ||
| 4711 | // Before the buffer goes: no copy into it is recorded after this (one already recorded runs before it is freed: | ||
| 4712 | // the buffer goes to the deferred queue, behind the submission that recorded it). | ||
| 4713 | void remove_copy_target(const std::uint8_t* mapped) { | ||
| 4714 | if (!shadow_gpu_enabled() || !mapped) return; | ||
| 4715 | VkBuffer buffer = VK_NULL_HANDLE; | ||
| 4716 | { | ||
| 4717 | std::lock_guard lock(shadow_import_mutex); | ||
| 4718 | const auto it = copy_targets.find(mapped); | ||
| 4719 | if (it == copy_targets.end()) return; | ||
| 4720 | buffer = it->second.buffer; | ||
| 4721 | copy_targets.erase(it); | ||
| 4722 | } | ||
| 4723 | if (heap_gpu) heap_gpu->drop_copies_to(buffer); | ||
| 4724 | } | ||
| 4725 | // Where [to, to + n) is on the GPU: the arena, a title-window block outside it, or a shadow's own buffer. | ||
| 4726 | bool copy_destination(const std::uint8_t* to, std::size_t n, VkBuffer& buffer, VkDeviceSize& offset) { | ||
| 4727 | if (arena.mapped && to >= arena.mapped && to + n <= arena.mapped + arena.size) { | ||
| 4728 | buffer = arena.buffer; | ||
| 4729 | offset = VkDeviceSize(to - arena.mapped); | ||
| 4730 | return true; | ||
| 4731 | } | ||
| 4732 | if (external_windows.find_mapped(to, n, buffer, offset)) return true; | ||
| 4733 | auto it = copy_targets.upper_bound(to); // shadow_import_mutex held | ||
| 4734 | if (it == copy_targets.begin()) return false; | ||
| 4735 | --it; | ||
| 4736 | if (to < it->first || n > it->second.bytes || std::size_t(to - it->first) > it->second.bytes - n) return false; | ||
| 4737 | buffer = it->second.buffer; | ||
| 4738 | offset = VkDeviceSize(to - it->first); | ||
| 4739 | return true; | ||
| 4740 | } | ||
| 4741 | bool gpu_copy_shadow(std::uint8_t* to, const std::uint8_t* from, std::size_t n) { | ||
| 4742 | if (!heap_gpu || !n) return false; | ||
| 4743 | std::lock_guard lock(shadow_import_mutex); | ||
| 4744 | VkBuffer dst_buffer = VK_NULL_HANDLE; | ||
| 4745 | VkDeviceSize dst_offset = 0; | ||
| 4746 | if (!copy_destination(to, n, dst_buffer, dst_offset)) { | ||
| 4747 | ++shadow_gpu_counts.outside; | ||
| 4748 | return false; | ||
| 4749 | } | ||
| 4750 | const auto src = reinterpret_cast<std::uintptr_t>(from); | ||
| 4751 | std::shared_ptr<ShadowImport> found; | ||
| 4752 | auto it = shadow_imports.upper_bound(src); | ||
| 4753 | if (it != shadow_imports.begin()) { | ||
| 4754 | --it; | ||
| 4755 | ShadowImport& cand = *it->second; | ||
| 4756 | if (src >= cand.base && src + n <= cand.base + cand.bytes) { | ||
| 4757 | std::uint64_t now = 0; | ||
| 4758 | bool moved = false; | ||
| 4759 | if (!leonida::title_memory_map::changes_since(cand.generation, now, cand.base, cand.base + cand.bytes, | ||
| 4760 | [&](std::uintptr_t, std::uintptr_t) { moved = true; })) | ||
| 4761 | moved = true; | ||
| 4762 | if (moved) { | ||
| 4763 | shadow_import_bytes -= cand.bytes; | ||
| 4764 | shadow_imports.erase(it); | ||
| 4765 | ++shadow_gpu_counts.dropped; | ||
| 4766 | } else { | ||
| 4767 | cand.generation = now; | ||
| 4768 | found = it->second; | ||
| 4769 | } | ||
| 4770 | } | ||
| 4771 | } | ||
| 4772 | if (!found && !(found = make_shadow_import(src, n))) { | ||
| 4773 | ++shadow_gpu_counts.refused; | ||
| 4774 | return false; | ||
| 4775 | } | ||
| 4776 | heap_gpu->queue_copy(found->buffer, src - found->base, dst_buffer, dst_offset, n, found); | ||
| 4777 | ++shadow_gpu_counts.copies; | ||
| 4778 | shadow_gpu_counts.bytes += n; | ||
| 4779 | return true; | ||
| 4780 | } | ||
| 4781 | // An import of the committed, readable view region around [src, src + n): its 2 MiB-aligned window, inside the | ||
| 4782 | // region. Null when it does not hold all of it, the budget (LEONIDA_SHADOW_GPU_MB, 1024) is spent, or the driver | ||
| 4783 | // refuses. shadow_import_mutex held. | ||
| 4784 | std::shared_ptr<ShadowImport> make_shadow_import(std::uintptr_t src, std::size_t n) { | ||
| 4785 | static const std::uint64_t budget = [] { | ||
| 4786 | char text[16] = {}; | ||
| 4787 | const DWORD c = GetEnvironmentVariableA("LEONIDA_SHADOW_GPU_MB", text, sizeof(text)); | ||
| 4788 | return (c > 0 && c < sizeof(text) ? std::strtoull(text, nullptr, 10) : 1024ull) << 20; | ||
| 4789 | }(); | ||
| 4790 | const std::uint64_t generation = leonida::title_memory_map::generation(); | ||
| 4791 | MEMORY_BASIC_INFORMATION region{}; | ||
| 4792 | const auto refuse = [&](const char* why) -> std::shared_ptr<ShadowImport> { | ||
| 4793 | static std::atomic<int> logged{0}; | ||
| 4794 | if (logged.fetch_add(1, std::memory_order_relaxed) < 8) | ||
| 4795 | std::fprintf(stderr, "[rt] d3d12: LEONIDA_SHADOW_GPU: no import of 0x%llx (+%zu; state 0x%lx protect 0x%lx " | ||
| 4796 | "type 0x%lx): %s; copied by the CPU\n", | ||
| 4797 | static_cast<unsigned long long>(src), n, static_cast<unsigned long>(region.State), | ||
| 4798 | static_cast<unsigned long>(region.Protect), static_cast<unsigned long>(region.Type), why); | ||
| 4799 | return nullptr; | ||
| 4800 | }; | ||
| 4801 | if (!VirtualQuery(reinterpret_cast<const void*>(src), ®ion, sizeof(region))) return refuse("no region"); | ||
| 4802 | if (region.State != MEM_COMMIT || !region.Protect || | ||
| 4803 | (region.Protect & (PAGE_NOACCESS | PAGE_GUARD | PAGE_WRITECOMBINE | PAGE_NOCACHE))) | ||
| 4804 | return refuse("not committed and readable"); | ||
| 4805 | // This import path supports mapped section views. | ||
| 4806 | if (region.Type != MEM_MAPPED) return refuse("not a section view"); | ||
| 4807 | constexpr std::uintptr_t kWindow = 2u << 20; | ||
| 4808 | const auto region_base = reinterpret_cast<std::uintptr_t>(region.BaseAddress); | ||
| 4809 | const std::uintptr_t region_end = region_base + region.RegionSize; | ||
| 4810 | const std::uintptr_t base = std::max(region_base, src & ~(kWindow - 1)); | ||
| 4811 | const std::uintptr_t end = std::min(region_end, (src + n + kWindow - 1) & ~(kWindow - 1)); | ||
| 4812 | if (src + n > end) return refuse("the run crosses the view's end"); | ||
| 4813 | if (shadow_import_bytes + (end - base) > budget) return refuse("LEONIDA_SHADOW_GPU_MB spent"); | ||
| 4814 | auto imp = std::make_shared<ShadowImport>(); | ||
| 4815 | imp->device = this; | ||
| 4816 | imp->base = base; | ||
| 4817 | imp->bytes = end - base; | ||
| 4818 | imp->generation = generation; | ||
| 4819 | VkDeviceAddress address = 0; | ||
| 4820 | if (!import_host_range(reinterpret_cast<void*>(base), imp->bytes, imp->buffer, imp->memory, address)) | ||
| 4821 | return refuse("the driver refused the import"); | ||
| 4822 | // Older imports over these pages are stale or redundant. | ||
| 4823 | for (auto it = shadow_imports.lower_bound(base > (64ull << 20) ? base - (64ull << 20) : 0); | ||
| 4824 | it != shadow_imports.end() && it->first < end;) { | ||
| 4825 | if (it->first + it->second->bytes > base) { | ||
| 4826 | shadow_import_bytes -= it->second->bytes; | ||
| 4827 | it = shadow_imports.erase(it); | ||
| 4828 | } else { | ||
| 4829 | ++it; | ||
| 4830 | } | ||
| 4831 | } | ||
| 4832 | shadow_imports[base] = imp; | ||
| 4833 | shadow_import_bytes += imp->bytes; | ||
| 4834 | ++shadow_gpu_counts.imports; | ||
| 4835 | shadow_gpu_counts.imported += imp->bytes; | ||
| 4836 | return imp; | ||
| 4837 | } | ||
| 4838 | |||
| 4839 | static bool console_heap_gpu_enabled() { | ||
| 4840 | static const bool on = [] { | ||
| 4841 | char value[4] = {}; | ||
| 4842 | return GetEnvironmentVariableA("LEONIDA_CONSOLE_HEAP_GPU", value, sizeof(value)) == 1 && value[0] == '1'; | ||
| 4843 | }(); | ||
| 4844 | return on; | ||
| 4845 | } | ||
| 4846 | static bool console_heap_arena_enabled() { | ||
| 4847 | static const bool on = [] { | ||
| 4848 | char value[4] = {}; | ||
| 4849 | return GetEnvironmentVariableA("LEONIDA_CONSOLE_HEAP_ARENA", value, sizeof(value)) == 1 && value[0] == '1'; | ||
| 4850 | }(); | ||
| 4851 | return on; | ||
| 4852 | } | ||
| 4853 | |||
| 4854 | void setup_console_heap_gpu(PFN_vkGetDeviceProcAddr get_device) { | ||
| 4855 | if ((!console_heap_gpu_enabled() && !shadow_gpu_enabled()) || !context || !get_device) return; | ||
| 4856 | auto gpu = std::make_unique<leonida::ConsoleHeapGpu>(get_device, info.device, memory); | ||
| 4857 | if (!gpu->init()) { | ||
| 4858 | std::fprintf(stderr, "[rt] d3d12: LEONIDA_CONSOLE_HEAP_GPU: the translation pass could not be made; the " | ||
| 4859 | "console heaps are fixed on the CPU\n"); | ||
| 4860 | return; | ||
| 4861 | } | ||
| 4862 | heap_gpu = std::move(gpu); | ||
| 4863 | heap_gpu->set_signed_offsets(signed_vsharp_offsets()); | ||
| 4864 | leonida::title_va_aliases().record_removals(true); | ||
| 4865 | context->set_prelude([this](VkCommandBuffer cb) { return heap_gpu->record(cb); }, | ||
| 4866 | [this](bool submitted, std::uint64_t ticket) { heap_gpu->commit(submitted, ticket); }); | ||
| 4867 | gpu_resolver = std::make_unique<GpuResolver>(); | ||
| 4868 | gpu_resolver->thread = std::thread([this, r = gpu_resolver.get()] { | ||
| 4869 | SetThreadDescription(GetCurrentThread(), L"leonida console heap resolver"); | ||
| 4870 | const auto words_hash = [](const leonida::gfx10::ImageWords& w) { | ||
| 4871 | std::uint64_t h = 1469598103934665603ull; | ||
| 4872 | for (const std::uint32_t x : w) h = (h ^ x) * 1099511628211ull; | ||
| 4873 | return h; | ||
| 4874 | }; | ||
| 4875 | const auto bind = [&](const leonida::gfx10::ImageWords& w) { | ||
| 4876 | const TitleImage result = bind_title_image(*this, w); | ||
| 4877 | gpu_tsharps[unsigned(result)].fetch_add(1, std::memory_order_relaxed); | ||
| 4878 | if (result == TitleImage::unknown || result == TitleImage::refused) { | ||
| 4879 | if (r->waiting.size() < 65536) r->waiting.emplace_back(std::chrono::steady_clock::now(), w); | ||
| 4880 | } else { | ||
| 4881 | if (r->registered.size() > (1u << 20)) r->registered.clear(); | ||
| 4882 | r->registered.insert(words_hash(w)); | ||
| 4883 | } | ||
| 4884 | }; | ||
| 4885 | for (;;) { | ||
| 4886 | std::vector<std::pair<leonida::ConsoleHeapKeys::Key, bool>> batch; | ||
| 4887 | std::vector<leonida::gfx10::ImageWords> tsharps; | ||
| 4888 | { | ||
| 4889 | std::unique_lock lock(r->mutex); | ||
| 4890 | // Woken for work, or every 100 ms for the T#s whose texture is still to come. | ||
| 4891 | r->wake.wait_for(lock, std::chrono::milliseconds(100), | ||
| 4892 | [r] { return r->stop || !r->requests.empty() || !r->tsharps.empty(); }); | ||
| 4893 | if (r->stop) return; | ||
| 4894 | batch.swap(r->requests); | ||
| 4895 | tsharps.swap(r->tsharps); | ||
| 4896 | } | ||
| 4897 | for (const auto& w : tsharps) | ||
| 4898 | if (!r->registered.count(words_hash(w))) bind(w); | ||
| 4899 | // Those still waiting for a texture, again every 500 ms, at most 256 a round. | ||
| 4900 | const auto now = std::chrono::steady_clock::now(); | ||
| 4901 | for (int n = 0; n < 256 && !r->waiting.empty() && | ||
| 4902 | now - r->waiting.front().first >= std::chrono::milliseconds(500); | ||
| 4903 | ++n) { | ||
| 4904 | const auto w = r->waiting.front().second; | ||
| 4905 | r->waiting.pop_front(); | ||
| 4906 | bind(w); | ||
| 4907 | } | ||
| 4908 | for (const auto& [key, retry] : batch) { | ||
| 4909 | std::uint64_t span = 0; | ||
| 4910 | const std::uint64_t to = resolve_vsharp_words(key, span); | ||
| 4911 | std::lock_guard lock(r->mutex); | ||
| 4912 | if (r->stop) return; | ||
| 4913 | r->answers.push_back({key, to, span, retry}); | ||
| 4914 | } | ||
| 4915 | } | ||
| 4916 | }); | ||
| 4917 | if (shadow_gpu_enabled()) { | ||
| 4918 | ShadowPages::gpu_copy_context = this; | ||
| 4919 | ShadowPages::gpu_copy = &shadow_gpu_copy; | ||
| 4920 | std::fprintf(stderr, "[rt] d3d12: LEONIDA_SHADOW_GPU=1: slot-133 shadows' aliased pages are copied by the " | ||
| 4921 | "GPU from imports of the title's pages\n"); | ||
| 4922 | } | ||
| 4923 | if (console_heap_gpu_enabled()) | ||
| 4924 | std::fprintf(stderr, "[rt] d3d12: LEONIDA_CONSOLE_HEAP_GPU=1: console heap V#s are rebased by a compute pass " | ||
| 4925 | "at the start of each submission\n"); | ||
| 4926 | } | ||
| 4927 | |||
| 4928 | // `bytes` of host memory at `host` as a buffer the GPU reads by its device address. False: not importable. | ||
| 4929 | bool import_host_range(void* host, VkDeviceSize bytes, VkBuffer& buffer, VkDeviceMemory& out, | ||
| 4930 | VkDeviceAddress& address) { | ||
| 4931 | auto& vk = context->vk; | ||
| 4932 | const VkDeviceSize alignment = info.host_pointer_alignment; | ||
| 4933 | if (!get_host_pointer_properties || !alignment || (reinterpret_cast<std::uintptr_t>(host) % alignment) || | ||
| 4934 | (bytes % alignment)) | ||
| 4935 | return false; | ||
| 4936 | VkExternalMemoryBufferCreateInfo external{VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO}; | ||
| 4937 | external.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; | ||
| 4938 | VkBufferCreateInfo create{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, &external}; | ||
| 4939 | create.size = bytes; | ||
| 4940 | create.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | | ||
| 4941 | VK_BUFFER_USAGE_TRANSFER_SRC_BIT; | ||
| 4942 | share(create); | ||
| 4943 | buffer = VK_NULL_HANDLE; | ||
| 4944 | out = VK_NULL_HANDLE; | ||
| 4945 | if (vk.vkCreateBuffer(info.device, &create, nullptr, &buffer) != VK_SUCCESS) return false; | ||
| 4946 | const auto fail = [&] { | ||
| 4947 | if (buffer) vk.vkDestroyBuffer(info.device, buffer, nullptr); | ||
| 4948 | if (out) vk.vkFreeMemory(info.device, out, nullptr); | ||
| 4949 | buffer = VK_NULL_HANDLE; | ||
| 4950 | out = VK_NULL_HANDLE; | ||
| 4951 | return false; | ||
| 4952 | }; | ||
| 4953 | VkMemoryRequirements requirements{}; | ||
| 4954 | vk.vkGetBufferMemoryRequirements(info.device, buffer, &requirements); | ||
| 4955 | VkMemoryHostPointerPropertiesEXT pointer{VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT}; | ||
| 4956 | if (get_host_pointer_properties(info.device, VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, host, | ||
| 4957 | &pointer) != VK_SUCCESS) | ||
| 4958 | return fail(); | ||
| 4959 | const std::uint32_t types = pointer.memoryTypeBits & requirements.memoryTypeBits; | ||
| 4960 | if (!types || bytes < requirements.size) return fail(); | ||
| 4961 | VkImportMemoryHostPointerInfoEXT import{VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT}; | ||
| 4962 | import.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; | ||
| 4963 | import.pHostPointer = host; | ||
| 4964 | VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, &import}; | ||
| 4965 | flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; | ||
| 4966 | for (const VkMemoryPropertyFlags want : | ||
| 4967 | {VkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT), | ||
| 4968 | VkMemoryPropertyFlags(0)}) { | ||
| 4969 | for (std::uint32_t i = 0; i < memory.memoryTypeCount && !out; ++i) { | ||
| 4970 | if (!(types & (1u << i)) || (memory.memoryTypes[i].propertyFlags & want) != want) continue; | ||
| 4971 | VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &flags}; | ||
| 4972 | allocate.allocationSize = bytes; | ||
| 4973 | allocate.memoryTypeIndex = i; | ||
| 4974 | if (vk.vkAllocateMemory(info.device, &allocate, nullptr, &out) != VK_SUCCESS) out = VK_NULL_HANDLE; | ||
| 4975 | } | ||
| 4976 | if (out) break; | ||
| 4977 | } | ||
| 4978 | if (!out || vk.vkBindBufferMemory(info.device, buffer, out, 0) != VK_SUCCESS) return fail(); | ||
| 4979 | VkBufferDeviceAddressInfo bda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; | ||
| 4980 | bda.buffer = buffer; | ||
| 4981 | address = vk.vkGetBufferDeviceAddress(info.device, &bda); | ||
| 4982 | if (!address) return fail(); | ||
| 4983 | return true; | ||
| 4984 | } | ||
| 4985 | |||
| 4986 | // A resource heap with its 3x scratch (copy, input, previous) goes to the pass: `input` imported, the copy | ||
| 4987 | // written by the pass where shaders read it (arena.address + shader_va: the scratch import or the arena range). | ||
| 4988 | void attach_console_heap_gpu(ConsoleHeap& heap) { | ||
| 4989 | VkDeviceAddress input = 0; | ||
| 4990 | if (!import_host_range(heap.input, heap.bytes, heap.input_buffer, heap.input_memory, input)) { | ||
| 4991 | std::fprintf(stderr, "[rt] d3d12: LEONIDA_CONSOLE_HEAP_GPU: console descriptor heap 0x%llx: its mirror " | ||
| 4992 | "could not be imported; fixed on the CPU\n", | ||
| 4993 | static_cast<unsigned long long>(heap.console_va)); | ||
| 4994 | return; | ||
| 4995 | } | ||
| 4996 | const int index = heap_gpu->add_heap(input, arena.address + heap.shader_va, | ||
| 4997 | std::uint32_t(heap.bytes / kDescriptorSize)); | ||
| 4998 | if (index < 0) { | ||
| 4999 | context->vk.vkDestroyBuffer(info.device, heap.input_buffer, nullptr); | ||
| 5000 | context->vk.vkFreeMemory(info.device, heap.input_memory, nullptr); | ||
| 5001 | heap.input_buffer = VK_NULL_HANDLE; | ||
| 5002 | heap.input_memory = VK_NULL_HANDLE; | ||
| 5003 | return; | ||
| 5004 | } | ||
| 5005 | heap.gpu = index; | ||
| 5006 | heap.vsharp_bits.assign((heap.bytes / kDescriptorSize + 63) / 64, 0); | ||
| 5007 | std::fprintf(stderr, "[rt] d3d12: LEONIDA_CONSOLE_HEAP_GPU: console descriptor heap 0x%llx (%llu slots) is " | ||
| 5008 | "translated by the pass (heap %d)\n", | ||
| 5009 | static_cast<unsigned long long>(heap.console_va), | ||
| 5010 | static_cast<unsigned long long>(heap.bytes / kDescriptorSize), index); | ||
| 5011 | } | ||
| 5012 | |||
| 5013 | static void set_vsharp_bit(ConsoleHeap& heap, std::size_t slot, bool on) { | ||
| 5014 | const std::uint64_t bit = 1ull << (slot & 63); | ||
| 5015 | auto& word = heap.vsharp_bits[slot >> 6]; | ||
| 5016 | word = on ? word | bit : word & ~bit; | ||
| 5017 | } | ||
| 5018 | |||
| 5019 | // The T# in a slot's title bytes, registered as fix_console_slot does (no write: the pass copies it). 0: not | ||
| 5020 | // settled (a T# whose texture is still to come); 1: settled; 2: settled, and the slot holds words that are no | ||
| 5021 | // buffer pair and no T# that decodes, whose dwords 0-3 the pass writes as zeros, as fix_console_slot does. | ||
| 5022 | int console_tsharp_check(ConsoleHeap& heap, std::size_t slot) { | ||
| 5023 | leonida::gfx10::ImageWords words; | ||
| 5024 | std::memcpy(words.data(), heap.previous + slot * kDescriptorSize, sizeof(words)); | ||
| 5025 | if (!(words[3] >> 30)) return 1; | ||
| 5026 | if (!leonida::gfx10::is_image(words)) { | ||
| 5027 | ++heap.images[unsigned(TitleImage::not_tsharp)]; | ||
| 5028 | return 2; | ||
| 5029 | } | ||
| 5030 | const char* why = nullptr; | ||
| 5031 | const TitleImage result = bind_title_image(*this, words, &why); | ||
| 5032 | if (result == TitleImage::unknown || result == TitleImage::refused) { | ||
| 5033 | note_refused_tsharp(heap, slot * kDescriptorSize, words, why); | ||
| 5034 | if (result == TitleImage::refused) ++heap.refused_reasons[why ? why : "?"]; | ||
| 5035 | } | ||
| 5036 | ++heap.images[unsigned(result)]; | ||
| 5037 | if (result == TitleImage::not_tsharp) return 2; | ||
| 5038 | return result != TitleImage::unknown && result != TitleImage::refused ? 1 : 0; | ||
| 5039 | } | ||
| 5040 | |||
| 5041 | // LEONIDA_CONSOLE_GPU_TSHARPS=0 keeps T# registration on the submitting thread (fix_console_slot's way, under the | ||
| 5042 | // fix budget); by default the resolver does it and the refresh only decodes. | ||
| 5043 | static bool tsharps_off_thread_enabled() { | ||
| 5044 | static const bool on = [] { | ||
| 5045 | char value[4] = {}; | ||
| 5046 | return !(GetEnvironmentVariableA("LEONIDA_CONSOLE_GPU_TSHARPS", value, sizeof(value)) == 1 && value[0] == '0'); | ||
| 5047 | }(); | ||
| 5048 | return on; | ||
| 5049 | } | ||
| 5050 | std::vector<leonida::gfx10::ImageWords> tsharp_jobs; // console_heap_mutex | ||
| 5051 | void refresh_console_heap_gpu(ConsoleHeap& heap) { // console_heap_mutex held | ||
| 5052 | const bool tsharps_off_thread = tsharps_off_thread_enabled() && gpu_resolver; | ||
| 5053 | static const std::uint64_t budget_us = [] { | ||
| 5054 | char text[16] = {}; | ||
| 5055 | const DWORD n = GetEnvironmentVariableA("LEONIDA_CONSOLE_FIX_US", text, sizeof(text)); | ||
| 5056 | return n > 0 && n < sizeof(text) ? std::strtoull(text, nullptr, 10) : 4000ull; | ||
| 5057 | }(); | ||
| 5058 | using clock = std::chrono::steady_clock; | ||
| 5059 | const auto ms = [](clock::time_point a, clock::time_point b) { | ||
| 5060 | return std::chrono::duration<double, std::milli>(b - a).count(); | ||
| 5061 | }; | ||
| 5062 | const auto t0 = clock::now(); | ||
| 5063 | heap.copied += heap.pages->refresh(); | ||
| 5064 | auto& queued = gpu_queue_scratch; | ||
| 5065 | queued.clear(); | ||
| 5066 | // The tracker zeroed these in `input` too: the pass copies the zeros. | ||
| 5067 | heap.pages->for_each_zeroed([&](std::size_t offset, std::size_t bytes) { | ||
| 5068 | std::memset(heap.previous + offset, 0, bytes); | ||
| 5069 | for (std::size_t slot = offset / kDescriptorSize; | ||
| 5070 | slot * kDescriptorSize < offset + bytes && slot < heap.retry.size(); ++slot) { | ||
| 5071 | heap.retry[slot] = 0; | ||
| 5072 | set_vsharp_bit(heap, slot, false); | ||
| 5073 | queued.push_back(std::uint32_t(slot)); | ||
| 5074 | } | ||
| 5075 | }); | ||
| 5076 | const auto t1 = clock::now(); | ||
| 5077 | std::uint32_t binds = 0; | ||
| 5078 | bool over = false; | ||
| 5079 | heap.pages->for_each_copied([&](std::size_t offset, std::size_t bytes) { | ||
| 5080 | const std::size_t end = std::min<std::size_t>(offset + bytes, std::size_t(heap.bytes)); | ||
| 5081 | for (std::size_t at = offset & ~std::size_t(kDescriptorSize - 1); at + kDescriptorSize <= end; | ||
| 5082 | at += kDescriptorSize) { | ||
| 5083 | if (!std::memcmp(heap.previous + at, heap.input + at, kDescriptorSize)) continue; | ||
| 5084 | std::memcpy(heap.previous + at, heap.input + at, kDescriptorSize); | ||
| 5085 | note_changed_slot(heap, heap.previous + at); | ||
| 5086 | const std::size_t slot = at / kDescriptorSize; | ||
| 5087 | heap.gpu_high = std::max(heap.gpu_high, std::uint32_t(slot + 1)); | ||
| 5088 | const auto* w = reinterpret_cast<const std::uint32_t*>(heap.previous + at); | ||
| 5089 | if (!(w[3] >> 30)) { | ||
| 5090 | queued.push_back(std::uint32_t(slot)); | ||
| 5091 | set_vsharp_bit(heap, slot, w[2] || w[6]); | ||
| 5092 | heap.retry[slot] = 0; | ||
| 5093 | continue; | ||
| 5094 | } | ||
| 5095 | set_vsharp_bit(heap, slot, false); | ||
| 5096 | if (tsharps_off_thread) { | ||
| 5097 | // Only decoded here: words that are no T# are zeroed by the pass; a T# goes to the resolver to | ||
| 5098 | // be registered (shaders find it by its words; until then they get the fallback). | ||
| 5099 | leonida::gfx10::ImageWords words; | ||
| 5100 | std::memcpy(words.data(), w, sizeof(words)); | ||
| 5101 | leonida::gfx10::Image image{}; | ||
| 5102 | const bool tsharp = leonida::gfx10::is_image(words) && leonida::gfx10::decode(words, image); | ||
| 5103 | queued.push_back(std::uint32_t(slot) | (tsharp ? 0u : leonida::ConsoleHeapGpu::kZeroFirst)); | ||
| 5104 | if (tsharp) tsharp_jobs.push_back(words); | ||
| 5105 | else ++heap.images[unsigned(TitleImage::not_tsharp)]; | ||
| 5106 | heap.retry[slot] = 0; | ||
| 5107 | continue; | ||
| 5108 | } | ||
| 5109 | // Past LEONIDA_CONSOLE_FIX_US of registering T#s, the rest wait for retry_console_tsharps (copied as | ||
| 5110 | // they are meanwhile). | ||
| 5111 | if (budget_us && !over && !(++binds & 15) && | ||
| 5112 | clock::now() - t1 >= std::chrono::microseconds(budget_us)) | ||
| 5113 | over = true; | ||
| 5114 | const int check = over ? 0 : console_tsharp_check(heap, slot); | ||
| 5115 | queued.push_back(std::uint32_t(slot) | (check == 2 ? leonida::ConsoleHeapGpu::kZeroFirst : 0u)); | ||
| 5116 | if (check) { | ||
| 5117 | heap.retry[slot] = 0; | ||
| 5118 | } else { | ||
| 5119 | if (over) ++heap.deferred_fixes; | ||
| 5120 | if (!heap.retry[slot]) { | ||
| 5121 | heap.retry[slot] = 1; | ||
| 5122 | heap.retries.push_back(std::uint32_t(slot)); | ||
| 5123 | } | ||
| 5124 | } | ||
| 5125 | } | ||
| 5126 | }); | ||
| 5127 | heap_gpu->queue(heap.gpu, queued.begin(), queued.end()); | ||
| 5128 | heap.gpu_queued += queued.size(); | ||
| 5129 | if (!tsharp_jobs.empty()) { | ||
| 5130 | { | ||
| 5131 | std::lock_guard lock(gpu_resolver->mutex); | ||
| 5132 | gpu_resolver->tsharps.insert(gpu_resolver->tsharps.end(), tsharp_jobs.begin(), tsharp_jobs.end()); | ||
| 5133 | } | ||
| 5134 | gpu_resolver->wake.notify_one(); | ||
| 5135 | tsharp_jobs.clear(); | ||
| 5136 | } | ||
| 5137 | const auto t2 = clock::now(); | ||
| 5138 | if (!heap.retries.empty()) retry_console_tsharps(heap); | ||
| 5139 | const auto t3 = clock::now(); | ||
| 5140 | heap.pages_ms += ms(t0, t1); | ||
| 5141 | heap.fix_ms += ms(t1, t2); | ||
| 5142 | heap.retry_ms += ms(t2, t3); | ||
| 5143 | } | ||
| 5144 | |||
| 5145 | // retry_console_slots for the GPU mode: only T#s wait there, and nothing is written. | ||
| 5146 | void retry_console_tsharps(ConsoleHeap& heap) { | ||
| 5147 | static const std::uint64_t budget_us = [] { | ||
| 5148 | char text[16] = {}; | ||
| 5149 | const DWORD n = GetEnvironmentVariableA("LEONIDA_CONSOLE_RETRY_US", text, sizeof(text)); | ||
| 5150 | return n > 0 && n < sizeof(text) ? std::strtoull(text, nullptr, 10) : 500ull; | ||
| 5151 | }(); | ||
| 5152 | const auto start = std::chrono::steady_clock::now(); | ||
| 5153 | std::size_t i = heap.retry_at, visited = 0; | ||
| 5154 | const std::size_t total = heap.retries.size(); | ||
| 5155 | while (visited < total && !heap.retries.empty()) { | ||
| 5156 | if (i >= heap.retries.size()) i = 0; | ||
| 5157 | const std::uint32_t slot = heap.retries[i]; | ||
| 5158 | ++visited; | ||
| 5159 | const int check = heap.retry[slot] ? console_tsharp_check(heap, slot) : 1; | ||
| 5160 | if (check == 2) heap_gpu->queue(heap.gpu, slot | leonida::ConsoleHeapGpu::kZeroFirst); | ||
| 5161 | if (check) { | ||
| 5162 | heap.retry[slot] = 0; | ||
| 5163 | heap.retries[i] = heap.retries.back(); | ||
| 5164 | heap.retries.pop_back(); | ||
| 5165 | } else { | ||
| 5166 | ++i; | ||
| 5167 | } | ||
| 5168 | if (budget_us && !(visited & 31) && | ||
| 5169 | std::chrono::steady_clock::now() - start >= std::chrono::microseconds(budget_us)) | ||
| 5170 | break; | ||
| 5171 | } | ||
| 5172 | heap.retry_at = i; | ||
| 5173 | heap.retried += visited; | ||
| 5174 | } | ||
| 5175 | |||
| 5176 | // What fix_vsharp's console path (VsharpPath::scratch) answers for the four words of a V# half: the shader VA, or 0 | ||
| 5177 | // (no backing). `span` gets the V#'s span. | ||
| 5178 | std::uint64_t resolve_vsharp_words(const leonida::ConsoleHeapKeys::Key& k, std::uint64_t& span) { | ||
| 5179 | const std::uint64_t base = std::uint64_t(k[0]) | (std::uint64_t(k[1] & 0xffff) << 32); | ||
| 5180 | const std::uint32_t stride = (k[1] >> 16) & 0x3fffu; | ||
| 5181 | span = std::uint64_t(k[2]) * (stride ? stride : 1); | ||
| 5182 | const leonida::gfx10::BufferWords words{k[0], k[1], k[2], k[3]}; | ||
| 5183 | leonida::gfx10::Buffer desc{}; | ||
| 5184 | const bool copy_geometry = leonida::gfx10::decode(words, desc) && | ||
| 5185 | (span <= kTitleWindowMax || (desc.format && leonida::gfx10::encode(desc) == words)); | ||
| 5186 | return vsharp_address(base, span, leonida::TitleVaAliases::table_view, false, copy_geometry); | ||
| 5187 | } | ||
| 5188 | |||
| 5189 | // vsharp_address's backed(): [offset, offset + bytes) of the shader VAs is a live allocation or geometry copy. | ||
| 5190 | bool shader_range_backed(std::uint64_t offset, std::uint64_t bytes) { | ||
| 5191 | constexpr std::uint64_t mask = (1ull << 48) - 1; | ||
| 5192 | if (!bytes) return false; | ||
| 5193 | const std::uint64_t limit = signed_vsharp_offsets() ? mask / 2 : mask; | ||
| 5194 | const bool encodable = offset <= limit ? bytes - 1 <= limit - offset | ||
| 5195 | : signed_vsharp_offsets() && offset >= UINT64_MAX - limit && | ||
| 5196 | bytes - 1 <= limit - offset; | ||
| 5197 | if (!encodable) return false; | ||
| 5198 | const auto bda = arena.address + offset; | ||
| 5199 | { | ||
| 5200 | std::lock_guard lock(backing_mutex); | ||
| 5201 | if (gpu_backings.covers(bda, bytes)) return true; | ||
| 5202 | } | ||
| 5203 | std::uint64_t host{}, room{}; | ||
| 5204 | return geometry.cap() && geometry.lookup(bda, host, room) && room >= bytes; | ||
| 5205 | } | ||
| 5206 | |||
| 5207 | // The range table from the alias table: a range keeps its check while it and its backing stay; `gone` (shader | ||
| 5208 | // VA ranges released since the last one) clears it. True when a checked range lost its backing. | ||
| 5209 | bool rebuild_gpu_ranges(const std::vector<std::pair<std::uint64_t, std::uint64_t>>& gone) { | ||
| 5210 | std::vector<leonida::TitleVaAliases::Mapping> mappings; | ||
| 5211 | leonida::title_va_aliases().mappings(mappings); | ||
| 5212 | const auto overlaps_gone = [&](std::uint64_t start, std::uint64_t end) { | ||
| 5213 | for (const auto& [s, n] : gone) | ||
| 5214 | if (s < end && start < s + n) return true; | ||
| 5215 | return false; | ||
| 5216 | }; | ||
| 5217 | bool lost = false; | ||
| 5218 | std::vector<leonida::ConsoleHeapRange> ranges; | ||
| 5219 | ranges.reserve(mappings.size()); | ||
| 5220 | for (const auto& m : mappings) { | ||
| 5221 | const std::uint64_t bytes = m.end - m.title_va; | ||
| 5222 | const bool released = !gone.empty() && overlaps_gone(m.shader_va, m.shader_va + bytes); | ||
| 5223 | auto it = std::lower_bound(gpu_ranges.begin(), gpu_ranges.end(), m.title_va, | ||
| 5224 | [](const leonida::ConsoleHeapRange& r, std::uint64_t va) { return r.title_va < va; }); | ||
| 5225 | bool checked; | ||
| 5226 | if (it != gpu_ranges.end() && it->title_va == m.title_va && it->end == m.end && | ||
| 5227 | it->shader_va == m.shader_va && !released) { | ||
| 5228 | checked = it->checked; | ||
| 5229 | } else { | ||
| 5230 | checked = shader_range_backed(m.shader_va, bytes); | ||
| 5231 | if (released && it != gpu_ranges.end() && it->title_va == m.title_va && it->checked) lost = true; | ||
| 5232 | } | ||
| 5233 | ranges.push_back({m.title_va, m.end, m.shader_va, checked}); | ||
| 5234 | } | ||
| 5235 | // A checked range that is gone from the table altogether had its slots answered from it. | ||
| 5236 | if (!lost) { | ||
| 5237 | for (const auto& r : gpu_ranges) { | ||
| 5238 | if (!r.checked) continue; | ||
| 5239 | auto it = std::lower_bound(ranges.begin(), ranges.end(), r.title_va, | ||
| 5240 | [](const leonida::ConsoleHeapRange& a, std::uint64_t va) { return a.title_va < va; }); | ||
| 5241 | if (it == ranges.end() || it->title_va != r.title_va || it->shader_va != r.shader_va || !it->checked) { | ||
| 5242 | lost = true; | ||
| 5243 | break; | ||
| 5244 | } | ||
| 5245 | } | ||
| 5246 | } | ||
| 5247 | gpu_ranges = ranges; | ||
| 5248 | heap_gpu->set_ranges(std::move(ranges)); | ||
| 5249 | return lost; | ||
| 5250 | } | ||
| 5251 | |||
| 5252 | // The backed table (src/console_heap_gpu.h): every live allocation's shader VAs and the geometry copies' blocks, | ||
| 5253 | // merged, and clipped to what a V# can name. Rebuilt from gpu_backings when allocations changed, at most every | ||
| 5254 | // 100 ms (one made since is a miss the CPU answers meanwhile); a release in between is cut out of it at once, so | ||
| 5255 | // the pass never leaves a V# on memory that is going (an overlapping allocation that stays is then a miss too | ||
| 5256 | // until the next rebuild). | ||
| 5257 | void update_gpu_backed(const std::vector<std::pair<std::uint64_t, std::uint64_t>>& gone) { | ||
| 5258 | const auto start = std::chrono::steady_clock::now(); | ||
| 5259 | const std::uint64_t generation = backing_generation.load(std::memory_order_relaxed); | ||
| 5260 | const std::uint64_t blocks = geometry.pool().layout_generation() + external_windows.layout_generation(); | ||
| 5261 | const bool changed = generation != gpu_backed_generation || blocks != gpu_backed_blocks; | ||
| 5262 | if (changed && (gpu_backed_generation == ~0ull || start - gpu_backed_at >= std::chrono::milliseconds(100))) { | ||
| 5263 | gpu_backed_generation = generation; | ||
| 5264 | gpu_backed_blocks = blocks; | ||
| 5265 | gpu_backed_at = start; | ||
| 5266 | gpu_backed.clear(); | ||
| 5267 | { | ||
| 5268 | std::lock_guard lock(backing_mutex); | ||
| 5269 | gpu_backings.for_each([&](std::uint64_t va, std::uint64_t bytes) { | ||
| 5270 | const std::uint64_t offset = va - arena.address; | ||
| 5271 | if (bytes && offset <= UINT64_MAX - bytes) gpu_backed.emplace_back(offset, offset + bytes); | ||
| 5272 | }); | ||
| 5273 | } | ||
| 5274 | const auto block = [&](VkDeviceAddress address, VkDeviceSize bytes) { | ||
| 5275 | const std::uint64_t offset = address - arena.address; | ||
| 5276 | if (address && bytes && offset <= UINT64_MAX - bytes) gpu_backed.emplace_back(offset, offset + bytes); | ||
| 5277 | }; | ||
| 5278 | geometry.pool().for_each_block(block); | ||
| 5279 | external_windows.for_each_block(block); | ||
| 5280 | leonida::merge_console_heap_spans(gpu_backed); | ||
| 5281 | // What a V# can name: 48 bits, or +-2^47 around heap_base with signed offsets. | ||
| 5282 | constexpr std::uint64_t k47 = 1ull << 47, k48 = 1ull << 48; | ||
| 5283 | leonida::ConsoleHeapSpans clipped; | ||
| 5284 | for (const auto& [a, b] : gpu_backed) { | ||
| 5285 | if (signed_vsharp_offsets()) { | ||
| 5286 | if (a < k47) clipped.emplace_back(a, std::min(b, k47)); | ||
| 5287 | else if (a >= 0ull - k47) clipped.emplace_back(a, b); | ||
| 5288 | } else if (a < k48) { | ||
| 5289 | clipped.emplace_back(a, std::min(b, k48)); | ||
| 5290 | } | ||
| 5291 | } | ||
| 5292 | gpu_backed.swap(clipped); | ||
| 5293 | heap_gpu->set_spans(leonida::ConsoleHeapGpu::backed_table, gpu_backed); | ||
| 5294 | ++gpu_counts.backed_rebuilds; | ||
| 5295 | } else if (!gone.empty() && !gpu_backed.empty()) { | ||
| 5296 | leonida::ConsoleHeapSpans out; | ||
| 5297 | for (const auto& [s0, bytes] : gone) { | ||
| 5298 | const std::uint64_t e0 = bytes > UINT64_MAX - s0 ? UINT64_MAX : s0 + bytes; | ||
| 5299 | out.clear(); | ||
| 5300 | for (const auto& [a, b] : gpu_backed) { | ||
| 5301 | if (b <= s0 || a >= e0) { | ||
| 5302 | out.emplace_back(a, b); | ||
| 5303 | continue; | ||
| 5304 | } | ||
| 5305 | if (a < s0) out.emplace_back(a, s0); | ||
| 5306 | if (b > e0) out.emplace_back(e0, b); | ||
| 5307 | } | ||
| 5308 | gpu_backed.swap(out); | ||
| 5309 | } | ||
| 5310 | heap_gpu->set_spans(leonida::ConsoleHeapGpu::backed_table, gpu_backed); | ||
| 5311 | ++gpu_counts.backed_cuts; | ||
| 5312 | } | ||
| 5313 | gpu_counts.backed_ms += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count(); | ||
| 5314 | } | ||
| 5315 | |||
| 5316 | // The ask table: the title's memory and both addresses of its GPU-window pairs. A V# base outside them that the | ||
| 5317 | // other tables do not answer is one vsharp_address could only answer 0 for. | ||
| 5318 | void update_gpu_ask() { | ||
| 5319 | auto& aliases = leonida::title_va_aliases(); | ||
| 5320 | const std::uint64_t generation = | ||
| 5321 | aliases.memory_generation() * 1000003ull + std::uint64_t(leonida::title_gpu_views::count()); | ||
| 5322 | if (generation == gpu_ask_generation) return; | ||
| 5323 | gpu_ask_generation = generation; | ||
| 5324 | gpu_ask = aliases.title_memory_ranges(); | ||
| 5325 | leonida::ConsoleHeapSpans views; | ||
| 5326 | leonida::title_gpu_views::spans(views); | ||
| 5327 | gpu_ask.insert(gpu_ask.end(), views.begin(), views.end()); | ||
| 5328 | leonida::merge_console_heap_spans(gpu_ask); | ||
| 5329 | heap_gpu->set_spans(leonida::ConsoleHeapGpu::ask_table, gpu_ask); | ||
| 5330 | } | ||
| 5331 | |||
| 5332 | // Once, when xmem's aliased pages are many: can they be imported as host memory (VK_EXT_external_memory_host)? | ||
| 5333 | // A successful import lets the GPU copy the section. Release the diagnostic import after the check. | ||
| 5334 | void probe_alias_imports() { | ||
| 5335 | static bool probed = false; | ||
| 5336 | if (probed) return; | ||
| 5337 | std::vector<std::uintptr_t> pages; | ||
| 5338 | const std::size_t total = leonida::title_page_aliases::sample(pages, 8); | ||
| 5339 | if (total < 256) return; | ||
| 5340 | probed = true; | ||
| 5341 | int ok = 0; | ||
| 5342 | for (const std::uintptr_t va : pages) { | ||
| 5343 | VkBuffer buffer = VK_NULL_HANDLE; | ||
| 5344 | VkDeviceMemory imported = VK_NULL_HANDLE; | ||
| 5345 | VkDeviceAddress address = 0; | ||
| 5346 | MEMORY_BASIC_INFORMATION region{}; | ||
| 5347 | VirtualQuery(reinterpret_cast<const void*>(va), ®ion, sizeof(region)); | ||
| 5348 | const bool done = import_host_range(reinterpret_cast<void*>(va), leonida::title_page_aliases::kPageSize, | ||
| 5349 | buffer, imported, address); | ||
| 5350 | ok += done; | ||
| 5351 | std::fprintf(stderr, | ||
| 5352 | "[rt] d3d12: alias import probe: page 0x%llx (state 0x%lx protect 0x%lx type 0x%lx): %s, " | ||
| 5353 | "device address 0x%llx\n", | ||
| 5354 | static_cast<unsigned long long>(va), static_cast<unsigned long>(region.State), | ||
| 5355 | static_cast<unsigned long>(region.Protect), static_cast<unsigned long>(region.Type), | ||
| 5356 | done ? "imported" : "refused", static_cast<unsigned long long>(address)); | ||
| 5357 | if (buffer) context->vk.vkDestroyBuffer(info.device, buffer, nullptr); | ||
| 5358 | if (imported) context->vk.vkFreeMemory(info.device, imported, nullptr); | ||
| 5359 | } | ||
| 5360 | std::fprintf(stderr, "[rt] d3d12: alias import probe: %d of %zu sampled pages imported (%zu aliased pages)\n", ok, | ||
| 5361 | pages.size(), total); | ||
| 5362 | } | ||
| 5363 | |||
| 5364 | // Before the heaps of a refresh: the misses of the passes that are done, the backings and alias ranges gone, the | ||
| 5365 | // range table. console_heap_mutex held. | ||
| 5366 | void console_heap_gpu_begin() { | ||
| 5367 | const auto start = std::chrono::steady_clock::now(); | ||
| 5368 | auto lap = [last = start](double& to) mutable { | ||
| 5369 | const auto now = std::chrono::steady_clock::now(); | ||
| 5370 | to += std::chrono::duration<double, std::milli>(now - last).count(); | ||
| 5371 | last = now; | ||
| 5372 | }; | ||
| 5373 | probe_alias_imports(); | ||
| 5374 | lap(gpu_counts.part_ms[0]); | ||
| 5375 | auto& misses = gpu_miss_scratch; | ||
| 5376 | misses.clear(); | ||
| 5377 | heap_gpu->drain( | ||
| 5378 | context->completed_retire_ticket(), | ||
| 5379 | [&](int h, std::uint32_t slot, std::uint32_t half) { | ||
| 5380 | ConsoleHeap* heap = h >= 0 && unsigned(h) < gpu_heaps.size() ? gpu_heaps[std::size_t(h)] : nullptr; | ||
| 5381 | ++gpu_counts.misses; | ||
| 5382 | if (!heap || slot >= heap->retry.size()) return; | ||
| 5383 | const auto* k = reinterpret_cast<const std::uint32_t*>(heap->previous + slot * kDescriptorSize) + 4 * half; | ||
| 5384 | if ((k[3] >> 30) || !k[2]) return; // rewritten since: queued by its change | ||
| 5385 | misses.push_back({{k[0], k[1], k[2], k[3]}, (std::uint32_t(h) << 28) | slot}); | ||
| 5386 | }, | ||
| 5387 | // A list that ran over: every V# slot again once what it did hold is resolved (at once would only | ||
| 5388 | // overflow it again with the same words). | ||
| 5389 | [&](int) { request_rescan_after_resolve(); }); | ||
| 5390 | if (!misses.empty()) { | ||
| 5391 | // Words the table has now (entered after that pass was recorded): only the slot again. The rest wait to | ||
| 5392 | // be resolved. | ||
| 5393 | std::vector<std::uint32_t> again; | ||
| 5394 | heap_gpu->with_keys([&](leonida::ConsoleHeapKeys& keys) { | ||
| 5395 | for (auto& m : misses) | ||
| 5396 | if (keys.find(m.key) >= 0) again.push_back(m.code), m.code = UINT32_MAX; | ||
| 5397 | return 0; | ||
| 5398 | }); | ||
| 5399 | for (const std::uint32_t code : again) | ||
| 5400 | if (gpu_heaps[code >> 28]) heap_gpu->queue(int(code >> 28), code & ((1u << 28) - 1)); | ||
| 5401 | gpu_counts.known_misses += again.size(); | ||
| 5402 | for (const auto& m : misses) { | ||
| 5403 | if (m.code == UINT32_MAX) continue; | ||
| 5404 | auto& slots = gpu_unresolved[m.key].slots; | ||
| 5405 | // Words shared by very many slots: the rest are found by the rescan after the answer. | ||
| 5406 | if (slots.size() < 4096) slots.push_back(m.code); | ||
| 5407 | else request_rescan_after_resolve(); | ||
| 5408 | } | ||
| 5409 | } | ||
| 5410 | std::vector<std::pair<std::uint64_t, std::uint64_t>> gone, removed; | ||
| 5411 | { | ||
| 5412 | std::lock_guard lock(backing_mutex); | ||
| 5413 | gone.swap(released_ranges); | ||
| 5414 | } | ||
| 5415 | auto& aliases = leonida::title_va_aliases(); | ||
| 5416 | aliases.take_removed(removed); | ||
| 5417 | gpu_counts.released += gone.size() + removed.size(); | ||
| 5418 | std::size_t dropped = 0; | ||
| 5419 | if (!gone.empty() || !removed.empty()) | ||
| 5420 | dropped = heap_gpu->with_keys([&](leonida::ConsoleHeapKeys& keys) { | ||
| 5421 | std::size_t n = 0; | ||
| 5422 | for (const auto& [s, bytes] : gone) n += keys.erase_overlapping(s, s + bytes); | ||
| 5423 | for (const auto& [s, bytes] : removed) n += keys.erase_overlapping(s, s + bytes); | ||
| 5424 | return n; | ||
| 5425 | }); | ||
| 5426 | gpu_counts.dropped += dropped; | ||
| 5427 | lap(gpu_counts.part_ms[1]); | ||
| 5428 | bool lost = false; | ||
| 5429 | const std::uint64_t generation = aliases.generation(); | ||
| 5430 | // At once when something went (the pass must not answer from it), else at most every 50 ms: a range added | ||
| 5431 | // since is a miss the resolver answers meanwhile (the alias table changes at most submissions). | ||
| 5432 | if ((generation != gpu_alias_generation && | ||
| 5433 | (!removed.empty() || start - gpu_ranges_at >= std::chrono::milliseconds(50))) || | ||
| 5434 | !gone.empty()) { | ||
| 5435 | gpu_alias_generation = generation; | ||
| 5436 | gpu_ranges_at = start; | ||
| 5437 | lost = rebuild_gpu_ranges(gone); | ||
| 5438 | } | ||
| 5439 | lap(gpu_counts.part_ms[2]); | ||
| 5440 | if (dropped || lost) { | ||
| 5441 | if (gpu_filter_enabled()) { | ||
| 5442 | gpu_rescan_filtered = true; | ||
| 5443 | for (const auto& [s, bytes] : gone) gpu_filter_shader.emplace_back(s, s + bytes); | ||
| 5444 | for (const auto& [s, bytes] : removed) gpu_filter_shader.emplace_back(s, s + bytes); | ||
| 5445 | } else { | ||
| 5446 | gpu_rescan = true; | ||
| 5447 | } | ||
| 5448 | } | ||
| 5449 | update_gpu_backed(gone); | ||
| 5450 | lap(gpu_counts.part_ms[3]); | ||
| 5451 | update_gpu_ask(); | ||
| 5452 | lap(gpu_counts.part_ms[4]); | ||
| 5453 | gpu_counts.begin_ms += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count(); | ||
| 5454 | } | ||
| 5455 | |||
| 5456 | // After the heaps: hand the missed words to the resolver, take its answers (entered in the key table, their slots | ||
| 5457 | // queued again), ask again for words that got no backing, and translate every V# slot again when something they | ||
| 5458 | // were answered from went. Nothing here waits for an answer. | ||
| 5459 | void console_heap_gpu_end() { | ||
| 5460 | static const std::uint64_t retry_ms = [] { | ||
| 5461 | char text[16] = {}; | ||
| 5462 | const DWORD n = GetEnvironmentVariableA("LEONIDA_CONSOLE_GPU_RETRY_MS", text, sizeof(text)); | ||
| 5463 | return n > 0 && n < sizeof(text) ? std::strtoull(text, nullptr, 10) : 2000ull; | ||
| 5464 | }(); | ||
| 5465 | using clock = std::chrono::steady_clock; | ||
| 5466 | const auto start = clock::now(); | ||
| 5467 | std::vector<GpuAnswer> answers; | ||
| 5468 | std::vector<std::pair<leonida::ConsoleHeapKeys::Key, bool>> requests; | ||
| 5469 | for (auto& [key, u] : gpu_unresolved) | ||
| 5470 | if (!u.asked) { | ||
| 5471 | u.asked = true; | ||
| 5472 | requests.emplace_back(key, false); | ||
| 5473 | } | ||
| 5474 | // Words with no backing, asked again once retry_ms old: at most 256 a refresh, and while the resolver has | ||
| 5475 | // fewer than 4096 waiting. | ||
| 5476 | const auto now = clock::now(); | ||
| 5477 | for (int n = 0; n < 256 && !gpu_unbacked.empty() && gpu_asked + requests.size() < 4096 && | ||
| 5478 | now >= gpu_unbacked.front().at; | ||
| 5479 | ++n) { | ||
| 5480 | requests.emplace_back(gpu_unbacked.front().key, true); | ||
| 5481 | gpu_unbacked_tries[gpu_unbacked.front().key] = gpu_unbacked.front().tries + 1; | ||
| 5482 | gpu_unbacked.pop_front(); | ||
| 5483 | ++gpu_counts.retried; | ||
| 5484 | } | ||
| 5485 | { | ||
| 5486 | std::lock_guard lock(gpu_resolver->mutex); | ||
| 5487 | answers.swap(gpu_resolver->answers); | ||
| 5488 | gpu_resolver->requests.insert(gpu_resolver->requests.end(), requests.begin(), requests.end()); | ||
| 5489 | } | ||
| 5490 | if (!requests.empty()) gpu_resolver->wake.notify_one(); | ||
| 5491 | gpu_asked += requests.size(); | ||
| 5492 | gpu_asked -= std::min(gpu_asked, answers.size()); | ||
| 5493 | const auto queue_slots = [&](const std::vector<std::uint32_t>& slots) { | ||
| 5494 | for (const std::uint32_t code : slots) { | ||
| 5495 | const std::uint32_t h = code >> 28; | ||
| 5496 | if (h < gpu_heaps.size() && gpu_heaps[h]) heap_gpu->queue(int(h), code & ((1u << 28) - 1)); | ||
| 5497 | } | ||
| 5498 | }; | ||
| 5499 | for (const GpuAnswer& a : answers) { | ||
| 5500 | if (a.retry) { | ||
| 5501 | if (!a.to) { | ||
| 5502 | // Still no backing: asked again after twice the wait, at most 64x retry_ms. | ||
| 5503 | const auto t = gpu_unbacked_tries.find(a.key); | ||
| 5504 | const std::uint32_t tries = t == gpu_unbacked_tries.end() ? 1 : t->second; | ||
| 5505 | if (t != gpu_unbacked_tries.end()) gpu_unbacked_tries.erase(t); | ||
| 5506 | const auto wait = std::chrono::milliseconds(retry_ms << std::min<std::uint32_t>(tries, 6)); | ||
| 5507 | gpu_unbacked.push_back({clock::now() + wait, a.key, tries}); | ||
| 5508 | continue; | ||
| 5509 | } | ||
| 5510 | gpu_unbacked_tries.erase(a.key); | ||
| 5511 | // Backed now: every slot that read "no backing" for these words, once all are in. | ||
| 5512 | const bool entered = heap_gpu->with_keys([&](leonida::ConsoleHeapKeys& keys) { | ||
| 5513 | std::uint64_t to = 0; | ||
| 5514 | bool none = false; | ||
| 5515 | return keys.lookup(a.key, to, none) && none && keys.put(a.key, a.to, a.span, false); | ||
| 5516 | }); | ||
| 5517 | if (entered) { | ||
| 5518 | ++gpu_counts.flips; | ||
| 5519 | if (gpu_filter_enabled()) { | ||
| 5520 | // The slots that read "no backing" for these words: those with this title base. | ||
| 5521 | const std::uint64_t base = a.key[0] | (std::uint64_t(a.key[1] & 0xffff) << 32); | ||
| 5522 | gpu_filter_title.emplace_back(base, base + 1); | ||
| 5523 | gpu_rescan_filtered = true; | ||
| 5524 | } else { | ||
| 5525 | gpu_rescan = true; | ||
| 5526 | } | ||
| 5527 | } | ||
| 5528 | continue; | ||
| 5529 | } | ||
| 5530 | ++gpu_counts.resolved; | ||
| 5531 | const auto it = gpu_unresolved.find(a.key); | ||
| 5532 | if (!heap_gpu->with_keys([&](leonida::ConsoleHeapKeys& keys) { return keys.put(a.key, a.to, a.span, !a.to); })) | ||
| 5533 | ++gpu_counts.put_failed; // every probe slot holds other words: these slots stay without records | ||
| 5534 | else if (it != gpu_unresolved.end()) | ||
| 5535 | queue_slots(it->second.slots); | ||
| 5536 | if (it != gpu_unresolved.end()) gpu_unresolved.erase(it); | ||
| 5537 | if (!a.to) { | ||
| 5538 | ++gpu_counts.none; | ||
| 5539 | gpu_unbacked.push_back({clock::now() + std::chrono::milliseconds(retry_ms), a.key, 0}); | ||
| 5540 | } | ||
| 5541 | } | ||
| 5542 | while (gpu_unbacked.size() > 65536) gpu_unbacked.pop_front(); // those stay "no backing" until a rescan | ||
| 5543 | // A key table past 60 % full: emptied at once (the next pass clears the GPU's), and every V# slot again. | ||
| 5544 | const auto [key_count, key_capacity] = heap_gpu->with_keys( | ||
| 5545 | [](leonida::ConsoleHeapKeys& k) { return std::pair<std::size_t, std::size_t>(k.size(), k.capacity()); }); | ||
| 5546 | if (key_count * 10 > key_capacity * 6) { | ||
| 5547 | heap_gpu->reset_keys(); | ||
| 5548 | gpu_unbacked.clear(); | ||
| 5549 | gpu_unresolved.clear(); | ||
| 5550 | ++gpu_counts.key_resets; | ||
| 5551 | gpu_rescan = true; | ||
| 5552 | } | ||
| 5553 | // Asked for after an overflow: once the misses are resolved, or a second later if new ones keep coming. | ||
| 5554 | if (gpu_rescan_after_resolve && | ||
| 5555 | (gpu_unresolved.empty() || clock::now() - gpu_rescan_asked >= std::chrono::seconds(1))) { | ||
| 5556 | gpu_rescan_after_resolve = false; | ||
| 5557 | gpu_rescan = true; | ||
| 5558 | } | ||
| 5559 | if (gpu_rescan) { | ||
| 5560 | gpu_rescan = false; | ||
| 5561 | ++gpu_counts.rescans; | ||
| 5562 | // On the GPU: one dispatch over the slots the title has written, pairs only (ConsoleHeapGpu::rescan). | ||
| 5563 | for (unsigned h = 0; h < gpu_heaps.size(); ++h) | ||
| 5564 | if (ConsoleHeap* heap = gpu_heaps[h]) heap_gpu->rescan(int(h), heap->gpu_high); | ||
| 5565 | gpu_rescan_filtered = false; // the full one covers it | ||
| 5566 | gpu_filter_shader.clear(); | ||
| 5567 | gpu_filter_title.clear(); | ||
| 5568 | } else if (gpu_rescan_filtered) { | ||
| 5569 | gpu_rescan_filtered = false; | ||
| 5570 | ++gpu_counts.filtered_rescans; | ||
| 5571 | // The spans go to the pass once (its change tables serve every heap). | ||
| 5572 | bool first = true; | ||
| 5573 | const leonida::ConsoleHeapSpans none; | ||
| 5574 | for (unsigned h = 0; h < gpu_heaps.size(); ++h) | ||
| 5575 | if (ConsoleHeap* heap = gpu_heaps[h]) { | ||
| 5576 | heap_gpu->rescan_filtered(int(h), heap->gpu_high, first ? gpu_filter_shader : none, | ||
| 5577 | first ? gpu_filter_title : none); | ||
| 5578 | first = false; | ||
| 5579 | } | ||
| 5580 | gpu_filter_shader.clear(); | ||
| 5581 | gpu_filter_title.clear(); | ||
| 5582 | } | ||
| 5583 | gpu_counts.resolve_ms += std::chrono::duration<double, std::milli>(clock::now() - start).count(); | ||
| 5584 | } | ||
| 5585 | |||
| 5586 | void log_console_heap_gpu(ConsoleHeap& heap, double count) { | ||
| 5587 | const auto stats = heap_gpu->take_stats(); | ||
| 5588 | const std::size_t keys = heap_gpu->with_keys([](leonida::ConsoleHeapKeys& k) { return k.size(); }); | ||
| 5589 | std::size_t checked = 0; | ||
| 5590 | for (const auto& r : gpu_ranges) checked += r.checked; | ||
| 5591 | std::fprintf(stderr, | ||
| 5592 | "[rt] d3d12: console descriptor heap 0x%llx on the GPU: %.1f slots queued a submission; passes " | ||
| 5593 | "%llu (%llu slots, %llu key updates, %llu misses, %llu overflowed, %llu not submitted); resolved " | ||
| 5594 | "%llu words (%llu with no backing, %llu asked again, %llu answered later, %llu not entered), %llu " | ||
| 5595 | "misses already " | ||
| 5596 | "entered, %zu waiting (%zu with the resolver), %zu unbacked; %llu rescans (%llu slots), " | ||
| 5597 | "%llu filtered rescans (%llu slots looked at), %llu key entries dropped for %llu releases; %zu keys (%llu resets), %zu ranges (%zu checked), %zu " | ||
| 5598 | "backed spans (%llu rebuilds, %llu cuts, %.3f ms a submission), %zu ask spans; %.3f ms before " | ||
| 5599 | "and %.3f ms resolving a submission\n", | ||
| 5600 | static_cast<unsigned long long>(heap.console_va), double(heap.gpu_queued) / count, | ||
| 5601 | static_cast<unsigned long long>(stats.passes), static_cast<unsigned long long>(stats.slots), | ||
| 5602 | static_cast<unsigned long long>(stats.updates), static_cast<unsigned long long>(stats.misses), | ||
| 5603 | static_cast<unsigned long long>(stats.overflows), static_cast<unsigned long long>(stats.failed), | ||
| 5604 | static_cast<unsigned long long>(gpu_counts.resolved), | ||
| 5605 | static_cast<unsigned long long>(gpu_counts.none), | ||
| 5606 | static_cast<unsigned long long>(gpu_counts.retried), | ||
| 5607 | static_cast<unsigned long long>(gpu_counts.flips), | ||
| 5608 | static_cast<unsigned long long>(gpu_counts.put_failed), | ||
| 5609 | static_cast<unsigned long long>(gpu_counts.known_misses), gpu_unresolved.size(), gpu_asked, | ||
| 5610 | gpu_unbacked.size(), static_cast<unsigned long long>(gpu_counts.rescans), | ||
| 5611 | static_cast<unsigned long long>(stats.rescanned), | ||
| 5612 | static_cast<unsigned long long>(gpu_counts.filtered_rescans), | ||
| 5613 | static_cast<unsigned long long>(stats.filtered), | ||
| 5614 | static_cast<unsigned long long>(gpu_counts.dropped), | ||
| 5615 | static_cast<unsigned long long>(gpu_counts.released), keys, | ||
| 5616 | static_cast<unsigned long long>(gpu_counts.key_resets), gpu_ranges.size(), checked, | ||
| 5617 | gpu_backed.size(), static_cast<unsigned long long>(gpu_counts.backed_rebuilds), | ||
| 5618 | static_cast<unsigned long long>(gpu_counts.backed_cuts), gpu_counts.backed_ms / count, | ||
| 5619 | gpu_ask.size(), | ||
| 5620 | gpu_counts.begin_ms / count, gpu_counts.resolve_ms / count); | ||
| 5621 | std::fprintf(stderr, | ||
| 5622 | "[rt] d3d12: console heap pass, before the heaps, ms a submission: alias probes %.3f, misses and " | ||
| 5623 | "releases %.3f, range table %.3f, backed table %.3f, ask table %.3f\n", | ||
| 5624 | gpu_counts.part_ms[0] / count, gpu_counts.part_ms[1] / count, gpu_counts.part_ms[2] / count, | ||
| 5625 | gpu_counts.part_ms[3] / count, gpu_counts.part_ms[4] / count); | ||
| 5626 | if (tsharps_off_thread_enabled()) { | ||
| 5627 | std::uint64_t t[5]; | ||
| 5628 | for (unsigned i = 0; i < 5; ++i) t[i] = gpu_tsharps[i].exchange(0, std::memory_order_relaxed); | ||
| 5629 | std::fprintf(stderr, | ||
| 5630 | "[rt] d3d12: console heap T#s registered by the resolver: %llu known, %llu bound, %llu naming no " | ||
| 5631 | "texture, %llu refused\n", | ||
| 5632 | static_cast<unsigned long long>(t[0]), static_cast<unsigned long long>(t[1]), | ||
| 5633 | static_cast<unsigned long long>(t[2]), static_cast<unsigned long long>(t[3])); | ||
| 5634 | } | ||
| 5635 | if (shadow_gpu_enabled()) { | ||
| 5636 | ShadowGpuCounts c; | ||
| 5637 | std::size_t imports = 0; | ||
| 5638 | std::uint64_t imported_bytes = 0; | ||
| 5639 | { | ||
| 5640 | std::lock_guard lock(shadow_import_mutex); | ||
| 5641 | c = std::exchange(shadow_gpu_counts, ShadowGpuCounts{}); | ||
| 5642 | imports = shadow_imports.size(); | ||
| 5643 | imported_bytes = shadow_import_bytes; | ||
| 5644 | } | ||
| 5645 | std::fprintf(stderr, | ||
| 5646 | "[rt] d3d12: slot-133 shadows on the GPU: %llu copies (%.1f KiB a submission), %llu imports made " | ||
| 5647 | "(%llu MiB), %llu dropped after a map change, %llu refused, %llu with no GPU destination; %zu imports " | ||
| 5648 | "live (%llu MiB); passes copied %llu regions\n", | ||
| 5649 | static_cast<unsigned long long>(c.copies), double(c.bytes) / 1024.0 / count, | ||
| 5650 | static_cast<unsigned long long>(c.imports), static_cast<unsigned long long>(c.imported >> 20), | ||
| 5651 | static_cast<unsigned long long>(c.dropped), static_cast<unsigned long long>(c.refused), | ||
| 5652 | static_cast<unsigned long long>(c.outside), imports, | ||
| 5653 | static_cast<unsigned long long>(imported_bytes >> 20), | ||
| 5654 | static_cast<unsigned long long>(stats.copies)); | ||
| 5655 | } | ||
| 5656 | heap.gpu_queued = 0; | ||
| 5657 | gpu_counts = {}; | ||
| 3715 | } | 5658 | } |
| 3716 | 5659 | ||
| 3717 | // LOCAL DIAGNOSTIC (desc-probe): which console-heap slots our API wrote and which the title wrote itself, what | 5660 | // LOCAL DIAGNOSTIC (desc-probe): which console-heap slots our API wrote and which the title wrote itself, what |
| @@ -3733,6 +5676,16 @@ struct DeviceState { | |||
| 3733 | unsigned recent_count = 0; | 5676 | unsigned recent_count = 0; |
| 3734 | }; | 5677 | }; |
| 3735 | std::mutex probe_mutex; // never under console_heap_mutex' callees; takes descriptor_mutex inside | 5678 | std::mutex probe_mutex; // never under console_heap_mutex' callees; takes descriptor_mutex inside |
| 5679 | // LEONIDA_DESC_PROBE=1 turns the diagnostic on (so does the compute input probe, which reads these records). Off | ||
| 5680 | // by default: at every submission it hashes each slot of every bound table, and formats a line under | ||
| 5681 | // descriptor_mutex for each slot the title wrote itself. | ||
| 5682 | static bool probe_enabled() { | ||
| 5683 | static const bool on = [] { | ||
| 5684 | const char* v = std::getenv("LEONIDA_DESC_PROBE"); | ||
| 5685 | return (v && *v == '1') || rt::compute_probe::enabled(); | ||
| 5686 | }(); | ||
| 5687 | return on; | ||
| 5688 | } | ||
| 3736 | std::vector<std::unique_ptr<HeapProbe>> probes; | 5689 | std::vector<std::unique_ptr<HeapProbe>> probes; |
| 3737 | std::uint64_t probe_submissions = 0; | 5690 | std::uint64_t probe_submissions = 0; |
| 3738 | static constexpr const char* kProbeKinds[8] = {"V# in arena", "V# title memory", "V# other", "T# key known", | 5691 | static constexpr const char* kProbeKinds[8] = {"V# in arena", "V# title memory", "V# other", "T# key known", |
| @@ -3741,7 +5694,7 @@ struct DeviceState { | |||
| 3741 | std::atomic<int> probe_view_logs{0}; | 5694 | std::atomic<int> probe_view_logs{0}; |
| 3742 | // Where a Create*View / CopyDescriptors* write landed, for the first ones. | 5695 | // Where a Create*View / CopyDescriptors* write landed, for the first ones. |
| 3743 | void probe_view(const char* what, SIZE_T ptr, UINT count) { | 5696 | void probe_view(const char* what, SIZE_T ptr, UINT count) { |
| 3744 | if (!leonida::local_diagnostics() || probe_view_logs.fetch_add(1) >= 48) return; | 5697 | if (!probe_enabled() || probe_view_logs.fetch_add(1) >= 48) return; |
| 3745 | std::lock_guard lock(probe_mutex); | 5698 | std::lock_guard lock(probe_mutex); |
| 3746 | for (const auto& p : probes) | 5699 | for (const auto& p : probes) |
| 3747 | if (ptr >= p->console_va && ptr < p->console_va + p->slots * kDescriptorSize) { | 5700 | if (ptr >= p->console_va && ptr < p->console_va + p->slots * kDescriptorSize) { |
| @@ -3766,8 +5719,7 @@ struct DeviceState { | |||
| 3766 | return !(q[0] | q[1] | q[2] | q[3]); | 5719 | return !(q[0] | q[1] | q[2] | q[3]); |
| 3767 | } | 5720 | } |
| 3768 | void probe_add(std::uint64_t console_va, std::uint64_t shader_va, std::size_t slots, bool shadowed) { | 5721 | void probe_add(std::uint64_t console_va, std::uint64_t shader_va, std::size_t slots, bool shadowed) { |
| 3769 | // Nothing reads a probe unless one of the two diagnostics is on; without probes the other probe_* are no-ops. | 5722 | if (!probe_enabled() && !rt::compute_probe::enabled()) return; |
| 3770 | if (!leonida::local_diagnostics() && !rt::compute_probe::enabled()) return; | ||
| 3771 | auto probe = std::make_unique<HeapProbe>(); | 5723 | auto probe = std::make_unique<HeapProbe>(); |
| 3772 | probe->console_va = console_va; | 5724 | probe->console_va = console_va; |
| 3773 | probe->shader_va = shader_va; | 5725 | probe->shader_va = shader_va; |
| @@ -3787,11 +5739,12 @@ struct DeviceState { | |||
| 3787 | shader_va + slots * kDescriptorSize <= arena.size ? "inside" : "PAST"); | 5739 | shader_va + slots * kDescriptorSize <= arena.size ? "inside" : "PAST"); |
| 3788 | } | 5740 | } |
| 3789 | void probe_remove(std::uint64_t console_va) { | 5741 | void probe_remove(std::uint64_t console_va) { |
| 5742 | if (!probe_enabled()) return; | ||
| 3790 | std::lock_guard lock(probe_mutex); | 5743 | std::lock_guard lock(probe_mutex); |
| 3791 | std::erase_if(probes, [console_va](const std::unique_ptr<HeapProbe>& p) { return p->console_va == console_va; }); | 5744 | std::erase_if(probes, [console_va](const std::unique_ptr<HeapProbe>& p) { return p->console_va == console_va; }); |
| 3792 | } | 5745 | } |
| 3793 | void probe_api(SIZE_T ptr, UINT count, const char* what = "CopyDescriptors") { | 5746 | void probe_api(SIZE_T ptr, UINT count, const char* what = "CopyDescriptors") { |
| 3794 | if (!ptr || !count) return; | 5747 | if (!ptr || !count || !probe_enabled()) return; |
| 3795 | std::lock_guard lock(probe_mutex); | 5748 | std::lock_guard lock(probe_mutex); |
| 3796 | for (const auto& p : probes) { | 5749 | for (const auto& p : probes) { |
| 3797 | if (ptr < p->console_va || ptr >= p->console_va + p->slots * kDescriptorSize) continue; | 5750 | if (ptr < p->console_va || ptr >= p->console_va + p->slots * kDescriptorSize) continue; |
| @@ -3863,6 +5816,7 @@ struct DeviceState { | |||
| 3863 | } | 5816 | } |
| 3864 | // At a descriptor-table scan (ExecuteCommandLists): the slots a bound table in a console heap declares. | 5817 | // At a descriptor-table scan (ExecuteCommandLists): the slots a bound table in a console heap declares. |
| 3865 | void probe_table(std::uint64_t table_va, std::uint32_t descriptors) { | 5818 | void probe_table(std::uint64_t table_va, std::uint32_t descriptors) { |
| 5819 | if (!probe_enabled()) return; | ||
| 3866 | std::lock_guard lock(probe_mutex); | 5820 | std::lock_guard lock(probe_mutex); |
| 3867 | for (const auto& p : probes) { | 5821 | for (const auto& p : probes) { |
| 3868 | const std::uint64_t span = p->slots * kDescriptorSize; | 5822 | const std::uint64_t span = p->slots * kDescriptorSize; |
| @@ -3921,7 +5875,7 @@ struct DeviceState { | |||
| 3921 | } | 5875 | } |
| 3922 | // Before a submission, after the console heaps' copies are refreshed: the whole heap, now and then. | 5876 | // Before a submission, after the console heaps' copies are refreshed: the whole heap, now and then. |
| 3923 | void probe_census() { | 5877 | void probe_census() { |
| 3924 | if (!leonida::local_diagnostics()) return; | 5878 | if (!probe_enabled()) return; |
| 3925 | const std::uint64_t n = ++probe_submissions; | 5879 | const std::uint64_t n = ++probe_submissions; |
| 3926 | if (n != 1 && n != 64 && n != 512 && n != 2048 && n % 4096) return; | 5880 | if (n != 1 && n != 64 && n != 512 && n != 2048 && n % 4096) return; |
| 3927 | std::lock_guard lock(probe_mutex); | 5881 | std::lock_guard lock(probe_mutex); |
| @@ -4376,8 +6330,14 @@ struct DeviceState { | |||
| 4376 | VkImageView sampled; | 6330 | VkImageView sampled; |
| 4377 | VkImageView storage; // the same range without a component mapping, for the storage bindings; or null | 6331 | VkImageView storage; // the same range without a component mapping, for the storage bindings; or null |
| 4378 | std::uint64_t address; | 6332 | std::uint64_t address; |
| 6333 | // A 2D view of the first layer in the 2D arrays (a 2D-array image's slice 0, BindlessSet::MirrorViews); or null | ||
| 6334 | VkImageView mirror_sampled = VK_NULL_HANDLE; | ||
| 6335 | VkImageView mirror_storage = VK_NULL_HANDLE; | ||
| 4379 | }; | 6336 | }; |
| 4380 | std::unique_ptr<leonida::BindlessSet> bindless; | 6337 | std::unique_ptr<leonida::BindlessSet> bindless; |
| 6338 | // True when the loaded library's modules read the table's kind word (create_bindless, descriptor_table.h): the | ||
| 6339 | // image inserts then record which arrays each index is bound in. | ||
| 6340 | bool descriptor_table_tagged = false; | ||
| 4381 | std::mutex descriptor_mutex; // the set and the containers below | 6341 | std::mutex descriptor_mutex; // the set and the containers below |
| 4382 | // vkDeviceWaitIdle calls made for the bindless set (none, unless LEONIDA_BINDLESS_IDLE_WAIT restores the old wait). | 6342 | // vkDeviceWaitIdle calls made for the bindless set (none, unless LEONIDA_BINDLESS_IDLE_WAIT restores the old wait). |
| 4383 | std::atomic<std::uint64_t> bindless_idle_waits{0}; | 6343 | std::atomic<std::uint64_t> bindless_idle_waits{0}; |
| @@ -4464,6 +6424,10 @@ struct DeviceState { | |||
| 4464 | context->defer_destroy(leonida::DeferredDeletionQueue::Kind::bindless_slot, slot_handle); | 6424 | context->defer_destroy(leonida::DeferredDeletionQueue::Kind::bindless_slot, slot_handle); |
| 4465 | if (entry.sampled) context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.sampled); | 6425 | if (entry.sampled) context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.sampled); |
| 4466 | if (entry.storage) context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.storage); | 6426 | if (entry.storage) context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.storage); |
| 6427 | if (entry.mirror_sampled) | ||
| 6428 | context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.mirror_sampled); | ||
| 6429 | if (entry.mirror_storage) | ||
| 6430 | context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.mirror_storage); | ||
| 4467 | } | 6431 | } |
| 4468 | 6432 | ||
| 4469 | struct PendingSample { | 6433 | struct PendingSample { |
| @@ -4641,12 +6605,10 @@ struct DeviceState { | |||
| 4641 | } | 6605 | } |
| 4642 | } | 6606 | } |
| 4643 | view_info.components = g::vulkan_swizzle(swizzle, channels_format); | 6607 | view_info.components = g::vulkan_swizzle(swizzle, channels_format); |
| 4644 | // The cast: MSVC's enums are ints, and it rejects int to VkImageAspectFlags in braces as narrowing. | 6608 | view_info.subresourceRange = g::vulkan_subresource_range( |
| 4645 | view_info.subresourceRange = { | 6609 | image, stencil ? VK_IMAGE_ASPECT_STENCIL_BIT |
| 4646 | VkImageAspectFlags(stencil ? VK_IMAGE_ASPECT_STENCIL_BIT | 6610 | : (aspects & VK_IMAGE_ASPECT_DEPTH_BIT) ? VK_IMAGE_ASPECT_DEPTH_BIT |
| 4647 | : (aspects & VK_IMAGE_ASPECT_DEPTH_BIT) ? VK_IMAGE_ASPECT_DEPTH_BIT | 6611 | : VK_IMAGE_ASPECT_COLOR_BIT); |
| 4648 | : VK_IMAGE_ASPECT_COLOR_BIT), | ||
| 4649 | image.first_mip, image.mip_count, image.first_layer, image.layer_count}; | ||
| 4650 | ImageEntry entry{dimension, 0, VK_NULL_HANDLE, VK_NULL_HANDLE, image.address}; | 6612 | ImageEntry entry{dimension, 0, VK_NULL_HANDLE, VK_NULL_HANDLE, image.address}; |
| 4651 | if (sampled) { | 6613 | if (sampled) { |
| 4652 | const VkResult result = vk.vkCreateImageView(info.device, &view_info, nullptr, &entry.sampled); | 6614 | const VkResult result = vk.vkCreateImageView(info.device, &view_info, nullptr, &entry.sampled); |
| @@ -4656,13 +6618,19 @@ struct DeviceState { | |||
| 4656 | } | 6618 | } |
| 4657 | } | 6619 | } |
| 4658 | leonida::StorageViews views{}; | 6620 | leonida::StorageViews views{}; |
| 6621 | VkImageViewCreateInfo storage_info{}; | ||
| 6622 | bool storage_info_valid = false; | ||
| 6623 | // storage_info's pNext chain: declared out here, since the 2D mirror below copies storage_info with its chain | ||
| 6624 | // after this block. Declared inside it, the chain dangled and the driver followed it into stale stack (the | ||
| 6625 | // 120 s hangs of d3d12_existing_heap, d3d12_r9g9b9e5_uav and the depth-storage tests). | ||
| 6626 | VkImageViewUsageCreateInfo storage_usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}; | ||
| 6627 | VkImageViewSlicedCreateInfoEXT sliced{VK_STRUCTURE_TYPE_IMAGE_VIEW_SLICED_CREATE_INFO_EXT}; | ||
| 4659 | if (storage) { | 6628 | if (storage) { |
| 4660 | VkImageViewCreateInfo storage_info = view_info; | 6629 | storage_info = view_info; |
| 6630 | storage_info_valid = true; | ||
| 4661 | storage_info.components = {}; | 6631 | storage_info.components = {}; |
| 4662 | storage_info.format = storage_format; | 6632 | storage_info.format = storage_format; |
| 4663 | VkImageViewUsageCreateInfo storage_usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}; | ||
| 4664 | storage_usage.usage = VK_IMAGE_USAGE_STORAGE_BIT; | 6633 | storage_usage.usage = VK_IMAGE_USAGE_STORAGE_BIT; |
| 4665 | VkImageViewSlicedCreateInfoEXT sliced{VK_STRUCTURE_TYPE_IMAGE_VIEW_SLICED_CREATE_INFO_EXT}; | ||
| 4666 | if (slices.count) { | 6634 | if (slices.count) { |
| 4667 | sliced.sliceOffset = slices.first; | 6635 | sliced.sliceOffset = slices.first; |
| 4668 | sliced.sliceCount = slices.count; | 6636 | sliced.sliceCount = slices.count; |
| @@ -4679,9 +6647,42 @@ struct DeviceState { | |||
| 4679 | (numeric == 1 ? views.as_uint : numeric == 2 ? views.as_sint : views.as_float) = entry.storage; | 6647 | (numeric == 1 ? views.as_uint : numeric == 2 ? views.as_sint : views.as_float) = entry.storage; |
| 4680 | if (storage_format == VK_FORMAT_R32_UINT) views.r32ui = entry.storage; | 6648 | if (storage_format == VK_FORMAT_R32_UINT) views.r32ui = entry.storage; |
| 4681 | } | 6649 | } |
| 6650 | // A 2D-array or cube image also gets a 2D view of its first layer, which the bindless set binds at the same | ||
| 6651 | // index in the 2D arrays: a 2D instruction reading this T# addresses slice 0 (BindlessSet::MirrorViews). | ||
| 6652 | leonida::BindlessSet::MirrorViews mirror{}; | ||
| 6653 | if (dimension == leonida::ImageDimension::dim_2d_array) { | ||
| 6654 | const auto make_mirror = [&](const VkImageViewCreateInfo& base, VkImageView* out) { | ||
| 6655 | VkImageViewCreateInfo layer = base; | ||
| 6656 | layer.viewType = VK_IMAGE_VIEW_TYPE_2D; | ||
| 6657 | layer.subresourceRange.baseArrayLayer = image.first_layer; | ||
| 6658 | layer.subresourceRange.layerCount = 1; | ||
| 6659 | return vk.vkCreateImageView(info.device, &layer, nullptr, out) == VK_SUCCESS; | ||
| 6660 | }; | ||
| 6661 | if (make_mirror(view_info, &entry.mirror_sampled)) { | ||
| 6662 | mirror.sampled = entry.mirror_sampled; | ||
| 6663 | mirror.sampled_layout = VK_IMAGE_LAYOUT_GENERAL; | ||
| 6664 | if (storage_info_valid && make_mirror(storage_info, &entry.mirror_storage)) { | ||
| 6665 | const int numeric = numeric_class(storage_info.format); | ||
| 6666 | (numeric == 1 ? mirror.storage.as_uint : numeric == 2 ? mirror.storage.as_sint | ||
| 6667 | : mirror.storage.as_float) = entry.mirror_storage; | ||
| 6668 | if (storage_info.format == VK_FORMAT_R32_UINT) mirror.storage.r32ui = entry.mirror_storage; | ||
| 6669 | } | ||
| 6670 | } else { | ||
| 6671 | log_once("no 2D view of this image's first layer; a 2D instruction reading its T# reads the fallback", | ||
| 6672 | int(image.type)); | ||
| 6673 | } | ||
| 6674 | } | ||
| 4682 | // Every state a shader can read or write the texture in is GENERAL (ResourceBinding::sampled_in_general). | 6675 | // Every state a shader can read or write the texture in is GENERAL (ResourceBinding::sampled_in_general). |
| 4683 | entry.index = bindless->add_image(dimension, entry.sampled, VK_IMAGE_LAYOUT_GENERAL, views, sampled_class); | 6676 | // `kind` says which arrays the index is bound in; a tagged module reads it from the table (insert_key). |
| 6677 | entry.index = bindless->add_image(dimension, entry.sampled, VK_IMAGE_LAYOUT_GENERAL, views, sampled_class, | ||
| 6678 | mirror.sampled ? &mirror : nullptr); | ||
| 4684 | if (!entry.index) { | 6679 | if (!entry.index) { |
| 6680 | vk.vkDestroyImageView(info.device, entry.mirror_sampled, nullptr); | ||
| 6681 | entry.mirror_sampled = VK_NULL_HANDLE; | ||
| 6682 | if (entry.mirror_storage) { | ||
| 6683 | vk.vkDestroyImageView(info.device, entry.mirror_storage, nullptr); | ||
| 6684 | entry.mirror_storage = VK_NULL_HANDLE; | ||
| 6685 | } | ||
| 4685 | if (first_diagnostic("a bindless image array is full; dimension", int(dimension))) { | 6686 | if (first_diagnostic("a bindless image array is full; dimension", int(dimension))) { |
| 4686 | // Whether the array holds live textures or stale views: the T#s it holds, the textures they name, | 6687 | // Whether the array holds live textures or stale views: the T#s it holds, the textures they name, |
| 4687 | // and the most T#s of one texture (a texture whose T#s keep changing, a streamed mip clamp say, | 6688 | // and the most T#s of one texture (a texture whose T#s keep changing, a streamed mip clamp say, |
| @@ -4712,7 +6713,10 @@ struct DeviceState { | |||
| 4712 | image_entries.emplace(words, entry); | 6713 | image_entries.emplace(words, entry); |
| 4713 | image_keys.emplace(image.address, words); | 6714 | image_keys.emplace(image.address, words); |
| 4714 | } | 6715 | } |
| 4715 | bindless->insert_key(words, entry.index); | 6716 | // The set derives the entry's kind from what it bound at this index (BindlessSet::image_kind_at); a plain |
| 6717 | // library's modules do not read it, so they get 0 as before. | ||
| 6718 | bindless->insert_key(words, entry.index, | ||
| 6719 | descriptor_table_tagged ? bindless->image_kind_at(dimension, entry.index) : 0u); | ||
| 4716 | leonida::fsdraw::note_tsharp(words.data()); // LOCAL DIAGNOSTIC | 6720 | leonida::fsdraw::note_tsharp(words.data()); // LOCAL DIAGNOSTIC |
| 4717 | return true; | 6721 | return true; |
| 4718 | } | 6722 | } |
| @@ -4726,6 +6730,26 @@ struct DeviceState { | |||
| 4726 | std::lock_guard lock(descriptor_mutex); | 6730 | std::lock_guard lock(descriptor_mutex); |
| 4727 | images_by_address[address] = resource; | 6731 | images_by_address[address] = resource; |
| 4728 | } | 6732 | } |
| 6733 | // LEONIDA_TRACE_TEXTURE=<address>[,<address>...] (hex, the base a T# names): the resource id of an image registered | ||
| 6734 | // at that address, so a draw's T# can be followed to the passes that write it (fsdraw rt0, UAV views, copies). | ||
| 6735 | static void trace_image(std::uint64_t address, leonida::ResourceId id, const char* where) { | ||
| 6736 | static const std::vector<std::uint64_t> traced = [] { | ||
| 6737 | std::vector<std::uint64_t> out; | ||
| 6738 | const char* v = std::getenv("LEONIDA_TRACE_TEXTURE"); | ||
| 6739 | for (const char* p = v; p && *p;) { | ||
| 6740 | char* end = nullptr; | ||
| 6741 | const std::uint64_t a = std::strtoull(p, &end, 16); | ||
| 6742 | if (end == p) break; | ||
| 6743 | out.push_back(a); | ||
| 6744 | p = *end == ',' ? end + 1 : end; | ||
| 6745 | } | ||
| 6746 | return out; | ||
| 6747 | }(); | ||
| 6748 | if (traced.empty() || std::find(traced.begin(), traced.end(), address) == traced.end()) return; | ||
| 6749 | std::fprintf(stderr, "[rt] trace-texture: address 0x%llx is resource 0x%llx (%s)\n", | ||
| 6750 | static_cast<unsigned long long>(address), static_cast<unsigned long long>(id), where); | ||
| 6751 | leonida::fsdraw::note_target(id); // read back with the captures (numbers: mean, nonzero texels) | ||
| 6752 | } | ||
| 4729 | // The texture registered at `address` (a title-placed texture's address can be taken over by a later one). | 6753 | // The texture registered at `address` (a title-placed texture's address can be taken over by a later one). |
| 4730 | const void* image_owner(std::uint64_t address) { | 6754 | const void* image_owner(std::uint64_t address) { |
| 4731 | std::lock_guard lock(descriptor_mutex); | 6755 | std::lock_guard lock(descriptor_mutex); |
| @@ -4968,7 +6992,8 @@ Format texture_format(const DeviceState& device, const D3D12_RESOURCE_DESC& desc | |||
| 4968 | // no-op. An A8 render target's VK_FORMAT_A8_UNORM_KHR image (Format::a8_as_alpha) is in a class of its own: no | 6992 | // no-op. An A8 render target's VK_FORMAT_A8_UNORM_KHR image (Format::a8_as_alpha) is in a class of its own: no |
| 4969 | // other format can be a view format of it, so any other castable format is refused here, before Vulkan. | 6993 | // other format can be a view format of it, so any other castable format is refused here, before Vulkan. |
| 4970 | HRESULT castable_view_formats(const Format& format, DXGI_FORMAT resource_format, UINT32 count, | 6994 | HRESULT castable_view_formats(const Format& format, DXGI_FORMAT resource_format, UINT32 count, |
| 4971 | const DXGI_FORMAT* castable, std::vector<VkFormat>& out, bool depth_uav_planes = false) { | 6995 | const DXGI_FORMAT* castable, std::vector<VkFormat>& out, bool depth_uav_planes = false, |
| 6996 | bool console_d16s8 = false) { | ||
| 4972 | if (!count || !castable) return S_OK; | 6997 | if (!count || !castable) return S_OK; |
| 4973 | const bool depth = (format.aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) != 0; | 6998 | const bool depth = (format.aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) != 0; |
| 4974 | const leonida::BlockFormat own = leonida::block_format(format.format, format.aspects); | 6999 | const leonida::BlockFormat own = leonida::block_format(format.format, format.aspects); |
| @@ -4985,6 +7010,13 @@ HRESULT castable_view_formats(const Format& format, DXGI_FORMAT resource_format, | |||
| 4985 | const bool valid = format.format == VK_FORMAT_D16_UNORM | 7010 | const bool valid = format.format == VK_FORMAT_D16_UNORM |
| 4986 | ? view == DXGI_FORMAT_R16_TYPELESS || view == DXGI_FORMAT_D16_UNORM || | 7011 | ? view == DXGI_FORMAT_R16_TYPELESS || view == DXGI_FORMAT_D16_UNORM || |
| 4987 | view == DXGI_FORMAT_R16_UNORM || view == DXGI_FORMAT_R16_UINT | 7012 | view == DXGI_FORMAT_R16_UNORM || view == DXGI_FORMAT_R16_UINT |
| 7013 | : (format.xbox_depth16_stencil8 || console_d16s8) | ||
| 7014 | ? view == xbox_d16s8 || view == xbox_d16_plane || view == xbox_s8_plane || | ||
| 7015 | (format.d24 && (view == DXGI_FORMAT_D24_UNORM_S8_UINT || | ||
| 7016 | view == DXGI_FORMAT_R24_UNORM_X8_TYPELESS || | ||
| 7017 | view == DXGI_FORMAT_X24_TYPELESS_G8_UINT)) || | ||
| 7018 | view == DXGI_FORMAT_R16_TYPELESS || view == DXGI_FORMAT_R16_UNORM || | ||
| 7019 | view == DXGI_FORMAT_R16_UINT || view == DXGI_FORMAT_R8_UINT | ||
| 4988 | : view == DXGI_FORMAT_R32G8X24_TYPELESS || view == DXGI_FORMAT_D32_FLOAT_S8X24_UINT || | 7020 | : view == DXGI_FORMAT_R32G8X24_TYPELESS || view == DXGI_FORMAT_D32_FLOAT_S8X24_UINT || |
| 4989 | view == DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS || view == DXGI_FORMAT_X32_TYPELESS_G8X24_UINT || | 7021 | view == DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS || view == DXGI_FORMAT_X32_TYPELESS_G8X24_UINT || |
| 4990 | view == DXGI_FORMAT_R32_FLOAT || view == DXGI_FORMAT_R8_UINT; | 7022 | view == DXGI_FORMAT_R32_FLOAT || view == DXGI_FORMAT_R8_UINT; |
| @@ -5324,9 +7356,10 @@ public: | |||
| 5324 | desc_.NumDescriptors >= 65536 | 7356 | desc_.NumDescriptors >= 65536 |
| 5325 | ? DeviceState::heap_guard_bytes() | 7357 | ? DeviceState::heap_guard_bytes() |
| 5326 | : 0; | 7358 | : 0; |
| 5327 | if (guard && device.arena_allocate(bytes + guard, 256, arena_offset_, DeviceState::arena_descriptor_heap)) | 7359 | if (guard && device.arena_allocate(bytes + guard, 256, arena_offset_, DeviceState::arena_descriptor_heap)) { |
| 5328 | guard_ = guard; | 7360 | guard_ = guard; |
| 5329 | else if (!device.arena_allocate(bytes, 256, arena_offset_, DeviceState::arena_descriptor_heap)) { | 7361 | device.arena_guard_bytes.fetch_add(guard, std::memory_order_relaxed); |
| 7362 | } else if (!device.arena_allocate(bytes, 256, arena_offset_, DeviceState::arena_descriptor_heap)) { | ||
| 5330 | log_once("GPU address arena full (raise LEONIDA_ARENA_MB); shader-visible heap size in KiB:", | 7363 | log_once("GPU address arena full (raise LEONIDA_ARENA_MB); shader-visible heap size in KiB:", |
| 5331 | int(std::min<VkDeviceSize>(bytes / 1024, INT_MAX))); | 7364 | int(std::min<VkDeviceSize>(bytes / 1024, INT_MAX))); |
| 5332 | return; | 7365 | return; |
| @@ -5338,10 +7371,6 @@ public: | |||
| 5338 | std::lock_guard lock(device.visible_heap_mutex); | 7371 | std::lock_guard lock(device.visible_heap_mutex); |
| 5339 | device.visible_heaps[arena_offset_] = {arena_offset_ + bytes, desc.Type}; | 7372 | device.visible_heaps[arena_offset_] = {arena_offset_ + bytes, desc.Type}; |
| 5340 | } | 7373 | } |
| 5341 | if (desc.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) { | ||
| 5342 | std::lock_guard lock(device.cbv_heap_mutex); | ||
| 5343 | device.cbv_heaps[arena_offset_] = arena_offset_ + bytes; | ||
| 5344 | } | ||
| 5345 | } else { | 7374 | } else { |
| 5346 | storage_.reset(new std::byte[std::size_t(bytes)]()); | 7375 | storage_.reset(new std::byte[std::size_t(bytes)]()); |
| 5347 | cpu_ = reinterpret_cast<std::uint8_t*>(storage_.get()); | 7376 | cpu_ = reinterpret_cast<std::uint8_t*>(storage_.get()); |
| @@ -5365,9 +7394,13 @@ public: | |||
| 5365 | std::lock_guard lock(device_.visible_heap_mutex); | 7394 | std::lock_guard lock(device_.visible_heap_mutex); |
| 5366 | device_.visible_heaps.erase(arena_offset_); | 7395 | device_.visible_heaps.erase(arena_offset_); |
| 5367 | } | 7396 | } |
| 7397 | if (in_arena_ && desc_.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) { | ||
| 7398 | device_.forget_nulled_table_slots(arena_offset_, VkDeviceSize(desc_.NumDescriptors) * kDescriptorSize); | ||
| 7399 | } | ||
| 5368 | if (in_arena_) device_.arena_release(arena_offset_, | 7400 | if (in_arena_) device_.arena_release(arena_offset_, |
| 5369 | VkDeviceSize(desc_.NumDescriptors) * kDescriptorSize + guard_, | 7401 | VkDeviceSize(desc_.NumDescriptors) * kDescriptorSize + guard_, |
| 5370 | DeviceState::arena_descriptor_heap); | 7402 | DeviceState::arena_descriptor_heap); |
| 7403 | if (guard_) device_.arena_guard_bytes.fetch_sub(guard_, std::memory_order_relaxed); | ||
| 5371 | } | 7404 | } |
| 5372 | 7405 | ||
| 5373 | bool ok() const { return cpu_ != nullptr; } | 7406 | bool ok() const { return cpu_ != nullptr; } |
| @@ -5495,6 +7528,7 @@ public: | |||
| 5495 | device_.context->remove_resource(id()); | 7528 | device_.context->remove_resource(id()); |
| 5496 | // Before the memory goes to the deferred queue: no submission copies into it after this. | 7529 | // Before the memory goes to the deferred queue: no submission copies into it after this. |
| 5497 | if (shadow_) device_.remove_shadow(shadow_); | 7530 | if (shadow_) device_.remove_shadow(shadow_); |
| 7531 | if (shadow_ && !in_arena_) device_.remove_copy_target(shadow_); | ||
| 5498 | if (host_import_) { | 7532 | if (host_import_) { |
| 5499 | // VK_EXT_external_memory_host needs the caller's pages to stay valid for the imported memory's whole | 7533 | // VK_EXT_external_memory_host needs the caller's pages to stay valid for the imported memory's whole |
| 5500 | // lifetime, and a title may free them right after releasing the resource. So the memory is not left to | 7534 | // lifetime, and a title may free them right after releasing the resource. So the memory is not left to |
| @@ -5619,13 +7653,12 @@ public: | |||
| 5619 | const bool host = cpu_visible(); | 7653 | const bool host = cpu_visible(); |
| 5620 | leonida::ResourceBinding binding{}; // a buffer: no image | 7654 | leonida::ResourceBinding binding{}; // a buffer: no image |
| 5621 | binding.size = desc_.Width; | 7655 | binding.size = desc_.Width; |
| 5622 | if (!host && device_.arena.mapped) { | 7656 | const bool use_arena = !host && device_.arena.mapped; |
| 5623 | if (!device_.arena_allocate(desc_.Width, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, arena_offset_, | 7657 | if (use_arena && desc_.Width > device_.arena.size) return E_OUTOFMEMORY; |
| 5624 | DeviceState::arena_buffer)) { | 7658 | // An otherwise valid committed buffer can outgrow the largest free slice. Give it its own |
| 5625 | log_once("GPU address arena full (raise LEONIDA_ARENA_MB); buffer size in KiB:", | 7659 | // addressable VkBuffer below, so the title can still use its arena-relative GPU VA. |
| 5626 | int(desc_.Width / 1024)); | 7660 | if (use_arena && device_.arena_allocate(desc_.Width, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, |
| 5627 | return E_OUTOFMEMORY; | 7661 | arena_offset_, DeviceState::arena_buffer)) { |
| 5628 | } | ||
| 5629 | in_arena_ = true; | 7662 | in_arena_ = true; |
| 5630 | std::memset(device_.arena.mapped + arena_offset_, 0, std::size_t(desc_.Width)); | 7663 | std::memset(device_.arena.mapped + arena_offset_, 0, std::size_t(desc_.Width)); |
| 5631 | va_ = arena_offset_; | 7664 | va_ = arena_offset_; |
| @@ -5636,8 +7669,8 @@ public: | |||
| 5636 | // No host pointer: this is DEFAULT-heap arena memory the GPU may write, so its mapped bytes can be | 7669 | // No host pointer: this is DEFAULT-heap arena memory the GPU may write, so its mapped bytes can be |
| 5637 | // stale. host_at() must not treat it as a CPU-written instance pointer list. | 7670 | // stale. host_at() must not treat it as a CPU-written instance pointer list. |
| 5638 | // A default-heap AS resource is one of these ranges: a GENERIC acceleration structure covers it where | 7671 | // A default-heap AS resource is one of these ranges: a GENERIC acceleration structure covers it where |
| 5639 | // it sits. It is named by its real device address (heap base + offset), as instance descriptors and | 7672 | // it sits. It is named by its device address (heap base + offset, as the driver reports it), as instance |
| 5640 | // BuildRaytracingAccelerationStructure hand that address to the driver, not a console VA. | 7673 | // descriptors and BuildRaytracingAccelerationStructure hand that address to the driver, not a console VA. |
| 5641 | if (device_.info.ray_tracing && | 7674 | if (device_.info.ray_tracing && |
| 5642 | initial_state == D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE && | 7675 | initial_state == D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE && |
| 5643 | vk.vkCreateAccelerationStructureKHR) { | 7676 | vk.vkCreateAccelerationStructureKHR) { |
| @@ -5648,12 +7681,34 @@ public: | |||
| 5648 | asci.type = VK_ACCELERATION_STRUCTURE_TYPE_GENERIC_KHR; | 7681 | asci.type = VK_ACCELERATION_STRUCTURE_TYPE_GENERIC_KHR; |
| 5649 | if (vk.vkCreateAccelerationStructureKHR(device_.info.device, &asci, nullptr, &accel_) == VK_SUCCESS) { | 7682 | if (vk.vkCreateAccelerationStructureKHR(device_.info.device, &asci, nullptr, &accel_) == VK_SUCCESS) { |
| 5650 | gpu_va_ = device_.arena.address + va_; | 7683 | gpu_va_ = device_.arena.address + va_; |
| 7684 | // An instance names its BLAS by a value obtained from vkGetAccelerationStructureDeviceAddressKHR | ||
| 7685 | // (VUID-vkCmdBuildAccelerationStructuresKHR-pInfos-12281), so ask for it, as the committed path | ||
| 7686 | // below does. For GENERIC the spec only promises that these addresses keep the offsets between | ||
| 7687 | // the structures of one buffer; drivers return buffer address + offset (vkd3d-proton checks the | ||
| 7688 | // same). If one ever does not, the driver's address is the one instances must hold. | ||
| 7689 | if (vk.vkGetAccelerationStructureDeviceAddressKHR) { | ||
| 7690 | VkAccelerationStructureDeviceAddressInfoKHR dai{ | ||
| 7691 | VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_DEVICE_ADDRESS_INFO_KHR}; | ||
| 7692 | dai.accelerationStructure = accel_; | ||
| 7693 | const std::uint64_t as_va = | ||
| 7694 | vk.vkGetAccelerationStructureDeviceAddressKHR(device_.info.device, &dai); | ||
| 7695 | if (as_va && as_va != gpu_va_) { | ||
| 7696 | log_once("GENERIC acceleration structure address is not its buffer address + offset; " | ||
| 7697 | "arena offset in KiB:", int(arena_offset_ / 1024)); | ||
| 7698 | buffer_va_ = gpu_va_; | ||
| 7699 | gpu_va_ = as_va; | ||
| 7700 | } | ||
| 7701 | } | ||
| 5651 | device_.context->register_acceleration_structure(gpu_va_, accel_); | 7702 | device_.context->register_acceleration_structure(gpu_va_, accel_); |
| 7703 | if (buffer_va_ && buffer_va_ != gpu_va_) | ||
| 7704 | device_.context->register_acceleration_structure(buffer_va_, accel_); | ||
| 5652 | } | 7705 | } |
| 5653 | } | 7706 | } |
| 5654 | device_.context->add_resource(id(), binding); | 7707 | device_.context->add_resource(id(), binding); |
| 5655 | return S_OK; | 7708 | return S_OK; |
| 5656 | } | 7709 | } |
| 7710 | if (use_arena) | ||
| 7711 | log_once("GPU address arena full; using a dedicated default buffer, size in KiB:", int(desc_.Width / 1024)); | ||
| 5657 | const bool addressable = device_.arena.buffer != VK_NULL_HANDLE; | 7712 | const bool addressable = device_.arena.buffer != VK_NULL_HANDLE; |
| 5658 | const bool need_bda = device_.info.buffer_device_address || device_.info.ray_tracing; | 7713 | const bool need_bda = device_.info.buffer_device_address || device_.info.ray_tracing; |
| 5659 | VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; | 7714 | VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; |
| @@ -5691,8 +7746,8 @@ public: | |||
| 5691 | VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; | 7746 | VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; |
| 5692 | address.buffer = buffer_; | 7747 | address.buffer = buffer_; |
| 5693 | va_ = vk.vkGetBufferDeviceAddress(device_.info.device, &address) - device_.arena.address; | 7748 | va_ = vk.vkGetBufferDeviceAddress(device_.info.device, &address) - device_.arena.address; |
| 5694 | device_.log_va(heap_.Type == D3D12_HEAP_TYPE_READBACK ? "readback buffer" : "upload buffer", va_, | 7749 | const char* name = heap_.Type == D3D12_HEAP_TYPE_READBACK ? "readback buffer" : "upload buffer"; |
| 5695 | desc_.Width); | 7750 | device_.log_va(host ? name : "default buffer", va_, desc_.Width); |
| 5696 | } | 7751 | } |
| 5697 | if (host) { | 7752 | if (host) { |
| 5698 | if (vk.vkMapMemory(device_.info.device, memory_, 0, VK_WHOLE_SIZE, 0, &mapped_) != VK_SUCCESS) | 7753 | if (vk.vkMapMemory(device_.info.device, memory_, 0, VK_WHOLE_SIZE, 0, &mapped_) != VK_SUCCESS) |
| @@ -6007,6 +8062,7 @@ public: | |||
| 6007 | vk.vkMapMemory(device_.info.device, memory_, 0, VK_WHOLE_SIZE, 0, &shadow) != VK_SUCCESS) | 8062 | vk.vkMapMemory(device_.info.device, memory_, 0, VK_WHOLE_SIZE, 0, &shadow) != VK_SUCCESS) |
| 6008 | return E_OUTOFMEMORY; | 8063 | return E_OUTOFMEMORY; |
| 6009 | shadow_ = static_cast<std::uint8_t*>(shadow); | 8064 | shadow_ = static_cast<std::uint8_t*>(shadow); |
| 8065 | device_.add_copy_target(shadow_, std::size_t(desc_.Width), buffer_); // LEONIDA_SHADOW_GPU | ||
| 6010 | device_.add_shadow(pages, shadow_, std::size_t(desc_.Width)); | 8066 | device_.add_shadow(pages, shadow_, std::size_t(desc_.Width)); |
| 6011 | // Map() answers the title's own pages, as the imported buffer does: a write to the shadow's memory would be | 8067 | // Map() answers the title's own pages, as the imported buffer does: a write to the shadow's memory would be |
| 6012 | // overwritten by the next copy. | 8068 | // overwritten by the next copy. |
| @@ -6105,6 +8161,7 @@ public: | |||
| 6105 | aspects_ = format.aspects; | 8161 | aspects_ = format.aspects; |
| 6106 | image_address_ = device_.next_image_address.fetch_add(256); | 8162 | image_address_ = device_.next_image_address.fetch_add(256); |
| 6107 | device_.note_image_address(image_address_, this); | 8163 | device_.note_image_address(image_address_, this); |
| 8164 | DeviceState::trace_image(image_address_, id(), "registered"); | ||
| 6108 | binding_.image = image_; | 8165 | binding_.image = image_; |
| 6109 | binding_.format = format_; | 8166 | binding_.format = format_; |
| 6110 | binding_.aspects = aspects_; | 8167 | binding_.aspects = aspects_; |
| @@ -6450,6 +8507,7 @@ public: | |||
| 6450 | aspects_ = format.aspects; | 8507 | aspects_ = format.aspects; |
| 6451 | image_address_ = device_.next_image_address.fetch_add(256); | 8508 | image_address_ = device_.next_image_address.fetch_add(256); |
| 6452 | device_.note_image_address(image_address_, this); | 8509 | device_.note_image_address(image_address_, this); |
| 8510 | DeviceState::trace_image(image_address_, id(), "registered"); | ||
| 6453 | binding.deferred_memory = deferred_attachment_.get(); | 8511 | binding.deferred_memory = deferred_attachment_.get(); |
| 6454 | if (origin == TitleImageOrigin::placed && leonida::mem_probe::interval_seconds()) | 8512 | if (origin == TitleImageOrigin::placed && leonida::mem_probe::interval_seconds()) |
| 6455 | binding.replay_seen = &replay_seen_; | 8513 | binding.replay_seen = &replay_seen_; |
| @@ -6570,10 +8628,13 @@ private: | |||
| 6570 | } | 8628 | } |
| 6571 | 8629 | ||
| 6572 | public: | 8630 | public: |
| 8631 | void mark_console_d16s8() { console_d16s8_ = true; } | ||
| 8632 | bool console_d16s8() const { return console_d16s8_; } | ||
| 8633 | |||
| 6573 | // The Xbox proxy calls this before publishing an allocated depth texture. Each storage plane owns a | 8634 | // The Xbox proxy calls this before publishing an allocated depth texture. Each storage plane owns a |
| 6574 | // regular color image with its own GFX10 address, so a UAV cannot replace the original SRV in set 0. | 8635 | // regular color image with its own GFX10 address, so a UAV cannot replace the original SRV in set 0. |
| 6575 | HRESULT enable_depth_stencil_uav(D3D12_HEAP_FLAGS storage_heap_flags) { | 8636 | HRESULT enable_depth_stencil_uav(D3D12_HEAP_FLAGS storage_heap_flags) { |
| 6576 | const bool narrow_stencil = desc_.Format == xbox_d16s8; | 8637 | const bool narrow_stencil = desc_.Format == xbox_d16s8 || console_d16s8_; |
| 6577 | const bool depth16 = desc_.Format == DXGI_FORMAT_R16_TYPELESS || narrow_stencil; | 8638 | const bool depth16 = desc_.Format == DXGI_FORMAT_R16_TYPELESS || narrow_stencil; |
| 6578 | if (!image_ || (!depth16 && desc_.Format != DXGI_FORMAT_R32G8X24_TYPELESS) || | 8639 | if (!image_ || (!depth16 && desc_.Format != DXGI_FORMAT_R32G8X24_TYPELESS) || |
| 6579 | !(desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) || | 8640 | !(desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) || |
| @@ -6590,7 +8651,10 @@ public: | |||
| 6590 | std::unique_ptr<Resource> conversion; | 8651 | std::unique_ptr<Resource> conversion; |
| 6591 | if (widened) { | 8652 | if (widened) { |
| 6592 | const auto blit = VK_FORMAT_FEATURE_2_BLIT_SRC_BIT | VK_FORMAT_FEATURE_2_BLIT_DST_BIT; | 8653 | const auto blit = VK_FORMAT_FEATURE_2_BLIT_SRC_BIT | VK_FORMAT_FEATURE_2_BLIT_DST_BIT; |
| 6593 | if (format_ != VK_FORMAT_D32_SFLOAT_S8_UINT || (device_.optimal_features(VK_FORMAT_R16_UNORM) & blit) != blit || | 8654 | const bool d24_backing = format_ == VK_FORMAT_D24_UNORM_S8_UINT; |
| 8655 | if ((format_ != VK_FORMAT_D32_SFLOAT_S8_UINT && !d24_backing) || | ||
| 8656 | (d24_backing && !device_.context->has_depth24()) || | ||
| 8657 | (device_.optimal_features(VK_FORMAT_R16_UNORM) & blit) != blit || | ||
| 6594 | (device_.optimal_features(VK_FORMAT_R32_SFLOAT) & blit) != blit) return E_NOTIMPL; | 8658 | (device_.optimal_features(VK_FORMAT_R32_SFLOAT) & blit) != blit) return E_NOTIMPL; |
| 6595 | auto intermediate = plane_desc; | 8659 | auto intermediate = plane_desc; |
| 6596 | intermediate.Format = DXGI_FORMAT_R32_FLOAT; | 8660 | intermediate.Format = DXGI_FORMAT_R32_FLOAT; |
| @@ -6673,6 +8737,7 @@ public: | |||
| 6673 | device_.forget_image(va); // an earlier texture placed at this address, still alive: its views are stale | 8737 | device_.forget_image(va); // an earlier texture placed at this address, still alive: its views are stale |
| 6674 | image_address_ = va; | 8738 | image_address_ = va; |
| 6675 | device_.note_image_address(image_address_, this); | 8739 | device_.note_image_address(image_address_, this); |
| 8740 | DeviceState::trace_image(image_address_, id(), "registered"); | ||
| 6676 | } | 8741 | } |
| 6677 | // The title's own address for a texture Xbox slot 133 placed. The image is still the committed fallback, so its | 8742 | // The title's own address for a texture Xbox slot 133 placed. The image is still the committed fallback, so its |
| 6678 | // pixels do not alias the title's pages yet; the address is what GetGPUVirtualAddress answers (XCL PR #168's | 8743 | // pixels do not alias the title's pages yet; the address is what GetGPUVirtualAddress answers (XCL PR #168's |
| @@ -6744,6 +8809,27 @@ public: | |||
| 6744 | // no pointer to give (its layout is the driver's), so D3D12 only lets it be mapped with a null pointer, before | 8809 | // no pointer to give (its layout is the driver's), so D3D12 only lets it be mapped with a null pointer, before |
| 6745 | // WriteToSubresource/ReadFromSubresource. | 8810 | // WriteToSubresource/ReadFromSubresource. |
| 6746 | HRESULT STDMETHODCALLTYPE Map(UINT subresource, const D3D12_RANGE* read, void** data) override { | 8811 | HRESULT STDMETHODCALLTYPE Map(UINT subresource, const D3D12_RANGE* read, void** data) override { |
| 8812 | // LOCAL DIAGNOSTIC: LEONIDA_LOCK_TRACE=1 logs the first 256 texture Maps with a read range: the title's | ||
| 8813 | // texture lock passes the subresource's byte range there, computed from its XG computer's | ||
| 8814 | // layout, and adds the range's start to the pointer this answers. | ||
| 8815 | static const bool lock_trace = [] { | ||
| 8816 | char value[2]{}; | ||
| 8817 | return GetEnvironmentVariableA("LEONIDA_LOCK_TRACE", value, sizeof(value)) == 1 && value[0] == '1'; | ||
| 8818 | }(); | ||
| 8819 | if (lock_trace && read && image_) { | ||
| 8820 | static std::atomic<int> logged{0}; | ||
| 8821 | if (logged.fetch_add(1, std::memory_order_relaxed) < 256) { | ||
| 8822 | const auto caller = reinterpret_cast<std::uintptr_t>(_ReturnAddress()); | ||
| 8823 | std::fprintf(stderr, | ||
| 8824 | "[rt] d3d12: LOCAL DIAGNOSTIC: Map sub %u range 0x%llx..0x%llx of texture %llux%ux%u " | ||
| 8825 | "fmt %d flags 0x%x at 0x%llx, caller 0x%llx\n", | ||
| 8826 | subresource, static_cast<unsigned long long>(read->Begin), | ||
| 8827 | static_cast<unsigned long long>(read->End), static_cast<unsigned long long>(desc_.Width), | ||
| 8828 | desc_.Height, unsigned(desc_.DepthOrArraySize), int(desc_.Format), unsigned(desc_.Flags), | ||
| 8829 | static_cast<unsigned long long>(reinterpret_cast<std::uintptr_t>(title_address_)), | ||
| 8830 | static_cast<unsigned long long>(caller)); | ||
| 8831 | } | ||
| 8832 | } | ||
| 6747 | // A texture whose lease says its title memory is linear (title_linear_) and that also has a placement | 8833 | // A texture whose lease says its title memory is linear (title_linear_) and that also has a placement |
| 6748 | // address (slot 133; the video planes among them) has two answers. The placement address, with the title | 8834 | // address (slot 133; the video planes among them) has two answers. The placement address, with the title |
| 6749 | // texture registry filling the image, is the one the retail boot ran through the intro movie and the story | 8835 | // texture registry filling the image, is the one the retail boot ran through the intro movie and the story |
| @@ -7134,6 +9220,7 @@ private: | |||
| 7134 | if (!device_.staging_queue) { | 9220 | if (!device_.staging_queue) { |
| 7135 | device_.staging_queue = std::make_unique<leonida::VulkanQueue>(*device_.context, device_.info.queue, | 9221 | device_.staging_queue = std::make_unique<leonida::VulkanQueue>(*device_.context, device_.info.queue, |
| 7136 | device_.info.queue_family); | 9222 | device_.info.queue_family); |
| 9223 | device_.staging_queue->make_synchronous(); // waited for at once (idle below) | ||
| 7137 | } | 9224 | } |
| 7138 | if (device_.staging_queue->ok()) { | 9225 | if (device_.staging_queue->ok()) { |
| 7139 | const leonida::CommandList* lists[] = {&list}; | 9226 | const leonida::CommandList* lists[] = {&list}; |
| @@ -7206,6 +9293,7 @@ private: | |||
| 7206 | leonida::ResourceBinding binding_{}; // a texture's, as registered with the context | 9293 | leonida::ResourceBinding binding_{}; // a texture's, as registered with the context |
| 7207 | std::unique_ptr<Resource> depth_conversion_; | 9294 | std::unique_ptr<Resource> depth_conversion_; |
| 7208 | std::array<std::unique_ptr<Resource>, 2> storage_planes_; // Xbox depth/stencil UAV, by plane | 9295 | std::array<std::unique_ptr<Resource>, 2> storage_planes_; // Xbox depth/stencil UAV, by plane |
| 9296 | bool console_d16s8_ = false; // created from Xbox format 118 (even when pc_format made it D24S8) | ||
| 7209 | VkImage shared_zero_ = VK_NULL_HANDLE; // owned by the device | 9297 | VkImage shared_zero_ = VK_NULL_HANDLE; // owned by the device |
| 7210 | std::unique_ptr<leonida::DeferredImageBinding> deferred_attachment_; | 9298 | std::unique_ptr<leonida::DeferredImageBinding> deferred_attachment_; |
| 7211 | std::atomic<bool> replay_seen_{false}; | 9299 | std::atomic<bool> replay_seen_{false}; |
| @@ -7808,6 +9896,7 @@ struct PipelineStream { | |||
| 7808 | D3D12_SHADER_BYTECODE as{}; | 9896 | D3D12_SHADER_BYTECODE as{}; |
| 7809 | bool has_cs = false; | 9897 | bool has_cs = false; |
| 7810 | bool has_graphics_stage = false; // VS, PS, DS, HS, GS, AS or MS | 9898 | bool has_graphics_stage = false; // VS, PS, DS, HS, GS, AS or MS |
| 9899 | bool depth_bounds = false; // DEPTH_STENCIL1/2 DepthBoundsTestEnable (not in the plain graphics desc) | ||
| 7811 | }; | 9900 | }; |
| 7812 | 9901 | ||
| 7813 | // Console stream retry adapted from Kokonotcu, ubiquitarianism/leonida #496 (GPL-3.0). | 9902 | // Console stream retry adapted from Kokonotcu, ubiquitarianism/leonida #496 (GPL-3.0). |
| @@ -7946,9 +10035,7 @@ HRESULT parse_pipeline_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, Pipe | |||
| 7946 | case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1: { | 10035 | case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1: { |
| 7947 | D3D12_DEPTH_STENCIL_DESC1 d{}; | 10036 | D3D12_DEPTH_STENCIL_DESC1 d{}; |
| 7948 | take(d); | 10037 | take(d); |
| 7949 | if (ok && d.DepthBoundsTestEnable) { | 10038 | if (ok) out.depth_bounds = d.DepthBoundsTestEnable != FALSE; |
| 7950 | return stream_unsupported("depth-bounds tests are not supported yet; stream subobject", int(type)); | ||
| 7951 | } | ||
| 7952 | g.DepthStencilState = {d.DepthEnable, d.DepthWriteMask, d.DepthFunc, d.StencilEnable, d.StencilReadMask, | 10039 | g.DepthStencilState = {d.DepthEnable, d.DepthWriteMask, d.DepthFunc, d.StencilEnable, d.StencilReadMask, |
| 7953 | d.StencilWriteMask, d.FrontFace, d.BackFace}; | 10040 | d.StencilWriteMask, d.FrontFace, d.BackFace}; |
| 7954 | break; | 10041 | break; |
| @@ -7957,9 +10044,7 @@ HRESULT parse_pipeline_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, Pipe | |||
| 7957 | D3D12_DEPTH_STENCIL_DESC2 d{}; | 10044 | D3D12_DEPTH_STENCIL_DESC2 d{}; |
| 7958 | take(d); | 10045 | take(d); |
| 7959 | if (!ok) break; | 10046 | if (!ok) break; |
| 7960 | if (d.DepthBoundsTestEnable) { | 10047 | out.depth_bounds = d.DepthBoundsTestEnable != FALSE; |
| 7961 | return stream_unsupported("depth-bounds tests are not supported yet; stream subobject", int(type)); | ||
| 7962 | } | ||
| 7963 | // Each face has its own read and write mask (OPTIONS14.IndependentFrontAndBackStencilRefMaskSupported): | 10048 | // Each face has its own read and write mask (OPTIONS14.IndependentFrontAndBackStencilRefMaskSupported): |
| 7964 | // the description takes the front face's, back_stencil the back face's. | 10049 | // the description takes the front face's, back_stencil the back face's. |
| 7965 | out.back_masks = true; | 10050 | out.back_masks = true; |
| @@ -8018,6 +10103,410 @@ HRESULT parse_pipeline_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, Pipe | |||
| 8018 | // its FSSM program in the translator's index, and the FSSM blob is copied into the arena as the shader's code base. | 10103 | // its FSSM program in the translator's index, and the FSSM blob is copied into the arena as the shader's code base. |
| 8019 | std::atomic<long> live_pipeline_state_count{0}; // live_pipeline_states() | 10104 | std::atomic<long> live_pipeline_state_count{0}; // live_pipeline_states() |
| 8020 | 10105 | ||
| 10106 | // What the bindless set layout was made from, for a compute pipeline's journal name: a pipeline built against another | ||
| 10107 | // layout is another pipeline. Field by field, so padding never reaches the hash. | ||
| 10108 | void hash_bindless_layout(leonida::pipeline_journal::Hasher& hash, const leonida::BindlessFeatures& features) { | ||
| 10109 | for (const std::uint32_t count : features.counts) hash.value(count); | ||
| 10110 | hash.value(std::uint8_t(features.update_after_bind)); | ||
| 10111 | hash.value(std::uint8_t(features.partially_bound)); | ||
| 10112 | hash.value(std::uint8_t(features.null_descriptor)); | ||
| 10113 | for (const VkSampleCountFlagBits samples : features.ms_samples) hash.value(std::uint32_t(samples)); | ||
| 10114 | } | ||
| 10115 | |||
| 10116 | // Opt in on this branch. Async workers normally compile while other queues submit. | ||
| 10117 | std::unique_lock<leonida::SubmitMutex> compute_driver_turn(DeviceState& device) { | ||
| 10118 | static const bool enabled = [] { | ||
| 10119 | wchar_t value[2]{}; | ||
| 10120 | return GetEnvironmentVariableW(L"LEONIDA_COMPILE_GATE", value, 2) == 1 && value[0] == L'1'; | ||
| 10121 | }(); | ||
| 10122 | std::unique_lock turn(device.context->submit_mutex(), std::defer_lock); | ||
| 10123 | if (enabled) turn.lock(); | ||
| 10124 | return turn; | ||
| 10125 | } | ||
| 10126 | |||
| 10127 | // LOCAL FIX (pipeline journal, pipeline_cache_journal.h): one compute pipeline's own VkPipelineCache for the length | ||
| 10128 | // of its build. load() reads the journal file, before any driver call. In the build's one compile-gate turn, | ||
| 10129 | // create() makes the cache from the file's contents (seeded) or empty, and finish() takes the cache's data when the | ||
| 10130 | // pipeline had to be compiled and destroys the cache. publish(), after the turn, writes the file, or refreshes its | ||
| 10131 | // last use after a hit: no file I/O in the turn. Nothing else uses the cache, so it needs no synchronization beyond | ||
| 10132 | // the build's own. | ||
| 10133 | class JournalCache { | ||
| 10134 | public: | ||
| 10135 | VkPipelineCache cache = VK_NULL_HANDLE; | ||
| 10136 | bool seeded = false; // made from the file's contents | ||
| 10137 | |||
| 10138 | JournalCache(DeviceState& device, leonida::SubmitMutex& submits, const char* trigger, const char* name) | ||
| 10139 | : device_(device), submits_(&submits), trigger_(trigger), name_(name) {} | ||
| 10140 | // A build outside the submit lock's owners (the async compile workers' own turn helper): compute_driver_turn. | ||
| 10141 | JournalCache(DeviceState& device, const char* name) : device_(device), name_(name) {} | ||
| 10142 | JournalCache(const JournalCache&) = delete; | ||
| 10143 | JournalCache& operator=(const JournalCache&) = delete; | ||
| 10144 | ~JournalCache() { | ||
| 10145 | if (!cache) return; // finish() always destroys it; this is only for a build that left early | ||
| 10146 | if (submits_) { | ||
| 10147 | const DriverTurn turn(*submits_, trigger_, "vkDestroyPipelineCache", true, name_); | ||
| 10148 | device_.context->vk.vkDestroyPipelineCache(device_.info.device, cache, nullptr); | ||
| 10149 | } else { | ||
| 10150 | const auto turn = compute_driver_turn(device_); | ||
| 10151 | device_.context->vk.vkDestroyPipelineCache(device_.info.device, cache, nullptr); | ||
| 10152 | } | ||
| 10153 | } | ||
| 10154 | |||
| 10155 | bool enabled() const { return enabled_; } | ||
| 10156 | bool has_file_data() const { return !file_.data.empty(); } | ||
| 10157 | bool found() const { return enabled_ && built_ && !write_; } // the pipeline came out of the journal file | ||
| 10158 | bool written() const { return written_; } // publish() wrote the file | ||
| 10159 | |||
| 10160 | void load(std::filesystem::path path) { | ||
| 10161 | const auto& vk = device_.context->vk; | ||
| 10162 | if (!vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache || !vk.vkGetPipelineCacheData) return; | ||
| 10163 | enabled_ = true; | ||
| 10164 | path_ = std::move(path); | ||
| 10165 | namespace journal = leonida::pipeline_journal; | ||
| 10166 | const auto role = compile_helper::build_host.load() ? journal::ReadRole::materialize_local : journal::ReadRole::runtime; | ||
| 10167 | file_ = journal::read_with_seed(path_, pipeline_journal_roots().seed, device_.pso_identity, role); | ||
| 10168 | } | ||
| 10169 | |||
| 10170 | // In the build's driver turn. | ||
| 10171 | void create() { | ||
| 10172 | if (!enabled_) return; | ||
| 10173 | const auto& vk = device_.context->vk; | ||
| 10174 | VkPipelineCacheCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, nullptr, 0, file_.data.size(), | ||
| 10175 | file_.data.empty() ? nullptr : file_.data.data()}; | ||
| 10176 | if (!file_.data.empty() && vk.vkCreatePipelineCache(device_.info.device, &info, nullptr, &cache) == VK_SUCCESS) { | ||
| 10177 | seeded = true; | ||
| 10178 | } else { | ||
| 10179 | cache = VK_NULL_HANDLE; // no file, or one the driver declined: start empty, and the build rewrites it | ||
| 10180 | info.initialDataSize = 0; | ||
| 10181 | info.pInitialData = nullptr; | ||
| 10182 | if (vk.vkCreatePipelineCache(device_.info.device, &info, nullptr, &cache) != VK_SUCCESS) cache = VK_NULL_HANDLE; | ||
| 10183 | } | ||
| 10184 | std::vector<char>().swap(file_.data); // the driver has its own copy | ||
| 10185 | } | ||
| 10186 | |||
| 10187 | // In the build's driver turn, after the create against `cache`. `built`: that create made the pipeline; `hit`: | ||
| 10188 | // its creation feedback; `driver_ms`: the vkCreateComputePipelines call alone. | ||
| 10189 | void finish(bool built, int hit, std::uint64_t driver_ms) { | ||
| 10190 | if (!cache) return; | ||
| 10191 | const auto& vk = device_.context->vk; | ||
| 10192 | built_ = built; | ||
| 10193 | write_ = built && leonida::pipeline_journal::should_write(seeded, hit, driver_ms); | ||
| 10194 | if (write_) { | ||
| 10195 | std::size_t size = 0; | ||
| 10196 | result_ = vk.vkGetPipelineCacheData(device_.info.device, cache, &size, nullptr); | ||
| 10197 | if (result_ == VK_SUCCESS && size > leonida::pipeline_cache_store::header_bytes && | ||
| 10198 | size <= leonida::pipeline_journal::entry_read_limit) { | ||
| 10199 | blob_.resize(size); | ||
| 10200 | result_ = vk.vkGetPipelineCacheData(device_.info.device, cache, &size, blob_.data()); | ||
| 10201 | blob_.resize(result_ == VK_SUCCESS ? size : 0); | ||
| 10202 | } | ||
| 10203 | data_size_ = size; | ||
| 10204 | } | ||
| 10205 | vk.vkDestroyPipelineCache(device_.info.device, cache, nullptr); | ||
| 10206 | cache = VK_NULL_HANDLE; | ||
| 10207 | } | ||
| 10208 | |||
| 10209 | // The shared cache had the pipeline (FAIL_ON_PIPELINE_COMPILE_REQUIRED gave it, as a hit or quickly). | ||
| 10210 | void found_in_shared() { report(device_.journal_shared_hits.fetch_add(1) + 1, "found in the shared cache"); } | ||
| 10211 | |||
| 10212 | // After the driver turn. | ||
| 10213 | void publish() { | ||
| 10214 | namespace journal = leonida::pipeline_journal; | ||
| 10215 | if (!enabled_ || !built_) return; | ||
| 10216 | if (!write_) { | ||
| 10217 | report(device_.journal_hits.fetch_add(1) + 1, "found in their journal file"); | ||
| 10218 | journal::touch_local_hit(path_, file_, std::filesystem::file_time_type::clock::now()); | ||
| 10219 | return; | ||
| 10220 | } | ||
| 10221 | if (blob_.size() <= leonida::pipeline_cache_store::header_bytes) { | ||
| 10222 | std::fprintf(stderr, "[rt] d3d12: pipeline journal: no cache data for %s (VkResult %d, %zu bytes)\n", | ||
| 10223 | name_, int(result_), data_size_); | ||
| 10224 | return; | ||
| 10225 | } | ||
| 10226 | // A rewrite replaces the file's old size. Two builds of one name at once may both count: the next boot's | ||
| 10227 | // tidy counts again. | ||
| 10228 | if (journal::replace_bytes(device_.journal_bytes.load(), file_.bytes, blob_.size()) > device_.journal_budget) { | ||
| 10229 | static std::atomic<bool> said{false}; | ||
| 10230 | if (!said.exchange(true)) | ||
| 10231 | std::fprintf(stderr, "[rt] d3d12: pipeline journal: %llu bytes on disk, the %llu-byte budget " | ||
| 10232 | "(LEONIDA_PIPELINE_JOURNAL_BYTES) is spent; nothing more is written this boot\n", | ||
| 10233 | static_cast<unsigned long long>(device_.journal_bytes.load()), | ||
| 10234 | static_cast<unsigned long long>(device_.journal_budget)); | ||
| 10235 | return; | ||
| 10236 | } | ||
| 10237 | if (const std::error_code error = journal::write_entry(path_, blob_.data(), blob_.size())) { | ||
| 10238 | static std::atomic<bool> said{false}; | ||
| 10239 | if (!said.exchange(true)) | ||
| 10240 | std::fprintf(stderr, "[rt] d3d12: pipeline journal: could not write %ls: %s\n", path_.c_str(), | ||
| 10241 | error.message().c_str()); | ||
| 10242 | return; | ||
| 10243 | } | ||
| 10244 | auto total = device_.journal_bytes.load(); | ||
| 10245 | while (!device_.journal_bytes.compare_exchange_weak(total, journal::replace_bytes(total, file_.bytes, blob_.size()))) { | ||
| 10246 | } | ||
| 10247 | written_ = true; | ||
| 10248 | report(device_.journal_writes.fetch_add(1) + 1, "compiled and written to their journal file"); | ||
| 10249 | } | ||
| 10250 | |||
| 10251 | private: | ||
| 10252 | // The first of each kind, then every 100th, with all three counts. | ||
| 10253 | void report(unsigned count, const char* what) const { | ||
| 10254 | if (count != 1 && count % 100) return; | ||
| 10255 | std::fprintf(stderr, "[rt] d3d12: pipeline journal: %u compute pipeline(s) %s (so far: %u from journal files, " | ||
| 10256 | "%u written, %u from the shared cache)\n", count, what, | ||
| 10257 | device_.journal_hits.load(), device_.journal_writes.load(), device_.journal_shared_hits.load()); | ||
| 10258 | } | ||
| 10259 | |||
| 10260 | DeviceState& device_; | ||
| 10261 | leonida::SubmitMutex* submits_ = nullptr; // null: compute_driver_turn, for a build outside the submit lock | ||
| 10262 | const char* trigger_ = ""; | ||
| 10263 | const char* name_; | ||
| 10264 | bool enabled_ = false; | ||
| 10265 | bool built_ = false; | ||
| 10266 | bool write_ = false; | ||
| 10267 | bool written_ = false; | ||
| 10268 | std::filesystem::path path_; | ||
| 10269 | leonida::pipeline_journal::EntryFile file_; | ||
| 10270 | std::vector<char> blob_; | ||
| 10271 | std::size_t data_size_ = 0; | ||
| 10272 | VkResult result_ = VK_SUCCESS; | ||
| 10273 | }; | ||
| 10274 | |||
| 10275 | // What one compute pipeline build did (build_compute_pipeline). | ||
| 10276 | struct ComputeBuild { | ||
| 10277 | VkPipeline pipeline = VK_NULL_HANDLE; // the caller's from here on | ||
| 10278 | VkResult result = VK_ERROR_UNKNOWN; | ||
| 10279 | std::size_t bytes = 0; // SPIR-V | ||
| 10280 | ULONGLONG ms = 0; // the whole build | ||
| 10281 | std::filesystem::path journal_path; // its journal file's name (empty with the journal off) | ||
| 10282 | bool skipped = false; // ComputeBuildOptions::skip_journaled and the journal file was there: nothing built | ||
| 10283 | bool busy = false; // ComputeBuildOptions::mark_building and another process is building it: nothing built | ||
| 10284 | bool deferred = false; // asked of the compile helper without waiting: nothing built yet | ||
| 10285 | bool journal_hit = false; // found in its journal file | ||
| 10286 | bool journaled = false; // compiled and written to its journal file | ||
| 10287 | bool from_shared = false; // found in the shared cache | ||
| 10288 | }; | ||
| 10289 | |||
| 10290 | struct ComputeBuildOptions { | ||
| 10291 | const char* trigger = "dispatch"; // what asked: dispatch, warmup, dispatch-worker, precompile... | ||
| 10292 | const std::string* cache_key = nullptr; // the title's PSO description key, for the compile trace | ||
| 10293 | bool serialize_big = true; // LEONIDA_SERIAL_BIG_COMPILES=1: modules over 128 KiB one at a time | ||
| 10294 | bool skip_journaled = false; // precompile: leave a pipeline whose journal file exists alone | ||
| 10295 | bool use_helper = true; // LEONIDA_COMPILE_HELPER: a missing journal file comes from the helper | ||
| 10296 | bool helper_wait = true; // wait for the helper's file (false: ask, and answer deferred) | ||
| 10297 | std::uint64_t helper_priority = 0; // the request's urgency: 0 a dispatch, else the warm-up's module size | ||
| 10298 | bool mark_building = false; // precompile, helper: claim the entry, skip it when another process has it | ||
| 10299 | bool key_only = false; // only name the journal file (journal_path), build nothing | ||
| 10300 | }; | ||
| 10301 | |||
| 10302 | // A compute pipeline from a library entry: what a PSO's first dispatch, the warm-up worker and gta6rt | ||
| 10303 | // --precompile-pipelines all build, so their journal names and the driver's keys are the same. `layout` is the push | ||
| 10304 | // range of leonida::ShaderUserData, with the device's bindless set 0 when the entry declares bindings; `subgroup` is | ||
| 10305 | // leonida::decide_subgroup_size's answer for the entry. | ||
| 10306 | ComputeBuild build_compute_pipeline(DeviceState& device, const leonida::ShaderEntry& compute_entry, | ||
| 10307 | VkPipelineLayout layout, const leonida::SubgroupRequest& subgroup, | ||
| 10308 | const ComputeBuildOptions& options) { | ||
| 10309 | ComputeBuild out; | ||
| 10310 | CompileActivity activity(device.active_compiles); | ||
| 10311 | const char* const trigger = options.trigger; | ||
| 10312 | std::filesystem::path marked; // mark_building: released on the way out | ||
| 10313 | struct Unmark { | ||
| 10314 | std::filesystem::path& path; | ||
| 10315 | ~Unmark() { | ||
| 10316 | if (!path.empty()) compile_helper::unmark_building(path); | ||
| 10317 | } | ||
| 10318 | } unmark{marked}; | ||
| 10319 | static const std::string no_key; | ||
| 10320 | auto& vk = device.context->vk; | ||
| 10321 | const VkDevice dev = device.info.device; | ||
| 10322 | const leonida::ShaderLibrary* library = device.library(); | ||
| 10323 | const leonida::ShaderEntry* entry = &compute_entry; | ||
| 10324 | if (!library) return out; | ||
| 10325 | // The driver's compiler needs hundreds of MiB per very large module; several at once exhausted host memory. By | ||
| 10326 | // default large modules share a memory budget (big_compile_gate, taken by the caller before any PSO lock: see | ||
| 10327 | // PipelineState::enter_build); LEONIDA_SERIAL_BIG_COMPILES=1 compiles them one at a time here instead. | ||
| 10328 | static std::mutex big_compile; | ||
| 10329 | std::unique_lock<std::mutex> big_lock(big_compile, std::defer_lock); // taken below, only for a compile here | ||
| 10330 | auto words = library->spirv(*entry); | ||
| 10331 | if (words.empty()) { | ||
| 10332 | std::fprintf(stderr, "[rt] d3d12: %s.spv is missing or not SPIR-V\n", entry->name.c_str()); | ||
| 10333 | return out; | ||
| 10334 | } | ||
| 10335 | const std::size_t bytes = words.size() * sizeof(std::uint32_t); | ||
| 10336 | out.bytes = bytes; | ||
| 10337 | VkComputePipelineCreateInfo pipeline_info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; | ||
| 10338 | pipeline_info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; | ||
| 10339 | pipeline_info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; | ||
| 10340 | pipeline_info.stage.pName = "main"; | ||
| 10341 | VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_size{}; | ||
| 10342 | leonida::apply_subgroup_request(subgroup, required_size, pipeline_info.stage); | ||
| 10343 | pipeline_info.layout = layout; | ||
| 10344 | pipeline_info.flags |= fast_pipeline_flags(true); // before the journal key, which hashes the flags | ||
| 10345 | const VkPipelineCache shared = device.pipeline_cache(); | ||
| 10346 | auto& submits = device.context->submit_mutex(); | ||
| 10347 | |||
| 10348 | // LOCAL FIX (pipeline journal, pipeline_cache_journal.h): the pipeline is created against its own cache, made | ||
| 10349 | // from its journal file or empty and written back after a compile, so a boot killed or crashed later keeps it. | ||
| 10350 | // The file is named by what the pipeline is made of and read here, before the driver turn. Without a file | ||
| 10351 | // the shared cache (seeded from the offline corpus or the last session) is asked first, without a compile. | ||
| 10352 | JournalCache journal(device, submits, trigger, entry->name.c_str()); | ||
| 10353 | if (const std::filesystem::path& journal_dir = pipeline_journal_dir(); !journal_dir.empty()) { | ||
| 10354 | leonida::pipeline_journal::Hasher key; | ||
| 10355 | key.text("cs"); | ||
| 10356 | key.value(std::uint64_t(words.size())); | ||
| 10357 | key.bytes(words.data(), bytes); | ||
| 10358 | key.text(pipeline_info.stage.pName); | ||
| 10359 | key.value(std::uint32_t(pipeline_info.flags)); | ||
| 10360 | key.value(std::uint32_t(pipeline_info.stage.flags)); | ||
| 10361 | key.value(std::uint32_t(pipeline_info.stage.pNext == &required_size ? required_size.requiredSubgroupSize : 0)); | ||
| 10362 | key.value(std::uint32_t(sizeof(leonida::ShaderUserData))); | ||
| 10363 | key.value(std::uint32_t(entry->binding_count != 0)); | ||
| 10364 | // NVIDIA's diagnostics config (LEONIDA_DEVICE_FAULT=1, Aftermath) compiles with shader debug info: other | ||
| 10365 | // pipelines, kept apart so switching it on and off does not rewrite every file. Absent when off, so the | ||
| 10366 | // names of ordinary boots stay as they were. | ||
| 10367 | if (device.info.device_diagnostics_config) { | ||
| 10368 | key.text("nv-diagnostics-config"); | ||
| 10369 | key.value(std::uint32_t(leonida::aftermath::extra_config_flags())); | ||
| 10370 | } | ||
| 10371 | if (entry->binding_count) hash_bindless_layout(key, device.bindless->features()); | ||
| 10372 | const auto path = leonida::pipeline_journal::entry_path(journal_dir, "cs", key.digest()); | ||
| 10373 | out.journal_path = path; | ||
| 10374 | if (options.key_only) return out; | ||
| 10375 | // Precompile: a usable file is there already, so the pipeline is not built (only its header is read). | ||
| 10376 | if (options.skip_journaled && leonida::pipeline_journal::entry_usable(path, device.pso_identity)) { | ||
| 10377 | out.skipped = true; | ||
| 10378 | return out; | ||
| 10379 | } | ||
| 10380 | journal.load(path); | ||
| 10381 | // LOCAL FIX (compile helper, d3d12_compile_helper.h): no file, so this would be a compile in this process, | ||
| 10382 | // where the driver's lock it holds stops the title's submissions. The helper process compiles it into the file | ||
| 10383 | // instead, and the create below is a hit. Asked without waiting, the build answers deferred and is asked | ||
| 10384 | // again at the pipeline's next use; waited for, nothing of ours is in the driver meanwhile. | ||
| 10385 | if (!journal.has_file_data() && options.use_helper && compile_helper::wanted(bytes)) { | ||
| 10386 | auto& helper = compile_helper::Client::instance(); | ||
| 10387 | std::string why; | ||
| 10388 | if (!options.helper_wait) { | ||
| 10389 | if (helper.request(path, entry->name, options.helper_priority, device.pso_identity, &why)) { | ||
| 10390 | out.deferred = true; | ||
| 10391 | return out; | ||
| 10392 | } | ||
| 10393 | std::fprintf(stderr, "[rt] d3d12: compile helper: %s for %s; built here\n", why.c_str(), | ||
| 10394 | entry->name.c_str()); | ||
| 10395 | } else { | ||
| 10396 | const ULONGLONG asked = GetTickCount64(); | ||
| 10397 | if (helper.build(path, entry->name, device.pso_identity, &why)) { | ||
| 10398 | journal.load(path); | ||
| 10399 | std::fprintf(stderr, "[rt] d3d12: compile helper built %s in %.1f s (%zu B SPIR-V, %s)\n", | ||
| 10400 | entry->name.c_str(), double(GetTickCount64() - asked) / 1000.0, bytes, trigger); | ||
| 10401 | } else { | ||
| 10402 | std::fprintf(stderr, "[rt] d3d12: compile helper: %s for %s after %.1f s; built here\n", | ||
| 10403 | why.c_str(), entry->name.c_str(), double(GetTickCount64() - asked) / 1000.0); | ||
| 10404 | } | ||
| 10405 | } | ||
| 10406 | } | ||
| 10407 | // Precompile and helper: another process compiling this entry is left to it. | ||
| 10408 | if (options.mark_building && !journal.has_file_data()) { | ||
| 10409 | if (!compile_helper::mark_building(path)) { | ||
| 10410 | out.busy = true; | ||
| 10411 | return out; | ||
| 10412 | } | ||
| 10413 | marked = path; | ||
| 10414 | } | ||
| 10415 | } | ||
| 10416 | // Only a compile here is serialized: a pipeline from its journal file takes milliseconds. | ||
| 10417 | if (!journal.has_file_data() && options.serialize_big && big_compiles() == BigCompiles::serial && big_compute(bytes)) | ||
| 10418 | big_lock.lock(); | ||
| 10419 | const bool ask_shared = journal.enabled() && !journal.has_file_data() && shared && device.pipeline_cache_seeded && | ||
| 10420 | device.info.pipeline_cache_control && device.journal_ask_shared.load(); | ||
| 10421 | |||
| 10422 | VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; | ||
| 10423 | module_info.codeSize = bytes; | ||
| 10424 | module_info.pCode = words.data(); | ||
| 10425 | VkShaderModule module = VK_NULL_HANDLE; | ||
| 10426 | const ULONGLONG started = GetTickCount64(); | ||
| 10427 | VkPipeline built = VK_NULL_HANDLE; | ||
| 10428 | CompileTrace trace; | ||
| 10429 | trace.begin(pipeline_info, device.info.pipeline_creation_feedback, trigger, entry->name.c_str(), 0, bytes, options.cache_key ? *options.cache_key : no_key); | ||
| 10430 | // Was it in the cache? Core feedback on a Vulkan 1.3 device; pipeline_cache_control implies one. | ||
| 10431 | if (journal.enabled() && device.info.pipeline_cache_control) trace.request_feedback(pipeline_info); | ||
| 10432 | const leonida::dev_status::Build dev_build(entry->name.c_str()); | ||
| 10433 | const leonida::pipeline_profile::DriverCall profile("cs", trigger, entry->name.c_str()); | ||
| 10434 | // LOCAL DIAGNOSTIC (early device loss): a vkQueueSubmit was measured blocking 10 s and losing the device | ||
| 10435 | // while another thread sat in this call. Name what is building (once past the gate: in the driver), and log | ||
| 10436 | // the start of big ones. | ||
| 10437 | auto& compiling = leonida::driver_compile; | ||
| 10438 | VkResult created = VK_ERROR_UNKNOWN; | ||
| 10439 | bool from_shared = false, probe_compiled = false; | ||
| 10440 | ULONGLONG probe_ms = 0, driver_ms = 0; | ||
| 10441 | { | ||
| 10442 | // Every driver call of the build (shader module, journal cache, pipeline) in one turn through the compile | ||
| 10443 | // gate: from the journal a build takes milliseconds and the warm-up worker makes them back to back, and | ||
| 10444 | // three warm boots lost the device in a vkQueueSubmit (no GPU fault, no TDR) while only the create was | ||
| 10445 | // gated. No file I/O in here. | ||
| 10446 | const DriverTurn turn(submits, trigger, "vkCreateComputePipelines", true, entry->name.c_str()); | ||
| 10447 | { | ||
| 10448 | const leonida::aftermath::ShaderName named(entry->name); | ||
| 10449 | if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return out; | ||
| 10450 | } | ||
| 10451 | pipeline_info.stage.module = module; | ||
| 10452 | journal.create(); | ||
| 10453 | const VkPipelineCache cache = journal.cache ? journal.cache : shared; | ||
| 10454 | compiling.bytes.store(bytes, std::memory_order_relaxed); | ||
| 10455 | compiling.trigger.store(trigger, std::memory_order_relaxed); | ||
| 10456 | compiling.since_ms.store(leonida::diagnostic_ms(), std::memory_order_relaxed); | ||
| 10457 | compiling.name.store(entry->name.c_str(), std::memory_order_release); | ||
| 10458 | if (bytes >= 128 * 1024) | ||
| 10459 | std::fprintf(stderr, "[rt] d3d12: compute pipeline %s (%zu B SPIR-V, %s) build starts at t=%.3f s\n", | ||
| 10460 | entry->name.c_str(), bytes, trigger, double(leonida::diagnostic_ms()) / 1000.0); | ||
| 10461 | if (ask_shared) { | ||
| 10462 | // VK_PIPELINE_COMPILE_REQUIRED (a success code, no pipeline) when the shared cache does not have it. | ||
| 10463 | pipeline_info.flags |= VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT; | ||
| 10464 | const ULONGLONG asked = GetTickCount64(); | ||
| 10465 | created = vk.vkCreateComputePipelines(dev, shared, 1, &pipeline_info, nullptr, &built); | ||
| 10466 | probe_ms = GetTickCount64() - asked; | ||
| 10467 | pipeline_info.flags &= ~VkPipelineCreateFlags(VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT); | ||
| 10468 | from_shared = created == VK_SUCCESS && built; | ||
| 10469 | if (from_shared && leonida::pipeline_journal::probe_compiled(trace.hit(), probe_ms)) { | ||
| 10470 | // NVIDIA 630.20 compiled it instead of answering VK_PIPELINE_COMPILE_REQUIRED, into the shared | ||
| 10471 | // cache. Built once more against the journal cache below, so it is journaled; asking stops. | ||
| 10472 | vk.vkDestroyPipeline(dev, built, nullptr); | ||
| 10473 | from_shared = false; | ||
| 10474 | probe_compiled = true; | ||
| 10475 | } | ||
| 10476 | if (!from_shared) built = VK_NULL_HANDLE; | ||
| 10477 | } | ||
| 10478 | if (!from_shared) { | ||
| 10479 | const ULONGLONG at = GetTickCount64(); | ||
| 10480 | created = vk.vkCreateComputePipelines(dev, cache, 1, &pipeline_info, nullptr, &built); | ||
| 10481 | driver_ms = GetTickCount64() - at; | ||
| 10482 | } | ||
| 10483 | compiling.name.store(nullptr, std::memory_order_release); | ||
| 10484 | vk.vkDestroyShaderModule(dev, module, nullptr); // Vulkan lets a module go once the pipeline exists | ||
| 10485 | journal.finish(!from_shared && created == VK_SUCCESS && built, trace.hit(), driver_ms); | ||
| 10486 | } | ||
| 10487 | std::vector<std::uint32_t>().swap(words); | ||
| 10488 | profile.finish(int(created)); | ||
| 10489 | trace.end(trigger, entry->name.c_str(), 0, bytes, created); | ||
| 10490 | if (big_lock.owns_lock()) big_lock.unlock(); | ||
| 10491 | if (probe_compiled && device.journal_ask_shared.exchange(false)) | ||
| 10492 | std::fprintf(stderr, "[rt] d3d12: pipeline journal: the driver compiled %s for " | ||
| 10493 | "FAIL_ON_PIPELINE_COMPILE_REQUIRED (%llu ms, no cache hit); built again for its journal " | ||
| 10494 | "file, and the shared cache is no longer asked first\n", entry->name.c_str(), | ||
| 10495 | static_cast<unsigned long long>(probe_ms)); | ||
| 10496 | if (from_shared) journal.found_in_shared(); | ||
| 10497 | journal.publish(); | ||
| 10498 | out.pipeline = built; | ||
| 10499 | out.result = created; | ||
| 10500 | out.from_shared = from_shared; | ||
| 10501 | out.journal_hit = journal.found(); | ||
| 10502 | out.journaled = journal.written(); | ||
| 10503 | out.ms = GetTickCount64() - started; | ||
| 10504 | if (created == VK_SUCCESS && built && out.ms >= 2000) | ||
| 10505 | std::fprintf(stderr, "[rt] d3d12: compute pipeline %s took %.1f s to build (%zu B SPIR-V)\n", | ||
| 10506 | entry->name.c_str(), double(out.ms) / 1000.0, bytes); | ||
| 10507 | return out; | ||
| 10508 | } | ||
| 10509 | |||
| 8021 | class PipelineState final | 10510 | class PipelineState final |
| 8022 | : public Child<PipelineState, XboxPipelineStateStubs, ID3D12Object, ID3D12DeviceChild, ID3D12Pageable, | 10511 | : public Child<PipelineState, XboxPipelineStateStubs, ID3D12Object, ID3D12DeviceChild, ID3D12Pageable, |
| 8023 | ID3D12PipelineState> { | 10512 | ID3D12PipelineState> { |
| @@ -8082,6 +10571,16 @@ public: | |||
| 8082 | // Asks for the subgroup size the shader was translated for, where the device allows (src/subgroup_size.h): the | 10571 | // Asks for the subgroup size the shader was translated for, where the device allows (src/subgroup_size.h): the |
| 8083 | // stage gets VkPipelineShaderStageRequiredSubgroupSizeCreateInfo in `storage` (which must outlive pipeline | 10572 | // stage gets VkPipelineShaderStageRequiredSubgroupSizeCreateInfo in `storage` (which must outlive pipeline |
| 8084 | // creation) and, for compute, REQUIRE_FULL_SUBGROUPS. A size the device cannot give is reported, not hidden. | 10573 | // creation) and, for compute, REQUIRE_FULL_SUBGROUPS. A size the device cannot give is reported, not hidden. |
| 10574 | // decide_subgroup_size's answer for a compute entry, reported and recorded as subgroup_size_for does; the build | ||
| 10575 | // applies it (build_compute_pipeline). | ||
| 10576 | leonida::SubgroupRequest subgroup_request_for(const leonida::ShaderEntry& entry) { | ||
| 10577 | const leonida::SubgroupRequest request = leonida::decide_subgroup_size(entry, device_.info.subgroup); | ||
| 10578 | if (request.outcome == leonida::SubgroupOutcome::unavailable) | ||
| 10579 | report_subgroup_unavailable(entry, request, device_.info.subgroup); | ||
| 10580 | subgroup_requests_.push_back(request); | ||
| 10581 | return request; | ||
| 10582 | } | ||
| 10583 | |||
| 8085 | void subgroup_size_for(const leonida::ShaderEntry& entry, VkPipelineShaderStageRequiredSubgroupSizeCreateInfo& storage, | 10584 | void subgroup_size_for(const leonida::ShaderEntry& entry, VkPipelineShaderStageRequiredSubgroupSizeCreateInfo& storage, |
| 8086 | VkPipelineShaderStageCreateInfo& stage) { | 10585 | VkPipelineShaderStageCreateInfo& stage) { |
| 8087 | const leonida::SubgroupRequest request = leonida::decide_subgroup_size(entry, device_.info.subgroup); | 10586 | const leonida::SubgroupRequest request = leonida::decide_subgroup_size(entry, device_.info.subgroup); |
| @@ -8218,7 +10717,7 @@ public: | |||
| 8218 | if (seen.insert(line).second) std::fprintf(stderr, "%s\n", line); | 10717 | if (seen.insert(line).second) std::fprintf(stderr, "%s\n", line); |
| 8219 | } | 10718 | } |
| 8220 | HRESULT create_graphics(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc, const D3D12_SHADER_BYTECODE* ms = nullptr, | 10719 | HRESULT create_graphics(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc, const D3D12_SHADER_BYTECODE* ms = nullptr, |
| 8221 | const D3D12_SHADER_BYTECODE* as = nullptr, const StencilFaceMasks* back_masks = nullptr) { | 10720 | const D3D12_SHADER_BYTECODE* as = nullptr, const StencilFaceMasks* back_masks = nullptr, bool depth_bounds = false) { |
| 8222 | auto& vk = device_.context->vk; | 10721 | auto& vk = device_.context->vk; |
| 8223 | const VkDevice dev = device_.info.device; | 10722 | const VkDevice dev = device_.info.device; |
| 8224 | const bool mesh = ms && ms->pShaderBytecode && ms->BytecodeLength; | 10723 | const bool mesh = ms && ms->pShaderBytecode && ms->BytecodeLength; |
| @@ -8488,8 +10987,8 @@ public: | |||
| 8488 | if (vs_stage.entry && ps_stage.entry && !gs_stage.entry && | 10987 | if (vs_stage.entry && ps_stage.entry && !gs_stage.entry && |
| 8489 | (!ps_stage.entry->f16_halves.empty() || !vs_stage.entry->f16_halves.empty())) { | 10988 | (!ps_stage.entry->f16_halves.empty() || !vs_stage.entry->f16_halves.empty())) { |
| 8490 | std::string link_error; | 10989 | std::string link_error; |
| 8491 | if (!leonida::link_f16_halves(vs_stage.words, *vs_stage.entry, ps_stage.words, *ps_stage.entry, | 10990 | if (!link_f16_halves(vs_stage.words, *vs_stage.entry, ps_stage.words, *ps_stage.entry, |
| 8492 | &link_error, device_.f16_half_top_location)) { | 10991 | &link_error)) { |
| 8493 | std::fprintf(stderr, "[rt] d3d12: %s\n", link_error.c_str()); | 10992 | std::fprintf(stderr, "[rt] d3d12: %s\n", link_error.c_str()); |
| 8494 | return E_FAIL; | 10993 | return E_FAIL; |
| 8495 | } | 10994 | } |
| @@ -8727,6 +11226,10 @@ public: | |||
| 8727 | depth.front = stencil_face(ds.FrontFace, ds.StencilReadMask, ds.StencilWriteMask); | 11226 | depth.front = stencil_face(ds.FrontFace, ds.StencilReadMask, ds.StencilWriteMask); |
| 8728 | depth.back = back_masks ? stencil_face(ds.BackFace, back_masks->read, back_masks->write) | 11227 | depth.back = back_masks ? stencil_face(ds.BackFace, back_masks->read, back_masks->write) |
| 8729 | : stencil_face(ds.BackFace, ds.StencilReadMask, ds.StencilWriteMask); | 11228 | : stencil_face(ds.BackFace, ds.StencilReadMask, ds.StencilWriteMask); |
| 11229 | // The depth-bounds test (DEPTH_STENCIL1/2): the bounds are dynamic, set from OMSetDepthBounds at each draw. | ||
| 11230 | depth.depthBoundsTestEnable = depth_bounds ? VK_TRUE : VK_FALSE; | ||
| 11231 | depth.minDepthBounds = 0.0f; | ||
| 11232 | depth.maxDepthBounds = 1.0f; | ||
| 8730 | 11233 | ||
| 8731 | std::vector<VkPipelineColorBlendAttachmentState> blends(desc.NumRenderTargets); | 11234 | std::vector<VkPipelineColorBlendAttachmentState> blends(desc.NumRenderTargets); |
| 8732 | for (UINT i = 0; i < desc.NumRenderTargets; ++i) { | 11235 | for (UINT i = 0; i < desc.NumRenderTargets; ++i) { |
| @@ -8770,6 +11273,13 @@ public: | |||
| 8770 | // State that needs a Vulkan feature the device did not enable (VulkanDeviceInfo::features) is refused, rather | 11273 | // State that needs a Vulkan feature the device did not enable (VulkanDeviceInfo::features) is refused, rather |
| 8771 | // than handed to the driver against the spec. | 11274 | // than handed to the driver against the spec. |
| 8772 | const VkPhysicalDeviceFeatures& features = device_.info.features; | 11275 | const VkPhysicalDeviceFeatures& features = device_.info.features; |
| 11276 | if (depth_bounds && !features.depthBounds) | ||
| 11277 | return stream_unsupported("depth-bounds tests need depthBounds, which the device lacks; stream subobject", 21); | ||
| 11278 | if (depth_bounds) { // how many PSOs use the test (they were all refused before) | ||
| 11279 | static std::atomic<unsigned> made{0}; | ||
| 11280 | const unsigned n = ++made; | ||
| 11281 | if ((n & (n - 1)) == 0) std::fprintf(stderr, "[rt] d3d12: depth-bounds PSO #%u\n", n); | ||
| 11282 | } | ||
| 8773 | 11283 | ||
| 8774 | if (raster.polygonMode != VK_POLYGON_MODE_FILL && !features.fillModeNonSolid) | 11284 | if (raster.polygonMode != VK_POLYGON_MODE_FILL && !features.fillModeNonSolid) |
| 8775 | return stream_unsupported("wireframe fill needs fillModeNonSolid, which the device lacks; fill mode", r.FillMode); | 11285 | return stream_unsupported("wireframe fill needs fillModeNonSolid, which the device lacks; fill mode", r.FillMode); |
| @@ -8893,6 +11403,7 @@ public: | |||
| 8893 | 11403 | ||
| 8894 | // Kept for variants: a draw that leaves a slot unbound needs this pipeline with that format undefined. | 11404 | // Kept for variants: a draw that leaves a slot unbound needs this pipeline with that format undefined. |
| 8895 | graphics_.mesh = mesh; | 11405 | graphics_.mesh = mesh; |
| 11406 | graphics_.depth_bounds = depth_bounds; | ||
| 8896 | recipe_.mesh = mesh; | 11407 | recipe_.mesh = mesh; |
| 8897 | recipe_.stages = std::move(stage_infos); | 11408 | recipe_.stages = std::move(stage_infos); |
| 8898 | recipe_.attributes = std::move(attributes); | 11409 | recipe_.attributes = std::move(attributes); |
| @@ -8928,7 +11439,9 @@ public: | |||
| 8928 | const auto it = variants_.find(unbound); | 11439 | const auto it = variants_.find(unbound); |
| 8929 | return it == variants_.end() ? VkPipeline(VK_NULL_HANDLE) : it->second; | 11440 | return it == variants_.end() ? VkPipeline(VK_NULL_HANDLE) : it->second; |
| 8930 | }; | 11441 | }; |
| 8931 | graphics_.large = spirv_bytes >= leonida::PipelineCompiles::large_spirv_bytes; | 11442 | graphics_.large = spirv_bytes >= leonida::PipelineCompiles::large_spirv_bytes && |
| 11443 | big_compiles() != BigCompiles::unlimited; | ||
| 11444 | graphics_.estimate = leonida::large_module_estimate(spirv_bytes); | ||
| 8932 | 11445 | ||
| 8933 | if (code_stage) { | 11446 | if (code_stage) { |
| 8934 | VkDeviceSize offset = 0; | 11447 | VkDeviceSize offset = 0; |
| @@ -8938,8 +11451,7 @@ public: | |||
| 8938 | code_base_ = offset; | 11451 | code_base_ = offset; |
| 8939 | graphics_.code_base = offset; | 11452 | graphics_.code_base = offset; |
| 8940 | } | 11453 | } |
| 8941 | // LOCAL DIAGNOSTIC: what this pipeline is, for the fsdraw probe's draw lines | 11454 | if (leonida::fsdraw::enabled()) { // LOCAL DIAGNOSTIC: what this pipeline is, for the fsdraw probe's draw lines |
| 8942 | if (leonida::local_diagnostics()) { | ||
| 8943 | const auto& rt0 = desc.BlendState.RenderTarget[0]; | 11455 | const auto& rt0 = desc.BlendState.RenderTarget[0]; |
| 8944 | char text[640]; | 11456 | char text[640]; |
| 8945 | std::snprintf(text, sizeof text, | 11457 | std::snprintf(text, sizeof text, |
| @@ -9058,6 +11570,7 @@ public: | |||
| 9058 | if (vk.vkCreatePipelineLayout(dev, &layout_info, nullptr, &pipeline_.layout) != VK_SUCCESS) return E_FAIL; | 11570 | if (vk.vkCreatePipelineLayout(dev, &layout_info, nullptr, &pipeline_.layout) != VK_SUCCESS) return E_FAIL; |
| 9059 | compute_entry_ = entry; | 11571 | compute_entry_ = entry; |
| 9060 | stage_bytes_ = spirv_bytes; | 11572 | stage_bytes_ = spirv_bytes; |
| 11573 | pipeline_.estimate = leonida::large_module_estimate(spirv_bytes); | ||
| 9061 | // The title creates hundreds of compute pipelines from job threads during startup and one of its init tasks | 11574 | // The title creates hundreds of compute pipelines from job threads during startup and one of its init tasks |
| 9062 | // waits for all of them; some modules (wave64-emulated ray-tracing resolves, 4 MiB of SPIR-V) take the driver | 11575 | // waits for all of them; some modules (wave64-emulated ray-tracing resolves, 4 MiB of SPIR-V) take the driver |
| 9063 | // minutes each. So the Vulkan pipeline is built on first use (build_compute): at the first dispatch that names | 11576 | // minutes each. So the Vulkan pipeline is built on first use (build_compute): at the first dispatch that names |
| @@ -9093,7 +11606,7 @@ public: | |||
| 9093 | std::unique_lock lock(pso->variants_mutex_, std::try_to_lock); // held: another thread is compiling it | 11606 | std::unique_lock lock(pso->variants_mutex_, std::try_to_lock); // held: another thread is compiling it |
| 9094 | return lock.owns_lock() ? pso->pipeline_.pipeline : VkPipeline(VK_NULL_HANDLE); | 11607 | return lock.owns_lock() ? pso->pipeline_.pipeline : VkPipeline(VK_NULL_HANDLE); |
| 9095 | }; | 11608 | }; |
| 9096 | pipeline_.large = serial_big_compile(spirv_bytes); | 11609 | pipeline_.large = big_compute(spirv_bytes) && big_compiles() != BigCompiles::unlimited; |
| 9097 | } else if (!build_compute("compute-create")) { | 11610 | } else if (!build_compute("compute-create")) { |
| 9098 | return E_FAIL; | 11611 | return E_FAIL; |
| 9099 | } | 11612 | } |
| @@ -9114,70 +11627,89 @@ public: | |||
| 9114 | } | 11627 | } |
| 9115 | 11628 | ||
| 9116 | private: | 11629 | private: |
| 11630 | using Work = leonida::LargeModuleGate::Work; | ||
| 11631 | |||
| 11632 | // Locks the PSO (`lock`, on variants_mutex_) for a build and, with an `estimate`, takes the build's place at the gate. A | ||
| 11633 | // thread that waits for its place holds no PSO's lock, and one that has its place waits for none: another thread may be | ||
| 11634 | // building that PSO, with a place of its own. Returns without a place when the PSO is `built` already. | ||
| 11635 | template<typename Built> | ||
| 11636 | leonida::LargeModuleGate::Ticket enter_build(std::unique_lock<std::mutex>& lock, std::uint64_t estimate, Work work, | ||
| 11637 | Built&& built) { | ||
| 11638 | for (;;) { | ||
| 11639 | lock.lock(); | ||
| 11640 | if (!estimate || built()) return {}; | ||
| 11641 | lock.unlock(); | ||
| 11642 | leonida::LargeModuleGate::Ticket place(big_compile_gate(), estimate, work); | ||
| 11643 | if (lock.try_lock()) return place; | ||
| 11644 | } | ||
| 11645 | } | ||
| 11646 | |||
| 9117 | // The compute pipeline, built once: by create_compute (LEONIDA_LAZY_COMPUTE=0), by the first dispatch that names | 11647 | // The compute pipeline, built once: by create_compute (LEONIDA_LAZY_COMPUTE=0), by the first dispatch that names |
| 9118 | // it (the replay layer calls ComputePipeline::build) or by the warm-up thread. Null when it cannot be built; the | 11648 | // it (the replay layer calls ComputePipeline::build) or by the warm-up thread. Null when it cannot be built; the |
| 9119 | // failure is logged and not retried. | 11649 | // failure is logged and not retried. |
| 9120 | VkPipeline build_compute(const char* trigger) { | 11650 | VkPipeline build_compute(const char* trigger, Work work = Work::demand) { |
| 9121 | CompileActivity activity(device_.active_compiles); | 11651 | // A large module's place at the compile gate is taken before the PSO's lock (enter_build): a thread that waits |
| 9122 | std::lock_guard lock(variants_mutex_); | 11652 | // for memory holds no PSO lock. |
| 11653 | std::unique_lock lock(variants_mutex_, std::defer_lock); | ||
| 11654 | const bool budgeted = big_compute(stage_bytes_) && big_compiles() == BigCompiles::budget; | ||
| 11655 | auto place = enter_build(lock, budgeted ? pipeline_.estimate : 0, work, | ||
| 11656 | [this] { return pipeline_.pipeline || compute_failed_; }); | ||
| 9123 | if (pipeline_.pipeline || compute_failed_) return pipeline_.pipeline; | 11657 | if (pipeline_.pipeline || compute_failed_) return pipeline_.pipeline; |
| 9124 | compute_failed_ = true; // until the pipeline exists | ||
| 9125 | auto& vk = device_.context->vk; | ||
| 9126 | const VkDevice dev = device_.info.device; | ||
| 9127 | const leonida::ShaderLibrary* library = device_.library(); | ||
| 9128 | const leonida::ShaderEntry* entry = compute_entry_; | 11658 | const leonida::ShaderEntry* entry = compute_entry_; |
| 9129 | if (!library || !entry) return VK_NULL_HANDLE; | 11659 | if (!device_.library() || !entry) { |
| 9130 | static std::mutex big_compile; | 11660 | compute_failed_ = true; |
| 9131 | std::unique_lock<std::mutex> big_lock(big_compile, std::defer_lock); | ||
| 9132 | if (serial_big_compile(stage_bytes_)) big_lock.lock(); | ||
| 9133 | auto words = library->spirv(*entry); | ||
| 9134 | if (words.empty()) { | ||
| 9135 | std::fprintf(stderr, "[rt] d3d12: %s.spv is missing or not SPIR-V\n", entry->name.c_str()); | ||
| 9136 | return VK_NULL_HANDLE; | 11661 | return VK_NULL_HANDLE; |
| 9137 | } | 11662 | } |
| 9138 | VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; | 11663 | // LOCAL FIX (compile helper, d3d12_compile_helper.h): asynchronous builds and warm-ups only ask the helper and |
| 9139 | module_info.codeSize = words.size() * 4; | 11664 | // are deferred (queue_build publishes nothing for them, so their next use asks again). While the helper is |
| 9140 | module_info.pCode = words.data(); | 11665 | // still making the file this answers at once, without reading the module; a use asks with replay's priority. |
| 9141 | VkShaderModule module = VK_NULL_HANDLE; | 11666 | // Only replay's own and the warm-up's triggers may answer deferred: compute-create (LEONIDA_LAZY_COMPUTE=0) is |
| 9142 | { | 11667 | // a create whose caller needs a pipeline now, so it waits for the file as a dispatch does in a strict replay |
| 9143 | const leonida::aftermath::ShaderName named(entry->name); | 11668 | // (LOCAL FIX, review: with LEONIDA_ASYNC_PIPELINES=1 it was deferred and returned E_FAIL). |
| 9144 | if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return VK_NULL_HANDLE; | 11669 | const bool warmup = !std::strcmp(trigger, "warmup"); |
| 11670 | const bool replay_trigger = !std::strcmp(trigger, "dispatch") || !std::strcmp(trigger, "dispatch-worker"); | ||
| 11671 | const bool helper_nowait = warmup || (replay_trigger && async_replay_compile()); | ||
| 11672 | if (!helper_file_.empty()) { | ||
| 11673 | auto& helper = compile_helper::Client::instance(); | ||
| 11674 | std::string why; | ||
| 11675 | const auto state = helper.state(helper_file_, device_.pso_identity, &why); | ||
| 11676 | if (state == compile_helper::Client::State::pending) { | ||
| 11677 | if (!warmup) helper.request(helper_file_, entry->name, 0, device_.pso_identity, nullptr); | ||
| 11678 | if (helper_nowait) { | ||
| 11679 | helper_deferred_ = true; | ||
| 11680 | return VK_NULL_HANDLE; | ||
| 11681 | } | ||
| 11682 | } else if (state != compile_helper::Client::State::ready) { | ||
| 11683 | std::fprintf(stderr, "[rt] d3d12: compile helper: %s for %s; built here\n", why.c_str(), | ||
| 11684 | entry->name.c_str()); | ||
| 11685 | helper_refused_ = true; | ||
| 11686 | } | ||
| 11687 | helper_file_.clear(); | ||
| 9145 | } | 11688 | } |
| 9146 | const auto bytes = module_info.codeSize; | 11689 | compute_failed_ = true; // until the pipeline exists |
| 9147 | std::vector<std::uint32_t>().swap(words); // vkCreateShaderModule consumed pCode | 11690 | ComputeBuildOptions options; |
| 9148 | VkComputePipelineCreateInfo pipeline_info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; | 11691 | options.trigger = trigger; |
| 9149 | pipeline_info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; | 11692 | options.cache_key = &cache_key_; |
| 9150 | pipeline_info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; | 11693 | options.use_helper = !helper_refused_; |
| 9151 | pipeline_info.stage.module = module; | 11694 | options.helper_wait = !helper_nowait; |
| 9152 | pipeline_info.stage.pName = "main"; | 11695 | options.helper_priority = warmup ? stage_bytes_ : 0; |
| 9153 | VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_size{}; | 11696 | const ComputeBuild build = build_compute_pipeline(device_, *entry, pipeline_.layout, subgroup_request_for(*entry), |
| 9154 | subgroup_size_for(*entry, required_size, pipeline_info.stage); | 11697 | options); |
| 9155 | pipeline_info.layout = pipeline_.layout; | 11698 | if (build.deferred) { |
| 9156 | const VkPipelineCache cache = device_.pipeline_cache(); | 11699 | compute_failed_ = false; |
| 9157 | 11700 | helper_file_ = build.journal_path; | |
| 9158 | const ULONGLONG started = GetTickCount64(); | 11701 | helper_deferred_ = true; |
| 9159 | VkPipeline built = VK_NULL_HANDLE; | 11702 | return VK_NULL_HANDLE; |
| 9160 | CompileTrace trace; | 11703 | } |
| 9161 | trace.begin(pipeline_info, device_.info.pipeline_creation_feedback, trigger, entry->name.c_str(), 0, bytes, cache_key_); | 11704 | if (build.result != VK_SUCCESS || !build.pipeline) { |
| 9162 | const leonida::pipeline_profile::DriverCall profile("cs", trigger, entry->name.c_str()); | ||
| 9163 | const VkResult created = vk.vkCreateComputePipelines(dev, cache, 1, &pipeline_info, nullptr, &built); | ||
| 9164 | profile.finish(int(created)); | ||
| 9165 | trace.end(trigger, entry->name.c_str(), 0, bytes, created); | ||
| 9166 | if (big_lock.owns_lock()) big_lock.unlock(); | ||
| 9167 | vk.vkDestroyShaderModule(dev, module, nullptr); // Vulkan lets a module go once the pipeline exists | ||
| 9168 | const ULONGLONG took = GetTickCount64() - started; | ||
| 9169 | if (created != VK_SUCCESS || !built) { | ||
| 9170 | std::fprintf(stderr, "[rt] d3d12: compute pipeline %s could not be built (VkResult %d); its dispatches are " | 11705 | std::fprintf(stderr, "[rt] d3d12: compute pipeline %s could not be built (VkResult %d); its dispatches are " |
| 9171 | "dropped\n", entry->name.c_str(), int(created)); | 11706 | "dropped\n", entry->name.c_str(), int(build.result)); |
| 9172 | return VK_NULL_HANDLE; | 11707 | return VK_NULL_HANDLE; |
| 9173 | } | 11708 | } |
| 9174 | if (took >= 2000) | 11709 | maybe_checkpoint(device_.pipeline_cache()); |
| 9175 | std::fprintf(stderr, "[rt] d3d12: compute pipeline %s took %.1f s to build (%zu B SPIR-V)\n", | 11710 | pipeline_.pipeline = build.pipeline; |
| 9176 | entry->name.c_str(), double(took) / 1000.0, bytes); | ||
| 9177 | maybe_checkpoint(cache); | ||
| 9178 | pipeline_.pipeline = built; | ||
| 9179 | compute_failed_ = false; | 11711 | compute_failed_ = false; |
| 9180 | return built; | 11712 | return build.pipeline; |
| 9181 | } | 11713 | } |
| 9182 | 11714 | ||
| 9183 | // Lazy compute pipelines are also built in the background, smallest module first, so most exist before their | 11715 | // Lazy compute pipelines are also built in the background, smallest module first, so most exist before their |
| @@ -9207,37 +11739,53 @@ private: | |||
| 9207 | if (!queued) device_.next_checkpoint.store(now + 120000); // refused after an exit stop, or out of memory | 11739 | if (!queued) device_.next_checkpoint.store(now + 120000); // refused after an exit stop, or out of memory |
| 9208 | } | 11740 | } |
| 9209 | 11741 | ||
| 9210 | VkPipeline queue_build(bool compute, std::uint32_t unbound, std::size_t warm_bytes = 0) { | 11742 | // Asynchronous builds (LEONIDA_ASYNC_PIPELINES=1): replay asks here at prepare, with the resource lock held. The |
| 11743 | // handle once built; otherwise a compile-worker job is queued (once) and null answered, so the draw or dispatch is | ||
| 11744 | // skipped and a later submission uses the pipeline. `warm_bytes`: a warm-up, queued by module size. `count_skip`: | ||
| 11745 | // false for a request made at record time (request_early), which skips nothing. | ||
| 11746 | VkPipeline queue_build(bool compute, std::uint32_t unbound, std::size_t warm_bytes = 0, bool count_skip = true) { | ||
| 9211 | static std::mutex publication; // ready handles only; no compiler call holds this lock | 11747 | static std::mutex publication; // ready handles only; no compiler call holds this lock |
| 9212 | const bool warm = warm_bytes != 0; | 11748 | const bool warm = warm_bytes != 0; |
| 9213 | // After an exit stop (stop_pipeline_compiles) nothing is queued: a warm-up is skipped, and a draw or dispatch | 11749 | // After an exit stop (stop_pipeline_compiles) nothing is queued: a warm-up or an early request is skipped, |
| 9214 | // builds in place, as without LEONIDA_ASYNC_PIPELINES, rather than waiting for a build that never comes. | 11750 | // and a draw or dispatch builds in place, as without LEONIDA_ASYNC_PIPELINES, rather than waiting for a build |
| 11751 | // that never comes. | ||
| 9215 | if (PipelineCompiler::instance().closed()) { | 11752 | if (PipelineCompiler::instance().closed()) { |
| 9216 | if (warm) return VK_NULL_HANDLE; | 11753 | if (warm || !count_skip) return VK_NULL_HANDLE; |
| 9217 | return compute ? build_compute("dispatch") : variant(unbound, "draw"); | 11754 | return compute ? build_compute("dispatch") : variant(unbound, "draw"); |
| 9218 | } | 11755 | } |
| 9219 | std::lock_guard lock(publication); | 11756 | std::lock_guard lock(publication); |
| 9220 | if (!warm) { | 11757 | if (!warm) { |
| 9221 | if (!requested_) requested_ = std::make_unique<Requests>(); | 11758 | if (!requested_) requested_ = std::make_unique<Requests>(); |
| 9222 | auto [it, inserted] = requested_->try_emplace(unbound); | 11759 | auto [it, inserted] = requested_->try_emplace(unbound); |
| 9223 | if (!it->second.handle) ++it->second.skips; | 11760 | if (!it->second.handle && count_skip) ++it->second.skips; |
| 9224 | if (!inserted) return it->second.handle; | 11761 | if (!inserted) return it->second.handle; |
| 9225 | } | 11762 | } |
| 9226 | bool queued = false; | 11763 | bool queued = false; |
| 9227 | try { | 11764 | try { |
| 9228 | queued = PipelineCompiler::instance().submit(compile_owner(), &device_, warm_bytes, [this, compute, warm, unbound] { | 11765 | queued = PipelineCompiler::instance().submit(compile_owner(), &device_, warm_bytes, |
| 11766 | [this, compute, warm, unbound, warm_bytes] { | ||
| 11767 | // A big warm-up while the title submits is left to the pipeline's first use (warmup_waits_for_quiet). | ||
| 11768 | if (warm && warmup_waits_for_quiet(warm_bytes)) return; | ||
| 9229 | VkPipeline built{}; | 11769 | VkPipeline built{}; |
| 9230 | try { | 11770 | try { |
| 9231 | built = compute ? build_compute(warm ? "warmup" : "dispatch-worker") | 11771 | built = compute ? build_compute(warm ? "warmup" : "dispatch-worker", |
| 11772 | warm ? Work::speculative : Work::demand) | ||
| 9232 | : variant(unbound, "draw-worker"); | 11773 | : variant(unbound, "draw-worker"); |
| 11774 | // The compile helper is still making the journal file (build_compute): not built, so nothing is | ||
| 11775 | // published and the next use asks again. | ||
| 11776 | const bool deferred = compute && helper_deferred_.exchange(false); | ||
| 9233 | if (async_replay_compile()) { | 11777 | if (async_replay_compile()) { |
| 9234 | unsigned long long skipped = 0; | 11778 | unsigned long long skipped = 0; |
| 9235 | { | 11779 | { |
| 9236 | std::lock_guard publish(publication); | 11780 | std::lock_guard publish(publication); |
| 9237 | if (!requested_) requested_ = std::make_unique<Requests>(); | 11781 | if (!requested_) requested_ = std::make_unique<Requests>(); |
| 9238 | auto& entry = (*requested_)[unbound]; | 11782 | if (deferred) { |
| 9239 | if (!entry.handle) skipped = entry.skips; | 11783 | if (!warm) requested_->erase(unbound); |
| 9240 | entry.handle = built; | 11784 | } else { |
| 11785 | auto& entry = (*requested_)[unbound]; | ||
| 11786 | if (!entry.handle) skipped = entry.skips; | ||
| 11787 | entry.handle = built; | ||
| 11788 | } | ||
| 9241 | } | 11789 | } |
| 9242 | if (skipped && trace_pipeline_compile()) | 11790 | if (skipped && trace_pipeline_compile()) |
| 9243 | std::fprintf(stderr, "[rt] pipeline-deferred type=%s skipped=%llu ready=%d\n", | 11791 | std::fprintf(stderr, "[rt] pipeline-deferred type=%s skipped=%llu ready=%d\n", |
| @@ -9246,7 +11794,7 @@ private: | |||
| 9246 | } catch (const std::exception& e) { | 11794 | } catch (const std::exception& e) { |
| 9247 | std::fprintf(stderr, "[rt] pipeline compile worker failed: %s\n", e.what()); | 11795 | std::fprintf(stderr, "[rt] pipeline compile worker failed: %s\n", e.what()); |
| 9248 | } | 11796 | } |
| 9249 | }); | 11797 | }, !compute); // a graphics build may also take the graphics worker |
| 9250 | } catch (...) { | 11798 | } catch (...) { |
| 9251 | } | 11799 | } |
| 9252 | // Not queued (refused by a stop that came after the check above, or out of memory): no request stays | 11800 | // Not queued (refused by a stop that came after the check above, or out of memory): no request stays |
| @@ -9255,6 +11803,53 @@ private: | |||
| 9255 | return VK_NULL_HANDLE; | 11803 | return VK_NULL_HANDLE; |
| 9256 | } | 11804 | } |
| 9257 | 11805 | ||
| 11806 | public: | ||
| 11807 | // Record time (SetPipelineState for compute, a draw for graphics, with the render-target slots it binds and | ||
| 11808 | // whether it binds a depth buffer): asynchronous builds start on the compile worker before the list is submitted. | ||
| 11809 | // Never waits; nothing to do when the variant is the last one asked for here. | ||
| 11810 | void request_early(std::uint32_t bound_targets, bool depth_bound) { | ||
| 11811 | if (!async_replay_compile() || !registered_) return; | ||
| 11812 | std::uint32_t unbound = 0; | ||
| 11813 | if (is_graphics_) { | ||
| 11814 | for (std::size_t slot = 0; slot < graphics_.color_formats.size() && slot < 8; ++slot) | ||
| 11815 | if (graphics_.color_formats[slot] != VK_FORMAT_UNDEFINED && !(bound_targets & (1u << slot))) | ||
| 11816 | unbound |= 1u << slot; | ||
| 11817 | if (graphics_.depth_format != VK_FORMAT_UNDEFINED && !depth_bound) | ||
| 11818 | unbound |= leonida::GraphicsPipeline::unbound_depth; | ||
| 11819 | if (!unbound && graphics_.pipeline) return; | ||
| 11820 | } else if (!pipeline_.build || pipeline_.skipped) { | ||
| 11821 | return; // an eager pipeline has no build | ||
| 11822 | } | ||
| 11823 | if (early_.exchange(unbound + 1, std::memory_order_relaxed) == unbound + 1) return; | ||
| 11824 | queue_build(!is_graphics_, unbound, 0, false); | ||
| 11825 | } | ||
| 11826 | |||
| 11827 | private: | ||
| 11828 | // LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES=<n> (opt-in; unset or 0: no limit, the warm-up builds every module as on | ||
| 11829 | // main): a warm-up of a module over n bytes of SPIR-V is not started while the title submits (a submission in the | ||
| 11830 | // last second); it is left to the pipeline's first use. A create holds the compile gate (SubmitMutex::CompileTurn) | ||
| 11831 | // for its whole length and every submission waits behind it; on NVIDIA 630.20 the modules over 640 KiB take 4-25 s | ||
| 11832 | // each. Measured in a native boot past the story load (with 131072): 694 warm-ups of modules over 128 KiB against | ||
| 11833 | // 25 such builds a dispatch asked for, and one run's submissions waited 140 s in all at the gate behind warm-ups. | ||
| 11834 | static bool warmup_waits_for_quiet(std::size_t bytes) { | ||
| 11835 | static const std::size_t limit = [] { | ||
| 11836 | char text[32]{}; | ||
| 11837 | const DWORD n = GetEnvironmentVariableA("LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES", text, sizeof(text)); | ||
| 11838 | return (n > 0 && n < sizeof(text)) ? static_cast<std::size_t>(std::strtoull(text, nullptr, 10)) | ||
| 11839 | : std::size_t{0}; | ||
| 11840 | }(); | ||
| 11841 | if (!limit || bytes <= limit || !leonida::pipeline_wait::title_submitting()) return false; | ||
| 11842 | if (compile_helper::wanted(bytes)) return false; // the helper compiles it, in its own process | ||
| 11843 | if (leonida::pipeline_wait::warmups_left().fetch_add(1, std::memory_order_relaxed) == 0) { | ||
| 11844 | static std::atomic<bool> logged{false}; | ||
| 11845 | if (!logged.exchange(true)) | ||
| 11846 | std::fprintf(stderr, "[rt] d3d12: compute warm-ups over %zu KiB are left to their first use while the " | ||
| 11847 | "title submits (LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES), from t=%.3f s\n", | ||
| 11848 | limit >> 10, double(leonida::diagnostic_ms()) / 1000.0); | ||
| 11849 | } | ||
| 11850 | return true; | ||
| 11851 | } | ||
| 11852 | |||
| 9258 | static void warmup_enqueue(PipelineState* pso, std::size_t bytes) { | 11853 | static void warmup_enqueue(PipelineState* pso, std::size_t bytes) { |
| 9259 | static const std::size_t max_bytes = [] { | 11854 | static const std::size_t max_bytes = [] { |
| 9260 | char text[32]{}; | 11855 | char text[32]{}; |
| @@ -9352,6 +11947,7 @@ private: | |||
| 9352 | dyn_list[dyn_count++] = VK_DYNAMIC_STATE_STENCIL_REFERENCE; | 11947 | dyn_list[dyn_count++] = VK_DYNAMIC_STATE_STENCIL_REFERENCE; |
| 9353 | dyn_list[dyn_count++] = VK_DYNAMIC_STATE_BLEND_CONSTANTS; | 11948 | dyn_list[dyn_count++] = VK_DYNAMIC_STATE_BLEND_CONSTANTS; |
| 9354 | if (!r.mesh && !r.bindings.empty()) dyn_list[dyn_count++] = VK_DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE; | 11949 | if (!r.mesh && !r.bindings.empty()) dyn_list[dyn_count++] = VK_DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE; |
| 11950 | if (r.depth.depthBoundsTestEnable) dyn_list[dyn_count++] = VK_DYNAMIC_STATE_DEPTH_BOUNDS; | ||
| 9355 | VkPipelineDynamicStateCreateInfo dynamic{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO}; | 11951 | VkPipelineDynamicStateCreateInfo dynamic{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO}; |
| 9356 | dynamic.dynamicStateCount = dyn_count; | 11952 | dynamic.dynamicStateCount = dyn_count; |
| 9357 | dynamic.pDynamicStates = dyn_list; | 11953 | dynamic.pDynamicStates = dyn_list; |
| @@ -9456,6 +12052,7 @@ private: | |||
| 9456 | info.pDynamicState = &dynamic; | 12052 | info.pDynamicState = &dynamic; |
| 9457 | info.flags=flags; | 12053 | info.flags=flags; |
| 9458 | info.layout = graphics_.layout; | 12054 | info.layout = graphics_.layout; |
| 12055 | info.flags |= fast_pipeline_flags(false); | ||
| 9459 | VkPipeline pipeline = VK_NULL_HANDLE; | 12056 | VkPipeline pipeline = VK_NULL_HANDLE; |
| 9460 | const auto cache = device_.pipeline_cache(); | 12057 | const auto cache = device_.pipeline_cache(); |
| 9461 | const char* program = "-", *fragment = "-"; | 12058 | const char* program = "-", *fragment = "-"; |
| @@ -9468,6 +12065,7 @@ private: | |||
| 9468 | } | 12065 | } |
| 9469 | CompileTrace trace; | 12066 | CompileTrace trace; |
| 9470 | trace.begin(info, device_.info.pipeline_creation_feedback, trigger, profile_shaders_.c_str(), unbound, bytes, cache_key_); | 12067 | trace.begin(info, device_.info.pipeline_creation_feedback, trigger, profile_shaders_.c_str(), unbound, bytes, cache_key_); |
| 12068 | const leonida::dev_status::Build dev_build(r.mesh ? "mesh pipeline" : "graphics pipeline"); | ||
| 9471 | const leonida::pipeline_profile::DriverCall profile(r.mesh ? "ms" : "vs", lazy_ ? "lazy" : "eager", | 12069 | const leonida::pipeline_profile::DriverCall profile(r.mesh ? "ms" : "vs", lazy_ ? "lazy" : "eager", |
| 9472 | program, fragment, unbound); | 12070 | program, fragment, unbound); |
| 9473 | const auto result = device_.context->vk.vkCreateGraphicsPipelines(device_.info.device, cache, 1, &info, nullptr, &pipeline); | 12071 | const auto result = device_.context->vk.vkCreateGraphicsPipelines(device_.info.device, cache, 1, &info, nullptr, &pipeline); |
| @@ -9502,12 +12100,24 @@ private: | |||
| 9502 | return true; | 12100 | return true; |
| 9503 | } | 12101 | } |
| 9504 | 12102 | ||
| 12103 | bool link_f16_halves(std::vector<std::uint32_t>& vs_words, const leonida::ShaderEntry& vs_entry, | ||
| 12104 | std::vector<std::uint32_t>& ps_words, const leonida::ShaderEntry& ps_entry, | ||
| 12105 | std::string* error) const { | ||
| 12106 | return leonida::link_f16_halves(vs_words, vs_entry, ps_words, ps_entry, error, | ||
| 12107 | device_.f16_half_top_location); | ||
| 12108 | } | ||
| 12109 | |||
| 12110 | public: | ||
| 9505 | bool stage_words(std::vector<std::vector<std::uint32_t>>& words, std::string& why) const { | 12111 | bool stage_words(std::vector<std::vector<std::uint32_t>>& words, std::string& why) const { |
| 9506 | const leonida::ShaderLibrary* library = device_.library(); | 12112 | const leonida::ShaderLibrary* library = device_.library(); |
| 9507 | if (!library) { | 12113 | if (!library) { |
| 9508 | why = "no shader library"; | 12114 | why = "no shader library"; |
| 9509 | return false; | 12115 | return false; |
| 9510 | } | 12116 | } |
| 12117 | if (sources_.empty()) { | ||
| 12118 | why = "not a lazy pipeline"; | ||
| 12119 | return false; | ||
| 12120 | } | ||
| 9511 | words.assign(sources_.size(), {}); | 12121 | words.assign(sources_.size(), {}); |
| 9512 | std::size_t vs = SIZE_MAX, ps = SIZE_MAX; | 12122 | std::size_t vs = SIZE_MAX, ps = SIZE_MAX; |
| 9513 | for (std::size_t i = 0; i < sources_.size(); ++i) { | 12123 | for (std::size_t i = 0; i < sources_.size(); ++i) { |
| @@ -9527,7 +12137,7 @@ private: | |||
| 9527 | } | 12137 | } |
| 9528 | if (f16_linked_) { | 12138 | if (f16_linked_) { |
| 9529 | if (vs == SIZE_MAX || ps == SIZE_MAX || | 12139 | if (vs == SIZE_MAX || ps == SIZE_MAX || |
| 9530 | !leonida::link_f16_halves(words[vs], *sources_[vs].entry, words[ps], *sources_[ps].entry, &why)) | 12140 | !link_f16_halves(words[vs], *sources_[vs].entry, words[ps], *sources_[ps].entry, &why)) |
| 9531 | return false; | 12141 | return false; |
| 9532 | } | 12142 | } |
| 9533 | for (std::size_t i = 0; i < sources_.size(); ++i) { | 12143 | for (std::size_t i = 0; i < sources_.size(); ++i) { |
| @@ -9550,9 +12160,13 @@ private: | |||
| 9550 | return true; | 12160 | return true; |
| 9551 | } | 12161 | } |
| 9552 | 12162 | ||
| 12163 | private: | ||
| 9553 | // Built on first use and kept until the PSO is released (replay may call this from any queue). | 12164 | // Built on first use and kept until the PSO is released (replay may call this from any queue). |
| 9554 | VkPipeline variant(std::uint32_t unbound, const char* trigger) { | 12165 | VkPipeline variant(std::uint32_t unbound, const char* trigger) { |
| 9555 | std::lock_guard lock(variants_mutex_); | 12166 | std::unique_lock lock(variants_mutex_, std::defer_lock); |
| 12167 | const bool budgeted = graphics_.large && big_compiles() == BigCompiles::budget; | ||
| 12168 | const auto place = enter_build(lock, budgeted ? graphics_.estimate : 0, Work::demand, | ||
| 12169 | [&] { return variants_.contains(unbound); }); | ||
| 9556 | if (const auto it = variants_.find(unbound); it != variants_.end()) return it->second; | 12170 | if (const auto it = variants_.find(unbound); it != variants_.end()) return it->second; |
| 9557 | const VkPipeline pipeline = build(unbound, trigger); | 12171 | const VkPipeline pipeline = build(unbound, trigger); |
| 9558 | if (!pipeline) { | 12172 | if (!pipeline) { |
| @@ -9589,6 +12203,12 @@ private: | |||
| 9589 | struct Request { VkPipeline handle{}; unsigned long long skips = 0; }; | 12203 | struct Request { VkPipeline handle{}; unsigned long long skips = 0; }; |
| 9590 | using Requests = std::map<std::uint32_t, Request>; | 12204 | using Requests = std::map<std::uint32_t, Request>; |
| 9591 | std::unique_ptr<Requests> requested_; | 12205 | std::unique_ptr<Requests> requested_; |
| 12206 | // Compile helper (build_compute, under variants_mutex_): the journal file asked for and not there yet; whether | ||
| 12207 | // the helper gave up on this pipeline (it is then built here); a build just deferred (read by queue_build). | ||
| 12208 | std::filesystem::path helper_file_; | ||
| 12209 | bool helper_refused_ = false; | ||
| 12210 | std::atomic<bool> helper_deferred_{false}; | ||
| 12211 | std::atomic<std::uint32_t> early_{0}; // request_early: the last mask asked for, plus one | ||
| 9592 | std::string profile_shaders_; // populated only with compile tracing enabled | 12212 | std::string profile_shaders_; // populated only with compile tracing enabled |
| 9593 | std::size_t stage_bytes_ = 0; | 12213 | std::size_t stage_bytes_ = 0; |
| 9594 | std::mutex variants_mutex_; | 12214 | std::mutex variants_mutex_; |
| @@ -10134,7 +12754,7 @@ struct TitleTexture { | |||
| 10134 | // misses. Video planes, rewritten whole every frame, are caught by the sampled one first. | 12754 | // misses. Video planes, rewritten whole every frame, are caught by the sampled one first. |
| 10135 | std::uint64_t full_hash = 0; | 12755 | std::uint64_t full_hash = 0; |
| 10136 | bool full_hashed = false; | 12756 | bool full_hashed = false; |
| 10137 | bool every_byte() const { return mapped && layout.layout.size <= (4u << 20); } | 12757 | bool every_byte() const { return mapped && (async_texture_refresh() || layout.layout.size <= (4u << 20)); } |
| 10138 | std::uint64_t fills = 0; | 12758 | std::uint64_t fills = 0; |
| 10139 | }; | 12759 | }; |
| 10140 | 12760 | ||
| @@ -10165,12 +12785,18 @@ bool title_xg_layout(const Resource& r, rt::xg_xs::Texture& out, std::array<std: | |||
| 10165 | return true; | 12785 | return true; |
| 10166 | } | 12786 | } |
| 10167 | 12787 | ||
| 12788 | void DeviceState::index_texture(const TitleTexture& t) { | ||
| 12789 | if (async_texture_refresh()) | ||
| 12790 | texture_ranges.set(t.address, t.cpu, t.layout_known && !t.gpu_written ? t.layout.layout.size : 0); | ||
| 12791 | } | ||
| 12792 | |||
| 10168 | void DeviceState::title_texture_mapped(const void* resource, std::uint64_t address) { | 12793 | void DeviceState::title_texture_mapped(const void* resource, std::uint64_t address) { |
| 10169 | std::lock_guard lock(title_texture_mutex); | 12794 | std::lock_guard lock(title_texture_mutex); |
| 10170 | const auto it = title_textures.find(address); | 12795 | const auto it = title_textures.find(address); |
| 10171 | if (it == title_textures.end() || it->second->resource != resource) return; | 12796 | if (it == title_textures.end() || it->second->resource != resource) return; |
| 10172 | TitleTexture& t = *it->second; | 12797 | TitleTexture& t = *it->second; |
| 10173 | t.mapped = true; | 12798 | t.mapped = true; |
| 12799 | if (async_texture_refresh() && !t.gpu_written) mapped_title_textures[address] = it->second; | ||
| 10174 | t.memory.retry(); | 12800 | t.memory.retry(); |
| 10175 | // The title computes the layout of what it writes right before it maps: take it when no view gave one. | 12801 | // The title computes the layout of what it writes right before it maps: take it when no view gave one. |
| 10176 | if (!t.gpu_written && (t.layout_guessed || !t.layout_known) && | 12802 | if (!t.gpu_written && (t.layout_guessed || !t.layout_known) && |
| @@ -10178,6 +12804,7 @@ void DeviceState::title_texture_mapped(const void* resource, std::uint64_t addre | |||
| 10178 | t.layout_known = true; | 12804 | t.layout_known = true; |
| 10179 | t.layout_guessed = false; | 12805 | t.layout_guessed = false; |
| 10180 | t.layout_from_xg = true; | 12806 | t.layout_from_xg = true; |
| 12807 | index_texture(t); | ||
| 10181 | t.hashed = false; | 12808 | t.hashed = false; |
| 10182 | } | 12809 | } |
| 10183 | static std::atomic<int> logged{0}; | 12810 | static std::atomic<int> logged{0}; |
| @@ -10229,7 +12856,12 @@ void DeviceState::title_texture_gone(const void* resource, std::uint64_t address | |||
| 10229 | gpu_placements.remove(address, resource); | 12856 | gpu_placements.remove(address, resource); |
| 10230 | } | 12857 | } |
| 10231 | const auto it = title_textures.find(address); | 12858 | const auto it = title_textures.find(address); |
| 10232 | if (it != title_textures.end() && it->second->resource == resource) title_textures.erase(it); | 12859 | if (it != title_textures.end() && it->second->resource == resource) { |
| 12860 | texture_ranges.erase(address); | ||
| 12861 | mapped_title_textures.erase(address); | ||
| 12862 | it->second->resource = nullptr; | ||
| 12863 | title_textures.erase(it); | ||
| 12864 | } | ||
| 10233 | } | 12865 | } |
| 10234 | 12866 | ||
| 10235 | void DeviceState::drain_titles_gone() { | 12867 | void DeviceState::drain_titles_gone() { |
| @@ -10268,6 +12900,8 @@ TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWord | |||
| 10268 | std::lock_guard lock(device.descriptor_mutex); | 12900 | std::lock_guard lock(device.descriptor_mutex); |
| 10269 | if (!device.bindless) return refuse("no bindless set"); | 12901 | if (!device.bindless) return refuse("no bindless set"); |
| 10270 | if (device.image_entries.count(words)) return TitleImage::known; | 12902 | if (device.image_entries.count(words)) return TitleImage::known; |
| 12903 | if (g::has_hardware_volume_uav_slice_offset(words, image)) | ||
| 12904 | return refuse("a title-written 3D UAV with a slice offset is not supported"); | ||
| 10271 | auto found = device.images_by_address.find(image.address); | 12905 | auto found = device.images_by_address.find(image.address); |
| 10272 | // Memory of the texture stream pool has two addresses, the CPU view's and the GPU-only alias the title hands | 12906 | // Memory of the texture stream pool has two addresses, the CPU view's and the GPU-only alias the title hands |
| 10273 | // to the GPU (title_gpu_views): a T# naming either finds a texture registered under the other. | 12907 | // to the GPU (title_gpu_views): a T# naming either finds a texture registered under the other. |
| @@ -10281,7 +12915,10 @@ TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWord | |||
| 10281 | const auto alias = leonida::title_gpu_views::other_view(image.address); | 12915 | const auto alias = leonida::title_gpu_views::other_view(image.address); |
| 10282 | if (auto* candidate = device.gpu_placements.find(image.address, alias, matches)) owner = candidate; | 12916 | if (auto* candidate = device.gpu_placements.find(image.address, alias, matches)) owner = candidate; |
| 10283 | } | 12917 | } |
| 10284 | if (!owner) return TitleImage::unknown; | 12918 | if (!owner) { |
| 12919 | if (why) *why = "no texture at T# address"; | ||
| 12920 | return TitleImage::unknown; | ||
| 12921 | } | ||
| 10285 | const Resource& r = *owner; | 12922 | const Resource& r = *owner; |
| 10286 | image.address = r.image_address(); // release this key with its actual owner | 12923 | image.address = r.image_address(); // release this key with its actual owner |
| 10287 | const D3D12_RESOURCE_DESC& d = r.desc(); | 12924 | const D3D12_RESOURCE_DESC& d = r.desc(); |
| @@ -10297,10 +12934,10 @@ TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWord | |||
| 10297 | if (!r.descriptor_image()) return refuse("the texture has no image"); | 12934 | if (!r.descriptor_image()) return refuse("the texture has no image"); |
| 10298 | if (!type_fits) return refuse("T# type or samples do not fit the texture"); | 12935 | if (!type_fits) return refuse("T# type or samples do not fit the texture"); |
| 10299 | if (!msaa && image.first_mip + image.mip_count > d.MipLevels) return refuse("T# names mips the texture lacks"); | 12936 | if (!msaa && image.first_mip + image.mip_count > d.MipLevels) return refuse("T# names mips the texture lacks"); |
| 12937 | if (image.type == g::ImageType::cube && !(r.format() && layers >= 6)) | ||
| 12938 | return refuse("cube T# on fewer than six layers"); | ||
| 10300 | if (!volume && image.first_layer + image.layer_count > layers) | 12939 | if (!volume && image.first_layer + image.layer_count > layers) |
| 10301 | return refuse("T# names layers the texture lacks"); | 12940 | return refuse("T# names layers the texture lacks"); |
| 10302 | if (image.type == g::ImageType::cube && !(r.format() && image.layer_count >= 6)) | ||
| 10303 | return refuse("cube T# on fewer than six layers"); | ||
| 10304 | const bool storage = (d.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && !msaa && | 12941 | const bool storage = (d.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && !msaa && |
| 10305 | r.aspects() == VK_IMAGE_ASPECT_COLOR_BIT; | 12942 | r.aspects() == VK_IMAGE_ASPECT_COLOR_BIT; |
| 10306 | if (!device.bind_image_locked(words, image, r.descriptor_image(), r.format(), r.aspects(), storage, | 12943 | if (!device.bind_image_locked(words, image, r.descriptor_image(), r.format(), r.aspects(), storage, |
| @@ -10647,11 +13284,17 @@ public: | |||
| 10647 | break; | 13284 | break; |
| 10648 | } | 13285 | } |
| 10649 | case h::so_statistics: | 13286 | case h::so_statistics: |
| 10650 | // The layer has no stream output: a graphics PSO with StreamOutput entries is refused (E_NOTIMPL) and | 13287 | // D3D-302: with VK_EXT_transform_feedback enabled, an SO_STATISTICS heap is a real transform-feedback |
| 10651 | // SOSetTargets is not implemented, so no primitive ever reaches a stream and every query of this heap | 13288 | // pool whose queries begin/end on a stream (vkCmdBeginQueryIndexedEXT); a resolve copies 16 bytes per |
| 10652 | // counts 0 written and 0 needed. That needs no Vulkan pool: Begin/EndQuery run nothing and a resolve fills zeros. When stream | 13289 | // query (NumPrimitivesWritten, PrimitivesStorageNeeded), in the same order. StreamOutput PSOs are still |
| 10653 | // output lands, this becomes a VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT pool (D3D-302). | 13290 | // refused and SOSetTargets is still not implemented, so no primitive reaches a stream yet and every |
| 10654 | return register_pool(desc); | 13291 | // query counts 0. The pool needs the transformFeedbackQueries property and at least one stream; without |
| 13292 | // them (or without the feature) the heap is made without a pool and every query resolves to zero. | ||
| 13293 | if (!device_.info.transform_feedback || !device_.info.transform_feedback_queries || | ||
| 13294 | !device_.info.max_transform_feedback_streams) | ||
| 13295 | return register_pool(desc); | ||
| 13296 | info.queryType = VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT; | ||
| 13297 | break; | ||
| 10655 | case h::pipeline_statistics: | 13298 | case h::pipeline_statistics: |
| 10656 | if (!device_.info.pipeline_statistics_query) { | 13299 | if (!device_.info.pipeline_statistics_query) { |
| 10657 | log_once("pipeline-statistics query heap: pipelineStatisticsQuery not enabled; type", desc.Type); | 13300 | log_once("pipeline-statistics query heap: pipelineStatisticsQuery not enabled; type", desc.Type); |
| @@ -10680,6 +13323,9 @@ private: | |||
| 10680 | pool.count = desc.Count; | 13323 | pool.count = desc.Count; |
| 10681 | pool.precise = device_.info.occlusion_query_precise; | 13324 | pool.precise = device_.info.occlusion_query_precise; |
| 10682 | pool.ended.assign(desc.Count, false); | 13325 | pool.ended.assign(desc.Count, false); |
| 13326 | // D3D-302: a real transform-feedback pool queries streams below maxTransformFeedbackStreams; D3D12 has four. | ||
| 13327 | if (pool_ && desc.Type == leonida::d3d12_query_heap::so_statistics) | ||
| 13328 | pool.streams = std::min<std::uint32_t>(4, device_.info.max_transform_feedback_streams); | ||
| 10683 | device_.context->add_query_pool(id(), pool); | 13329 | device_.context->add_query_pool(id(), pool); |
| 10684 | registered_ = true; | 13330 | registered_ = true; |
| 10685 | return S_OK; | 13331 | return S_OK; |
| @@ -10696,6 +13342,23 @@ private: | |||
| 10696 | bool registered_ = false; // added to the context, so removed from it on destruction | 13342 | bool registered_ = false; // added to the context, so removed from it on destruction |
| 10697 | }; | 13343 | }; |
| 10698 | 13344 | ||
| 13345 | // The live devices whose session pipeline cache an ending process writes (save_pipeline_caches_at_exit). A title | ||
| 13346 | // never releases its device, so ~Device, the only other writer, does not run in a real boot: without this, a run that | ||
| 13347 | // ends (normally, at a console close or in a crash) keeps none of what it compiled. Timed, so a crash handler that | ||
| 13348 | // finds it held gives up instead of hanging the process. | ||
| 13349 | std::timed_mutex exit_cache_mutex; | ||
| 13350 | std::vector<DeviceState*> exit_cache_devices; | ||
| 13351 | std::atomic<bool> exit_cache_saved{false}; | ||
| 13352 | |||
| 13353 | // VK_EXT_memory_budget read from a device's info: the reader a device publishes for the title HUD and the dev overlay | ||
| 13354 | // (src/memory_figures.h), and vulkan_vram_budget. Not available without the extension. | ||
| 13355 | leonida::VramBudget read_vram_budget(const VulkanDeviceInfo& info) { | ||
| 13356 | if (!info.memory_budget || !info.get_instance_proc || !info.instance) return {}; | ||
| 13357 | const auto get = reinterpret_cast<PFN_vkGetPhysicalDeviceMemoryProperties2>( | ||
| 13358 | info.get_instance_proc(info.instance, "vkGetPhysicalDeviceMemoryProperties2")); | ||
| 13359 | return leonida::query_vram_budget(get, info.physical); | ||
| 13360 | } | ||
| 13361 | |||
| 10699 | // The Vulkan objects create_vulkan_device_standalone made, destroyed with the device. | 13362 | // The Vulkan objects create_vulkan_device_standalone made, destroyed with the device. |
| 10700 | struct OwnedRuntime { | 13363 | struct OwnedRuntime { |
| 10701 | PFN_vkDestroyDevice destroy_device = nullptr; | 13364 | PFN_vkDestroyDevice destroy_device = nullptr; |
| @@ -10722,6 +13385,15 @@ public: | |||
| 10722 | // worker still has a warm-up to run is one too high. The proxy's count waits for the pool. | 13385 | // worker still has a warm-up to run is one too high. The proxy's count waits for the pool. |
| 10723 | rt::d3d12_xs::set_reference_settler([] { PipelineCompiler::instance().wait_idle(); }); | 13386 | rt::d3d12_xs::set_reference_settler([] { PipelineCompiler::instance().wait_idle(); }); |
| 10724 | state_.info = info; | 13387 | state_.info = info; |
| 13388 | { | ||
| 13389 | std::lock_guard lock(exit_cache_mutex); | ||
| 13390 | exit_cache_devices.push_back(&state_); | ||
| 13391 | } | ||
| 13392 | // The GPU memory figure of the title HUD and the dev overlay: the newest device with VK_EXT_memory_budget. | ||
| 13393 | if (info.memory_budget) | ||
| 13394 | leonida::memory_figures::publish_vram_reader( | ||
| 13395 | [](const void* context) { return read_vram_budget(static_cast<const DeviceState*>(context)->info); }, | ||
| 13396 | &state_); | ||
| 10725 | queue_users_.resize(info.command_queues.size(), 0); | 13397 | queue_users_.resize(info.command_queues.size(), 0); |
| 10726 | compute_users_.resize(info.compute_queues.size(), 0); | 13398 | compute_users_.resize(info.compute_queues.size(), 0); |
| 10727 | copy_users_.resize(info.copy_queues.size(), 0); | 13399 | copy_users_.resize(info.copy_queues.size(), 0); |
| @@ -10831,8 +13503,10 @@ public: | |||
| 10831 | VK_SAMPLE_COUNT_1_BIT | VK_SAMPLE_COUNT_4_BIT | VK_SAMPLE_COUNT_8_BIT | VK_SAMPLE_COUNT_16_BIT; | 13503 | VK_SAMPLE_COUNT_1_BIT | VK_SAMPLE_COUNT_4_BIT | VK_SAMPLE_COUNT_8_BIT | VK_SAMPLE_COUNT_16_BIT; |
| 10832 | state_.no_output_sample_counts = | 13504 | state_.no_output_sample_counts = |
| 10833 | static_cast<UINT>(props.limits.framebufferNoAttachmentsSampleCounts & kD3D12SampleCounts); | 13505 | static_cast<UINT>(props.limits.framebufferNoAttachmentsSampleCounts & kD3D12SampleCounts); |
| 10834 | state_.f16_half_top_location = leonida::f16_half_top_location( | 13506 | state_.f16_half_top_location = info.f16_half_top_location != 0 |
| 10835 | props.limits.maxVertexOutputComponents, props.limits.maxFragmentInputComponents); | 13507 | ? info.f16_half_top_location |
| 13508 | : leonida::f16_half_top_location( | ||
| 13509 | props.limits.maxVertexOutputComponents, props.limits.maxFragmentInputComponents); | ||
| 10836 | } | 13510 | } |
| 10837 | if (const auto get_props2 = reinterpret_cast<PFN_vkGetPhysicalDeviceProperties2>( | 13511 | if (const auto get_props2 = reinterpret_cast<PFN_vkGetPhysicalDeviceProperties2>( |
| 10838 | info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties2"))) { | 13512 | info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties2"))) { |
| @@ -10869,7 +13543,8 @@ public: | |||
| 10869 | indirect); | 13543 | indirect); |
| 10870 | if (info.device_fault_diagnostics) { | 13544 | if (info.device_fault_diagnostics) { |
| 10871 | state_.context->configure_device_fault(get_device, | 13545 | state_.context->configure_device_fault(get_device, |
| 10872 | {info.device_fault_info, info.device_checkpoints, info.device_diagnostics_config}); | 13546 | {info.device_fault_info, info.device_checkpoints, info.device_diagnostics_config, info.device_markers}, |
| 13547 | &state_.memory); | ||
| 10873 | state_.context->add_diagnostic_queue(info.queue); | 13548 | state_.context->add_diagnostic_queue(info.queue); |
| 10874 | for (auto queue : info.command_queues) state_.context->add_diagnostic_queue(queue); | 13549 | for (auto queue : info.command_queues) state_.context->add_diagnostic_queue(queue); |
| 10875 | for (auto queue : info.compute_queues) state_.context->add_diagnostic_queue(queue); | 13550 | for (auto queue : info.compute_queues) state_.context->add_diagnostic_queue(queue); |
| @@ -10883,6 +13558,9 @@ public: | |||
| 10883 | if (auto* fault = state_.context->device_fault()) | 13558 | if (auto* fault = state_.context->device_fault()) |
| 10884 | fault->set_lost_hook([this] { rt::compute_probe::recheck(state_); }); | 13559 | fault->set_lost_hook([this] { rt::compute_probe::recheck(state_); }); |
| 10885 | } | 13560 | } |
| 13561 | if (async_texture_refresh()) start_title_filler(); | ||
| 13562 | state_.setup_console_heap_gpu(get_device); // LEONIDA_CONSOLE_HEAP_GPU: the context's prelude | ||
| 13563 | state_.context->set_after_execute([this] { state_.geometry_execute_end(); }); | ||
| 10886 | state_.context->set_before_execute([this] { | 13564 | state_.context->set_before_execute([this] { |
| 10887 | namespace phases = leonida::submit_phases; | 13565 | namespace phases = leonida::submit_phases; |
| 10888 | // LEONIDA_REFRESH_PER_FRAME (for runs that only need the title to go on): 1 = the slot-133 shadows, title | 13566 | // LEONIDA_REFRESH_PER_FRAME (for runs that only need the title to go on): 1 = the slot-133 shadows, title |
| @@ -10895,11 +13573,13 @@ public: | |||
| 10895 | const char* v = std::getenv("LEONIDA_REFRESH_PER_FRAME"); | 13573 | const char* v = std::getenv("LEONIDA_REFRESH_PER_FRAME"); |
| 10896 | return v && *v ? std::atoi(v) : 0; | 13574 | return v && *v ? std::atoi(v) : 0; |
| 10897 | }(); | 13575 | }(); |
| 13576 | state_.geometry_execute_begin(); | ||
| 10898 | bool full = true; | 13577 | bool full = true; |
| 10899 | if (per_frame) { | 13578 | if (per_frame) { |
| 10900 | const std::uint64_t serial = phases::totals().present_serial.load(std::memory_order_relaxed); | 13579 | const std::uint64_t serial = phases::totals().present_serial.load(std::memory_order_relaxed); |
| 10901 | full = refreshed_present_.exchange(serial, std::memory_order_relaxed) != serial; | 13580 | full = refreshed_present_.exchange(serial, std::memory_order_relaxed) != serial; |
| 10902 | } | 13581 | } |
| 13582 | state_.drain_geometry_releases(); | ||
| 10903 | state_.refresh_shadows(full || per_frame < 2, full); | 13583 | state_.refresh_shadows(full || per_frame < 2, full); |
| 10904 | // LEONIDA_GEOMETRY_ASYNC=1 (for runs that only need the title to go on): the geometry copies are brought | 13584 | // LEONIDA_GEOMETRY_ASYNC=1 (for runs that only need the title to go on): the geometry copies are brought |
| 10905 | // up to date on a worker of ours, started here and not waited for, instead of on the title's GPU submit | 13585 | // up to date on a worker of ours, started here and not waited for, instead of on the title's GPU submit |
| @@ -10916,7 +13596,14 @@ public: | |||
| 10916 | state_.geometry.refresh(DeviceState::copy_geometry); | 13596 | state_.geometry.refresh(DeviceState::copy_geometry); |
| 10917 | } | 13597 | } |
| 10918 | const phases::Scope timed(phases::textures); | 13598 | const phases::Scope timed(phases::textures); |
| 10919 | refresh_title_textures(); | 13599 | if (async_texture_refresh()) { |
| 13600 | if (!t_in_title_textures) { | ||
| 13601 | fill_first_mapped_textures(); | ||
| 13602 | request_title_refresh(); | ||
| 13603 | } | ||
| 13604 | } else { | ||
| 13605 | refresh_title_textures(); | ||
| 13606 | } | ||
| 10920 | }); | 13607 | }); |
| 10921 | { | 13608 | { |
| 10922 | char text[16] = {}; | 13609 | char text[16] = {}; |
| @@ -10937,6 +13624,10 @@ public: | |||
| 10937 | threads.count); | 13624 | threads.count); |
| 10938 | if (threads.count) | 13625 | if (threads.count) |
| 10939 | state_.context->set_pipeline_workers(std::make_unique<leonida::PipelineWorkers>(threads.count)); | 13626 | state_.context->set_pipeline_workers(std::make_unique<leonida::PipelineWorkers>(threads.count)); |
| 13627 | if (big_compiles() == BigCompiles::budget) | ||
| 13628 | state_.context->set_large_compiles( | ||
| 13629 | [] { return big_compile_gate().budget(); }, | ||
| 13630 | [] { return std::make_shared<leonida::LargeModuleGate::Demand>(big_compile_gate()); }); | ||
| 10940 | } | 13631 | } |
| 10941 | leonida::title_va_aliases().set_hooks( | 13632 | leonida::title_va_aliases().set_hooks( |
| 10942 | &state_, | 13633 | &state_, |
| @@ -11085,12 +13776,15 @@ public: | |||
| 11085 | // device addresses the same scratch holds the triangle indices of indexed quad lists (quad_index_expand.h): | 13776 | // device addresses the same scratch holds the triangle indices of indexed quad lists (quad_index_expand.h): |
| 11086 | // a compute pass writes them through the chunk's address and the draw binds the chunk as its index buffer. | 13777 | // a compute pass writes them through the chunk's address and the draw binds the chunk as its index buffer. |
| 11087 | const bool index_scratch = info.buffer_device_address; | 13778 | const bool index_scratch = info.buffer_device_address; |
| 13779 | const VkBufferUsageFlags scratch_extra = | ||
| 13780 | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | | ||
| 13781 | (index_scratch ? VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0); | ||
| 11088 | state_.context->enable_copy_scratch( | 13782 | state_.context->enable_copy_scratch( |
| 11089 | get_device, | 13783 | get_device, |
| 11090 | [this, index_scratch](const VkMemoryRequirements& requirements) { | 13784 | [this, index_scratch](const VkMemoryRequirements& requirements) { |
| 11091 | return state_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, nullptr, index_scratch); | 13785 | return state_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, nullptr, index_scratch); |
| 11092 | }, | 13786 | }, |
| 11093 | index_scratch ? VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0, state_.families); | 13787 | scratch_extra, state_.families); |
| 11094 | if (info.buffer_device_address && info.physical && info.get_instance_proc) { | 13788 | if (info.buffer_device_address && info.physical && info.get_instance_proc) { |
| 11095 | if (const auto get_props = reinterpret_cast<PFN_vkGetPhysicalDeviceProperties>( | 13789 | if (const auto get_props = reinterpret_cast<PFN_vkGetPhysicalDeviceProperties>( |
| 11096 | info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties"))) { | 13790 | info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties"))) { |
| @@ -11105,7 +13799,8 @@ public: | |||
| 11105 | return state_.allocate(requirements, 0, | 13799 | return state_.allocate(requirements, 0, |
| 11106 | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, | 13800 | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, |
| 11107 | nullptr, /*device_address=*/true); | 13801 | nullptr, /*device_address=*/true); |
| 11108 | }); | 13802 | }, |
| 13803 | state_.families); | ||
| 11109 | } | 13804 | } |
| 11110 | } | 13805 | } |
| 11111 | // The copies of a D24 texture stored as D32 convert on the GPU (vulkan_depth24.h), and so do the copies of | 13806 | // The copies of a D24 texture stored as D32 convert on the GPU (vulkan_depth24.h), and so do the copies of |
| @@ -11237,6 +13932,41 @@ public: | |||
| 11237 | std::fprintf(stderr, "[rt] d3d12: descriptor hash: %s (all %zu modules)\n", | 13932 | std::fprintf(stderr, "[rt] d3d12: descriptor hash: %s (all %zu modules)\n", |
| 11238 | leonida::descriptor_hash_kind_name(descriptor_hash), hash_modules.total()); | 13933 | leonida::descriptor_hash_kind_name(descriptor_hash), hash_modules.total()); |
| 11239 | } | 13934 | } |
| 13935 | // Which entry layout the loaded modules read (descriptor_table.h): a tagged module reads the kind word next to | ||
| 13936 | // each index and uses it to tell which array that index is bound in (a 3D T# read by a 2D op is not another | ||
| 13937 | // image), and the inserts below fill it. A plain library reads only the index, exactly as before. The kind | ||
| 13938 | // word is additive, so one tagged module needs the tagged layout whatever the plain count (the library's | ||
| 13939 | // vote); chosen once here, like the hash kind, and LEONIDA_DESCRIPTOR_TABLE overrides. | ||
| 13940 | leonida::DescriptorTableCensus table_modules{}; | ||
| 13941 | leonida::DescriptorTableLayout descriptor_table = leonida::DescriptorTableLayout::plain; | ||
| 13942 | if (const leonida::ShaderLibrary* library = state_.library()) { | ||
| 13943 | table_modules = library->descriptor_table_census(); | ||
| 13944 | descriptor_table = library->descriptor_table_layout(); | ||
| 13945 | } | ||
| 13946 | leonida::DescriptorTableLayout override_table = descriptor_table; | ||
| 13947 | if (leonida::descriptor_table_layout_from_env(std::getenv("LEONIDA_DESCRIPTOR_TABLE"), &override_table)) { | ||
| 13948 | std::fprintf(stderr, | ||
| 13949 | "[rt] d3d12: descriptor table: %s (LEONIDA_DESCRIPTOR_TABLE; %zu tagged / %zu plain modules)\n", | ||
| 13950 | leonida::descriptor_table_layout_name(override_table), table_modules.tagged, | ||
| 13951 | table_modules.plain); | ||
| 13952 | descriptor_table = override_table; | ||
| 13953 | // Under a plain table a tagged module reads no kind at all, so every image an instruction reads through | ||
| 13954 | // another dimension's array takes that array's fallback. That is what the override asks for; say so. | ||
| 13955 | if (override_table == leonida::DescriptorTableLayout::plain && table_modules.tagged) | ||
| 13956 | std::fprintf(stderr, | ||
| 13957 | "[rt] d3d12: LEONIDA_DESCRIPTOR_TABLE forces the plain descriptor table while %zu " | ||
| 13958 | "module(s) read the kind word; their image lookups through another dimension's array " | ||
| 13959 | "take the fallback\n", | ||
| 13960 | table_modules.tagged); | ||
| 13961 | } else if (table_modules.tagged && table_modules.plain) { | ||
| 13962 | std::fprintf(stderr, "[rt] d3d12: descriptor table: %zu tagged / %zu plain modules; using %s\n", | ||
| 13963 | table_modules.tagged, table_modules.plain, | ||
| 13964 | leonida::descriptor_table_layout_name(descriptor_table)); | ||
| 13965 | } else { | ||
| 13966 | std::fprintf(stderr, "[rt] d3d12: descriptor table: %s (all %zu modules)\n", | ||
| 13967 | leonida::descriptor_table_layout_name(descriptor_table), table_modules.total()); | ||
| 13968 | } | ||
| 13969 | state_.descriptor_table_tagged = descriptor_table == leonida::DescriptorTableLayout::tagged; | ||
| 11240 | const auto get_properties = reinterpret_cast<PFN_vkGetPhysicalDeviceProperties2>( | 13970 | const auto get_properties = reinterpret_cast<PFN_vkGetPhysicalDeviceProperties2>( |
| 11241 | state_.info.get_instance_proc(state_.info.instance, "vkGetPhysicalDeviceProperties2")); | 13971 | state_.info.get_instance_proc(state_.info.instance, "vkGetPhysicalDeviceProperties2")); |
| 11242 | if (get_properties) { | 13972 | if (get_properties) { |
| @@ -11311,6 +14041,7 @@ public: | |||
| 11311 | // after it, so the generations flush() retires are free at once. | 14041 | // after it, so the generations flush() retires are free at once. |
| 11312 | { | 14042 | { |
| 11313 | std::lock_guard submit(context.submit_mutex()); | 14043 | std::lock_guard submit(context.submit_mutex()); |
| 14044 | const leonida::SubmitMutex::SubmitTurn turn(context.submit_mutex()); // the compile gate | ||
| 11314 | context.observe_result(context.vk.vkDeviceWaitIdle(state_.info.device), "vkDeviceWaitIdle"); | 14045 | context.observe_result(context.vk.vkDeviceWaitIdle(state_.info.device), "vkDeviceWaitIdle"); |
| 11315 | } | 14046 | } |
| 11316 | state_.bindless_idle_waits.fetch_add(1, std::memory_order_relaxed); | 14047 | state_.bindless_idle_waits.fetch_add(1, std::memory_order_relaxed); |
| @@ -11400,7 +14131,14 @@ public: | |||
| 11400 | if (!vk.vkGetBufferDeviceAddress) return false; | 14131 | if (!vk.vkGetBufferDeviceAddress) return false; |
| 11401 | char text[16] = {}; | 14132 | char text[16] = {}; |
| 11402 | size_t length = 0; | 14133 | size_t length = 0; |
| 11403 | const bool set = getenv_s(&length, text, "LEONIDA_ARENA_MB") == 0 && length > 1; | 14134 | bool set = getenv_s(&length, text, "LEONIDA_ARENA_MB") == 0 && length > 1; |
| 14135 | // A value the CRT's copy of the environment does not give (or one past this buffer): asked of Windows too, | ||
| 14136 | // then report the size applied to the arena. | ||
| 14137 | if (!set) { | ||
| 14138 | const DWORD n = GetEnvironmentVariableA("LEONIDA_ARENA_MB", text, sizeof(text)); | ||
| 14139 | set = n > 0 && n < sizeof(text); | ||
| 14140 | if (set) std::fprintf(stderr, "[rt] d3d12: LEONIDA_ARENA_MB was read from the process environment, not the CRT's\n"); | ||
| 14141 | } | ||
| 11404 | const leonida::ArenaLimits limits{state_.info.max_buffer_size, state_.info.max_memory_allocation_size}; | 14142 | const leonida::ArenaLimits limits{state_.info.max_buffer_size, state_.info.max_memory_allocation_size}; |
| 11405 | leonida::ArenaSize size = leonida::decide_arena_size(set ? text : nullptr, limits); | 14143 | leonida::ArenaSize size = leonida::decide_arena_size(set ? text : nullptr, limits); |
| 11406 | auto& arena = state_.arena; | 14144 | auto& arena = state_.arena; |
| @@ -11485,6 +14223,8 @@ public: | |||
| 11485 | return false; | 14223 | return false; |
| 11486 | } | 14224 | } |
| 11487 | arena.mapped = static_cast<std::uint8_t*>(mapped); | 14225 | arena.mapped = static_cast<std::uint8_t*>(mapped); |
| 14226 | std::fprintf(stderr, "[rt] d3d12: GPU address arena: %llu MiB (LEONIDA_ARENA_MB %s)\n", | ||
| 14227 | static_cast<unsigned long long>(info.size >> 20), set ? text : "unset"); | ||
| 11488 | // LEONIDA_ARENA_NULL_MB=<n> (for compute-on boots): the first n MiB of the arena, at heap_base + 0, are zeroed | 14228 | // LEONIDA_ARENA_NULL_MB=<n> (for compute-on boots): the first n MiB of the arena, at heap_base + 0, are zeroed |
| 11489 | // and never handed out, and the zero page and the quad indices move above them. A translated shader whose | 14229 | // and never handed out, and the zero page and the quad indices move above them. A translated shader whose |
| 11490 | // address arithmetic starts from a null base (a scalar or flat load the translator does not bounds-check) | 14230 | // address arithmetic starts from a null base (a scalar or flat load the translator does not bounds-check) |
| @@ -11536,6 +14276,7 @@ public: | |||
| 11536 | arena.log = getenv_s(&length, log, "LEONIDA_ARENA_LOG") == 0 && length > 1 && log[0] != '0'; | 14276 | arena.log = getenv_s(&length, log, "LEONIDA_ARENA_LOG") == 0 && length > 1 && log[0] != '0'; |
| 11537 | state_.context->set_heap_base(arena.address, arena.size); | 14277 | state_.context->set_heap_base(arena.address, arena.size); |
| 11538 | leonida::fsdraw::note_arena(arena.mapped, arena.size); // LOCAL DIAGNOSTIC | 14278 | leonida::fsdraw::note_arena(arena.mapped, arena.size); // LOCAL DIAGNOSTIC |
| 14279 | leonida::fsdraw::backing_hook().store(&fsdraw_backing, std::memory_order_release); | ||
| 11539 | state_.context->set_zero_page(arena.buffer, null_bytes, kZeroPage); | 14280 | state_.context->set_zero_page(arena.buffer, null_bytes, kZeroPage); |
| 11540 | state_.context->set_quad_indices(arena.buffer, null_bytes + kZeroPage, kQuadIndexCount); | 14281 | state_.context->set_quad_indices(arena.buffer, null_bytes + kZeroPage, kQuadIndexCount); |
| 11541 | // Copy only registered title data. Each immutable upload stays alive in the queue command slot | 14282 | // Copy only registered title data. Each immutable upload stays alive in the queue command slot |
| @@ -11572,6 +14313,12 @@ public: | |||
| 11572 | } | 14313 | } |
| 11573 | 14314 | ||
| 11574 | ~Device() override { | 14315 | ~Device() override { |
| 14316 | leonida::memory_figures::withdraw_vram_reader(&state_); // waits for a read of this device in progress | ||
| 14317 | { | ||
| 14318 | // Before anything goes: an exit save in progress finishes with this device first. | ||
| 14319 | std::lock_guard lock(exit_cache_mutex); | ||
| 14320 | std::erase(exit_cache_devices, &state_); | ||
| 14321 | } | ||
| 11575 | leonida::value_sink::clear_arena(&state_); // first: it waits for a value write into the arena in progress | 14322 | leonida::value_sink::clear_arena(&state_); // first: it waits for a value write into the arena in progress |
| 11576 | raw_images_.clear(); | 14323 | raw_images_.clear(); |
| 11577 | geometry_refresher_.reset(); // its refresh uses state_.geometry | 14324 | geometry_refresher_.reset(); // its refresh uses state_.geometry |
| @@ -11603,6 +14350,7 @@ public: | |||
| 11603 | if (state_.context) { | 14350 | if (state_.context) { |
| 11604 | { | 14351 | { |
| 11605 | std::lock_guard lock(state_.context->submit_mutex()); | 14352 | std::lock_guard lock(state_.context->submit_mutex()); |
| 14353 | const leonida::SubmitMutex::SubmitTurn turn(state_.context->submit_mutex()); // the compile gate | ||
| 11606 | state_.context->observe_result(state_.context->vk.vkDeviceWaitIdle(state_.info.device), | 14354 | state_.context->observe_result(state_.context->vk.vkDeviceWaitIdle(state_.info.device), |
| 11607 | "vkDeviceWaitIdle"); | 14355 | "vkDeviceWaitIdle"); |
| 11608 | } | 14356 | } |
| @@ -11612,6 +14360,8 @@ public: | |||
| 11612 | state_.context->set_bindless_current(nullptr); // the retired generations go with state_.bindless below | 14360 | state_.context->set_bindless_current(nullptr); // the retired generations go with state_.bindless below |
| 11613 | } | 14361 | } |
| 11614 | if (state_.context) { | 14362 | if (state_.context) { |
| 14363 | if (state_.gpu_resolver) state_.gpu_resolver->halt(); // it calls into the geometry copies | ||
| 14364 | ShadowPages::gpu_copy = nullptr; | ||
| 11615 | state_.geometry.release(state_); | 14365 | state_.geometry.release(state_); |
| 11616 | state_.external_windows.release(state_); | 14366 | state_.external_windows.release(state_); |
| 11617 | std::lock_guard upload(state_.title_upload_mutex); | 14367 | std::lock_guard upload(state_.title_upload_mutex); |
| @@ -11639,7 +14389,7 @@ public: | |||
| 11639 | if (const unsigned building = state_.active_compiles.load()) | 14389 | if (const unsigned building = state_.active_compiles.load()) |
| 11640 | std::fprintf(stderr, "[rt] d3d12: %u pipeline build(s) still running at device teardown; " | 14390 | std::fprintf(stderr, "[rt] d3d12: %u pipeline build(s) still running at device teardown; " |
| 11641 | "pipeline_cache.session.bin not written\n", building); | 14391 | "pipeline_cache.session.bin not written\n", building); |
| 11642 | else | 14392 | else if (!compile_helper::build_host) |
| 11643 | save_session_pipeline_cache(state_.context->vk, state_.info.device, state_.pipeline_cache_handle); | 14393 | save_session_pipeline_cache(state_.context->vk, state_.info.device, state_.pipeline_cache_handle); |
| 11644 | state_.context->vk.vkDestroyPipelineCache(state_.info.device, state_.pipeline_cache_handle, nullptr); | 14394 | state_.context->vk.vkDestroyPipelineCache(state_.info.device, state_.pipeline_cache_handle, nullptr); |
| 11645 | } | 14395 | } |
| @@ -11650,6 +14400,8 @@ public: | |||
| 11650 | } | 14400 | } |
| 11651 | 14401 | ||
| 11652 | bool ok() const { return state_.context && state_.context->loaded(); } | 14402 | bool ok() const { return state_.context && state_.context->loaded(); } |
| 14403 | // gta6rt --precompile-pipelines builds against the device's own state (precompile_compute_pipelines). | ||
| 14404 | DeviceState& build_state() { return state_; } | ||
| 11653 | const VulkanDeviceInfo& info() const { return state_.info; } | 14405 | const VulkanDeviceInfo& info() const { return state_.info; } |
| 11654 | // Acceleration-structure resources work: KHR builds, or the XDXR records (which need the GPU address arena). | 14406 | // Acceleration-structure resources work: KHR builds, or the XDXR records (which need the GPU address arena). |
| 11655 | bool acceleration_structures() const { | 14407 | bool acceleration_structures() const { |
| @@ -11658,6 +14410,7 @@ public: | |||
| 11658 | bool upload_in_vram() const { return state_.upload_in_vram; } | 14410 | bool upload_in_vram() const { return state_.upload_in_vram; } |
| 11659 | leonida::VulkanContext& context() { return *state_.context; } | 14411 | leonida::VulkanContext& context() { return *state_.context; } |
| 11660 | const leonida::BindlessSet* bindless() const { return state_.bindless.get(); } | 14412 | const leonida::BindlessSet* bindless() const { return state_.bindless.get(); } |
| 14413 | DeviceState& state() { return state_; } | ||
| 11661 | const DeviceState& state() const { return state_; } | 14414 | const DeviceState& state() const { return state_; } |
| 11662 | HRESULT create_native_graphics(const leonida::native_pso::GraphicsDesc& desc, REFIID iid, void** out) { | 14415 | HRESULT create_native_graphics(const leonida::native_pso::GraphicsDesc& desc, REFIID iid, void** out) { |
| 11663 | const auto* shaders = state_.library(); | 14416 | const auto* shaders = state_.library(); |
| @@ -11826,7 +14579,8 @@ public: | |||
| 11826 | d.height, unsigned(d.depth_or_array), d.format, unsigned(srv.Format), unsigned(d.mips), unsigned(written)); | 14579 | d.height, unsigned(d.depth_or_array), d.format, unsigned(srv.Format), unsigned(d.mips), unsigned(written)); |
| 11827 | if (!written && stats.refusals == refusals) refuse_title_view("no reason recorded", d, address); | 14580 | if (!written && stats.refusals == refusals) refuse_title_view("no reason recorded", d, address); |
| 11828 | if (!written) ++stats.null_views; | 14581 | if (!written) ++stats.null_views; |
| 11829 | if (stats.views == 64 || !(stats.views % 2048)) log_title_census("slot-70 texture views"); | 14582 | if (leonida::fsdraw::enabled() && (stats.views == 64 || !(stats.views % 2048))) |
| 14583 | log_title_census("slot-70 texture views"); | ||
| 11830 | } | 14584 | } |
| 11831 | state_.drain_titles_gone(); | 14585 | state_.drain_titles_gone(); |
| 11832 | return written; | 14586 | return written; |
| @@ -11923,6 +14677,8 @@ public: | |||
| 11923 | } | 14677 | } |
| 11924 | auto& slot = state_.title_textures[address]; | 14678 | auto& slot = state_.title_textures[address]; |
| 11925 | if (slot && slot->owned) retire_title_texture(*slot); | 14679 | if (slot && slot->owned) retire_title_texture(*slot); |
| 14680 | state_.mapped_title_textures.erase(address); | ||
| 14681 | state_.index_texture(*entry); | ||
| 11926 | slot = std::move(entry); | 14682 | slot = std::move(entry); |
| 11927 | ++title_stats_.registered; | 14683 | ++title_stats_.registered; |
| 11928 | } | 14684 | } |
| @@ -11969,7 +14725,11 @@ public: | |||
| 11969 | // title_texture_gone while this thread holds the registry mutex: the entry stops naming the resource and is | 14725 | // title_texture_gone while this thread holds the registry mutex: the entry stops naming the resource and is |
| 11970 | // erased by drain_titles_gone after the pass. Every walk below visits a snapshot, never an iterator into the | 14726 | // erased by drain_titles_gone after the pass. Every walk below visits a snapshot, never an iterator into the |
| 11971 | // registry, and skips an entry without a resource. | 14727 | // registry, and skips an entry without a resource. |
| 11972 | const auto entries = leonida::title_texture_snapshot(state_.title_textures); | 14728 | // The worker gives journal hits priority. Rotate a small slice for direct writes with no notification. |
| 14729 | const bool async = async_texture_refresh(); | ||
| 14730 | const auto entries = async ? leonida::title_texture_snapshot(state_.title_textures, title_slice_, 128) | ||
| 14731 | : leonida::title_texture_snapshot(state_.title_textures); | ||
| 14732 | if (async) title_slice_ = entries.size() == 128 ? entries.back().first + 1 : 0; | ||
| 11973 | title_pass_ = true; | 14733 | title_pass_ = true; |
| 11974 | std::uint64_t checked = 0, filled = 0, fill_pass_ns = 0; | 14734 | std::uint64_t checked = 0, filled = 0, fill_pass_ns = 0; |
| 11975 | const auto visit = [&](TitleTexture& t) { | 14735 | const auto visit = [&](TitleTexture& t) { |
| @@ -11991,7 +14751,8 @@ public: | |||
| 11991 | } | 14751 | } |
| 11992 | std::uint64_t hash = 0; | 14752 | std::uint64_t hash = 0; |
| 11993 | if (!title_texture_readable(t)) return; | 14753 | if (!title_texture_readable(t)) return; |
| 11994 | checked += hashed_bytes(span); | 14754 | const bool full_mapped = async && always; |
| 14755 | checked += full_mapped ? span : hashed_bytes(span); | ||
| 11995 | ++stats.checked; | 14756 | ++stats.checked; |
| 11996 | const auto* bytes = reinterpret_cast<const std::uint8_t*>(static_cast<std::uintptr_t>(t.cpu)); | 14757 | const auto* bytes = reinterpret_cast<const std::uint8_t*>(static_cast<std::uintptr_t>(t.cpu)); |
| 11997 | const auto timed_hash = [&](std::uint64_t& out, bool all = false) { | 14758 | const auto timed_hash = [&](std::uint64_t& out, bool all = false) { |
| @@ -12000,11 +14761,33 @@ public: | |||
| 12000 | stats.hash_ns += std::chrono::duration_cast<std::chrono::nanoseconds>(clock::now() - start).count(); | 14761 | stats.hash_ns += std::chrono::duration_cast<std::chrono::nanoseconds>(clock::now() - start).count(); |
| 12001 | return ok; | 14762 | return ok; |
| 12002 | }; | 14763 | }; |
| 12003 | if (!timed_hash(hash)) { | 14764 | if (full_mapped) { |
| 14765 | // Direct writes through a persistent Map have no journal entry. Check every byte on the | ||
| 14766 | // worker. A large mapped plane must not hold up view creation while its hash is computed. | ||
| 14767 | const auto address = t.address, fills = t.fills; | ||
| 14768 | const auto start = clock::now(); | ||
| 14769 | title_pass_ = false; | ||
| 14770 | lock.unlock(); | ||
| 14771 | const bool ok = hash_guarded(bytes, std::size_t(span), hash, true); | ||
| 14772 | lock.lock(); | ||
| 14773 | title_pass_ = true; | ||
| 14774 | stats.hash_ns += std::chrono::duration_cast<std::chrono::nanoseconds>(clock::now() - start).count(); | ||
| 14775 | const auto it = state_.title_textures.find(address); | ||
| 14776 | if (it == state_.title_textures.end() || it->second.get() != &t || !t.resource || | ||
| 14777 | !t.layout_known || t.layout.layout.size != span || t.fills != fills) return; | ||
| 14778 | ++stats.mapped_checks; | ||
| 14779 | if (!ok) { | ||
| 14780 | t.memory.defer(); | ||
| 14781 | t.stale = true; | ||
| 14782 | return; | ||
| 14783 | } | ||
| 14784 | if (t.hashed && t.full_hashed && t.full_hash == hash && !t.stale) return; | ||
| 14785 | ++stats.mapped_changed; | ||
| 14786 | } else if (!timed_hash(hash)) { | ||
| 12004 | t.memory.defer(); | 14787 | t.memory.defer(); |
| 12005 | return; | 14788 | return; |
| 12006 | } | 14789 | } |
| 12007 | if (t.hashed && hash == t.hash && !t.stale) { | 14790 | if (!full_mapped && t.hashed && hash == t.hash && !t.stale) { |
| 12008 | if (!t.every_byte() || stats.passes % 6) return; | 14791 | if (!t.every_byte() || stats.passes % 6) return; |
| 12009 | std::uint64_t full = 0; | 14792 | std::uint64_t full = 0; |
| 12010 | checked += span; | 14793 | checked += span; |
| @@ -12021,7 +14804,10 @@ public: | |||
| 12021 | return; | 14804 | return; |
| 12022 | } | 14805 | } |
| 12023 | const auto fill_start = clock::now(); | 14806 | const auto fill_start = clock::now(); |
| 12024 | filled += fill_title_texture(t, false); | 14807 | const auto uploaded = fill_title_texture(t, false); |
| 14808 | filled += uploaded; | ||
| 14809 | if (full_mapped && uploaded) ++stats.mapped_fills; | ||
| 14810 | if (async && t.stale) queue_title_fill(t.address); // generic staging needs an outer fill | ||
| 12025 | const std::uint64_t fill_ns = | 14811 | const std::uint64_t fill_ns = |
| 12026 | std::chrono::duration_cast<std::chrono::nanoseconds>(clock::now() - fill_start).count(); | 14812 | std::chrono::duration_cast<std::chrono::nanoseconds>(clock::now() - fill_start).count(); |
| 12027 | stats.fill_ns += fill_ns; | 14813 | stats.fill_ns += fill_ns; |
| @@ -12047,34 +14833,93 @@ public: | |||
| 12047 | if (!written.empty() || overflow || map_all || !title_map_changes_.empty()) { | 14833 | if (!written.empty() || overflow || map_all || !title_map_changes_.empty()) { |
| 12048 | stats.written_ranges += written.size(); | 14834 | stats.written_ranges += written.size(); |
| 12049 | leonida::merge_title_writes(written); | 14835 | leonida::merge_title_writes(written); |
| 12050 | for (const auto& entry : entries) { | 14836 | const auto invalidate = [&](TitleTexture& t, bool write) { |
| 12051 | TitleTexture& t = *entry.second; | 14837 | if (t.gpu_written || !t.layout_known) return; |
| 12052 | if (t.gpu_written || !t.layout_known) continue; | 14838 | t.memory.retry(); |
| 12053 | const std::uint64_t begin = t.cpu, end = t.cpu + t.layout.layout.size; | 14839 | if (write) t.stale = true; |
| 12054 | if (map_all || leonida::title_write_overlaps(title_map_changes_, begin, end)) t.memory.retry(); | 14840 | if (overflow) t.hashed = false; |
| 12055 | if (leonida::title_write_overlaps(written, begin, end)) { | 14841 | }; |
| 12056 | t.memory.retry(); | 14842 | if (!async || overflow || map_all) { |
| 12057 | t.stale = true; | 14843 | // No fills or callbacks during invalidation; registry iterators stay valid. |
| 12058 | } | 14844 | for (const auto& [key, ptr] : state_.title_textures) { |
| 12059 | if (overflow) { | 14845 | auto& t = *ptr; |
| 12060 | t.memory.retry(); | 14846 | const auto end = t.cpu + t.layout.layout.size; |
| 12061 | t.hashed = false; | 14847 | const bool write = leonida::title_write_overlaps(written, t.cpu, end); |
| 14848 | if (write || map_all || overflow || leonida::title_write_overlaps(title_map_changes_, t.cpu, end)) | ||
| 14849 | invalidate(t, write); | ||
| 12062 | } | 14850 | } |
| 14851 | } else { | ||
| 14852 | const auto apply = [&](const auto& ranges, bool write) { | ||
| 14853 | for (const auto& [from, to] : ranges) | ||
| 14854 | state_.texture_ranges.overlapping(from, to, [&](auto key) { | ||
| 14855 | auto& t = *state_.title_textures.at(key); | ||
| 14856 | invalidate(t, write); | ||
| 14857 | if (t.stale) queue_title_fill(key); | ||
| 14858 | }); | ||
| 14859 | }; | ||
| 14860 | apply(title_map_changes_, false); | ||
| 14861 | apply(written, true); | ||
| 12063 | } | 14862 | } |
| 12064 | } | 14863 | } |
| 12065 | const auto every_start = clock::now(); | 14864 | const auto every_start = clock::now(); |
| 12066 | stats.written_ns += std::chrono::duration_cast<std::chrono::nanoseconds>(every_start - now).count(); | 14865 | stats.written_ns += std::chrono::duration_cast<std::chrono::nanoseconds>(every_start - now).count(); |
| 12067 | for (const auto& entry : entries) | 14866 | // LEONIDA_TITLE_EVERY_BUDGET_US (0, the default: no limit, as before) limits the synchronous pass, the one that |
| 12068 | if (entry.second->mapped || entry.second->stale) { | 14867 | // runs before a submission on the title's submitting thread: the mapped and stale textures are visited for at |
| 14868 | // most this long a pass, in address order from where the last pass stopped, instead of all of them every pass | ||
| 14869 | // (thousands during a streaming burst on retail, 30-75 ms a pass). The texture that crosses the limit is | ||
| 14870 | // finished; one not reached keeps its mark and waits for a later pass. With LEONIDA_TEXTURE_REFRESH_ASYNC the | ||
| 14871 | // pass runs on the refresh worker, and the limit does not apply. | ||
| 14872 | static const std::uint64_t every_budget_us = setting("LEONIDA_TITLE_EVERY_BUDGET_US", 0); | ||
| 14873 | if (async) { | ||
| 14874 | // Poll every persistent mapping each pass, independently of the bounded stale sweep. | ||
| 14875 | const auto mapped = leonida::title_texture_snapshot(state_.mapped_title_textures); | ||
| 14876 | for (const auto& [address, entry] : mapped) { | ||
| 14877 | if (!entry->resource) continue; | ||
| 14878 | const auto it = state_.title_textures.find(address); | ||
| 14879 | if (it == state_.title_textures.end() || it->second != entry) continue; | ||
| 12069 | ++stats.every_pass_visits; | 14880 | ++stats.every_pass_visits; |
| 12070 | visit(*entry.second); | 14881 | visit(*entry); |
| 12071 | } | 14882 | } |
| 14883 | for (const auto& entry : entries) | ||
| 14884 | if (!entry.second->mapped && entry.second->stale) { | ||
| 14885 | const auto it = state_.title_textures.find(entry.first); | ||
| 14886 | if (it == state_.title_textures.end() || it->second != entry.second) continue; | ||
| 14887 | ++stats.every_pass_visits; | ||
| 14888 | visit(*entry.second); | ||
| 14889 | } | ||
| 14890 | } else if (!every_budget_us) { | ||
| 14891 | for (const auto& entry : entries) | ||
| 14892 | if (entry.second->mapped || entry.second->stale) { | ||
| 14893 | ++stats.every_pass_visits; | ||
| 14894 | visit(*entry.second); | ||
| 14895 | } | ||
| 14896 | } else { | ||
| 14897 | leonida::visit_marked_title_textures( | ||
| 14898 | entries, title_every_cursor_, | ||
| 14899 | [&](TitleTexture& t) { | ||
| 14900 | ++stats.every_pass_visits; | ||
| 14901 | visit(t); | ||
| 14902 | }, | ||
| 14903 | // A mapped texture never filled yet does not wait for its turn: the title has written it and the GPU | ||
| 14904 | // has nothing of it (a video plane of #1827 would show frozen until its turn came). | ||
| 14905 | [](const TitleTexture& t) { return t.mapped && !t.fills; }, | ||
| 14906 | [&] { return clock::now() - every_start >= std::chrono::microseconds(every_budget_us); }); | ||
| 14907 | } | ||
| 12072 | stats.every_pass_ns += std::chrono::duration_cast<std::chrono::nanoseconds>(clock::now() - every_start).count(); | 14908 | stats.every_pass_ns += std::chrono::duration_cast<std::chrono::nanoseconds>(clock::now() - every_start).count(); |
| 12073 | // The budget is the round robin's: mapped and stale textures above are checked every pass whatever it is. | 14909 | // The budget is the round robin's: mapped and stale textures above are checked every pass whatever it is |
| 14910 | // (unless LEONIDA_TITLE_EVERY_BUDGET_US limits them). | ||
| 12074 | const auto first_bytes = checked, first_hash_ns = stats.hash_ns; | 14911 | const auto first_bytes = checked, first_hash_ns = stats.hash_ns; |
| 12075 | if (check_budget) { | 14912 | if (check_budget) { |
| 12076 | const auto sweep_start = clock::now(); | 14913 | const auto sweep_start = clock::now(); |
| 12077 | leonida::poll_title_textures(entries, title_refresh_cursor_, visit, [&] { | 14914 | // The normal hash sweep has its own cursor: a byte/time cutoff in a slice must not |
| 14915 | // skip the remainder next time just because the stale-texture sweep moved ahead. | ||
| 14916 | decltype(leonida::title_texture_snapshot(state_.title_textures)) background; | ||
| 14917 | if (async) { | ||
| 14918 | if (!state_.title_textures.empty() && title_refresh_cursor_ > state_.title_textures.rbegin()->first) | ||
| 14919 | title_refresh_cursor_ = 0; | ||
| 14920 | background = leonida::title_texture_snapshot(state_.title_textures, title_refresh_cursor_, 128); | ||
| 14921 | } | ||
| 14922 | leonida::poll_title_textures(async ? background : entries, title_refresh_cursor_, visit, [&] { | ||
| 12078 | if (checked - first_bytes >= check_budget || | 14923 | if (checked - first_bytes >= check_budget || |
| 12079 | (hash_budget_us && (stats.hash_ns - first_hash_ns) / 1000 >= hash_budget_us)) return true; | 14924 | (hash_budget_us && (stats.hash_ns - first_hash_ns) / 1000 >= hash_budget_us)) return true; |
| 12080 | if (!sweep_budget_us) return false; | 14925 | if (!sweep_budget_us) return false; |
| @@ -12098,7 +14943,14 @@ public: | |||
| 12098 | stats.max_refresh_ns = std::max(stats.max_refresh_ns, pass_ns); | 14943 | stats.max_refresh_ns = std::max(stats.max_refresh_ns, pass_ns); |
| 12099 | if (now - stats.last_log >= std::chrono::seconds(10)) { | 14944 | if (now - stats.last_log >= std::chrono::seconds(10)) { |
| 12100 | stats.last_log = now; | 14945 | stats.last_log = now; |
| 12101 | log_title_census("refresh"); | 14946 | if (async) { |
| 14947 | std::fprintf(stderr, "[rt] async texture refresh: %llu mapped checks, %llu changed or stale, %llu uploaded in pass\n", | ||
| 14948 | static_cast<unsigned long long>(stats.mapped_checks), | ||
| 14949 | static_cast<unsigned long long>(stats.mapped_changed), | ||
| 14950 | static_cast<unsigned long long>(stats.mapped_fills)); | ||
| 14951 | stats.mapped_checks = stats.mapped_changed = stats.mapped_fills = 0; | ||
| 14952 | } | ||
| 14953 | if (leonida::fsdraw::enabled()) log_title_census("refresh"); | ||
| 12102 | } | 14954 | } |
| 12103 | inside.reset(); | 14955 | inside.reset(); |
| 12104 | lock.unlock(); | 14956 | lock.unlock(); |
| @@ -12108,6 +14960,7 @@ public: | |||
| 12108 | 14960 | ||
| 12109 | private: | 14961 | private: |
| 12110 | struct TitleTextureStats { | 14962 | struct TitleTextureStats { |
| 14963 | std::uint64_t mapped_checks = 0, mapped_changed = 0, mapped_fills = 0; | ||
| 12111 | // (format, Layout word, dimension, mips) of the slot-70 texture views -> views | 14964 | // (format, Layout word, dimension, mips) of the slot-70 texture views -> views |
| 12112 | std::map<std::array<std::uint32_t, 4>, std::uint64_t> asked; | 14965 | std::map<std::array<std::uint32_t, 4>, std::uint64_t> asked; |
| 12113 | std::map<std::string, std::uint64_t> refused; // why a view is a null view -> views | 14966 | std::map<std::string, std::uint64_t> refused; // why a view is a null view -> views |
| @@ -12149,7 +15002,7 @@ private: | |||
| 12149 | std::condition_variable wake; | 15002 | std::condition_variable wake; |
| 12150 | std::deque<std::uint64_t> queue; // texture addresses | 15003 | std::deque<std::uint64_t> queue; // texture addresses |
| 12151 | std::unordered_set<std::uint64_t> queued; | 15004 | std::unordered_set<std::uint64_t> queued; |
| 12152 | bool stop = false; | 15005 | bool stop = false, refresh = false; |
| 12153 | std::thread thread; | 15006 | std::thread thread; |
| 12154 | std::uint64_t filled = 0, skipped = 0; | 15007 | std::uint64_t filled = 0, skipped = 0; |
| 12155 | std::vector<std::uint8_t> tiled; // the worker's own snapshot of a texture's bytes (fill_unlocked) | 15008 | std::vector<std::uint8_t> tiled; // the worker's own snapshot of a texture's bytes (fill_unlocked) |
| @@ -12165,12 +15018,49 @@ private: | |||
| 12165 | }; | 15018 | }; |
| 12166 | std::unique_ptr<TitleFiller> title_filler_; | 15019 | std::unique_ptr<TitleFiller> title_filler_; |
| 12167 | std::once_flag title_filler_once_; | 15020 | std::once_flag title_filler_once_; |
| 12168 | void queue_title_fill(std::uint64_t address) { | 15021 | void start_title_filler() { |
| 12169 | std::call_once(title_filler_once_, [this] { | 15022 | std::call_once(title_filler_once_, [this] { |
| 12170 | title_filler_ = std::make_unique<TitleFiller>(); | 15023 | title_filler_ = std::make_unique<TitleFiller>(); |
| 12171 | TitleFiller* f = title_filler_.get(); | 15024 | TitleFiller* f = title_filler_.get(); |
| 12172 | f->thread = std::thread([this, f] { run_title_filler(*f); }); | 15025 | f->thread = std::thread([this, f] { run_title_filler(*f); }); |
| 12173 | }); | 15026 | }); |
| 15027 | } | ||
| 15028 | // LEONIDA_TEXTURE_REFRESH_ASYNC=1, before a submission: a mapped texture that has never been filled (a video plane | ||
| 15029 | // the title maps, writes and draws right away) is filled here, on the submitting thread, so its first draw does not | ||
| 15030 | // sample an empty image while the worker has not come to it yet. Everything else stays on the worker. Only when | ||
| 15031 | // the registry is free: the worker may hold it for a fill that needs this queue, so waiting here could deadlock. | ||
| 15032 | void fill_first_mapped_textures() { | ||
| 15033 | std::unique_lock lock(state_.title_texture_mutex, std::try_to_lock); | ||
| 15034 | if (!lock.owns_lock()) return; | ||
| 15035 | std::vector<std::shared_ptr<TitleTexture>> first; | ||
| 15036 | for (const auto& [address, t] : state_.mapped_title_textures) | ||
| 15037 | if (t->resource && !t->fills && !t->gpu_written && t->layout_known) first.push_back(t); | ||
| 15038 | if (first.empty()) return; | ||
| 15039 | { | ||
| 15040 | const InTitleTextures inside; | ||
| 15041 | for (const auto& t : first) { | ||
| 15042 | // A fill can submit and retire an image (title_texture_gone): look each one up again. | ||
| 15043 | const auto it = state_.title_textures.find(t->address); | ||
| 15044 | if (it == state_.title_textures.end() || it->second != t || !t->resource || t->fills) continue; | ||
| 15045 | fill_title_texture(*t, false); | ||
| 15046 | if (t->stale) queue_title_fill(t->address); // generic staging needs an outer fill (the worker's) | ||
| 15047 | } | ||
| 15048 | } | ||
| 15049 | lock.unlock(); | ||
| 15050 | state_.drain_titles_gone(); | ||
| 15051 | } | ||
| 15052 | |||
| 15053 | void request_title_refresh() { | ||
| 15054 | { | ||
| 15055 | // A busy queue can take the next submission's request. Dirty entries stay on the worker. | ||
| 15056 | std::unique_lock lock(title_filler_->mutex, std::try_to_lock); | ||
| 15057 | if (!lock.owns_lock() || title_filler_->refresh) return; | ||
| 15058 | title_filler_->refresh = true; | ||
| 15059 | } | ||
| 15060 | title_filler_->wake.notify_one(); | ||
| 15061 | } | ||
| 15062 | void queue_title_fill(std::uint64_t address) { | ||
| 15063 | start_title_filler(); | ||
| 12174 | { | 15064 | { |
| 12175 | std::lock_guard lock(title_filler_->mutex); | 15065 | std::lock_guard lock(title_filler_->mutex); |
| 12176 | if (!title_filler_->queued.insert(address).second) return; | 15066 | if (!title_filler_->queued.insert(address).second) return; |
| @@ -12183,14 +15073,21 @@ private: | |||
| 12183 | auto since = clock::now(); | 15073 | auto since = clock::now(); |
| 12184 | for (;;) { | 15074 | for (;;) { |
| 12185 | std::uint64_t address = 0; | 15075 | std::uint64_t address = 0; |
| 15076 | bool refresh = false, fill = false; | ||
| 12186 | { | 15077 | { |
| 12187 | std::unique_lock lock(f.mutex); | 15078 | std::unique_lock lock(f.mutex); |
| 12188 | f.wake.wait(lock, [&] { return f.stop || !f.queue.empty(); }); | 15079 | f.wake.wait(lock, [&] { return f.stop || f.refresh || !f.queue.empty(); }); |
| 12189 | if (f.stop) return; | 15080 | if (f.stop) return; |
| 12190 | address = f.queue.front(); | 15081 | refresh = std::exchange(f.refresh, false); |
| 12191 | f.queue.pop_front(); | 15082 | fill = !f.queue.empty(); |
| 12192 | f.queued.erase(address); | 15083 | if (fill) { |
| 15084 | address = f.queue.front(); | ||
| 15085 | f.queue.pop_front(); | ||
| 15086 | f.queued.erase(address); | ||
| 15087 | } | ||
| 12193 | } | 15088 | } |
| 15089 | if (refresh) refresh_title_textures(); | ||
| 15090 | if (!fill) continue; | ||
| 12194 | bool filled = false; | 15091 | bool filled = false; |
| 12195 | // A staged texture is filled without the registry lock (the title's threads creating views wait for | 15092 | // A staged texture is filled without the registry lock (the title's threads creating views wait for |
| 12196 | // it: speed-31, 12 % of the main thread): its bytes, layout and resource are taken under the lock, the | 15093 | // it: speed-31, 12 % of the main thread): its bytes, layout and resource are taken under the lock, the |
| @@ -12218,6 +15115,7 @@ private: | |||
| 12218 | every_byte = t.every_byte(); | 15115 | every_byte = t.every_byte(); |
| 12219 | } else { | 15116 | } else { |
| 12220 | filled = fill_title_texture(t, true) != 0; | 15117 | filled = fill_title_texture(t, true) != 0; |
| 15118 | if (!filled) t.stale = true; | ||
| 12221 | } | 15119 | } |
| 12222 | } | 15120 | } |
| 12223 | } | 15121 | } |
| @@ -12332,7 +15230,9 @@ private: | |||
| 12332 | } | 15230 | } |
| 12333 | geometry_refresher_->wake.notify_one(); | 15231 | geometry_refresher_->wake.notify_one(); |
| 12334 | } | 15232 | } |
| 15233 | std::uint64_t title_slice_ = 0; // next registry slice on the async worker | ||
| 12335 | std::uint64_t title_refresh_cursor_ = 0; // under title_texture_mutex | 15234 | std::uint64_t title_refresh_cursor_ = 0; // under title_texture_mutex |
| 15235 | std::uint64_t title_every_cursor_ = 0; // likewise: LEONIDA_TITLE_EVERY_BUDGET_US's resume point | ||
| 12336 | std::uint64_t title_map_generation_ = 0; // likewise: the map changes the passes have seen | 15236 | std::uint64_t title_map_generation_ = 0; // likewise: the map changes the passes have seen |
| 12337 | std::chrono::steady_clock::time_point title_retry_all_{}; // likewise | 15237 | std::chrono::steady_clock::time_point title_retry_all_{}; // likewise |
| 12338 | leonida::TitleWriteRanges title_map_changes_; // likewise, scratch | 15238 | leonida::TitleWriteRanges title_map_changes_; // likewise, scratch |
| @@ -12428,6 +15328,7 @@ private: | |||
| 12428 | t->layout = layout; | 15328 | t->layout = layout; |
| 12429 | t->desc = words; | 15329 | t->desc = words; |
| 12430 | t->layout_known = true; | 15330 | t->layout_known = true; |
| 15331 | state_.index_texture(*t); | ||
| 12431 | t->layout_guessed = t->layout_from_xg = false; | 15332 | t->layout_guessed = t->layout_from_xg = false; |
| 12432 | t->hashed = false; | 15333 | t->hashed = false; |
| 12433 | } else { | 15334 | } else { |
| @@ -12446,6 +15347,7 @@ private: | |||
| 12446 | rt::xg_xs::format_info(t->desc[8]).side == rt::xg_xs::format_info(words[8]).side; | 15347 | rt::xg_xs::format_info(t->desc[8]).side == rt::xg_xs::format_info(words[8]).side; |
| 12447 | }(); | 15348 | }(); |
| 12448 | retire_title_texture(*t); | 15349 | retire_title_texture(*t); |
| 15350 | state_.texture_ranges.erase(address); | ||
| 12449 | textures.erase(address); | 15351 | textures.erase(address); |
| 12450 | t = make_title_texture(d, words, srv, address, same_shape ? formats : std::vector<DXGI_FORMAT>{}); | 15352 | t = make_title_texture(d, words, srv, address, same_shape ? formats : std::vector<DXGI_FORMAT>{}); |
| 12451 | } else if (t) { | 15353 | } else if (t) { |
| @@ -12545,6 +15447,7 @@ private: | |||
| 12545 | } | 15447 | } |
| 12546 | ++title_stats_.made; | 15448 | ++title_stats_.made; |
| 12547 | TitleTexture* t = entry.get(); | 15449 | TitleTexture* t = entry.get(); |
| 15450 | state_.index_texture(*entry); | ||
| 12548 | state_.title_textures[address] = std::move(entry); | 15451 | state_.title_textures[address] = std::move(entry); |
| 12549 | if (title_fill_async() && !t->memory.pending()) queue_title_fill(address); | 15452 | if (title_fill_async() && !t->memory.pending()) queue_title_fill(address); |
| 12550 | return t; | 15453 | return t; |
| @@ -13788,7 +16691,7 @@ public: | |||
| 13788 | pipeline->attach_device(identity()); | 16691 | pipeline->attach_device(identity()); |
| 13789 | const HRESULT hr = stream.has_cs ? pipeline->create_compute(stream.compute) | 16692 | const HRESULT hr = stream.has_cs ? pipeline->create_compute(stream.compute) |
| 13790 | : pipeline->create_graphics(stream.graphics, &stream.ms, &stream.as, | 16693 | : pipeline->create_graphics(stream.graphics, &stream.ms, &stream.as, |
| 13791 | stream.back_masks ? &stream.back_stencil : nullptr); | 16694 | stream.back_masks ? &stream.back_stencil : nullptr, stream.depth_bounds); |
| 13792 | if (FAILED(hr)) { | 16695 | if (FAILED(hr)) { |
| 13793 | pipeline->Release(); | 16696 | pipeline->Release(); |
| 13794 | return finish(hr); | 16697 | return finish(hr); |
| @@ -14066,8 +16969,7 @@ public: | |||
| 14066 | words[3] = 0x0002403Cu; | 16969 | words[3] = 0x0002403Cu; |
| 14067 | } | 16970 | } |
| 14068 | std::memcpy(reinterpret_cast<void*>(destination.ptr), words.data(), sizeof(words)); | 16971 | std::memcpy(reinterpret_cast<void*>(destination.ptr), words.data(), sizeof(words)); |
| 14069 | // LOCAL DIAGNOSTIC: the CBVs the title makes, where they go and what V# they get | 16972 | if (leonida::fsdraw::enabled()) { // LOCAL DIAGNOSTIC: the CBVs the title makes, where they go and what V# they get |
| 14070 | if (leonida::local_diagnostics()) { | ||
| 14071 | static std::atomic<std::uint64_t> made{0}; | 16973 | static std::atomic<std::uint64_t> made{0}; |
| 14072 | const std::uint64_t n = ++made; | 16974 | const std::uint64_t n = ++made; |
| 14073 | if (n <= 8 || n % 600 == 0 || n % 600 == 1) | 16975 | if (n <= 8 || n % 600 == 0 || n % 600 == 1) |
| @@ -14272,8 +17174,7 @@ public: | |||
| 14272 | } | 17174 | } |
| 14273 | } | 17175 | } |
| 14274 | write_image_descriptor(*r, view, destination, ImageViewUse::sampled); | 17176 | write_image_descriptor(*r, view, destination, ImageViewUse::sampled); |
| 14275 | // LOCAL DIAGNOSTIC: the texture SRVs the title makes, where they go and the T# they get | 17177 | if (leonida::fsdraw::enabled()) { // LOCAL DIAGNOSTIC: the texture SRVs the title makes, where they go and the T# they get |
| 14276 | if (leonida::local_diagnostics()) { | ||
| 14277 | static std::atomic<std::uint64_t> made{0}; | 17178 | static std::atomic<std::uint64_t> made{0}; |
| 14278 | const std::uint64_t n = ++made; | 17179 | const std::uint64_t n = ++made; |
| 14279 | if (n <= 8 || n % 600 == 0 || n % 600 == 1) { | 17180 | if (n <= 8 || n % 600 == 0 || n % 600 == 1) { |
| @@ -14483,7 +17384,7 @@ public: | |||
| 14483 | return; | 17384 | return; |
| 14484 | } | 17385 | } |
| 14485 | const Resource* storage = r->depth_stencil_uav(view.plane); | 17386 | const Resource* storage = r->depth_stencil_uav(view.plane); |
| 14486 | const bool raw_narrow = storage && r->desc().Format == xbox_d16s8 && view.plane == 0 && | 17387 | const bool raw_narrow = storage && (r->desc().Format == xbox_d16s8 || r->console_d16s8()) && view.plane == 0 && |
| 14487 | (view.format == DXGI_FORMAT_R16_UINT || | 17388 | (view.format == DXGI_FORMAT_R16_UINT || |
| 14488 | (storage->desc().Format == DXGI_FORMAT_R16_TYPELESS && view.format == DXGI_FORMAT_R16_UNORM)); | 17389 | (storage->desc().Format == DXGI_FORMAT_R16_TYPELESS && view.format == DXGI_FORMAT_R16_UNORM)); |
| 14489 | if (!storage || (!raw_narrow && view.format != storage->desc().Format)) { | 17390 | if (!storage || (!raw_narrow && view.format != storage->desc().Format)) { |
| @@ -15219,9 +18120,17 @@ public: | |||
| 15219 | if (out) *out = nullptr; | 18120 | if (out) *out = nullptr; |
| 15220 | auto* heap = Heap::from<Heap>(heap_interface); | 18121 | auto* heap = Heap::from<Heap>(heap_interface); |
| 15221 | if (!heap || !desc) return d3d12_trace::result(method, E_INVALIDARG); | 18122 | if (!heap || !desc) return d3d12_trace::result(method, E_INVALIDARG); |
| 18123 | const bool from_xbox_d16s8 = desc->Format == xbox_d16s8; | ||
| 15222 | D3D12_RESOURCE_DESC canonical = *desc; | 18124 | D3D12_RESOURCE_DESC canonical = *desc; |
| 15223 | canonical.Format = pc_format(canonical.Format); // the console's D16S8 family as D24S8 | 18125 | canonical.Format = pc_format(canonical.Format); // the console's D16S8 family as D24S8 |
| 15224 | desc = &canonical; | 18126 | desc = &canonical; |
| 18127 | // Its clear value too, or the clear format's family (118) would not match the resource's (D24S8) below. | ||
| 18128 | D3D12_CLEAR_VALUE canonical_clear{}; | ||
| 18129 | if (clear) { | ||
| 18130 | canonical_clear = *clear; | ||
| 18131 | canonical_clear.Format = pc_format(canonical_clear.Format); | ||
| 18132 | clear = &canonical_clear; | ||
| 18133 | } | ||
| 15225 | if (heap->host_address()) { | 18134 | if (heap->host_address()) { |
| 15226 | // An existing heap is not an arena range, and the placed path addresses resources by arena offset. | 18135 | // An existing heap is not an arena range, and the placed path addresses resources by arena offset. |
| 15227 | log_once("a placed resource in an existing heap (OpenExistingHeapFromAddress) is not supported yet; " | 18136 | log_once("a placed resource in an existing heap (OpenExistingHeapFromAddress) is not supported yet; " |
| @@ -15309,6 +18218,7 @@ public: | |||
| 15309 | // create_texture makes for 1D, 2D and 3D alike (arrays and mips included), as for a committed texture. | 18218 | // create_texture makes for 1D, 2D and 3D alike (arrays and mips included), as for a committed texture. |
| 15310 | const VkDeviceSize placed_va = desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? heap->offset() + heap_offset : 0; | 18219 | const VkDeviceSize placed_va = desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? heap->offset() + heap_offset : 0; |
| 15311 | auto* resource = new Resource(state_, *desc, heap->properties(), heap->flags(), placed_va); | 18220 | auto* resource = new Resource(state_, *desc, heap->properties(), heap->flags(), placed_va); |
| 18221 | if (from_xbox_d16s8) resource->mark_console_d16s8(); | ||
| 15312 | resource->attach_device(identity()); | 18222 | resource->attach_device(identity()); |
| 15313 | HRESULT hr = E_NOTIMPL; | 18223 | HRESULT hr = E_NOTIMPL; |
| 15314 | if (buffer) { | 18224 | if (buffer) { |
| @@ -15320,7 +18230,8 @@ public: | |||
| 15320 | hr = E_INVALIDARG; | 18230 | hr = E_INVALIDARG; |
| 15321 | } else { | 18231 | } else { |
| 15322 | std::vector<VkFormat> cast_formats; | 18232 | std::vector<VkFormat> cast_formats; |
| 15323 | hr = castable_view_formats(format, desc->Format, castable_count, castable, cast_formats); | 18233 | hr = castable_view_formats(format, desc->Format, castable_count, castable, cast_formats, false, |
| 18234 | from_xbox_d16s8); | ||
| 15324 | if (SUCCEEDED(hr)) hr = resource->create_texture(format, cast_formats); | 18235 | if (SUCCEEDED(hr)) hr = resource->create_texture(format, cast_formats); |
| 15325 | if (SUCCEEDED(hr)) resource->keep_castable_formats(castable_count, castable); | 18236 | if (SUCCEEDED(hr)) resource->keep_castable_formats(castable_count, castable); |
| 15326 | } | 18237 | } |
| @@ -15580,7 +18491,7 @@ public: | |||
| 15580 | if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS2)) return d3d12_trace::result(method, E_INVALIDARG); | 18491 | if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS2)) return d3d12_trace::result(method, E_INVALIDARG); |
| 15581 | auto* opts = static_cast<D3D12_FEATURE_DATA_D3D12_OPTIONS2*>(data); | 18492 | auto* opts = static_cast<D3D12_FEATURE_DATA_D3D12_OPTIONS2*>(data); |
| 15582 | *opts = {}; | 18493 | *opts = {}; |
| 15583 | opts->DepthBoundsTestSupported = FALSE; | 18494 | opts->DepthBoundsTestSupported = state_.info.features.depthBounds ? TRUE : FALSE; |
| 15584 | opts->ProgrammableSamplePositionsTier = D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_NOT_SUPPORTED; | 18495 | opts->ProgrammableSamplePositionsTier = D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_NOT_SUPPORTED; |
| 15585 | return d3d12_trace::result(method, S_OK); | 18496 | return d3d12_trace::result(method, S_OK); |
| 15586 | } | 18497 | } |
| @@ -16588,6 +19499,7 @@ private: | |||
| 16588 | TitleImageOrigin origin = TitleImageOrigin::ordinary) { | 19499 | TitleImageOrigin origin = TitleImageOrigin::ordinary) { |
| 16589 | if (out) *out = nullptr; | 19500 | if (out) *out = nullptr; |
| 16590 | if (!heap || !desc) return E_INVALIDARG; | 19501 | if (!heap || !desc) return E_INVALIDARG; |
| 19502 | const bool from_xbox_d16s8 = desc->Format == xbox_d16s8; | ||
| 16591 | D3D12_RESOURCE_DESC canonical = *desc; | 19503 | D3D12_RESOURCE_DESC canonical = *desc; |
| 16592 | canonical.Format = pc_format(canonical.Format); // the console's D16S8 family as D24S8 | 19504 | canonical.Format = pc_format(canonical.Format); // the console's D16S8 family as D24S8 |
| 16593 | desc = &canonical; | 19505 | desc = &canonical; |
| @@ -16596,6 +19508,7 @@ private: | |||
| 16596 | return E_INVALIDARG; | 19508 | return E_INVALIDARG; |
| 16597 | } | 19509 | } |
| 16598 | auto* resource = new Resource(state_, *desc, *heap, heap_flags); | 19510 | auto* resource = new Resource(state_, *desc, *heap, heap_flags); |
| 19511 | if (from_xbox_d16s8) resource->mark_console_d16s8(); | ||
| 16599 | resource->attach_device(identity()); | 19512 | resource->attach_device(identity()); |
| 16600 | HRESULT hr = E_NOTIMPL; | 19513 | HRESULT hr = E_NOTIMPL; |
| 16601 | if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { | 19514 | if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { |
| @@ -16632,7 +19545,8 @@ private: | |||
| 16632 | hr = E_INVALIDARG; | 19545 | hr = E_INVALIDARG; |
| 16633 | } else { | 19546 | } else { |
| 16634 | std::vector<VkFormat> cast_formats; | 19547 | std::vector<VkFormat> cast_formats; |
| 16635 | hr = castable_view_formats(format, desc->Format, castable_count, castable, cast_formats, storage_heap_flags.has_value()); | 19548 | hr = castable_view_formats(format, desc->Format, castable_count, castable, cast_formats, |
| 19549 | storage_heap_flags.has_value(), from_xbox_d16s8); | ||
| 16636 | if (SUCCEEDED(hr)) hr = resource->create_texture(format, cast_formats, origin); | 19550 | if (SUCCEEDED(hr)) hr = resource->create_texture(format, cast_formats, origin); |
| 16637 | if (SUCCEEDED(hr)) resource->keep_castable_formats(castable_count, castable); | 19551 | if (SUCCEEDED(hr)) resource->keep_castable_formats(castable_count, castable); |
| 16638 | if (SUCCEEDED(hr) && storage_heap_flags) hr = resource->enable_depth_stencil_uav(*storage_heap_flags); | 19552 | if (SUCCEEDED(hr) && storage_heap_flags) hr = resource->enable_depth_stencil_uav(*storage_heap_flags); |
| @@ -16906,6 +19820,60 @@ bool stop_pipeline_compiles(unsigned wait_ms) { | |||
| 16906 | return idle; | 19820 | return idle; |
| 16907 | } | 19821 | } |
| 16908 | 19822 | ||
| 19823 | // How long an exit save waits for the write itself (save_session_pipeline_cache): a 77 MiB cache was measured at about | ||
| 19824 | // 36 ms (fill and publish), so this only bounds a driver that blocks the read. | ||
| 19825 | constexpr unsigned kExitCacheWriteMs = 3000; | ||
| 19826 | |||
| 19827 | bool save_pipeline_caches_at_exit(unsigned wait_ms) { | ||
| 19828 | if (exit_cache_saved.exchange(true)) return false; // once: a crash during the normal exit's save does not redo it | ||
| 19829 | std::unique_lock lock(exit_cache_mutex, std::defer_lock); | ||
| 19830 | if (!lock.try_lock_for(std::chrono::milliseconds(wait_ms))) { | ||
| 19831 | std::fprintf(stderr, "[rt] d3d12: device list busy for %u ms at exit; pipeline_cache.session.bin not written\n", | ||
| 19832 | wait_ms); | ||
| 19833 | return false; | ||
| 19834 | } | ||
| 19835 | bool wrote = false; | ||
| 19836 | const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(wait_ms); | ||
| 19837 | for (DeviceState* d : exit_cache_devices) { | ||
| 19838 | if (!d->context || !d->pipeline_cache_handle) continue; | ||
| 19839 | // A build still running (a large one takes minutes; at a crash the faulting thread may be inside one) is | ||
| 19840 | // given until the deadline, then the cache is written without it. Unlike at teardown, the previous file is | ||
| 19841 | // not kept instead: the process is ending, so waiting longer is not possible and keeping the old file throws | ||
| 19842 | // away everything this run compiled (measured: a 1,308 s boot that ended in a title fault with 2 builds | ||
| 19843 | // running). The cache is not created EXTERNALLY_SYNCHRONIZED, so reading it during a build is valid; the | ||
| 19844 | // snapshot holds the pipelines finished so far. | ||
| 19845 | while (d->active_compiles.load() && std::chrono::steady_clock::now() < deadline) | ||
| 19846 | std::this_thread::sleep_for(std::chrono::milliseconds(5)); | ||
| 19847 | if (const unsigned building = d->active_compiles.load()) | ||
| 19848 | std::fprintf(stderr, "[rt] d3d12: %u pipeline build(s) still running at exit; writing the pipelines " | ||
| 19849 | "finished so far\n", building); | ||
| 19850 | // On a thread of its own: a driver that holds the cache until a build ends would otherwise hold the ending | ||
| 19851 | // process too. Past the deadline the process goes on ending; the file is published by a rename | ||
| 19852 | // (CacheStagingFile), so a write cut off there leaves the previous file whole. | ||
| 19853 | struct Write { | ||
| 19854 | std::mutex mutex; | ||
| 19855 | std::condition_variable done_cv; | ||
| 19856 | bool done = false; | ||
| 19857 | }; | ||
| 19858 | auto write = std::make_shared<Write>(); | ||
| 19859 | std::thread([write, d] { | ||
| 19860 | save_session_pipeline_cache(d->context->vk, d->info.device, d->pipeline_cache_handle, false, "exit"); | ||
| 19861 | std::lock_guard done_lock(write->mutex); | ||
| 19862 | write->done = true; | ||
| 19863 | write->done_cv.notify_all(); | ||
| 19864 | }).detach(); | ||
| 19865 | std::unique_lock write_lock(write->mutex); | ||
| 19866 | if (!write->done_cv.wait_for(write_lock, std::chrono::milliseconds(kExitCacheWriteMs), | ||
| 19867 | [&] { return write->done; })) { | ||
| 19868 | std::fprintf(stderr, "[rt] d3d12: pipeline cache still being written after %u ms at exit; the process " | ||
| 19869 | "ends without waiting for it\n", kExitCacheWriteMs); | ||
| 19870 | return wrote; // the device list stays as it is: the write still uses this device | ||
| 19871 | } | ||
| 19872 | wrote = true; | ||
| 19873 | } | ||
| 19874 | return wrote; | ||
| 19875 | } | ||
| 19876 | |||
| 16909 | HRESULT create_vulkan_device(const VulkanDeviceInfo& info, REFIID riid, void** out) { | 19877 | HRESULT create_vulkan_device(const VulkanDeviceInfo& info, REFIID riid, void** out) { |
| 16910 | if (!out) return E_POINTER; | 19878 | if (!out) return E_POINTER; |
| 16911 | *out = nullptr; | 19879 | *out = nullptr; |
| @@ -17042,11 +20010,28 @@ std::uintptr_t graphics_pipeline_id(ID3D12PipelineState* pipeline) { | |||
| 17042 | return p && p->resolve_type(true) ? p->id() : 0; | 20010 | return p && p->resolve_type(true) ? p->id() : 0; |
| 17043 | } | 20011 | } |
| 17044 | 20012 | ||
| 20013 | void request_pipeline_build(std::uintptr_t id, std::uint32_t bound_targets, bool depth_bound) { | ||
| 20014 | if (!id || !async_replay_compile()) return; | ||
| 20015 | // The id is the PSO's own ID3D12PipelineState pointer (PipelineState::id), which the list keeps a reference to. | ||
| 20016 | auto* pso = static_cast<PipelineState*>(reinterpret_cast<ID3D12PipelineState*>(id)); | ||
| 20017 | pso->request_early(bound_targets, depth_bound); | ||
| 20018 | } | ||
| 20019 | |||
| 17045 | const std::vector<leonida::SubgroupRequest>* pipeline_subgroup_requests(ID3D12PipelineState* pipeline) { | 20020 | const std::vector<leonida::SubgroupRequest>* pipeline_subgroup_requests(ID3D12PipelineState* pipeline) { |
| 17046 | const PipelineState* p = PipelineState::from<PipelineState>(pipeline); | 20021 | const PipelineState* p = PipelineState::from<PipelineState>(pipeline); |
| 17047 | return p && (p->compute() || p->graphics()) ? &p->subgroup_requests() : nullptr; | 20022 | return p && (p->compute() || p->graphics()) ? &p->subgroup_requests() : nullptr; |
| 17048 | } | 20023 | } |
| 17049 | 20024 | ||
| 20025 | bool pipeline_stage_words(ID3D12PipelineState* pipeline, std::vector<std::vector<std::uint32_t>>& words, | ||
| 20026 | std::string& why) { | ||
| 20027 | const PipelineState* p = PipelineState::from<PipelineState>(pipeline); | ||
| 20028 | if (!p) { | ||
| 20029 | why = "not a PipelineState"; | ||
| 20030 | return false; | ||
| 20031 | } | ||
| 20032 | return p->stage_words(words, why); | ||
| 20033 | } | ||
| 20034 | |||
| 17050 | long live_pipeline_states() { return live_pipeline_state_count.load(); } | 20035 | long live_pipeline_states() { return live_pipeline_state_count.load(); } |
| 17051 | 20036 | ||
| 17052 | bool write_placed_buffer_view(ID3D12Device* device, bool unordered, const void* view, std::uint64_t address, | 20037 | bool write_placed_buffer_view(ID3D12Device* device, bool unordered, const void* view, std::uint64_t address, |
| @@ -17069,6 +20054,10 @@ D3D12_GPU_VIRTUAL_ADDRESS console_descriptor_table_va(D3D12_GPU_VIRTUAL_ADDRESS | |||
| 17069 | return console_heap_ranges().shader_va(va); | 20054 | return console_heap_ranges().shader_va(va); |
| 17070 | } | 20055 | } |
| 17071 | 20056 | ||
| 20057 | bool console_descriptor_heap_range(D3D12_GPU_VIRTUAL_ADDRESS va, std::uint64_t& console_va, std::uint64_t& bytes) { | ||
| 20058 | return console_heap_ranges().range_of(va, console_va, bytes); | ||
| 20059 | } | ||
| 20060 | |||
| 17072 | // The device a command list of this module belongs to: its attached device is the d3d12_xs proxy when the title made | 20061 | // The device a command list of this module belongs to: its attached device is the d3d12_xs proxy when the title made |
| 17073 | // the list through one (Device::identity), which does not answer Device's tag itself. | 20062 | // the list through one (Device::identity), which does not answer Device's tag itself. |
| 17074 | Device* list_device(IUnknown* device) { | 20063 | Device* list_device(IUnknown* device) { |
| @@ -17158,6 +20147,11 @@ const VulkanDeviceInfo* vulkan_device_info(ID3D12Device* device) { | |||
| 17158 | return nullptr; | 20147 | return nullptr; |
| 17159 | } | 20148 | } |
| 17160 | 20149 | ||
| 20150 | leonida::VramBudget vulkan_vram_budget(ID3D12Device* device) { | ||
| 20151 | const VulkanDeviceInfo* info = vulkan_device_info(device); | ||
| 20152 | return info ? read_vram_budget(*info) : leonida::VramBudget{}; | ||
| 20153 | } | ||
| 20154 | |||
| 17161 | std::uint64_t title_shadow_refresh_queries(ID3D12Device* device) { | 20155 | std::uint64_t title_shadow_refresh_queries(ID3D12Device* device) { |
| 17162 | auto* d = Device::from<Device>(device); | 20156 | auto* d = Device::from<Device>(device); |
| 17163 | if (!d) return 0; | 20157 | if (!d) return 0; |
| @@ -17794,6 +20788,10 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin | |||
| 17794 | VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR}; | 20788 | VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR}; |
| 17795 | VkPhysicalDeviceRayQueryFeaturesKHR rq_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_QUERY_FEATURES_KHR}; | 20789 | VkPhysicalDeviceRayQueryFeaturesKHR rq_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_QUERY_FEATURES_KHR}; |
| 17796 | VkPhysicalDeviceMeshShaderFeaturesEXT mesh_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT}; | 20790 | VkPhysicalDeviceMeshShaderFeaturesEXT mesh_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT}; |
| 20791 | VkPhysicalDeviceTransformFeedbackFeaturesEXT transform_feedback_features{ | ||
| 20792 | VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_FEATURES_EXT}; | ||
| 20793 | VkPhysicalDeviceTransformFeedbackPropertiesEXT transform_feedback_properties{ | ||
| 20794 | VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_PROPERTIES_EXT}; | ||
| 17797 | { | 20795 | { |
| 17798 | std::uint32_t extension_count = 0; | 20796 | std::uint32_t extension_count = 0; |
| 17799 | vkEnumerateDeviceExtensionProperties(info.physical, nullptr, &extension_count, nullptr); | 20797 | vkEnumerateDeviceExtensionProperties(info.physical, nullptr, &extension_count, nullptr); |
| @@ -17818,10 +20816,28 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin | |||
| 17818 | vkGetPhysicalDeviceFeatures2(info.physical, &features); | 20816 | vkGetPhysicalDeviceFeatures2(info.physical, &features); |
| 17819 | info.mesh_shader = mesh_features.meshShader == VK_TRUE; | 20817 | info.mesh_shader = mesh_features.meshShader == VK_TRUE; |
| 17820 | info.mesh_shader_queries = mesh_features.meshShaderQueries == VK_TRUE; | 20818 | info.mesh_shader_queries = mesh_features.meshShaderQueries == VK_TRUE; |
| 20819 | } else if (!std::strcmp(e.extensionName, VK_EXT_TRANSFORM_FEEDBACK_EXTENSION_NAME)) { | ||
| 20820 | VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, | ||
| 20821 | &transform_feedback_features}; | ||
| 20822 | vkGetPhysicalDeviceFeatures2(info.physical, &features); | ||
| 20823 | info.transform_feedback = transform_feedback_features.transformFeedback == VK_TRUE; | ||
| 20824 | info.transform_feedback_geometry_streams = transform_feedback_features.geometryStreams == VK_TRUE; | ||
| 20825 | // D3D-302: the queries and the stream count are properties, not features. | ||
| 20826 | VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, | ||
| 20827 | &transform_feedback_properties}; | ||
| 20828 | vkGetPhysicalDeviceProperties2(info.physical, &properties); | ||
| 20829 | info.transform_feedback_queries = transform_feedback_properties.transformFeedbackQueries == VK_TRUE; | ||
| 20830 | info.max_transform_feedback_streams = transform_feedback_properties.maxTransformFeedbackStreams; | ||
| 17821 | } | 20831 | } |
| 17822 | } | 20832 | } |
| 17823 | if (!info.mesh_shader) | 20833 | if (!info.mesh_shader) |
| 17824 | std::fprintf(stderr, "[rt] d3d12: the GPU has no VK_EXT_mesh_shader: mesh-shader PSOs are unsupported\n"); | 20834 | std::fprintf(stderr, "[rt] d3d12: the GPU has no VK_EXT_mesh_shader: mesh-shader PSOs are unsupported\n"); |
| 20835 | if (!info.transform_feedback) | ||
| 20836 | std::fprintf(stderr, | ||
| 20837 | "[rt] d3d12: the GPU has no VK_EXT_transform_feedback: SO_STATISTICS query pools read zero\n"); | ||
| 20838 | else if (!info.transform_feedback_queries || !info.max_transform_feedback_streams) | ||
| 20839 | std::fprintf(stderr, "[rt] d3d12: the GPU has no transform-feedback queries (transformFeedbackQueries, " | ||
| 20840 | "maxTransformFeedbackStreams): SO_STATISTICS query pools read zero\n"); | ||
| 17825 | if (has_as && has_dho && has_rq && chosen12.bufferDeviceAddress) { | 20841 | if (has_as && has_dho && has_rq && chosen12.bufferDeviceAddress) { |
| 17826 | as_features.pNext = &rq_features; | 20842 | as_features.pNext = &rq_features; |
| 17827 | VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &as_features}; | 20843 | VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &as_features}; |
| @@ -17857,11 +20873,22 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin | |||
| 17857 | // The mesh-primitives query, which counts the primitives a mesh shader emits (D3D-MESH-CLIPPING-COUNTER). | 20873 | // The mesh-primitives query, which counts the primitives a mesh shader emits (D3D-MESH-CLIPPING-COUNTER). |
| 17858 | enable_mesh.meshShaderQueries = info.mesh_shader_queries ? VK_TRUE : VK_FALSE; | 20874 | enable_mesh.meshShaderQueries = info.mesh_shader_queries ? VK_TRUE : VK_FALSE; |
| 17859 | 20875 | ||
| 20876 | // D3D-302: real SO_STATISTICS queries need transformFeedback; geometryStreams is only requested when the device | ||
| 20877 | // already offers it, so the enable chain matches vk_pipeline_check's (a driver keys the pipeline cache on it). | ||
| 20878 | VkPhysicalDeviceTransformFeedbackFeaturesEXT enable_transform_feedback{ | ||
| 20879 | VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_FEATURES_EXT}; | ||
| 20880 | enable_transform_feedback.transformFeedback = VK_TRUE; | ||
| 20881 | enable_transform_feedback.geometryStreams = info.transform_feedback_geometry_streams ? VK_TRUE : VK_FALSE; | ||
| 20882 | |||
| 17860 | void* ext_chain = nullptr; | 20883 | void* ext_chain = nullptr; |
| 17861 | if (info.mesh_shader) { | 20884 | if (info.mesh_shader) { |
| 17862 | enable_mesh.pNext = ext_chain; | 20885 | enable_mesh.pNext = ext_chain; |
| 17863 | ext_chain = &enable_mesh; | 20886 | ext_chain = &enable_mesh; |
| 17864 | } | 20887 | } |
| 20888 | if (info.transform_feedback) { | ||
| 20889 | enable_transform_feedback.pNext = ext_chain; | ||
| 20890 | ext_chain = &enable_transform_feedback; | ||
| 20891 | } | ||
| 17865 | if (info.ray_tracing) { | 20892 | if (info.ray_tracing) { |
| 17866 | enable_rq.pNext = ext_chain; | 20893 | enable_rq.pNext = ext_chain; |
| 17867 | enable_as.pNext = &enable_rq; | 20894 | enable_as.pNext = &enable_rq; |
| @@ -18192,6 +21219,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin | |||
| 18192 | enable.logicOp = chosen_features.logicOp; | 21219 | enable.logicOp = chosen_features.logicOp; |
| 18193 | enable.depthClamp = chosen_features.depthClamp; | 21220 | enable.depthClamp = chosen_features.depthClamp; |
| 18194 | enable.multiViewport = chosen_features.multiViewport; | 21221 | enable.multiViewport = chosen_features.multiViewport; |
| 21222 | enable.depthBounds = chosen_features.depthBounds; // DEPTH_STENCIL1/2 DepthBoundsTestEnable, OMSetDepthBounds | ||
| 18195 | enable.geometryShader = chosen_features.geometryShader; // translated geometry shaders (195 in the corpus) | 21223 | enable.geometryShader = chosen_features.geometryShader; // translated geometry shaders (195 in the corpus) |
| 18196 | // What translated shaders declare (the index's `features`): 64-bit integers in most of the corpus (25,803 of | 21224 | // What translated shaders declare (the index's `features`): 64-bit integers in most of the corpus (25,803 of |
| 18197 | // 26,503 entries), doubles, 16-bit integers, clip and cull distances in a few vertex shaders, formatless image | 21225 | // 26,503 entries), doubles, 16-bit integers, clip and cull distances in a few vertex shaders, formatless image |
| @@ -18332,6 +21360,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin | |||
| 18332 | v13.add_extensions(device_extensions); | 21360 | v13.add_extensions(device_extensions); |
| 18333 | if (info.depth_range_unrestricted) device_extensions.push_back(VK_EXT_DEPTH_RANGE_UNRESTRICTED_EXTENSION_NAME); | 21361 | if (info.depth_range_unrestricted) device_extensions.push_back(VK_EXT_DEPTH_RANGE_UNRESTRICTED_EXTENSION_NAME); |
| 18334 | info.pipeline_creation_feedback = v13.core || has_device_extension(VK_EXT_PIPELINE_CREATION_FEEDBACK_EXTENSION_NAME); | 21362 | info.pipeline_creation_feedback = v13.core || has_device_extension(VK_EXT_PIPELINE_CREATION_FEEDBACK_EXTENSION_NAME); |
| 21363 | info.pipeline_cache_control = v13.core && v13.pipeline_creation_cache_control; | ||
| 18335 | if (trace_pipeline_compile() && !v13.core && info.pipeline_creation_feedback) | 21364 | if (trace_pipeline_compile() && !v13.core && info.pipeline_creation_feedback) |
| 18336 | device_extensions.push_back(VK_EXT_PIPELINE_CREATION_FEEDBACK_EXTENSION_NAME); | 21365 | device_extensions.push_back(VK_EXT_PIPELINE_CREATION_FEEDBACK_EXTENSION_NAME); |
| 18337 | if (info.conservative_rasterization) device_extensions.push_back(VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME); | 21366 | if (info.conservative_rasterization) device_extensions.push_back(VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME); |
| @@ -18364,6 +21393,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin | |||
| 18364 | if (has_swapchain && instance_has_surface) device_extensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME); | 21393 | if (has_swapchain && instance_has_surface) device_extensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME); |
| 18365 | if (swapchain_m1_name) device_extensions.push_back(swapchain_m1_name); | 21394 | if (swapchain_m1_name) device_extensions.push_back(swapchain_m1_name); |
| 18366 | if (info.mesh_shader) device_extensions.push_back(VK_EXT_MESH_SHADER_EXTENSION_NAME); | 21395 | if (info.mesh_shader) device_extensions.push_back(VK_EXT_MESH_SHADER_EXTENSION_NAME); |
| 21396 | if (info.transform_feedback) device_extensions.push_back(VK_EXT_TRANSFORM_FEEDBACK_EXTENSION_NAME); | ||
| 18367 | if (info.ray_tracing) { | 21397 | if (info.ray_tracing) { |
| 18368 | device_extensions.push_back(VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME); | 21398 | device_extensions.push_back(VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME); |
| 18369 | device_extensions.push_back(VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME); | 21399 | device_extensions.push_back(VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME); |
| @@ -18374,18 +21404,28 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin | |||
| 18374 | if (info.custom_border_color) device_extensions.push_back(custom_border_name); | 21404 | if (info.custom_border_color) device_extensions.push_back(custom_border_name); |
| 18375 | if (info.null_descriptor || info.robust_index_view) device_extensions.push_back(VK_EXT_ROBUSTNESS_2_EXTENSION_NAME); | 21405 | if (info.null_descriptor || info.robust_index_view) device_extensions.push_back(VK_EXT_ROBUSTNESS_2_EXTENSION_NAME); |
| 18376 | if (info.host_pointer_alignment) device_extensions.push_back(VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME); | 21406 | if (info.host_pointer_alignment) device_extensions.push_back(VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME); |
| 21407 | // Optional: VK_EXT_memory_budget gives the GPU memory in use and the budget (vulkan_vram_budget, the title HUD). | ||
| 21408 | info.memory_budget = has_device_extension(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME); | ||
| 21409 | if (info.memory_budget) device_extensions.push_back(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME); | ||
| 18377 | leonida::DeviceFaultFeatures fault_features; | 21410 | leonida::DeviceFaultFeatures fault_features; |
| 18378 | const bool aftermath = leonida::aftermath::enable(); // already on, before the instance: see above | 21411 | const bool aftermath = leonida::aftermath::enable(); // already on, before the instance: see above |
| 18379 | char device_fault[2]{}; | 21412 | char device_fault[2]{}; |
| 21413 | // LEONIDA_DEVICE_FAULT=1: fault info, checkpoints and NVIDIA's diagnostics config. =2: fault info and checkpoints | ||
| 21414 | // only — the diagnostics config compiles pipelines with debug info under other cache keys, so =2 keeps the warmed | ||
| 21415 | // pipeline journal usable for a boot that only wants the fault report. | ||
| 18380 | if (GetEnvironmentVariableA("LEONIDA_DEVICE_FAULT", device_fault, sizeof(device_fault)) == 1 && | 21416 | if (GetEnvironmentVariableA("LEONIDA_DEVICE_FAULT", device_fault, sizeof(device_fault)) == 1 && |
| 18381 | device_fault[0] == '1') { | 21417 | (device_fault[0] == '1' || device_fault[0] == '2')) { |
| 18382 | info.device_fault_diagnostics = true; | 21418 | info.device_fault_diagnostics = true; |
| 21419 | const bool with_config = device_fault[0] == '1'; | ||
| 21420 | // LEONIDA_DEVICE_MARKERS=1: also VK_AMD_buffer_marker, for the AMD breadcrumbs (vulkan_device_markers.h). | ||
| 18383 | const auto fault = fault_features.enable(info.physical, vkGetPhysicalDeviceFeatures2, extensions, | 21421 | const auto fault = fault_features.enable(info.physical, vkGetPhysicalDeviceFeatures2, extensions, |
| 18384 | device_extensions, device_info, | 21422 | device_extensions, device_info, |
| 18385 | {true, true, leonida::aftermath::extra_config_flags()}); | 21423 | {true, with_config, leonida::aftermath::extra_config_flags(), |
| 21424 | leonida::device_markers_requested()}); | ||
| 18386 | info.device_fault_info = fault.fault; | 21425 | info.device_fault_info = fault.fault; |
| 18387 | info.device_checkpoints = fault.checkpoints; | 21426 | info.device_checkpoints = fault.checkpoints; |
| 18388 | info.device_diagnostics_config = fault.diagnostics_config; | 21427 | info.device_diagnostics_config = fault.diagnostics_config; |
| 21428 | info.device_markers = fault.markers; | ||
| 18389 | } else if (aftermath) { | 21429 | } else if (aftermath) { |
| 18390 | // The diagnostics config alone: shader debug info, resource tracking and automatic checkpoints in the dump. | 21430 | // The diagnostics config alone: shader debug info, resource tracking and automatic checkpoints in the dump. |
| 18391 | const auto fault = fault_features.enable(info.physical, vkGetPhysicalDeviceFeatures2, extensions, | 21431 | const auto fault = fault_features.enable(info.physical, vkGetPhysicalDeviceFeatures2, extensions, |
| @@ -18393,6 +21433,9 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin | |||
| 18393 | {false, true, leonida::aftermath::extra_config_flags()}); | 21433 | {false, true, leonida::aftermath::extra_config_flags()}); |
| 18394 | info.device_diagnostics_config = fault.diagnostics_config; | 21434 | info.device_diagnostics_config = fault.diagnostics_config; |
| 18395 | } | 21435 | } |
| 21436 | if (leonida::device_markers_requested() && !info.device_fault_diagnostics) | ||
| 21437 | std::fprintf(stderr, "[rt] device-markers: unavailable: LEONIDA_DEVICE_MARKERS=1 needs LEONIDA_DEVICE_FAULT=1 " | ||
| 21438 | "or 2\n"); | ||
| 18396 | if (aftermath && !info.device_diagnostics_config) | 21439 | if (aftermath && !info.device_diagnostics_config) |
| 18397 | std::fprintf(stderr, "[rt] aftermath: VK_NV_device_diagnostics_config unavailable; the dump has no shader " | 21440 | std::fprintf(stderr, "[rt] aftermath: VK_NV_device_diagnostics_config unavailable; the dump has no shader " |
| 18398 | "debug info, resource tracking or checkpoints\n"); | 21441 | "debug info, resource tracking or checkpoints\n"); |
| @@ -18449,6 +21492,532 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin | |||
| 18449 | return hand_out(device, riid, out); | 21492 | return hand_out(device, riid, out); |
| 18450 | } | 21493 | } |
| 18451 | 21494 | ||
| 21495 | // A Vulkan device made as `gta6rt --run` makes it, for building the library's compute pipelines with no title | ||
| 21496 | // (--precompile-pipelines, --compile-server), with the two layouts create_compute makes. | ||
| 21497 | class BuildHost { | ||
| 21498 | public: | ||
| 21499 | explicit BuildHost(const char* tag) : tag_(tag) {} | ||
| 21500 | BuildHost(const BuildHost&) = delete; | ||
| 21501 | BuildHost& operator=(const BuildHost&) = delete; | ||
| 21502 | ~BuildHost() { | ||
| 21503 | if (!d3d_) return; | ||
| 21504 | if (device_) { | ||
| 21505 | auto& vk = device_->context->vk; | ||
| 21506 | if (plain_) vk.vkDestroyPipelineLayout(device_->info.device, plain_, nullptr); | ||
| 21507 | if (with_set0_) vk.vkDestroyPipelineLayout(device_->info.device, with_set0_, nullptr); | ||
| 21508 | } | ||
| 21509 | d3d_->Release(); | ||
| 21510 | } | ||
| 21511 | |||
| 21512 | bool open() { | ||
| 21513 | // The GPU address arena holds nothing here and does not change a pipeline: 64 MB, not a title's 2 GB. | ||
| 21514 | _putenv_s("LEONIDA_ARENA_MB", "64"); | ||
| 21515 | compile_helper::build_host = true; | ||
| 21516 | if (FAILED(create_vulkan_device_standalone(__uuidof(ID3D12Device), reinterpret_cast<void**>(&d3d_), | ||
| 21517 | QueueTestSettings::ignore)) || !d3d_) { | ||
| 21518 | d3d_ = nullptr; | ||
| 21519 | std::fprintf(stderr, "%s the Vulkan device could not be created\n", tag_); | ||
| 21520 | return false; | ||
| 21521 | } | ||
| 21522 | Device* device = Device::from<Device>(d3d_); | ||
| 21523 | if (!device) return false; | ||
| 21524 | device_ = &device->build_state(); | ||
| 21525 | DeviceState& state = *device_; | ||
| 21526 | library_ = state.library(); | ||
| 21527 | if (!library_) { | ||
| 21528 | std::fprintf(stderr, "%s no translated shader library (LEONIDA_SHADERS)\n", tag_); | ||
| 21529 | return false; | ||
| 21530 | } | ||
| 21531 | if (pipeline_journal_dir().empty()) | ||
| 21532 | std::fprintf(stderr, "%s the pipeline journal is off (LEONIDA_PIPELINE_JOURNAL=0 or " | ||
| 21533 | "LEONIDA_PIPELINE_CACHE_BYTES=0): only the driver's own cache is filled\n", tag_); | ||
| 21534 | state.pipeline_cache(); // the shared cache and the journal's upkeep, as at a title's first pipeline | ||
| 21535 | // Every pipeline goes into a journal file: one found in the shared cache would not be. | ||
| 21536 | state.journal_ask_shared = false; | ||
| 21537 | auto& vk = state.context->vk; | ||
| 21538 | const VkDevice dev = state.info.device; | ||
| 21539 | if (state.info.max_push_constants_size && state.info.max_push_constants_size < sizeof(leonida::ShaderUserData)) { | ||
| 21540 | std::fprintf(stderr, "%s maxPushConstantsSize %u is under the shaders' %zu bytes: the runtime builds no " | ||
| 21541 | "compute pipeline on this device\n", | ||
| 21542 | tag_, state.info.max_push_constants_size, sizeof(leonida::ShaderUserData)); | ||
| 21543 | return false; | ||
| 21544 | } | ||
| 21545 | const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(leonida::ShaderUserData)}; | ||
| 21546 | VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; | ||
| 21547 | layout_info.pushConstantRangeCount = 1; | ||
| 21548 | layout_info.pPushConstantRanges = &push; | ||
| 21549 | if (vk.vkCreatePipelineLayout(dev, &layout_info, nullptr, &plain_) != VK_SUCCESS) return false; | ||
| 21550 | if (state.bindless) { | ||
| 21551 | const VkDescriptorSetLayout set0 = state.bindless->layout(); | ||
| 21552 | layout_info.setLayoutCount = 1; | ||
| 21553 | layout_info.pSetLayouts = &set0; | ||
| 21554 | if (vk.vkCreatePipelineLayout(dev, &layout_info, nullptr, &with_set0_) != VK_SUCCESS) | ||
| 21555 | with_set0_ = VK_NULL_HANDLE; | ||
| 21556 | } | ||
| 21557 | if (const auto get_props = reinterpret_cast<PFN_vkGetPhysicalDeviceProperties>( | ||
| 21558 | state.info.get_instance_proc | ||
| 21559 | ? state.info.get_instance_proc(state.info.instance, "vkGetPhysicalDeviceProperties") | ||
| 21560 | : nullptr)) { | ||
| 21561 | VkPhysicalDeviceProperties props{}; | ||
| 21562 | get_props(state.info.physical, &props); | ||
| 21563 | max_shared_ = props.limits.maxComputeSharedMemorySize; | ||
| 21564 | } | ||
| 21565 | return true; | ||
| 21566 | } | ||
| 21567 | |||
| 21568 | DeviceState& state() { return *device_; } | ||
| 21569 | const leonida::ShaderLibrary* library() const { return library_; } | ||
| 21570 | |||
| 21571 | // Why create_compute would refuse the entry, or null. | ||
| 21572 | const char* unbuildable(const leonida::ShaderEntry& entry, std::size_t bytes) const { | ||
| 21573 | if (!bytes) return "no .spv"; | ||
| 21574 | if (skip_compute(entry.name)) return "LEONIDA_SKIP_COMPUTE"; | ||
| 21575 | if (entry.binding_count && !with_set0_) return "set-0 bindings and no bindless set"; | ||
| 21576 | if (entry.lds_bytes && max_shared_ && entry.lds_bytes > max_shared_) return "workgroup memory over the limit"; | ||
| 21577 | return nullptr; | ||
| 21578 | } | ||
| 21579 | |||
| 21580 | ComputeBuild build(const leonida::ShaderEntry& entry, const ComputeBuildOptions& options) { | ||
| 21581 | const leonida::SubgroupRequest subgroup = leonida::decide_subgroup_size(entry, device_->info.subgroup); | ||
| 21582 | return build_compute_pipeline(*device_, entry, entry.binding_count ? with_set0_ : plain_, subgroup, options); | ||
| 21583 | } | ||
| 21584 | |||
| 21585 | void destroy(VkPipeline pipeline) { | ||
| 21586 | if (pipeline) device_->context->vk.vkDestroyPipeline(device_->info.device, pipeline, nullptr); | ||
| 21587 | } | ||
| 21588 | |||
| 21589 | private: | ||
| 21590 | const char* tag_; | ||
| 21591 | ID3D12Device* d3d_ = nullptr; | ||
| 21592 | DeviceState* device_ = nullptr; | ||
| 21593 | const leonida::ShaderLibrary* library_ = nullptr; | ||
| 21594 | VkPipelineLayout plain_ = VK_NULL_HANDLE, with_set0_ = VK_NULL_HANDLE; | ||
| 21595 | std::uint32_t max_shared_ = 0; | ||
| 21596 | }; | ||
| 21597 | |||
| 21598 | // gta6rt --precompile-pipelines (d3d12_precompile.h). | ||
| 21599 | int precompile_compute_pipelines(const PrecompileOptions& options) { | ||
| 21600 | using Clock = std::chrono::steady_clock; | ||
| 21601 | const auto began = Clock::now(); | ||
| 21602 | BuildHost host("[precompile]"); | ||
| 21603 | if (!host.open()) return 1; | ||
| 21604 | const leonida::ShaderLibrary* library = host.library(); | ||
| 21605 | |||
| 21606 | // What to build: every compute entry the runtime could create a pipeline for. | ||
| 21607 | struct Job { | ||
| 21608 | const leonida::ShaderEntry* entry; | ||
| 21609 | std::size_t bytes; | ||
| 21610 | }; | ||
| 21611 | std::vector<Job> jobs; | ||
| 21612 | std::size_t not_buildable = 0, filtered = 0; | ||
| 21613 | for (const leonida::ShaderEntry* entry : library->stage_entries("cs")) { | ||
| 21614 | if (!options.filters.empty() && | ||
| 21615 | std::none_of(options.filters.begin(), options.filters.end(), | ||
| 21616 | [&](const std::string& part) { return entry->name.find(part) != std::string::npos; })) { | ||
| 21617 | ++filtered; | ||
| 21618 | continue; | ||
| 21619 | } | ||
| 21620 | const std::size_t bytes = library->spirv_bytes(*entry); | ||
| 21621 | if ((options.min_bytes && bytes < options.min_bytes) || (options.max_bytes && bytes > options.max_bytes)) { | ||
| 21622 | ++filtered; | ||
| 21623 | continue; | ||
| 21624 | } | ||
| 21625 | if (const char* why = host.unbuildable(*entry, bytes)) { | ||
| 21626 | ++not_buildable; | ||
| 21627 | std::fprintf(stderr, "[precompile] %s: not built (%s)\n", entry->name.c_str(), why); | ||
| 21628 | continue; | ||
| 21629 | } | ||
| 21630 | jobs.push_back({entry, bytes}); | ||
| 21631 | } | ||
| 21632 | std::stable_sort(jobs.begin(), jobs.end(), [&](const Job& a, const Job& b) { | ||
| 21633 | return options.smallest_first ? a.bytes < b.bytes : a.bytes > b.bytes; | ||
| 21634 | }); | ||
| 21635 | if (options.limit && jobs.size() > options.limit) jobs.resize(options.limit); | ||
| 21636 | std::uint64_t total_bytes = 0; | ||
| 21637 | for (const Job& job : jobs) total_bytes += job.bytes; | ||
| 21638 | const unsigned threads = (std::max)(1u, options.threads); | ||
| 21639 | const unsigned big_threads = options.big_threads ? (std::min)(options.big_threads, threads) : threads; | ||
| 21640 | std::fprintf(stderr, "[precompile] %zu compute entries to build (%.1f MB of SPIR-V; %zu filtered out, %zu not " | ||
| 21641 | "buildable), %s first, %u thread(s), at most %u on modules over %zu bytes; journal %ls\n", | ||
| 21642 | jobs.size(), double(total_bytes) / 1e6, filtered, not_buildable, | ||
| 21643 | options.smallest_first ? "smallest" : "largest", threads, big_threads, options.big_bytes, | ||
| 21644 | pipeline_journal_dir().c_str()); | ||
| 21645 | if (options.dry_run) { | ||
| 21646 | for (const Job& job : jobs) std::printf("%zu %s\n", job.bytes, job.entry->name.c_str()); | ||
| 21647 | return 0; | ||
| 21648 | } | ||
| 21649 | |||
| 21650 | std::atomic<std::size_t> next{0}; | ||
| 21651 | std::mutex progress_mutex; | ||
| 21652 | std::size_t done = 0, compiled = 0, skipped = 0, hits = 0, failed = 0; | ||
| 21653 | std::uint64_t done_bytes = 0; | ||
| 21654 | std::mutex big_mutex; | ||
| 21655 | std::condition_variable big_free; | ||
| 21656 | unsigned big_running = 0; | ||
| 21657 | auto worker = [&] { | ||
| 21658 | SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); | ||
| 21659 | for (;;) { | ||
| 21660 | const std::size_t i = next.fetch_add(1); | ||
| 21661 | if (i >= jobs.size()) return; | ||
| 21662 | const Job& job = jobs[i]; | ||
| 21663 | const bool big = job.bytes > options.big_bytes; | ||
| 21664 | if (big) { | ||
| 21665 | std::unique_lock lock(big_mutex); | ||
| 21666 | big_free.wait(lock, [&] { return big_running < big_threads; }); | ||
| 21667 | ++big_running; | ||
| 21668 | } | ||
| 21669 | ComputeBuildOptions build_options; | ||
| 21670 | build_options.trigger = "precompile"; | ||
| 21671 | build_options.serialize_big = false; // nothing else is building; big_threads bounds them instead | ||
| 21672 | build_options.skip_journaled = !options.rebuild; | ||
| 21673 | build_options.use_helper = options.via_helper; | ||
| 21674 | build_options.mark_building = !options.via_helper; // an entry another process is compiling is left to it | ||
| 21675 | ComputeBuild build; | ||
| 21676 | try { | ||
| 21677 | build = host.build(*job.entry, build_options); | ||
| 21678 | } catch (const std::exception& e) { | ||
| 21679 | std::fprintf(stderr, "[precompile] %s: %s\n", job.entry->name.c_str(), e.what()); | ||
| 21680 | } | ||
| 21681 | host.destroy(build.pipeline); | ||
| 21682 | if (big) { | ||
| 21683 | std::lock_guard lock(big_mutex); | ||
| 21684 | --big_running; | ||
| 21685 | big_free.notify_one(); | ||
| 21686 | } | ||
| 21687 | std::lock_guard lock(progress_mutex); | ||
| 21688 | ++done; | ||
| 21689 | done_bytes += job.bytes; | ||
| 21690 | const char* what = "failed"; | ||
| 21691 | if (build.skipped) ++skipped, what = "journaled already"; | ||
| 21692 | else if (build.busy) ++skipped, what = "being built by another process"; | ||
| 21693 | else if (build.result != VK_SUCCESS || (!build.pipeline && !build.skipped)) ++failed; | ||
| 21694 | else if (build.journal_hit || build.from_shared) ++hits, what = "found in a cache"; | ||
| 21695 | else ++compiled, what = build.journaled ? "compiled and journaled" : "compiled (not journaled)"; | ||
| 21696 | const double elapsed = std::chrono::duration<double>(Clock::now() - began).count(); | ||
| 21697 | const double eta = done_bytes ? elapsed / double(done_bytes) * double(total_bytes - done_bytes) : 0.0; | ||
| 21698 | // Skips are not logged one by one (a resumed run skips thousands); every 100th is, with the counts. | ||
| 21699 | if (!build.skipped || done % 100 == 0 || done == jobs.size()) | ||
| 21700 | std::fprintf(stderr, "[precompile] %zu/%zu %s (%zu B): %s in %.1f s (VkResult %d) | %zu compiled, %zu " | ||
| 21701 | "from a cache, %zu skipped, %zu failed; %.0f s elapsed, ~%.0f s left by size\n", | ||
| 21702 | done, jobs.size(), job.entry->name.c_str(), job.bytes, what, double(build.ms) / 1000.0, | ||
| 21703 | int(build.result), compiled, hits, skipped, failed, elapsed, eta); | ||
| 21704 | } | ||
| 21705 | }; | ||
| 21706 | std::vector<std::thread> pool; | ||
| 21707 | for (unsigned t = 0; t < threads; ++t) pool.emplace_back(worker); | ||
| 21708 | for (std::thread& t : pool) t.join(); | ||
| 21709 | std::fprintf(stderr, "[precompile] done: %zu compiled, %zu from a cache, %zu journaled already, %zu failed, %zu " | ||
| 21710 | "not buildable, in %.0f s\n", compiled, hits, skipped, failed, not_buildable, | ||
| 21711 | std::chrono::duration<double>(Clock::now() - began).count()); | ||
| 21712 | return failed ? 2 : 0; | ||
| 21713 | } | ||
| 21714 | |||
| 21715 | // What a compute pipeline's journal name depends on besides its module: a name remembered for a module is good for | ||
| 21716 | // another run while this is unchanged (compile_server's index). | ||
| 21717 | std::uint64_t journal_name_context(DeviceState& state) { | ||
| 21718 | leonida::pipeline_journal::Hasher hash; | ||
| 21719 | hash.text("journal-name-context"); | ||
| 21720 | hash.value(std::uint32_t(sizeof(leonida::ShaderUserData))); | ||
| 21721 | const leonida::SubgroupSizeCaps& sub = state.info.subgroup; | ||
| 21722 | hash.value(std::uint32_t(sub.subgroup_size_control)); | ||
| 21723 | hash.value(std::uint32_t(sub.compute_full_subgroups)); | ||
| 21724 | hash.value(sub.min_size); | ||
| 21725 | hash.value(sub.max_size); | ||
| 21726 | hash.value(sub.default_size); | ||
| 21727 | hash.value(std::uint32_t(sub.required_stages)); | ||
| 21728 | hash.value(std::uint32_t(state.info.device_diagnostics_config)); | ||
| 21729 | if (state.info.device_diagnostics_config) hash.value(std::uint32_t(leonida::aftermath::extra_config_flags())); | ||
| 21730 | if (state.bindless) hash_bindless_layout(hash, state.bindless->features()); | ||
| 21731 | return hash.digest(); | ||
| 21732 | } | ||
| 21733 | |||
| 21734 | // gta6rt --compile-server (d3d12_compile_helper.h): builds what the games using this journal ask for, most urgent | ||
| 21735 | // first, and with nothing asked fills the rest of the library, smallest module first, at idle priority. | ||
| 21736 | int compile_server(const CompileServerOptions& options) { | ||
| 21737 | namespace helper = compile_helper; | ||
| 21738 | namespace journal = leonida::pipeline_journal; | ||
| 21739 | const std::filesystem::path& dir = pipeline_journal_dir(); | ||
| 21740 | if (dir.empty()) { | ||
| 21741 | std::fprintf(stderr, "[compile-server] the pipeline journal is off: nothing to serve\n"); | ||
| 21742 | return 1; | ||
| 21743 | } | ||
| 21744 | const auto requests = helper::requests_dir(dir); | ||
| 21745 | std::error_code ec; | ||
| 21746 | std::filesystem::create_directories(requests, ec); | ||
| 21747 | // One helper per journal: a second (two games, or one started by hand) leaves the requests to the first. | ||
| 21748 | journal::Hasher dir_hash; | ||
| 21749 | dir_hash.text(dir.string().c_str()); | ||
| 21750 | const std::wstring mutex_name = L"Local\\leonida-compile-server-" + std::to_wstring(dir_hash.digest()); | ||
| 21751 | const HANDLE single = CreateMutexW(nullptr, TRUE, mutex_name.c_str()); | ||
| 21752 | if (!single || GetLastError() == ERROR_ALREADY_EXISTS) { | ||
| 21753 | std::fprintf(stderr, "[compile-server] another helper serves %ls\n", dir.c_str()); | ||
| 21754 | return 0; | ||
| 21755 | } | ||
| 21756 | // It ends with the game that started it, at once: whatever it was building is in no file yet, and a file is | ||
| 21757 | // written whole or not at all. A .building marker it leaves names a dead process and is taken over. | ||
| 21758 | if (options.parent_pid) { | ||
| 21759 | const HANDLE parent = OpenProcess(SYNCHRONIZE, FALSE, options.parent_pid); | ||
| 21760 | if (!parent) { | ||
| 21761 | std::fprintf(stderr, "[compile-server] process %lu is gone\n", options.parent_pid); | ||
| 21762 | return 0; | ||
| 21763 | } | ||
| 21764 | std::thread([parent] { | ||
| 21765 | WaitForSingleObject(parent, INFINITE); | ||
| 21766 | TerminateProcess(GetCurrentProcess(), 0); | ||
| 21767 | }).detach(); | ||
| 21768 | } | ||
| 21769 | BuildHost host("[compile-server]"); | ||
| 21770 | if (!host.open()) return 1; | ||
| 21771 | const leonida::ShaderLibrary* library = host.library(); | ||
| 21772 | const std::vector<const leonida::ShaderEntry*> entries = library->stage_entries("cs"); | ||
| 21773 | std::map<std::string, const leonida::ShaderEntry*> by_name; | ||
| 21774 | for (const leonida::ShaderEntry* entry : entries) by_name.emplace(entry->name, entry); | ||
| 21775 | const unsigned threads = (std::max)(1u, options.threads); | ||
| 21776 | const unsigned idle_threads = (std::min)(options.idle_threads, threads - 1); // one is always free for a request | ||
| 21777 | std::fprintf(stderr, "[compile-server] serving %ls: %u thread(s) for requests, %u of them filling the library " | ||
| 21778 | "when nothing is asked, %zu compute entries\n", requests.c_str(), threads, idle_threads, | ||
| 21779 | entries.size()); | ||
| 21780 | |||
| 21781 | std::mutex mutex; | ||
| 21782 | std::condition_variable wake; | ||
| 21783 | std::vector<helper::Request> pending; // the last listing, most urgent first | ||
| 21784 | std::set<std::string> busy; // stems being built here | ||
| 21785 | std::map<std::string, std::chrono::steady_clock::time_point> elsewhere; // stems another process is building | ||
| 21786 | bool stop = false; | ||
| 21787 | std::atomic<unsigned> requests_done{0}, filled{0}; | ||
| 21788 | |||
| 21789 | // A request this helper can take: listed, not being built here, not one another process was building a moment ago. | ||
| 21790 | auto take_locked = [&](helper::Request& out) { | ||
| 21791 | const auto now = std::chrono::steady_clock::now(); | ||
| 21792 | for (const helper::Request& request : pending) { | ||
| 21793 | if (busy.count(request.stem)) continue; | ||
| 21794 | if (const auto it = elsewhere.find(request.stem); it != elsewhere.end() && now - it->second < std::chrono::seconds(5)) | ||
| 21795 | continue; | ||
| 21796 | busy.insert(request.stem); | ||
| 21797 | out = request; | ||
| 21798 | return true; | ||
| 21799 | } | ||
| 21800 | return false; | ||
| 21801 | }; | ||
| 21802 | auto build_entry = [&](const leonida::ShaderEntry& entry, const char* trigger) { | ||
| 21803 | ComputeBuildOptions build_options; | ||
| 21804 | build_options.trigger = trigger; | ||
| 21805 | build_options.serialize_big = false; | ||
| 21806 | build_options.skip_journaled = true; | ||
| 21807 | build_options.use_helper = false; | ||
| 21808 | build_options.mark_building = true; | ||
| 21809 | ComputeBuild build = host.build(entry, build_options); | ||
| 21810 | host.destroy(build.pipeline); | ||
| 21811 | build.pipeline = VK_NULL_HANDLE; | ||
| 21812 | return build; | ||
| 21813 | }; | ||
| 21814 | auto serve = [&] { // normal priority: a title waits for these | ||
| 21815 | for (;;) { | ||
| 21816 | helper::Request request; | ||
| 21817 | { | ||
| 21818 | std::unique_lock lock(mutex); | ||
| 21819 | wake.wait_for(lock, std::chrono::milliseconds(100), [&] { return stop || take_locked(request); }); | ||
| 21820 | if (stop) return; | ||
| 21821 | if (request.stem.empty()) continue; | ||
| 21822 | } | ||
| 21823 | std::string failure; | ||
| 21824 | bool leave = false; // another process is building it: its file answers the request | ||
| 21825 | const auto it = by_name.find(request.name); | ||
| 21826 | const leonida::ShaderEntry* entry = it == by_name.end() ? nullptr : it->second; | ||
| 21827 | const std::size_t bytes = entry ? library->spirv_bytes(*entry) : 0; | ||
| 21828 | if (!entry) failure = "no compute entry of that name in this library"; | ||
| 21829 | else if (const char* why = host.unbuildable(*entry, bytes)) failure = why; | ||
| 21830 | // LOCAL FIX (compile helper: the journal name was checked after the build): the name is hashed from the | ||
| 21831 | // module and this device's environment, which costs no driver call. A request from a game whose environment | ||
| 21832 | // differs is answered before a compile is spent on a file that game never reads; the build below would only | ||
| 21833 | // have found the same mismatch. | ||
| 21834 | if (failure.empty()) { | ||
| 21835 | ComputeBuildOptions key_options; | ||
| 21836 | key_options.trigger = "compile-server"; | ||
| 21837 | key_options.key_only = true; | ||
| 21838 | key_options.use_helper = false; | ||
| 21839 | const std::filesystem::path key_path = host.build(*entry, key_options).journal_path; | ||
| 21840 | if (!key_path.empty() && key_path.stem().string() != request.stem) | ||
| 21841 | failure = "its journal name here is " + key_path.stem().string() + | ||
| 21842 | ": the helper's environment differs from the game's"; | ||
| 21843 | } | ||
| 21844 | if (failure.empty()) { | ||
| 21845 | ComputeBuild build; | ||
| 21846 | try { | ||
| 21847 | build = build_entry(*entry, "compile-server"); | ||
| 21848 | } catch (const std::exception& e) { | ||
| 21849 | failure = e.what(); | ||
| 21850 | } | ||
| 21851 | if (failure.empty()) { | ||
| 21852 | if (build.busy) | ||
| 21853 | leave = true; | ||
| 21854 | else if (!build.skipped && (build.result != VK_SUCCESS || !(build.journaled || build.journal_hit))) | ||
| 21855 | failure = "not built or not journaled (VkResult " + std::to_string(int(build.result)) + ")"; | ||
| 21856 | else if (!leonida::pipeline_journal::entry_usable(build.journal_path, host.state().pso_identity)) | ||
| 21857 | failure = "requested writable journal file is missing or incompatible"; | ||
| 21858 | else | ||
| 21859 | std::fprintf(stderr, "[compile-server] %s (%zu B, priority %llu): %s in %.1f s\n", | ||
| 21860 | request.name.c_str(), bytes, static_cast<unsigned long long>(request.priority), | ||
| 21861 | build.skipped ? "journaled already" : "built and journaled", | ||
| 21862 | double(build.ms) / 1000.0); | ||
| 21863 | } | ||
| 21864 | } | ||
| 21865 | std::error_code ignored; | ||
| 21866 | // LOCAL FIX (compile helper: a .failed left with its .request listed): the .req goes first. A request with | ||
| 21867 | // no .req and no .failed is one the game reads as answered, so it builds the pipeline itself instead of | ||
| 21868 | // waiting for a file that is not coming (Client::state). | ||
| 21869 | if (!leave) std::filesystem::remove(requests / (request.stem + ".req"), ignored); | ||
| 21870 | if (!failure.empty()) { | ||
| 21871 | helper::write_line(requests / (request.stem + ".failed"), failure); | ||
| 21872 | std::fprintf(stderr, "[compile-server] %s: %s\n", request.name.c_str(), failure.c_str()); | ||
| 21873 | } | ||
| 21874 | if (!leave) ++requests_done; | ||
| 21875 | std::lock_guard lock(mutex); | ||
| 21876 | busy.erase(request.stem); | ||
| 21877 | if (leave) elsewhere[request.stem] = std::chrono::steady_clock::now(); | ||
| 21878 | } | ||
| 21879 | }; | ||
| 21880 | |||
| 21881 | // The rest of the library, smallest module first, while nothing is asked. The journal names of modules looked at | ||
| 21882 | // before are kept in requests/names.idx (with each module's size and time, and what the names depend on), so a | ||
| 21883 | // later helper finds what is missing without reading every module again. | ||
| 21884 | struct Indexed { | ||
| 21885 | std::uint64_t size = 0; | ||
| 21886 | long long mtime = 0; | ||
| 21887 | std::string stem; | ||
| 21888 | }; | ||
| 21889 | std::map<std::string, Indexed> index; | ||
| 21890 | std::mutex index_mutex; | ||
| 21891 | const auto index_file = requests / "names.idx"; | ||
| 21892 | const std::string signature = "v1 " + std::to_string(journal_name_context(host.state())); | ||
| 21893 | { | ||
| 21894 | std::ifstream in(index_file, std::ios::binary); | ||
| 21895 | std::string line; | ||
| 21896 | if (std::getline(in, line) && line == signature) { | ||
| 21897 | while (std::getline(in, line)) { | ||
| 21898 | const auto t1 = line.find('\t'), t2 = line.find('\t', t1 + 1), t3 = line.find('\t', t2 + 1); | ||
| 21899 | if (t3 == std::string::npos) continue; | ||
| 21900 | index[line.substr(0, t1)] = {std::strtoull(line.c_str() + t1 + 1, nullptr, 10), | ||
| 21901 | std::strtoll(line.c_str() + t2 + 1, nullptr, 10), line.substr(t3 + 1)}; | ||
| 21902 | } | ||
| 21903 | } | ||
| 21904 | } | ||
| 21905 | auto save_index = [&] { | ||
| 21906 | std::string text = signature + "\n"; | ||
| 21907 | std::lock_guard lock(index_mutex); | ||
| 21908 | for (const auto& [name, item] : index) | ||
| 21909 | text += name + "\t" + std::to_string(item.size) + "\t" + std::to_string(item.mtime) + "\t" + item.stem + "\n"; | ||
| 21910 | journal::write_entry(index_file, text.data(), text.size()); | ||
| 21911 | }; | ||
| 21912 | std::vector<const leonida::ShaderEntry*> fill_order = entries; | ||
| 21913 | std::vector<std::size_t> fill_bytes(fill_order.size()); | ||
| 21914 | { | ||
| 21915 | std::vector<std::pair<std::size_t, const leonida::ShaderEntry*>> sized; | ||
| 21916 | for (const leonida::ShaderEntry* entry : entries) sized.emplace_back(library->spirv_bytes(*entry), entry); | ||
| 21917 | std::stable_sort(sized.begin(), sized.end(), [](const auto& x, const auto& y) { return x.first < y.first; }); | ||
| 21918 | for (std::size_t i = 0; i < sized.size(); ++i) { | ||
| 21919 | fill_order[i] = sized[i].second; | ||
| 21920 | fill_bytes[i] = sized[i].first; | ||
| 21921 | } | ||
| 21922 | } | ||
| 21923 | std::atomic<std::size_t> fill_next{0}; | ||
| 21924 | std::atomic<unsigned> fill_unsaved{0}; | ||
| 21925 | auto fill = [&] { | ||
| 21926 | SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_IDLE); | ||
| 21927 | for (;;) { | ||
| 21928 | { | ||
| 21929 | // Requests first: wait while one is listed that this helper could take. | ||
| 21930 | std::unique_lock lock(mutex); | ||
| 21931 | wake.wait_for(lock, std::chrono::milliseconds(200), [&] { | ||
| 21932 | if (stop) return true; | ||
| 21933 | for (const helper::Request& request : pending) | ||
| 21934 | if (!busy.count(request.stem)) return false; | ||
| 21935 | return true; | ||
| 21936 | }); | ||
| 21937 | if (stop) return; | ||
| 21938 | bool asked = false; | ||
| 21939 | for (const helper::Request& request : pending) | ||
| 21940 | if (!busy.count(request.stem)) asked = true; | ||
| 21941 | if (asked) continue; | ||
| 21942 | } | ||
| 21943 | const std::size_t i = fill_next.fetch_add(1); | ||
| 21944 | if (i >= fill_order.size()) { | ||
| 21945 | if (i == fill_order.size()) { | ||
| 21946 | save_index(); | ||
| 21947 | std::fprintf(stderr, "[compile-server] the library is in the journal (%u built while idle)\n", | ||
| 21948 | filled.load()); | ||
| 21949 | } | ||
| 21950 | return; | ||
| 21951 | } | ||
| 21952 | const leonida::ShaderEntry& entry = *fill_order[i]; | ||
| 21953 | if (host.unbuildable(entry, fill_bytes[i])) continue; | ||
| 21954 | std::error_code stat; | ||
| 21955 | const auto spv = library->spirv_file(entry); | ||
| 21956 | const long long mtime = static_cast<long long>(std::filesystem::last_write_time(spv, stat).time_since_epoch().count()); | ||
| 21957 | std::filesystem::path path; | ||
| 21958 | { | ||
| 21959 | std::lock_guard lock(index_mutex); | ||
| 21960 | const auto it = index.find(entry.name); | ||
| 21961 | if (it != index.end() && it->second.size == fill_bytes[i] && it->second.mtime == mtime) | ||
| 21962 | path = dir / (it->second.stem + ".bin"); | ||
| 21963 | } | ||
| 21964 | if (path.empty()) { | ||
| 21965 | ComputeBuildOptions key_options; | ||
| 21966 | key_options.key_only = true; | ||
| 21967 | key_options.use_helper = false; | ||
| 21968 | path = host.build(entry, key_options).journal_path; | ||
| 21969 | if (path.empty()) continue; | ||
| 21970 | { | ||
| 21971 | std::lock_guard lock(index_mutex); | ||
| 21972 | index[entry.name] = {fill_bytes[i], mtime, path.stem().string()}; | ||
| 21973 | } | ||
| 21974 | if (++fill_unsaved % 200 == 0) save_index(); | ||
| 21975 | } | ||
| 21976 | if (journal::entry_usable(path, host.state().pso_identity)) continue; | ||
| 21977 | ComputeBuild build; | ||
| 21978 | try { | ||
| 21979 | build = build_entry(entry, "idle-fill"); | ||
| 21980 | } catch (const std::exception& e) { | ||
| 21981 | std::fprintf(stderr, "[compile-server] %s: %s\n", entry.name.c_str(), e.what()); | ||
| 21982 | continue; | ||
| 21983 | } | ||
| 21984 | if (!build.skipped && !build.busy && build.result == VK_SUCCESS && build.journaled) { | ||
| 21985 | ++filled; | ||
| 21986 | std::fprintf(stderr, "[compile-server] idle: %s (%zu B) built and journaled in %.1f s (%zu/%zu)\n", | ||
| 21987 | entry.name.c_str(), fill_bytes[i], double(build.ms) / 1000.0, i + 1, fill_order.size()); | ||
| 21988 | } | ||
| 21989 | } | ||
| 21990 | }; | ||
| 21991 | |||
| 21992 | std::vector<std::thread> pool; | ||
| 21993 | for (unsigned t = 0; t < threads - idle_threads; ++t) pool.emplace_back(serve); | ||
| 21994 | for (unsigned t = 0; t < idle_threads; ++t) pool.emplace_back(fill); | ||
| 21995 | auto quiet_since = std::chrono::steady_clock::now(); | ||
| 21996 | for (;;) { | ||
| 21997 | auto listing = helper::list_requests(requests); | ||
| 21998 | { | ||
| 21999 | std::lock_guard lock(mutex); | ||
| 22000 | pending = std::move(listing); | ||
| 22001 | if (!pending.empty() || !busy.empty()) quiet_since = std::chrono::steady_clock::now(); | ||
| 22002 | } | ||
| 22003 | wake.notify_all(); | ||
| 22004 | if (options.idle_exit_s && | ||
| 22005 | std::chrono::steady_clock::now() - quiet_since > std::chrono::seconds(options.idle_exit_s)) | ||
| 22006 | break; | ||
| 22007 | std::this_thread::sleep_for(std::chrono::milliseconds(50)); | ||
| 22008 | } | ||
| 22009 | { | ||
| 22010 | std::lock_guard lock(mutex); | ||
| 22011 | stop = true; | ||
| 22012 | } | ||
| 22013 | wake.notify_all(); | ||
| 22014 | for (std::thread& t : pool) t.join(); | ||
| 22015 | save_index(); | ||
| 22016 | std::fprintf(stderr, "[compile-server] nothing asked for %u s: done (%u requests, %u built while idle)\n", | ||
| 22017 | options.idle_exit_s, requests_done.load(), filled.load()); | ||
| 22018 | return 0; | ||
| 22019 | } | ||
| 22020 | |||
| 18452 | bool has_global_realtime_privilege() { | 22021 | bool has_global_realtime_privilege() { |
| 18453 | const int override_state = g_global_realtime_privilege_override.load(std::memory_order_relaxed); | 22022 | const int override_state = g_global_realtime_privilege_override.load(std::memory_order_relaxed); |
| 18454 | if (override_state >= 0) return override_state != 0; | 22023 | if (override_state >= 0) return override_state != 0; |
| @@ -18496,6 +22065,38 @@ HRESULT create_console_descriptor_heap(ID3D12Device* device, const D3D12_DESCRIP | |||
| 18496 | return d->create_console_descriptor_heap(desc, console_address, console_size, riid, out); | 22065 | return d->create_console_descriptor_heap(desc, console_address, console_size, riid, out); |
| 18497 | } | 22066 | } |
| 18498 | 22067 | ||
| 22068 | UnboundTsharpStats unbound_tsharp_stats() { | ||
| 22069 | return unbound_tsharp_tracker().stats(); | ||
| 22070 | } | ||
| 22071 | |||
| 22072 | void reset_unbound_tsharp_stats() { | ||
| 22073 | unbound_tsharp_tracker().reset(); | ||
| 22074 | } | ||
| 22075 | |||
| 22076 | void note_refused_tsharp_for_test(std::uint64_t heap_va, std::size_t offset, | ||
| 22077 | const std::array<std::uint32_t, 8>& words, const char* why) { | ||
| 22078 | leonida::gfx10::ImageWords w; | ||
| 22079 | std::memcpy(w.data(), words.data(), sizeof(w)); | ||
| 22080 | unbound_tsharp_tracker().note(heap_va, offset, w, why); | ||
| 22081 | } | ||
| 22082 | |||
| 22083 | TitleImage test_bind_title_image(ID3D12Device* device, const std::array<std::uint32_t, 8>& words, | ||
| 22084 | const char** why) { | ||
| 22085 | if (!device) return TitleImage::not_tsharp; | ||
| 22086 | ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); | ||
| 22087 | Device* d = Device::from<Device>(real ? real : device); | ||
| 22088 | if (!d) return TitleImage::not_tsharp; | ||
| 22089 | leonida::gfx10::ImageWords w; | ||
| 22090 | std::memcpy(w.data(), words.data(), sizeof(w)); | ||
| 22091 | return bind_title_image(d->state(), w, why); | ||
| 22092 | } | ||
| 22093 | |||
| 22094 | std::uint64_t resource_image_address(ID3D12Resource* resource) { | ||
| 22095 | if (!resource) return 0; | ||
| 22096 | const Resource* r = Resource::from<Resource>(resource); | ||
| 22097 | return r ? r->image_address() : 0; | ||
| 22098 | } | ||
| 22099 | |||
| 18499 | std::filesystem::path configured_shader_directory(std::string* error, const std::filesystem::path& config) { | 22100 | std::filesystem::path configured_shader_directory(std::string* error, const std::filesystem::path& config) { |
| 18500 | return leonida::shader_paths::configured(error, config); | 22101 | return leonida::shader_paths::configured(error, config); |
| 18501 | } | 22102 | } |