upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/shims
diff options
context:
space:
mode:
authorJan Trencansky <jan.trencansky@protonmail.com>2026-11-26 16:55:04 -0500
committerJan Trencansky <jan.trencansky@protonmail.com>2026-11-26 16:55:04 -0500
commitdf92abca8ee2a8f9093efea7fcaa4dadc3ddaebc (patch)
tree97ef8f95544fe263049d3f7360823f16100de209 /runtime/shims
parent49a0b69fcdb80db1f2a44ce7ca0ab8dfdec1e403 (diff)
parente5a7c8942678b323f655939c81f5d8855d20c248 (diff)
Merge main e5a7c8942 into shadow-aliased-guard (#1867)
One conflict, runtime/README.md: this branch rewrote the LEONIDA_SHADOW_ALIAS_MS row, main (#2163) added the LEONIDA_SHADOW_KEEP row after it. Both rows kept; the keep row's "aliased" now reads "aliased while they can't be guarded at every address", since aliased pages are no longer copied without a sign of a write. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime/shims')
-rw-r--r--runtime/shims/d3d12_com.h3
-rw-r--r--runtime/shims/d3d12_geometry_views.h62
-rw-r--r--runtime/shims/d3d12_precompile.h6
-rw-r--r--runtime/shims/d3d12_title_buffer_windows.h57
-rw-r--r--runtime/shims/d3d12_vulkan_device.cpp1454
-rw-r--r--runtime/shims/d3d12_xs_device.cpp66
-rw-r--r--runtime/shims/d3d12_xs_list_values.h167
-rw-r--r--runtime/shims/dstorage.cpp172
-rw-r--r--runtime/shims/gameinput.cpp77
-rw-r--r--runtime/shims/gameinput_no_sdl.cpp96
-rw-r--r--runtime/shims/gameinput_script.h30
-rw-r--r--runtime/shims/process.cpp35
-rw-r--r--runtime/shims/xapu_chad.cpp123
-rw-r--r--runtime/shims/xapu_queue.cpp438
-rw-r--r--runtime/shims/xgameruntime_gamesave.cpp25
-rw-r--r--runtime/shims/xmem.cpp55
-rw-r--r--runtime/shims/xmem.h2
17 files changed, 2328 insertions, 540 deletions
diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h
index ca2b02789..3bad0b767 100644
--- a/runtime/shims/d3d12_com.h
+++ b/runtime/shims/d3d12_com.h
@@ -169,6 +169,9 @@ struct VulkanDeviceInfo {
169 bool occlusion_query_precise = false; 169 bool occlusion_query_precise = false;
170 bool prepare_on_bind = false; 170 bool prepare_on_bind = false;
171 bool cold_graphics_compile = false; // Driver supports a cache-only create and reports when compilation is pending. 171 bool cold_graphics_compile = false; // Driver supports a cache-only create and reports when compilation is pending.
172 // pipelineCreationCacheControl is on for the heavy pipeline cache (src/heavy_pipeline_cache.h): a pipeline the
173 // offline cache does not have is created against the cache of pipeline_cache.heavy.bin, written back as it grows.
174 bool heavy_pipeline_cache = false;
172 bool pipeline_statistics_query = false; 175 bool pipeline_statistics_query = false;
173 bool presentation = false; // VK_KHR_surface + VK_KHR_win32_surface on the instance, VK_KHR_swapchain on the device 176 bool presentation = false; // VK_KHR_surface + VK_KHR_win32_surface on the instance, VK_KHR_swapchain on the device
174 // VK_KHR_swapchain_maintenance1 (or VK_EXT_swapchain_maintenance1) and its swapchainMaintenance1 feature are 177 // VK_KHR_swapchain_maintenance1 (or VK_EXT_swapchain_maintenance1) and its swapchainMaintenance1 feature are
diff --git a/runtime/shims/d3d12_geometry_views.h b/runtime/shims/d3d12_geometry_views.h
index feb4ff52e..02f9590ba 100644
--- a/runtime/shims/d3d12_geometry_views.h
+++ b/runtime/shims/d3d12_geometry_views.h
@@ -1,6 +1,7 @@
1#pragma once 1#pragma once
2 2
3#include "d3d12_title_buffer_windows.h" 3#include "d3d12_title_buffer_windows.h"
4#include "../src/memory_breakdown.h"
4#include "../src/title_geometry_watch.h" 5#include "../src/title_geometry_watch.h"
5#include <atomic> 6#include <atomic>
6#include <chrono> 7#include <chrono>
@@ -9,13 +10,14 @@
9#include <mutex> 10#include <mutex>
10#include <set> 11#include <set>
11#include <shared_mutex> 12#include <shared_mutex>
13#include <type_traits>
12#include <unordered_map> 14#include <unordered_map>
13#include <utility> 15#include <utility>
14#include <vector> 16#include <vector>
15 17
16namespace rt::d3d12 { 18namespace rt::d3d12 {
17 19
18// One persistent device-local copy for each geometry extent. The console heap retains its original indices. 20// One persistent copy for each geometry extent, in device-local memory (or system memory: LEONIDA_GEOMETRY_HOST). The console heap retains its original indices.
19// Every CPU mapping of a source tile is watched; a physical remap changes which aliases must be watched. 21// Every CPU mapping of a source tile is watched; a physical remap changes which aliases must be watched.
20// Views whose title range is released are retired immediately and their backing storage is reclaimed once 22// Views whose title range is released are retired immediately and their backing storage is reclaimed once
21// in-flight GPU submissions up to their retire ticket have completed; previously cap-refused ranges retry 23// in-flight GPU submissions up to their retire ticket have completed; previously cap-refused ranges retry
@@ -30,6 +32,7 @@ class GeometryViews {
30 struct NoopRetire { 32 struct NoopRetire {
31 void operator()(Address, std::size_t, VkDeviceSize) const noexcept {} 33 void operator()(Address, std::size_t, VkDeviceSize) const noexcept {}
32 }; 34 };
35 struct NoCopy {};
33 struct View { 36 struct View {
34 Address source{}; 37 Address source{};
35 std::size_t size{}; 38 std::size_t size{};
@@ -121,7 +124,7 @@ class GeometryViews {
121 std::atomic<std::uint64_t> free_generation_{0}; 124 std::atomic<std::uint64_t> free_generation_{0};
122 std::uint64_t serial_{}, bytes_{}, cap_refusals_{}, allocation_failures_{}, ready_{}, uploads_{}, uploaded_{}; 125 std::uint64_t serial_{}, bytes_{}, cap_refusals_{}, allocation_failures_{}, ready_{}, uploads_{}, uploaded_{};
123 std::uint64_t submissions_{}, dirty_refreshes_{}, refilled_{}, tile_fills_{}; 126 std::uint64_t submissions_{}, dirty_refreshes_{}, refilled_{}, tile_fills_{};
124 std::uint64_t evicted_{}, reaped_{}, retries_succeeded_{}; 127 std::uint64_t evicted_{}, reaped_{}, retries_succeeded_{}, final_copies_{};
125 std::unordered_map<Address, std::size_t> tile_reads_; // refresh(): offset in tile_scratch_, SIZE_MAX unreadable 128 std::unordered_map<Address, std::size_t> tile_reads_; // refresh(): offset in tile_scratch_, SIZE_MAX unreadable
126 // refresh() scratch: per view, whether it waits on a tile (pinned), is filled whole, was touched, was counted; 129 // refresh() scratch: per view, whether it waits on a tile (pinned), is filled whole, was touched, was counted;
127 // and the tiles found written, in address order. 130 // and the tiles found written, in address order.
@@ -213,6 +216,7 @@ class GeometryViews {
213 216
214public: 217public:
215 explicit GeometryViews(std::uint64_t cap_override = 0) : cap_override_(cap_override) { 218 explicit GeometryViews(std::uint64_t cap_override = 0) : cap_override_(cap_override) {
219 pool_.set_system_memory(system_memory_setting());
216 leonida::geometry_writes::subscribe(releases_); 220 leonida::geometry_writes::subscribe(releases_);
217 } 221 }
218 ~GeometryViews() { leonida::geometry_writes::unsubscribe(releases_); } 222 ~GeometryViews() { leonida::geometry_writes::unsubscribe(releases_); }
@@ -231,6 +235,16 @@ public:
231 235
232 std::uint64_t effective_cap() const { return cap_override_ ? cap_override_ : cap(); } 236 std::uint64_t effective_cap() const { return cap_override_ ? cap_override_ : cap(); }
233 237
238 // LEONIDA_GEOMETRY_HOST: where the copies live. Unset or 0: device-local memory (the BAR) while the driver gives it;
239 // 1: system memory, write-back (cached) where the device offers it; 2: system memory, write-combined. The GPU then
240 // reads the copies over the bus (VRAM saved, each read of a vertex or index slower).
241 static int system_memory_setting() {
242 const char* v = std::getenv("LEONIDA_GEOMETRY_HOST");
243 if (!v || !*v || *v == '0') return TitleBufferWindows::kDeviceLocal;
244 return *v == '2' ? TitleBufferWindows::kSystemUncached : TitleBufferWindows::kSystemCached;
245 }
246 int system_memory() const { return pool_.system_memory(); }
247
234 bool has_released() const { return leonida::geometry_writes::has_released(releases_); } 248 bool has_released() const { return leonida::geometry_writes::has_released(releases_); }
235 bool has_retired() const { return retired_count_.load(std::memory_order_acquire) != 0; } 249 bool has_retired() const { return retired_count_.load(std::memory_order_acquire) != 0; }
236 bool has_pending_reclaim() const { return has_released() || has_retired(); } 250 bool has_pending_reclaim() const { return has_released() || has_retired(); }
@@ -258,6 +272,10 @@ public:
258 std::lock_guard lock(mutex_); 272 std::lock_guard lock(mutex_);
259 return evicted_; 273 return evicted_;
260 } 274 }
275 std::uint64_t final_copies() const {
276 std::lock_guard lock(mutex_);
277 return final_copies_;
278 }
261 std::uint64_t reaped() const { 279 std::uint64_t reaped() const {
262 std::lock_guard lock(mutex_); 280 std::lock_guard lock(mutex_);
263 return reaped_; 281 return reaped_;
@@ -301,6 +319,7 @@ public:
301 VkDeviceSize va{}; 319 VkDeviceSize va{};
302 bool at_cap = false; 320 bool at_cap = false;
303 const bool over_bytes = bytes_ >= limit || bytes > limit - bytes_; 321 const bool over_bytes = bytes_ >= limit || bytes > limit - bytes_;
322 leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::geometry);
304 if (over_bytes || !pool_.allocate(device, bytes, va, mapped, true, limit, &at_cap)) { 323 if (over_bytes || !pool_.allocate(device, bytes, va, mapped, true, limit, &at_cap)) {
305 if (at_cap || over_bytes) { 324 if (at_cap || over_bytes) {
306 refused_[key] = gen; 325 refused_[key] = gen;
@@ -393,9 +412,14 @@ public:
393 // Retires every live view overlapping [begin, end), unlinking it from lookup/refresh/watch immediately and 412 // Retires every live view overlapping [begin, end), unlinking it from lookup/refresh/watch immediately and
394 // deferring its backing storage reclamation until GPU submissions through `retire_ticket` have completed 413 // deferring its backing storage reclamation until GPU submissions through `retire_ticket` have completed
395 // (kAfterExecutes: through the submissions of every replay in progress now, see execute_end). 414 // (kAfterExecutes: through the submissions of every replay in progress now, see execute_end).
396 template<class OnRetire = NoopRetire> 415 // With `final_copy` (a refresh's copy), a ready view whose title range is readable now is copied from it once more
416 // before it leaves the refresh: a released range that is still readable (a heap block freed in memory that stays
417 // committed) may hold new bytes, and a list recorded before the release that runs in a submission the view waits
418 // for reads those, as it would have read them in the console's memory. Decommitted or unmapped memory is not
419 // readable, so such a view keeps what it held.
420 template<class OnRetire = NoopRetire, class Copy = NoCopy>
397 std::size_t retire_range(Address begin, Address end, std::uint64_t retire_ticket = 0, 421 std::size_t retire_range(Address begin, Address end, std::uint64_t retire_ticket = 0,
398 OnRetire&& on_retire = {}) { 422 OnRetire&& on_retire = {}, Copy&& final_copy = {}) {
399 if (end <= begin) return 0; 423 if (end <= begin) return 0;
400 struct CallbackItem { 424 struct CallbackItem {
401 Address source; 425 Address source;
@@ -425,6 +449,13 @@ public:
425 const std::size_t first_retired = retired_.size(); 449 const std::size_t first_retired = retired_.size();
426 for (const auto id : ids) { 450 for (const auto id : ids) {
427 View& v = views_[id]; 451 View& v = views_[id];
452 if constexpr (!std::is_same_v<std::decay_t<Copy>, NoCopy>) {
453 if (v.ready && final_copy(v.dst, reinterpret_cast<const std::uint8_t*>(v.source), v.size) ==
454 GeometryCopy::copied) {
455 ++final_copies_;
456 uploaded_ += v.size;
457 }
458 }
428 detach_tiles_locked(id, v.source, v.size); 459 detach_tiles_locked(id, v.source, v.size);
429 if (v.ready) { 460 if (v.ready) {
430 --ready_; 461 --ready_;
@@ -495,21 +526,21 @@ public:
495 return freed; 526 return freed;
496 } 527 }
497 528
498 // Drains released title ranges recorded by xmem (retiring matching views at `retire_ticket`) and reaps retired 529 // Drains released title ranges recorded by xmem (retiring matching views at `retire_ticket`, with `final_copy` as
499 // views whose GPU work completed by `completed_ticket`. 530 // retire_range takes it) and reaps retired views whose GPU work completed by `completed_ticket`.
500 template<class Device, class OnRetire = NoopRetire> 531 template<class Device, class OnRetire = NoopRetire, class Copy = NoCopy>
501 void drain_released(Device& device, std::uint64_t retire_ticket, std::uint64_t completed_ticket, 532 void drain_released(Device& device, std::uint64_t retire_ticket, std::uint64_t completed_ticket,
502 OnRetire&& on_retire = {}) { 533 OnRetire&& on_retire = {}, Copy&& final_copy = {}) {
503 std::vector<std::pair<Address, Address>> ranges; 534 std::vector<std::pair<Address, Address>> ranges;
504 leonida::geometry_writes::take_released(releases_, ranges); 535 leonida::geometry_writes::take_released(releases_, ranges);
505 for (const auto& [begin, end] : ranges) { 536 for (const auto& [begin, end] : ranges) {
506 retire_range(begin, end, retire_ticket, on_retire); 537 retire_range(begin, end, retire_ticket, on_retire, final_copy);
507 leonida::title_gpu_views::Range pair{}; 538 leonida::title_gpu_views::Range pair{};
508 if (end > begin && leonida::title_gpu_views::view_at(begin, 1, pair) && 539 if (end > begin && leonida::title_gpu_views::view_at(begin, 1, pair) &&
509 begin >= pair.gpu && begin - pair.gpu < pair.size) { 540 begin >= pair.gpu && begin - pair.gpu < pair.size) {
510 const Address offset = begin - pair.gpu; 541 const Address offset = begin - pair.gpu;
511 const Address span = (std::min)(end - begin, pair.size - offset); 542 const Address span = (std::min)(end - begin, pair.size - offset);
512 retire_range(pair.cpu + offset, pair.cpu + offset + span, retire_ticket, on_retire); 543 retire_range(pair.cpu + offset, pair.cpu + offset + span, retire_ticket, on_retire, final_copy);
513 } 544 }
514 } 545 }
515 reap(device, completed_ticket); 546 reap(device, completed_ticket);
@@ -666,14 +697,17 @@ public:
666 if (!effective_cap()) return; 697 if (!effective_cap()) return;
667 std::lock_guard lock(mutex_); 698 std::lock_guard lock(mutex_);
668 std::fprintf(stderr, "[rt] geometry buffers: seen %zu, backed %zu (%llu bytes), populated %llu, cap %llu MiB, " 699 std::fprintf(stderr, "[rt] geometry buffers: seen %zu, backed %zu (%llu bytes), populated %llu, cap %llu MiB, "
669 "cap refused %llu, retried ok %llu, evicted %llu (reaped %llu, retired %zu), " 700 "cap refused %llu, retried ok %llu, evicted %llu (reaped %llu, retired %zu, copied at "
670 "allocation failures %llu, uploads %llu (%llu bytes), watched tiles %zu, reserved %llu bytes\n", 701 "retirement %llu), allocation failures %llu, uploads %llu (%llu bytes), watched tiles %zu, "
702 "reserved %llu bytes (%s)\n",
671 keys_.size() + refused_.size(), live_views_, (unsigned long long)bytes_, (unsigned long long)ready_, 703 keys_.size() + refused_.size(), live_views_, (unsigned long long)bytes_, (unsigned long long)ready_,
672 (unsigned long long)(effective_cap() >> 20), (unsigned long long)cap_refusals_, 704 (unsigned long long)(effective_cap() >> 20), (unsigned long long)cap_refusals_,
673 (unsigned long long)retries_succeeded_, (unsigned long long)evicted_, 705 (unsigned long long)retries_succeeded_, (unsigned long long)evicted_,
674 (unsigned long long)reaped_, retired_.size(), (unsigned long long)allocation_failures_, 706 (unsigned long long)reaped_, retired_.size(), (unsigned long long)final_copies_,
707 (unsigned long long)allocation_failures_,
675 (unsigned long long)uploads_, (unsigned long long)uploaded_, tiles_.size(), 708 (unsigned long long)uploads_, (unsigned long long)uploaded_, tiles_.size(),
676 static_cast<unsigned long long>(pool_.reserved())); 709 static_cast<unsigned long long>(pool_.reserved()),
710 pool_.system_memory() ? "system memory" : "device-local");
677 std::fprintf(stderr, "[rt] geometry refresh: %llu/%llu submissions uploaded dirty views, %llu bytes (%llu views by " 711 std::fprintf(stderr, "[rt] geometry refresh: %llu/%llu submissions uploaded dirty views, %llu bytes (%llu views by "
678 "their written tiles only); %.3f s checking and refreshing sources, %llu bytes cleared\n", 712 "their written tiles only); %.3f s checking and refreshing sources, %llu bytes cleared\n",
679 static_cast<unsigned long long>(dirty_refreshes_), static_cast<unsigned long long>(submissions_), 713 static_cast<unsigned long long>(dirty_refreshes_), static_cast<unsigned long long>(submissions_),
diff --git a/runtime/shims/d3d12_precompile.h b/runtime/shims/d3d12_precompile.h
index 447c4db4e..ca96bb764 100644
--- a/runtime/shims/d3d12_precompile.h
+++ b/runtime/shims/d3d12_precompile.h
@@ -8,6 +8,11 @@
8// (src/pipeline_cache_journal.h) under the name the game looks it up by, and in the driver's own disk cache, which 8// (src/pipeline_cache_journal.h) under the name the game looks it up by, and in the driver's own disk cache, which
9// NVIDIA keys by the executable's name. Entries whose journal file is there are skipped, so a run can be stopped at 9// NVIDIA keys by the executable's name. Entries whose journal file is there are skipped, so a run can be stopped at
10// any time and started again. 10// any time and started again.
11//
12// LEONIDA_SKIP_COMPUTE (the play-time list of compute programs whose dispatches are dropped) does not narrow the
13// build: a player runs this with the game's environment, and a program kept out of the journal here would stay out
14// after the list is shortened. --skip-listed leaves the listed entries out on purpose. The last line counts what was
15// built, what was journaled already and what was left out, and why.
11#pragma once 16#pragma once
12 17
13#include <cstddef> 18#include <cstddef>
@@ -25,6 +30,7 @@ struct PrecompileOptions {
25 std::size_t limit = 0; // at most this many entries (0: all) 30 std::size_t limit = 0; // at most this many entries (0: all)
26 std::size_t min_bytes = 0, max_bytes = 0; // SPIR-V size bounds (0: none) 31 std::size_t min_bytes = 0, max_bytes = 0; // SPIR-V size bounds (0: none)
27 std::vector<std::string> filters; // only entries whose name contains one of these 32 std::vector<std::string> filters; // only entries whose name contains one of these
33 bool skip_listed = false; // --skip-listed: leave out the entries LEONIDA_SKIP_COMPUTE names
28 bool dry_run = false; // --list: print the plan, build nothing 34 bool dry_run = false; // --list: print the plan, build nothing
29 bool via_helper = false; // --via-helper: as a title does with LEONIDA_COMPILE_HELPER=1 (a test) 35 bool via_helper = false; // --via-helper: as a title does with LEONIDA_COMPILE_HELPER=1 (a test)
30}; 36};
diff --git a/runtime/shims/d3d12_title_buffer_windows.h b/runtime/shims/d3d12_title_buffer_windows.h
index 06927cb4b..c85809e8e 100644
--- a/runtime/shims/d3d12_title_buffer_windows.h
+++ b/runtime/shims/d3d12_title_buffer_windows.h
@@ -38,6 +38,10 @@ class TitleBufferWindows {
38 std::chrono::steady_clock::time_point failed_at_{}; 38 std::chrono::steady_clock::time_point failed_at_{};
39 bool failed_ = false; 39 bool failed_ = false;
40 bool local_refused_ = false; // device-local blocks refused once: host memory from then on 40 bool local_refused_ = false; // device-local blocks refused once: host memory from then on
41 // SystemMemory: where a device_local allocation goes instead (set_system_memory; GeometryViews from
42 // LEONIDA_GEOMETRY_HOST).
43 int system_memory_ = 0;
44 bool system_memory_logged_ = false;
41 std::uint64_t quick_refusals_ = 0; 45 std::uint64_t quick_refusals_ = 0;
42 // The blocks' (device address, capacity), readable without the owner's lock: published in order, a slot never 46 // The blocks' (device address, capacity), readable without the owner's lock: published in order, a slot never
43 // reused before release(). A destroyed block's slot keeps its other fields and only its address goes to 0 (the 47 // reused before release(). A destroyed block's slot keeps its other fields and only its address goes to 0 (the
@@ -73,7 +77,38 @@ class TitleBufferWindows {
73 blocks_.erase(it); 77 blocks_.erase(it);
74 } 78 }
75 79
80 // The memory types a system-memory block may take: host-visible ones outside device-local memory (the GPU reads
81 // them over the bus), the write-back (cached) ones only when `cached`, else the write-combined ones only. None of
82 // them: every type `bits` allows (an integrated GPU, whose memory is all device-local).
83 template<class Device>
84 static std::uint32_t system_memory_types(const Device& d, std::uint32_t bits, bool cached) {
85 if constexpr (requires { d.memory.memoryTypes[0].propertyFlags; d.memory.memoryTypeCount; }) {
86 std::uint32_t host = 0, wanted = 0;
87 for (std::uint32_t i = 0; i < d.memory.memoryTypeCount && i < 32; ++i) {
88 if (!(bits & (1u << i))) continue;
89 const VkMemoryPropertyFlags f = d.memory.memoryTypes[i].propertyFlags;
90 if ((f & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) || !(f & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) ||
91 !(f & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT))
92 continue;
93 host |= 1u << i;
94 if (bool(f & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) == cached) wanted |= 1u << i;
95 }
96 return wanted ? wanted : host ? host : bits;
97 } else {
98 (void)d;
99 (void)cached;
100 return bits;
101 }
102 }
103
76public: 104public:
105 // Where blocks asked for as device_local go: kDeviceLocal (Resizable BAR while the driver gives it, the default),
106 // kSystemCached (host memory outside VRAM, write-back where the device offers it: what VIctory gives its copies
107 // of title memory) or kSystemUncached (host memory outside VRAM, write-combined). The GPU reads the system-memory
108 // kinds over the bus. Set before the first allocation.
109 static constexpr int kDeviceLocal = 0, kSystemCached = 1, kSystemUncached = 2;
110 void set_system_memory(int kind) { system_memory_ = kind; }
111 int system_memory() const { return system_memory_; }
77 VkDeviceSize reserved() const { return reserved_; } 112 VkDeviceSize reserved() const { return reserved_; }
78 // f(device address, capacity) for each live block; from any thread. 113 // f(device address, capacity) for each live block; from any thread.
79 template <class F> 114 template <class F>
@@ -186,10 +221,26 @@ public:
186 // story load the driver refused every 4 MiB device-local, host-visible block with a device address 221 // story load the driver refused every 4 MiB device-local, host-visible block with a device address
187 // (VK_ERROR_OUT_OF_HOST_MEMORY, speed-8/-9) while host memory still served: once that happens, later blocks 222 // (VK_ERROR_OUT_OF_HOST_MEMORY, speed-8/-9) while host memory still served: once that happens, later blocks
188 // go straight to host memory instead of through DeviceState::allocate's sleeping retries first. 223 // go straight to host memory instead of through DeviceState::allocate's sleeping retries first.
224 // A device_local request under set_system_memory takes system memory instead, out of the types that are not
225 // device-local (memory_type_order would otherwise give the first host-visible type, which can be the BAR).
189 VkMemoryPropertyFlags chosen = 0; 226 VkMemoryPropertyFlags chosen = 0;
190 const bool want_local = device_local && !local_refused_; 227 const bool system = device_local && system_memory_ != kDeviceLocal;
191 b.memory = d.allocate(req, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, 228 const bool want_local = device_local && !local_refused_ && !system;
192 want_local ? VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT : 0, &chosen, true); 229 VkMemoryRequirements types = req;
230 if (system) types.memoryTypeBits = system_memory_types(d, req.memoryTypeBits, system_memory_ == kSystemCached);
231 b.memory = d.allocate(types, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
232 want_local ? VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT
233 : system && system_memory_ == kSystemCached ? VK_MEMORY_PROPERTY_HOST_CACHED_BIT
234 : 0,
235 &chosen, true);
236 if (b.memory && system && !system_memory_logged_) {
237 system_memory_logged_ = true;
238 std::fprintf(stderr, "[rt] d3d12: title buffer copies in system memory (LEONIDA_GEOMETRY_HOST): memory "
239 "flags 0x%x (%s, %s)\n",
240 unsigned(chosen),
241 (chosen & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) ? "device-local: no other type" : "not VRAM",
242 (chosen & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) ? "write-back" : "write-combined");
243 }
193 if (b.memory && want_local && !(chosen & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) { 244 if (b.memory && want_local && !(chosen & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) {
194 local_refused_ = true; 245 local_refused_ = true;
195 std::fprintf(stderr, "[rt] d3d12: title buffer windows: device-local memory refused a %llu KiB block; " 246 std::fprintf(stderr, "[rt] d3d12: title buffer windows: device-local memory refused a %llu KiB block; "
diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp
index ca25ccc9e..f2fa3a45c 100644
--- a/runtime/shims/d3d12_vulkan_device.cpp
+++ b/runtime/shims/d3d12_vulkan_device.cpp
@@ -32,6 +32,7 @@
32#include "dxgi_com.h" 32#include "dxgi_com.h"
33#include "../src/arena_size.h" 33#include "../src/arena_size.h"
34#include "../src/value_write_sink.h" 34#include "../src/value_write_sink.h"
35#include "../src/address_guard.h"
35#include "../src/arena_blocks.h" 36#include "../src/arena_blocks.h"
36#include "../src/gfx10_descriptors.h" 37#include "../src/gfx10_descriptors.h"
37#include "../src/depth24_fragment.h" 38#include "../src/depth24_fragment.h"
@@ -47,6 +48,7 @@
47#include "../src/pipeline_cache_file.h" 48#include "../src/pipeline_cache_file.h"
48#include "../src/pipeline_profile.h" 49#include "../src/pipeline_profile.h"
49#include "../src/submit_phases.h" 50#include "../src/submit_phases.h"
51#include "../src/heavy_pipeline_cache.h"
50#include "../src/pipeline_cache_store.h" 52#include "../src/pipeline_cache_store.h"
51#include "../src/pipeline_cache_journal.h" 53#include "../src/pipeline_cache_journal.h"
52#include "../src/large_module_gate.h" 54#include "../src/large_module_gate.h"
@@ -55,6 +57,7 @@
55#include "../src/resource_detile.h" 57#include "../src/resource_detile.h"
56#include "../src/console_texture_layout.h" 58#include "../src/console_texture_layout.h"
57#include "../src/shader_library.h" 59#include "../src/shader_library.h"
60#include "../src/shadow_keep.h"
58#include "../src/dstorage_trace.h" 61#include "../src/dstorage_trace.h"
59#include "../src/title_page_watch.h" 62#include "../src/title_page_watch.h"
60#include "../src/guarded_copy.h" 63#include "../src/guarded_copy.h"
@@ -65,7 +68,7 @@
65#include "../src/spirv_f16_halves.h" 68#include "../src/spirv_f16_halves.h"
66#include "../src/spirv_stores.h" 69#include "../src/spirv_stores.h"
67#include "../src/title_va_alias.h" 70#include "../src/title_va_alias.h"
68#include "../src/console_heap_vsharp_slots.h" 71#include "../src/console_heap_slot_records.h"
69#include "../src/title_window_plan.h" 72#include "../src/title_window_plan.h"
70#include "../src/vulkan_present.h" 73#include "../src/vulkan_present.h"
71#include "../src/vulkan_device_filter.h" 74#include "../src/vulkan_device_filter.h"
@@ -127,6 +130,8 @@ constexpr VkDeviceSize kZeroPage = 64 * 1024; // zeroed: what unbound vertex an
127constexpr auto kQuadIndicesPerQuad = std::uint32_t(leonida::quad_triangle_indices.size()); 130constexpr auto kQuadIndicesPerQuad = std::uint32_t(leonida::quad_triangle_indices.size());
128constexpr std::uint32_t kQuadIndexCount = 16 * 1024 * kQuadIndicesPerQuad; 131constexpr std::uint32_t kQuadIndexCount = 16 * 1024 * kQuadIndicesPerQuad;
129constexpr VkDeviceSize kArenaReserved = kZeroPage + VkDeviceSize(kQuadIndexCount) * sizeof(std::uint32_t); 132constexpr VkDeviceSize kArenaReserved = kZeroPage + VkDeviceSize(kQuadIndexCount) * sizeof(std::uint32_t);
133// LEONIDA_ADDRESS_GUARD's header and sinks follow the quad indices (src/address_guard.h).
134static_assert(kArenaReserved <= leonida::address_guard::kGuardHeader);
130static_assert(sizeof(leonida::TargetView) <= kDescriptorSize); 135static_assert(sizeof(leonida::TargetView) <= kDescriptorSize);
131// pipeline_cache_store.h reads this layout without vulkan.h (D3D-704); remember the two. 136// pipeline_cache_store.h reads this layout without vulkan.h (D3D-704); remember the two.
132static_assert(sizeof(VkPipelineCacheHeaderVersionOne) == leonida::pipeline_cache_store::header_bytes); 137static_assert(sizeof(VkPipelineCacheHeaderVersionOne) == leonida::pipeline_cache_store::header_bytes);
@@ -159,6 +164,18 @@ void log_once(const char* what, int value) {
159 if (first_diagnostic(what, value)) std::fprintf(stderr, "[rt] d3d12: %s %d\n", what, value); 164 if (first_diagnostic(what, value)) std::fprintf(stderr, "[rt] d3d12: %s %d\n", what, value);
160} 165}
161 166
167// LEONIDA_ADDRESS_GUARD=1: the address guard (docs/d3d12_vulkan.md, "Address guard"). The arena keeps its guard
168// header and sinks at heap_base + 0x70000..0x80000 and a page table of every backing outside it is kept current
169// before each submission, so shaders translated with `rdna2spirv.py --address-guard` read 0 from, and drop stores
170// to, an address nothing backs. Without it those shaders find no header and check nothing.
171bool address_guard_enabled() {
172 static const bool on = [] {
173 wchar_t value[2]{};
174 return GetEnvironmentVariableW(L"LEONIDA_ADDRESS_GUARD", value, 2) == 1 && value[0] == L'1';
175 }();
176 return on;
177}
178
162// Matches the offset interpretation of the selected shader pack. 179// Matches the offset interpretation of the selected shader pack.
163bool signed_vsharp_offsets() { 180bool signed_vsharp_offsets() {
164 static const bool on = [] { 181 static const bool on = [] {
@@ -225,18 +242,24 @@ bool copy_guarded(std::uint8_t* to, const std::uint8_t* from, std::size_t bytes,
225// (streaming, file reads, XG copies) or whole planes (video), never a few bytes inside a page. The same sampling as 242// (streaming, file reads, XG copies) or whole planes (video), never a few bytes inside a page. The same sampling as
226// OpenScarlett's texture hash before submission (src/gpu/d3d12_xs/device_x.cpp, f8e24d4, MIT), with more samples. 243// OpenScarlett's texture hash before submission (src/gpu/d3d12_xs/device_x.cpp, f8e24d4, MIT), with more samples.
227// False when a page faults (the title unmapped it). No C++ objects here: it is a __try frame. 244// False when a page faults (the title unmapped it). No C++ objects here: it is a __try frame.
228inline std::uint64_t mix_words(std::uint64_t h, const std::uint8_t* at, std::size_t n) { 245#pragma pack(push, 1)
246struct UnalignedWord64 {
247 std::uint64_t value;
248};
249#pragma pack(pop)
250
251LEONIDA_GUARDED_NO_BUILTIN inline std::uint64_t mix_words(std::uint64_t h, const std::uint8_t* at, std::size_t n) {
229 for (std::size_t i = 0; i + 8 <= n; i += 8) { 252 for (std::size_t i = 0; i + 8 <= n; i += 8) {
230 std::uint64_t w; 253 const std::uint64_t w = reinterpret_cast<const UnalignedWord64*>(at + i)->value;
231 std::memcpy(&w, at + i, 8);
232 h = (h ^ w) * 0x100000001b3ull; 254 h = (h ^ w) * 0x100000001b3ull;
233 h ^= h >> 29; 255 h ^= h >> 29;
234 } 256 }
235 return h; 257 return h;
236} 258}
237// The reads of hash_guarded, in a frame of its own: an inline load inside the __try is not covered by clang-cl 259// The reads of hash_guarded, in a frame of its own: an inline load inside the __try is not covered by clang-cl
238// without /EHa (src/guarded_copy.h). 260// without /EHa, and a CRT memcpy call is not covered under Wine (src/guarded_copy.h).
239__declspec(noinline) std::uint64_t hash_bytes(const std::uint8_t* p, std::size_t bytes, bool every_byte) { 261__declspec(noinline) LEONIDA_GUARDED_NO_BUILTIN std::uint64_t hash_bytes(const std::uint8_t* p, std::size_t bytes,
262 bool every_byte) {
240 std::uint64_t h = 0x9e3779b97f4a7c15ull ^ bytes; 263 std::uint64_t h = 0x9e3779b97f4a7c15ull ^ bytes;
241 if (bytes <= (256u << 10) || every_byte) { 264 if (bytes <= (256u << 10) || every_byte) {
242 h = mix_words(h, p, bytes & ~std::size_t(7)); 265 h = mix_words(h, p, bytes & ~std::size_t(7));
@@ -358,6 +381,7 @@ public:
358 last_ = (end_ + kPage - 1) & ~(kPage - 1); 381 last_ = (end_ + kPage - 1) & ~(kPage - 1);
359 state_.assign((last_ - first_) / kPage, 0); 382 state_.assign((last_ - first_) / kPage, 0);
360 idle_.assign(state_.size(), 0); 383 idle_.assign(state_.size(), 0);
384 sums_.assign(state_.size() * kPieces, 0);
361 cover_.assign(state_.size(), 1); 385 cover_.assign(state_.size(), 1);
362 targets_.push_back({begin_, end_, shadow}); 386 targets_.push_back({begin_, end_, shadow});
363 index_targets(); 387 index_targets();
@@ -377,6 +401,83 @@ public:
377 ShadowPages(const ShadowPages&) = delete; 401 ShadowPages(const ShadowPages&) = delete;
378 ShadowPages& operator=(const ShadowPages&) = delete; 402 ShadowPages& operator=(const ShadowPages&) = delete;
379 403
404 // What the GPU writes into the copies of [from, to) goes back to the title's pages. Returns the bytes written.
405 // Called before the next refresh, so a page the title writes again is copied forward over the result, as on a GPU
406 // that shares the memory.
407 //
408 // Only the bytes a copy holds differently from the title's page go back, and only on a page known unchanged since
409 // it was copied: guarded (read-only since that copy), or write-watched and found unwritten by an asking made here.
410 // The asking comes first because write_back runs before refresh() asks: a hot page still carried kClean from the
411 // last asking, so the title's writes since then were copied over with the older copy. Comparing first leaves a
412 // read-only binding's pages alone (guarded, so a write the title makes meanwhile faults and waits on the lock),
413 // where opening them for a whole copy lost a write made between the opening and the copy; and of two copies of
414 // the same bytes only the one that differs is written, where the last one won.
415 std::size_t write_back(std::uintptr_t from, std::uintptr_t to) {
416 from = std::max(from, first_), to = std::min(to, last_);
417 if (from >= to) return 0;
418 AcquireSRWLockExclusive(&lock_);
419 // What changed since the last refresh, as refresh() learns it: mappings (the journal), kernel-write pins, and
420 // the write watch. A journal that no longer reaches back makes nothing known: nothing goes back.
421 std::uint64_t map_generation = leonida::title_memory_map::generation();
422 bool known = map_generation_ != ~std::uint64_t(0);
423 if (known && map_generation != map_generation_)
424 known = leonida::title_memory_map::changes_since(
425 map_generation_, map_generation, first_, last_, [&](std::uintptr_t a, std::uintptr_t b) {
426 for (std::size_t i = (a - first_) / kPage, i1 = (b - first_ + kPage - 1) / kPage;
427 i < i1 && i < state_.size(); ++i)
428 state_[i] |= kRequery;
429 });
430 if (!known) {
431 ReleaseSRWLockExclusive(&lock_);
432 return 0;
433 }
434 leonida::kernel_writes::for_each_pin(from, to, [&](std::uintptr_t a, std::uintptr_t b) {
435 for (std::uintptr_t p = std::max(a, from) & ~(kPage - 1); p < std::min(b, to); p += kPage)
436 state_[(p - first_) / kPage] |= kPinned;
437 pinned_ = true;
438 });
439 ask_written_locked();
440 // A page the title wrote since it was last copied holds the newer bytes already: its GPU result is dropped and
441 // the refresh's own copy carries the title's. So is a page whose mapping changed, one a kernel write may be
442 // filling, and one xmem maps at another address too (a write there is seen by no guard and no watch here).
443 const auto held = [&](std::size_t i) {
444 const std::uint8_t s = state_[i];
445 return (s & (kZero | kRequery | kPinned | kAliased)) || (!(s & kProtected) && !(s & kClean));
446 };
447 constexpr std::uintptr_t kPiece = 256; // compared and copied in pieces this size
448 std::size_t written = 0;
449 for (std::uintptr_t at = from & ~(kPage - 1); at < ((to + kPage - 1) & ~(kPage - 1));) {
450 std::size_t pages = 0;
451 while (at + (pages + 1) * kPage <= ((to + kPage - 1) & ~(kPage - 1)) &&
452 held((at - first_) / kPage + pages) == held((at - first_) / kPage))
453 ++pages;
454 if (!held((at - first_) / kPage)) {
455 const std::uintptr_t a = std::max(at, from), b = std::min(at + pages * kPage, to);
456 bool opened = false;
457 for (const Target& t : targets_) {
458 const std::uintptr_t x = std::max(a, t.begin), y = std::min(b, t.end);
459 if (x >= y || !t.shadow) continue;
460 for (std::uintptr_t c = x; c < y;) {
461 const std::uintptr_t e = std::min(y, (c + kPiece) & ~(kPiece - 1));
462 const std::uint8_t* copy = t.shadow + (c - t.begin);
463 if (std::memcmp(reinterpret_cast<const void*>(c), copy, e - c) != 0) {
464 if (!opened) {
465 reopen_locked(at, at + pages * kPage);
466 opened = true;
467 }
468 std::memcpy(reinterpret_cast<void*>(c), copy, e - c);
469 written += e - c;
470 }
471 c = e;
472 }
473 }
474 }
475 at += pages * kPage;
476 }
477 ReleaseSRWLockExclusive(&lock_);
478 return written;
479 }
480
380 // The bytes of all targets, and how many there are. 481 // The bytes of all targets, and how many there are.
381 std::size_t size() const { return target_bytes_; } 482 std::size_t size() const { return target_bytes_; }
382 std::size_t targets() const { return targets_.size(); } 483 std::size_t targets() const { return targets_.size(); }
@@ -453,38 +554,8 @@ public:
453 }); 554 });
454 // The write-watched pages written since the last asking are no longer clean: asked before the walk, so a write 555 // The write-watched pages written since the last asking are no longer clean: asked before the walk, so a write
455 // after this is in the next asking. 556 // after this is in the next asking.
456 const std::uint64_t watch_generation = leonida::title_write_watch::generation();
457 if (watch_generation != watch_generation_) {
458 watch_generation_ = watch_generation;
459 update_watched();
460 }
461 if (runs_stale_) rebuild_watch_runs();
462 refresh_asks_ = refresh_written_ = 0; 557 refresh_asks_ = refresh_written_ = 0;
463 if (!watch_runs_.empty()) { 558 if (ask_written_locked()) cool(); // a block it guards again leaves the runs at the next refresh
464 if (!reader_) {
465 reader_ = leonida::title_write_watch::open_reader();
466 forget_clean();
467 }
468 refresh_asks_ = watch_runs_.size();
469 leonida::title_write_watch::ask(
470 reader_, watch_runs_,
471 [&](std::uintptr_t from, std::uintptr_t to) {
472 for (std::uintptr_t p = from; p < to; p += kPage) {
473 std::uint8_t& s = state_[(p - first_) / kPage];
474 if (!(s & kHot)) continue; // asked over a gap between hot pages: guarded
475 refresh_written_ += (s & kClean) != 0;
476 s &= ~kClean;
477 warm(p);
478 }
479 },
480 [&](std::uintptr_t from, std::uintptr_t to) {
481 // Not write-watched after all (released and reserved again): guarded from now on.
482 for (std::uintptr_t p = from; p < to; p += kPage)
483 state_[(p - first_) / kPage] &= ~(kWatched | kClean | kHot);
484 runs_stale_ = true;
485 });
486 cool(); // a block it guards again leaves the runs at the next refresh
487 }
488 for (std::uintptr_t at = first_; at < last_;) { 559 for (std::uintptr_t at = first_; at < last_;) {
489 const std::size_t i0 = (at - first_) / kPage; 560 const std::size_t i0 = (at - first_) / kPage;
490 if (!cover_[i0]) { // no copy reads it: left as the title set it 561 if (!cover_[i0]) { // no copy reads it: left as the title set it
@@ -533,6 +604,7 @@ public:
533 if (state_[i] & kZero) continue; 604 if (state_[i] & kZero) continue;
534 const auto [offset, bytes] = span_of(i, i + 1); 605 const auto [offset, bytes] = span_of(i, i + 1);
535 zero_targets(offset, bytes); 606 zero_targets(offset, bytes);
607 leonida::shadow_keep::forget(sums_.data(), first_, begin_ + offset, begin_ + offset + bytes);
536 if (!zeroed_.empty() && zeroed_.back().offset + zeroed_.back().bytes == offset) 608 if (!zeroed_.empty() && zeroed_.back().offset + zeroed_.back().bytes == offset)
537 zeroed_.back().bytes += bytes; 609 zeroed_.back().bytes += bytes;
538 else 610 else
@@ -600,6 +672,10 @@ public:
600 pieces_.walk_ms = std::chrono::duration<double, std::milli>(copy_start - walk_start).count(); 672 pieces_.walk_ms = std::chrono::duration<double, std::milli>(copy_start - walk_start).count();
601 std::size_t copied = 0; 673 std::size_t copied = 0;
602 for (const Job& job : jobs_) { 674 for (const Job& job : jobs_) {
675 if (keep_gpu_writes()) { // only the pieces whose title bytes changed (src/shadow_keep.h)
676 copied += copy_changed(job);
677 continue;
678 }
603 std::uint8_t* run_dst = nullptr; 679 std::uint8_t* run_dst = nullptr;
604 const std::uint8_t* run_src = nullptr; 680 const std::uint8_t* run_src = nullptr;
605 std::size_t run_bytes = 0; 681 std::size_t run_bytes = 0;
@@ -650,12 +726,14 @@ public:
650 const std::size_t n = (first_ - first) / kPage; 726 const std::size_t n = (first_ - first) / kPage;
651 state_.insert(state_.begin(), n, std::uint8_t(0)); 727 state_.insert(state_.begin(), n, std::uint8_t(0));
652 idle_.insert(idle_.begin(), n, std::uint8_t(0)); 728 idle_.insert(idle_.begin(), n, std::uint8_t(0));
729 sums_.insert(sums_.begin(), n * kPieces, std::uint64_t(0));
653 cover_.insert(cover_.begin(), n, 0u); 730 cover_.insert(cover_.begin(), n, 0u);
654 first_ = first; 731 first_ = first;
655 } 732 }
656 if (last > last_) { 733 if (last > last_) {
657 state_.resize((last - first_) / kPage, 0); 734 state_.resize((last - first_) / kPage, 0);
658 idle_.resize(state_.size(), 0); 735 idle_.resize(state_.size(), 0);
736 sums_.resize(state_.size() * kPieces, 0);
659 cover_.resize(state_.size(), 0); 737 cover_.resize(state_.size(), 0);
660 last_ = last; 738 last_ = last;
661 } 739 }
@@ -675,6 +753,8 @@ public:
675 state_[at + i] |= other.state_[i]; 753 state_[at + i] |= other.state_[i];
676 cover_[at + i] += other.cover_[i]; 754 cover_[at + i] += other.cover_[i];
677 idle_[at + i] = other.idle_[i]; 755 idle_[at + i] = other.idle_[i];
756 std::copy_n(other.sums_.begin() + std::ptrdiff_t(i * kPieces), kPieces,
757 sums_.begin() + std::ptrdiff_t((at + i) * kPieces));
678 } 758 }
679 targets_.insert(targets_.end(), other.targets_.begin(), other.targets_.end()); 759 targets_.insert(targets_.end(), other.targets_.begin(), other.targets_.end());
680 if (other.map_generation_ != map_generation_) map_generation_ = ~std::uint64_t(0); 760 if (other.map_generation_ != map_generation_) map_generation_ = ~std::uint64_t(0);
@@ -721,15 +801,42 @@ public:
721 kind = classify(region); 801 kind = classify(region);
722 } 802 }
723 const std::uintptr_t from = std::max(at, begin), to = std::min(next, end); 803 const std::uintptr_t from = std::max(at, begin), to = std::min(next, end);
724 if (kind == Kind::zero) 804 if (kind == Kind::zero) {
725 std::memset(shadow + (from - begin), 0, to - from); 805 std::memset(shadow + (from - begin), 0, to - from);
726 else 806 } else {
727 copy_run(shadow + (from - begin), reinterpret_cast<const std::uint8_t*>(from), to - from, 807 const bool streaming = (region.Protect & PAGE_WRITECOMBINE) != 0;
728 (region.Protect & PAGE_WRITECOMBINE) != 0); 808 copy_run(shadow + (from - begin), reinterpret_cast<const std::uint8_t*>(from), to - from, streaming);
809 // The sums stand for what every target holds. The new target now holds the title's current bytes, so
810 // the pieces where those differ from the sums are brought to the other targets too, and the sums
811 // follow; otherwise a title that later writes the old bytes back would leave the new target behind.
812 // Whole pieces (inside this page, so this region) up to the targets' ends, as a refresh sums them: a
813 // piece cut at the new target's edge would be summed short and copied again at the next refresh.
814 constexpr std::uintptr_t kPiece = leonida::shadow_keep::kPiece;
815 if (keep_gpu_writes())
816 reconcile(std::max(from & ~(kPiece - 1), begin_), std::min((to + kPiece - 1) & ~(kPiece - 1), end_),
817 streaming);
818 }
729 at = next; 819 at = next;
730 } 820 }
731 } 821 }
732 822
823 // [from, to), readable title pages: the pieces whose bytes differ from the sums are copied to every target over
824 // them and their sums updated, as a refresh does.
825 void reconcile(std::uintptr_t from, std::uintptr_t to, bool streaming) {
826 alignas(64) std::uint8_t page[kPage];
827 for (std::uintptr_t va = from; va < to;) {
828 const std::size_t n = std::min<std::size_t>(to - va, kPage - (va & (kPage - 1)));
829 copy_run(page, reinterpret_cast<const std::uint8_t*>(va), n, streaming);
830 leonida::shadow_keep::copy_changed(
831 page, va, n, sums_.data(), first_, [&](std::uintptr_t a, std::uintptr_t b, const std::uint8_t* source) {
832 for_each_target(a, b, [&](const Target& t, std::uintptr_t lo, std::uintptr_t hi) {
833 std::memcpy(t.shadow + (lo - t.begin), source + (lo - a), hi - lo);
834 });
835 });
836 va += n;
837 }
838 }
839
733 // Under shadow_mutex: `shadow` is no longer a target. Pages no other target covers are made writable again and 840 // Under shadow_mutex: `shadow` is no longer a target. Pages no other target covers are made writable again and
734 // passed over from now on. False when it isn't one of this tracker's. 841 // passed over from now on. False when it isn't one of this tracker's.
735 bool remove_target(const std::uint8_t* shadow) { 842 bool remove_target(const std::uint8_t* shadow) {
@@ -858,6 +965,42 @@ private:
858 return s == kProtected || s == (kWatched | kProtected) || s == (kWatched | kHot | kClean); 965 return s == kProtected || s == (kWatched | kProtected) || s == (kWatched | kHot | kClean);
859 } 966 }
860 967
968 // One asking of the write watch, under lock_: the hot pages written since the last asking lose kClean (counted in
969 // refresh_written_). From refresh() before its walk, and from write_back() before it trusts kClean. False when no
970 // page is write-watched here.
971 bool ask_written_locked() {
972 const std::uint64_t watch_generation = leonida::title_write_watch::generation();
973 if (watch_generation != watch_generation_) {
974 watch_generation_ = watch_generation;
975 update_watched();
976 }
977 if (runs_stale_) rebuild_watch_runs();
978 if (watch_runs_.empty()) return false;
979 if (!reader_) {
980 reader_ = leonida::title_write_watch::open_reader();
981 forget_clean();
982 }
983 refresh_asks_ += watch_runs_.size();
984 leonida::title_write_watch::ask(
985 reader_, watch_runs_,
986 [&](std::uintptr_t from, std::uintptr_t to) {
987 for (std::uintptr_t p = from; p < to; p += kPage) {
988 std::uint8_t& s = state_[(p - first_) / kPage];
989 if (!(s & kHot)) continue; // asked over a gap between hot pages: guarded
990 refresh_written_ += (s & kClean) != 0;
991 s &= ~kClean;
992 warm(p);
993 }
994 },
995 [&](std::uintptr_t from, std::uintptr_t to) {
996 // Not write-watched after all (released and reserved again): guarded from now on.
997 for (std::uintptr_t p = from; p < to; p += kPage)
998 state_[(p - first_) / kPage] &= ~(kWatched | kClean | kHot);
999 runs_stale_ = true;
1000 });
1001 return true;
1002 }
1003
861 // A hot page `p` was found written: its block is not idle. 1004 // A hot page `p` was found written: its block is not idle.
862 void warm(std::uintptr_t p) { 1005 void warm(std::uintptr_t p) {
863 const std::uintptr_t block = p & ~(kBlock - 1); 1006 const std::uintptr_t block = p & ~(kBlock - 1);
@@ -1127,6 +1270,40 @@ private:
1127 jobs_.push_back({offset, bytes, streaming, aliased}); 1270 jobs_.push_back({offset, bytes, streaming, aliased});
1128 } 1271 }
1129 1272
1273 // LEONIDA_SHADOW_KEEP (on; 0: every job copied whole, as before): a job's bytes reach the copies only where they
1274 // differ from those copied last (src/shadow_keep.h), so a shader's write into a copy of pages copied without a
1275 // sign that the title wrote them stays until the title changes those bytes.
1276 // shortcut: a title that rewrites the same bytes to reset a GPU-written value is not seen; needs a real write
1277 // signal (a write-back to the title's pages) then.
1278 static bool keep_gpu_writes() {
1279 static const bool on = [] {
1280 char value[2] = {};
1281 std::size_t length = 0;
1282 return getenv_s(&length, value, sizeof(value), "LEONIDA_SHADOW_KEEP") != 0 || length == 0 ||
1283 value[0] != '0';
1284 }();
1285 return on;
1286 }
1287 static constexpr std::size_t kPieces = kPage / leonida::shadow_keep::kPiece;
1288 std::size_t copy_changed(const Job& job) {
1289 std::size_t copied = 0;
1290 alignas(64) std::uint8_t page[kPage];
1291 for (std::size_t at = job.offset, end = job.offset + job.bytes; at < end;) {
1292 const std::uintptr_t va = begin_ + at;
1293 const std::size_t n = std::min<std::size_t>(end - at, kPage - (va & (kPage - 1)));
1294 copy_run(page, reinterpret_cast<const std::uint8_t*>(va), n, job.streaming);
1295 leonida::shadow_keep::copy_changed(
1296 page, va, n, sums_.data(), first_, [&](std::uintptr_t a, std::uintptr_t b, const std::uint8_t* source) {
1297 for_each_target(a, b, [&](const Target& t, std::uintptr_t from, std::uintptr_t to) {
1298 std::memcpy(t.shadow + (from - t.begin), source + (from - a), to - from);
1299 copied += to - from;
1300 });
1301 });
1302 at += n;
1303 }
1304 return copied;
1305 }
1306
1130 // The targets sorted by start, the bytes they hold, and reach_[k], the furthest end among targets_[0..k]: the 1307 // The targets sorted by start, the bytes they hold, and reach_[k], the furthest end among targets_[0..k]: the
1131 // targets over [from, to) are found from the first whose reach passes `from`. 1308 // targets over [from, to) are found from the first whose reach passes `from`.
1132 void index_targets() { 1309 void index_targets() {
@@ -1260,6 +1437,7 @@ private:
1260 std::uint64_t reader_ = 0; 1437 std::uint64_t reader_ = 0;
1261 std::size_t watched_pages_ = 0, hot_pages_ = 0; // covered pages write-watched, and hot 1438 std::size_t watched_pages_ = 0, hot_pages_ = 0; // covered pages write-watched, and hot
1262 Vector<std::uint8_t> idle_; // per 4 KiB page: refreshes a hot page went without a write (kCool) 1439 Vector<std::uint8_t> idle_; // per 4 KiB page: refreshes a hot page went without a write (kCool)
1440 Vector<std::uint64_t> sums_; // per 256-byte piece from first_: sum of the bytes copied last, 0: not known
1263 bool runs_stale_ = false; // a page became hot or cold: watch_runs_ is rebuilt at the next refresh 1441 bool runs_stale_ = false; // a page became hot or cold: watch_runs_ is rebuilt at the next refresh
1264 std::uint64_t refresh_asks_ = 0; 1442 std::uint64_t refresh_asks_ = 0;
1265 std::uint64_t refresh_written_ = 0; 1443 std::uint64_t refresh_written_ = 0;
@@ -1499,6 +1677,30 @@ std::filesystem::path pipeline_cache_session_path() {
1499 return path; 1677 return path;
1500} 1678}
1501 1679
1680// The pipelines the offline seed does not have, kept next to it and written while the game runs
1681// (src/heavy_pipeline_cache.h).
1682std::filesystem::path pipeline_cache_heavy_path() {
1683 std::filesystem::path path = pipeline_cache_path();
1684 if (!path.empty()) path.replace_filename(L"pipeline_cache.heavy.bin");
1685 return path;
1686}
1687
1688// LEONIDA_HEAVY_PIPELINE_CACHE_MS: a compile at least this long schedules a write of the heavy cache; 0 turns the
1689// heavy cache off. One line for a value that is not a number.
1690std::uint32_t heavy_pipeline_cache_ms() {
1691 static const std::uint32_t ms = [] {
1692 char text[32] = {};
1693 size_t length = 0;
1694 const bool present = getenv_s(&length, text, "LEONIDA_HEAVY_PIPELINE_CACHE_MS") == 0 && length > 1;
1695 const auto threshold = leonida::heavy_pipeline_cache::parse_threshold(present ? text : "");
1696 if (!threshold.valid)
1697 std::fprintf(stderr, "[rt] d3d12: LEONIDA_HEAVY_PIPELINE_CACHE_MS=%s is not a number of milliseconds; "
1698 "using %u\n", text, threshold.ms);
1699 return threshold.ms;
1700 }();
1701 return ms;
1702}
1703
1502std::size_t pipeline_cache_save_limit(); 1704std::size_t pipeline_cache_save_limit();
1503 1705
1504// LOCAL FIX (pipeline journal, pipeline_cache_journal.h): where each compute pipeline's own cache file goes, beside 1706// LOCAL FIX (pipeline journal, pipeline_cache_journal.h): where each compute pipeline's own cache file goes, beside
@@ -1529,6 +1731,10 @@ const std::filesystem::path& pipeline_journal_dir() {
1529 return pipeline_journal_roots().writable; 1731 return pipeline_journal_roots().writable;
1530} 1732}
1531 1733
1734// The offline seed's size (pipeline_cache.bin) when the device cache was created from it, 0 otherwise: the save limit
1735// does not count it (pipeline_cache_store::over_save_limit).
1736std::atomic<std::size_t> g_offline_seed_bytes{0};
1737
1532// LEONIDA_PIPELINE_CACHE_BYTES, in bytes; 0 turns the session file off. One line for a value that is not a number. 1738// LEONIDA_PIPELINE_CACHE_BYTES, in bytes; 0 turns the session file off. One line for a value that is not a number.
1533std::size_t pipeline_cache_save_limit() { 1739std::size_t pipeline_cache_save_limit() {
1534 char text[32] = {}; 1740 char text[32] = {};
@@ -1601,6 +1807,7 @@ VkPipelineCache create_seeded_pipeline_cache(PFN_vkCreatePipelineCache create_ca
1601 return VK_NULL_HANDLE; 1807 return VK_NULL_HANDLE;
1602 } 1808 }
1603 std::fprintf(stderr, "[rt] d3d12: loaded %zu bytes from %s\n", seed.size(), name); 1809 std::fprintf(stderr, "[rt] d3d12: loaded %zu bytes from %s\n", seed.size(), name);
1810 if (!session) g_offline_seed_bytes.store(seed.size(), std::memory_order_relaxed);
1604 if (trace_pipeline_compile()) 1811 if (trace_pipeline_compile())
1605 std::fprintf(stderr, "[rt] pipeline-cache op=load bytes=%zu map_us=%lld driver_us=%lld file=%s\n", 1812 std::fprintf(stderr, "[rt] pipeline-cache op=load bytes=%zu map_us=%lld driver_us=%lld file=%s\n",
1606 seed.size(), mapped-start, compile_us()-mapped, name); 1813 seed.size(), mapped-start, compile_us()-mapped, name);
@@ -1649,6 +1856,7 @@ bool merge_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDe
1649// never built and every dispatch of theirs is dropped ("all" or "*": every compute program). For getting past a 1856// never built and every dispatch of theirs is dropped ("all" or "*": every compute program). For getting past a
1650// program that hangs the GPU, such as a translated loop that never ends on the input it is given here, while the 1857// program that hangs the GPU, such as a translated loop that never ends on the input it is given here, while the
1651// program or its input is being fixed. What the program would have written keeps its previous contents. 1858// program or its input is being fixed. What the program would have written keeps its previous contents.
1859// gta6rt --precompile-pipelines builds the listed programs anyway unless it is given --skip-listed.
1652bool skip_compute(const std::string& name) { 1860bool skip_compute(const std::string& name) {
1653 static const std::vector<std::string> parts = [] { 1861 static const std::vector<std::string> parts = [] {
1654 std::vector<std::string> out; 1862 std::vector<std::string> out;
@@ -1741,16 +1949,17 @@ bool startup_cache_checkpoints_enabled() {
1741void save_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache, 1949void save_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache,
1742 bool checkpoint = false, const char* op = nullptr) { 1950 bool checkpoint = false, const char* op = nullptr) {
1743 if (!cache || !vk.vkGetPipelineCacheData) return; 1951 if (!cache || !vk.vkGetPipelineCacheData) return;
1744 auto limit = pipeline_cache_save_limit(); 1952 // The output is an opaque Vulkan blob. A prefix is not an incremental cache, so past the limit nothing is written.
1745 // The output is an opaque Vulkan blob. A prefix is not an incremental cache. 1953 const auto limit = pipeline_cache_save_limit();
1746 if (checkpoint) limit = (std::min)(limit, std::size_t{512} << 20);
1747 if (!limit) return; 1954 if (!limit) return;
1748 const auto start = compile_us(); 1955 const auto start = compile_us();
1749 std::size_t size = 0; 1956 std::size_t size = 0;
1750 if (vk.vkGetPipelineCacheData(device, cache, &size, nullptr) != VK_SUCCESS || 1957 if (vk.vkGetPipelineCacheData(device, cache, &size, nullptr) != VK_SUCCESS ||
1751 size <= sizeof(VkPipelineCacheHeaderVersionOne)) return; 1958 size <= sizeof(VkPipelineCacheHeaderVersionOne)) return;
1752 if (size > limit) { 1959 const std::size_t seed = g_offline_seed_bytes.load(std::memory_order_relaxed);
1753 std::fprintf(stderr, "[rt] d3d12: pipeline cache is %zu bytes, over the %zu-byte write limit\n", size, limit); 1960 if (leonida::pipeline_cache_store::over_save_limit(size, seed, limit)) {
1961 std::fprintf(stderr, "[rt] d3d12: pipeline cache is %zu bytes (%zu of them the offline seed), over the "
1962 "%zu-byte write limit for what a session adds\n", size, seed, limit);
1754 return; 1963 return;
1755 } 1964 }
1756 const auto queried = compile_us(); 1965 const auto queried = compile_us();
@@ -1776,6 +1985,66 @@ void save_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDev
1776 else std::fprintf(stderr, "[rt] d3d12: pipeline cache snapshot incomplete (%d); previous session retained\n", int(result)); 1985 else std::fprintf(stderr, "[rt] d3d12: pipeline cache snapshot incomplete (%d); previous session retained\n", int(result));
1777} 1986}
1778 1987
1988// The heavy cache, seeded from pipeline_cache.heavy.bin when it is there and made for this device; empty otherwise.
1989VkPipelineCache create_heavy_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device,
1990 const leonida::cached_pso::Identity& identity) {
1991 const auto path = pipeline_cache_heavy_path();
1992 clean_stale_cache_files(path);
1993 VkPipelineCache cache = VK_NULL_HANDLE;
1994 {
1995 const PipelineCacheSeed seed(path);
1996 if (seed.data() && seed.compatible(identity)) {
1997 const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, nullptr, 0,
1998 seed.size(), seed.data()};
1999 if (vk.vkCreatePipelineCache(device, &create, nullptr, &cache) == VK_SUCCESS) {
2000 std::fprintf(stderr, "[rt] d3d12: loaded %zu bytes from pipeline_cache.heavy.bin\n", seed.size());
2001 return cache;
2002 }
2003 std::fprintf(stderr, "[rt] d3d12: Vulkan declined pipeline_cache.heavy.bin; starting it empty\n");
2004 } else if (seed.data()) {
2005 std::fprintf(stderr, "[rt] d3d12: pipeline_cache.heavy.bin does not match this Vulkan device; starting "
2006 "it empty\n");
2007 }
2008 }
2009 const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO};
2010 if (vk.vkCreatePipelineCache(device, &create, nullptr, &cache) != VK_SUCCESS) return VK_NULL_HANDLE;
2011 return cache;
2012}
2013
2014// Writes the heavy cache whole: a staging file renamed over pipeline_cache.heavy.bin, so the file on disk is always
2015// a complete blob. It only holds what the offline seed missed, so it has no size limit of its own.
2016bool save_heavy_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache,
2017 std::uint64_t compiles, std::uint64_t hits) {
2018 if (!cache || !vk.vkGetPipelineCacheData) return false;
2019 const auto path = pipeline_cache_heavy_path();
2020 if (path.empty()) return false;
2021 const auto start = compile_us();
2022 std::size_t size = 0;
2023 if (vk.vkGetPipelineCacheData(device, cache, &size, nullptr) != VK_SUCCESS ||
2024 size <= sizeof(VkPipelineCacheHeaderVersionOne))
2025 return false;
2026 CacheStagingFile staging(path, size);
2027 if (!staging.data) {
2028 std::fprintf(stderr, "[rt] d3d12: could not map a staging file for %zu heavy pipeline cache bytes\n", size);
2029 return false;
2030 }
2031 auto written = size;
2032 const VkResult result = vk.vkGetPipelineCacheData(device, cache, &written, staging.data);
2033 // VK_INCOMPLETE means the cache grew after the size query and the blob is a truncated snapshot; it must not
2034 // replace a complete file. The writer tries again later with a fresh size.
2035 const bool ok = result == VK_SUCCESS && written > sizeof(VkPipelineCacheHeaderVersionOne) && written <= size &&
2036 staging.publish(path, written);
2037 if (ok)
2038 std::fprintf(stderr, "[rt] d3d12: wrote %zu bytes to pipeline_cache.heavy.bin in %.1f s (%llu slow builds "
2039 "and %llu other builds past the offline cache so far)\n",
2040 written, double(compile_us() - start) / 1e6, static_cast<unsigned long long>(compiles),
2041 static_cast<unsigned long long>(hits));
2042 else
2043 std::fprintf(stderr, "[rt] d3d12: pipeline_cache.heavy.bin not written (%d); the previous file is kept\n",
2044 int(result));
2045 return ok;
2046}
2047
1779// A shader whose subgroup size cannot be had runs at the device's: inexact if it crosses the halves of a wave64 (or, 2048// A shader whose subgroup size cannot be had runs at the device's: inexact if it crosses the halves of a wave64 (or,
1780// for a wave32 shader on a 64-wide default, reads lanes that are not its own), unless the translator's 2049// for a wave32 shader on a 64-wide default, reads lanes that are not its own), unless the translator's
1781// partition-invariance tier says otherwise. Logged once per stage with the first shader's name, then again at 10, 100, 2050// partition-invariance tier says otherwise. Logged once per stage with the first shader's name, then again at 10, 100,
@@ -2411,6 +2680,105 @@ struct DeviceState {
2411 return pipeline_cache_handle; 2680 return pipeline_cache_handle;
2412 } 2681 }
2413 2682
2683 // The heavy pipeline cache (src/heavy_pipeline_cache.h) and the thread that writes it.
2684 std::once_flag heavy_cache_once;
2685 VkPipelineCache heavy_cache_handle = VK_NULL_HANDLE;
2686 std::mutex heavy_mutex;
2687 std::condition_variable heavy_wake;
2688 leonida::heavy_pipeline_cache::WriteSchedule heavy_schedule; // under heavy_mutex
2689 bool heavy_stop = false; // under heavy_mutex
2690 std::thread heavy_writer; // started at the first slow build
2691 std::atomic<std::uint64_t> heavy_compiles{0}, heavy_hits{0};
2692 std::atomic<bool> heavy_changed{false}; // a build went into the heavy cache since it was loaded
2693
2694 VkPipelineCache heavy_cache() {
2695 std::call_once(heavy_cache_once, [this] {
2696 if (context->vk.vkCreatePipelineCache)
2697 heavy_cache_handle = create_heavy_pipeline_cache(context->vk, info.device, pso_identity);
2698 });
2699 return heavy_cache_handle;
2700 }
2701
2702 // A build past the offline cache took `took_ms`: a slow one schedules a write.
2703 void note_heavy_build(ULONGLONG took_ms) {
2704 heavy_changed = true;
2705 if (took_ms < heavy_pipeline_cache_ms()) {
2706 ++heavy_hits;
2707 return;
2708 }
2709 ++heavy_compiles;
2710 std::lock_guard lock(heavy_mutex);
2711 if (heavy_stop) return;
2712 heavy_schedule.note_heavy(GetTickCount64());
2713 if (!heavy_writer.joinable()) {
2714 try {
2715 heavy_writer = std::thread([this] { write_heavy_cache_loop(); });
2716 } catch (const std::exception&) {
2717 return; // no thread: the cache is still written at teardown
2718 }
2719 }
2720 heavy_wake.notify_one();
2721 }
2722
2723 void write_heavy_cache_loop() {
2724 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);
2725 std::unique_lock lock(heavy_mutex);
2726 while (!heavy_stop) {
2727 if (!heavy_schedule.dirty()) {
2728 heavy_wake.wait(lock);
2729 continue;
2730 }
2731 const std::uint64_t now = GetTickCount64();
2732 if (!heavy_schedule.due(now)) {
2733 heavy_wake.wait_for(lock, std::chrono::milliseconds(heavy_schedule.due_ms() - now));
2734 continue;
2735 }
2736 const std::uint64_t generation = heavy_schedule.generation();
2737 lock.unlock();
2738 const bool saved = save_heavy_pipeline_cache(context->vk, info.device, heavy_cache_handle,
2739 heavy_compiles.load(), heavy_hits.load());
2740 lock.lock();
2741 // A failed write leaves the cache dirty: it is tried again after a growing delay, not only at teardown.
2742 if (saved) heavy_schedule.written(generation, now);
2743 else heavy_schedule.failed(now);
2744 }
2745 }
2746
2747 // At device teardown, with no build running: stop the writer and write the cache if any build went into it.
2748 // Fast builds never schedule a write, so this is where they are kept: without an offline seed every build is
2749 // a miss, and these are the builds pipeline_cache.session.bin used to keep.
2750 void finish_heavy_cache() {
2751 {
2752 std::lock_guard lock(heavy_mutex);
2753 heavy_stop = true;
2754 }
2755 heavy_wake.notify_all();
2756 if (heavy_writer.joinable()) heavy_writer.join();
2757 if (!heavy_cache_handle) return;
2758 if (heavy_changed.load() && !active_compiles.load())
2759 save_heavy_pipeline_cache(context->vk, info.device, heavy_cache_handle, heavy_compiles.load(),
2760 heavy_hits.load());
2761 context->vk.vkDestroyPipelineCache(info.device, heavy_cache_handle, nullptr);
2762 heavy_cache_handle = VK_NULL_HANDLE;
2763 }
2764
2765 // vkCreateGraphicsPipelines through `create(cache, flags)` (compute pipelines have their journal). With the heavy
2766 // cache, the offline cache is asked first without compiling; a pipeline it does not have is built against the heavy
2767 // cache, which a slow build then writes back to disk. A caller that already asked for a cache-only create keeps it.
2768 template <class Create>
2769 VkResult create_pipeline(VkPipelineCreateFlags flags, Create&& create) {
2770 constexpr VkPipelineCreateFlags cache_only = VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT;
2771 const VkPipelineCache corpus = pipeline_cache();
2772 if (!info.heavy_pipeline_cache || (flags & cache_only)) return create(corpus, flags);
2773 const VkResult cached = create(corpus, flags | cache_only);
2774 if (cached != VK_PIPELINE_COMPILE_REQUIRED) return cached;
2775 const VkPipelineCache heavy = heavy_cache();
2776 const ULONGLONG started = GetTickCount64();
2777 const VkResult built = create(heavy ? heavy : corpus, flags);
2778 if (built == VK_SUCCESS && heavy) note_heavy_build(GetTickCount64() - started);
2779 return built;
2780 }
2781
2414 QueueClock clock; // device-wide calibration entry points 2782 QueueClock clock; // device-wide calibration entry points
2415 std::vector<std::uint32_t> timestamp_bits; 2783 std::vector<std::uint32_t> timestamp_bits;
2416 2784
@@ -2548,6 +2916,7 @@ struct DeviceState {
2548 if (!pages) return; 2916 if (!pages) return;
2549 const leonida::submit_phases::Scope timed(leonida::submit_phases::shadows); 2917 const leonida::submit_phases::Scope timed(leonida::submit_phases::shadows);
2550 std::lock_guard lock(shadow_mutex); 2918 std::lock_guard lock(shadow_mutex);
2919 write_back_titles(); // what the last submission wrote in the copies, before the forward copy below
2551 if (shadows.empty()) return; 2920 if (shadows.empty()) return;
2552 const auto start = clock::now(); 2921 const auto start = clock::now();
2553 // LEONIDA_SHADOW_ALIAS_MS (0 by default: every submission): pages xmem maps at two addresses that a write 2922 // LEONIDA_SHADOW_ALIAS_MS (0 by default: every submission): pages xmem maps at two addresses that a write
@@ -2675,7 +3044,24 @@ struct DeviceState {
2675 std::atomic<std::size_t> title_window_count{0}; // title_windows.size(), read without the mutex 3044 std::atomic<std::size_t> title_window_count{0}; // title_windows.size(), read without the mutex
2676 std::uint64_t title_window_bytes = 0; 3045 std::uint64_t title_window_bytes = 0;
2677 std::uint64_t title_window_cap = 64ull << 20; 3046 std::uint64_t title_window_cap = 64ull << 20;
2678 // The stream pools' mappings (title_gpu_views): one per readable run of a pool, kept for the device's life. 3047 // What the GPU wrote into a copy of the title's memory goes back to the title's pages: the ranges reached since
3048 // the last submission (title_va_alias.h note_reached), copied back at the next refresh before the forward copy.
3049 // A window is a read-side mirror, so without this a UAV or a raw write lands in the copy and the title never sees
3050 // it (#1537, the WRITE_INVALID stop at the world start).
3051 std::mutex title_write_back_mutex; // its own: taken under shadow_mutex, never the other way round
3052 std::map<std::uint64_t, std::uint64_t> title_write_back; // start -> end, of the submission about to run
3053 std::deque<std::pair<std::uint64_t, std::map<std::uint64_t, std::uint64_t>>> title_write_back_pending; // by ticket
3054 std::uint64_t title_write_back_refused = 0; // ranges past the caps, logged once
3055 std::uint64_t title_write_back_bytes = 0; // queued for this submission
3056 std::uint64_t title_write_back_total = 0; // copied back, all submissions
3057 std::uint64_t title_write_back_calls = 0; // log line count
3058 std::uint64_t title_write_back_unfenced = 0;
3059 static constexpr std::size_t kTitleWriteBackBatches = 64; // pending batches before the oldest goes back unfenced
3060 static constexpr std::size_t kTitleWriteBackRanges = 8192; // ranges kept per submission
3061 static constexpr std::uint64_t kTitleWriteBackBytes = 64ull << 20; // bytes copied back per submission
3062 // The stream pools' mappings (title_gpu_views): one per readable run of a pool. A window is kept for the device's
3063 // life; a geometry copy goes when its view is retired (the pages were freed, unmapped or remapped:
3064 // drain_geometry_releases), and the next request for those pages makes a new one.
2679 struct PoolSpan { 3065 struct PoolSpan {
2680 std::uint64_t source; // the readable side of the pair the copy is made from 3066 std::uint64_t source; // the readable side of the pair the copy is made from
2681 std::uint64_t twin; // the extent's address in the pair's other view (0 when there is none) 3067 std::uint64_t twin; // the extent's address in the pair's other view (0 when there is none)
@@ -2686,6 +3072,7 @@ struct DeviceState {
2686 std::vector<PoolSpan> pool_spans; 3072 std::vector<PoolSpan> pool_spans;
2687 std::atomic<std::size_t> pool_span_count{0}; 3073 std::atomic<std::size_t> pool_span_count{0};
2688 std::uint64_t pool_span_bytes = 0; 3074 std::uint64_t pool_span_bytes = 0;
3075 std::uint64_t pool_spans_retired = 0; // geometry-copy extents whose view was retired (forget_pool_span)
2689 std::uint64_t title_window_refusals = 0; // windows neither the budget nor the arena allowed 3076 std::uint64_t title_window_refusals = 0; // windows neither the budget nor the arena allowed
2690 std::uint64_t unbacked_requests = 0; // title addresses no backing could be made for (zero-size views) 3077 std::uint64_t unbacked_requests = 0; // title addresses no backing could be made for (zero-size views)
2691 3078
@@ -2707,26 +3094,67 @@ struct DeviceState {
2707 // another queue's replay that translated its slots before this retirement may still name it. A ticket read here 3094 // another queue's replay that translated its slots before this retirement may still name it. A ticket read here
2708 // would be one short of this submission, which records its own only after before_execute_ (and with an idle GPU 3095 // would be one short of this submission, which records its own only after before_execute_ (and with an idle GPU
2709 // the view would be reaped in this very call). 3096 // the view would be reaped in this very call).
3097 // A retired view's last copy is made here from the title's pages as they are now, when they are still readable
3098 // (GeometryViews::retire_range).
3099 // A stream-pool extent it backed leaves pool_spans: the next request for those pages makes a new mapping.
2710 void drain_geometry_releases() { 3100 void drain_geometry_releases() {
2711 if (!context || !geometry.has_pending_reclaim()) return; 3101 if (!context || !geometry.has_pending_reclaim()) return;
2712 const std::uint64_t completed_ticket = geometry.has_retired() ? context->completed_retire_ticket() : 0; 3102 const std::uint64_t completed_ticket = geometry.has_retired() ? context->completed_retire_ticket() : 0;
2713 geometry.drain_released(*this, rt::d3d12::GeometryViews::kAfterExecutes, completed_ticket, 3103 geometry.drain_released(
2714 forget_geometry_alias); 3104 *this, rt::d3d12::GeometryViews::kAfterExecutes, completed_ticket,
3105 [this](std::uintptr_t source, std::size_t size, VkDeviceSize va) {
3106 forget_geometry_alias(source, size, va);
3107 forget_pool_span(va);
3108 },
3109 copy_geometry);
3110 }
3111 void forget_pool_span(VkDeviceSize va) {
3112 std::lock_guard windows(title_window_mutex);
3113 const auto it = std::find_if(pool_spans.begin(), pool_spans.end(),
3114 [&](const PoolSpan& span) { return span.geometry && span.shader_va == va; });
3115 if (it == pool_spans.end()) return;
3116 pool_span_bytes -= it->size;
3117 pool_spans.erase(it);
3118 pool_span_count.store(pool_spans.size(), std::memory_order_relaxed);
3119 ++pool_spans_retired;
2715 } 3120 }
2716 // ExecuteCommandLists replays in progress, for GeometryViews::kAfterExecutes (see drain_geometry_releases). 3121 // ExecuteCommandLists replays in progress, for GeometryViews::kAfterExecutes (see drain_geometry_releases).
2717 static std::vector<std::uint64_t>& geometry_execute_serials() { 3122 // A plain aggregate on purpose: a C++ thread_local with a destructor in gta6rt.exe adds TLS callbacks to the image
2718 thread_local std::vector<std::uint64_t> serials; 3123 // the loader's TLS index-0 move must not have (pe_loader.cpp reserve_tls_index0; VulkanContext::stage_xdxr_table
3124 // keeps its range list a member for the same reason). A std::vector here made the title's CRT abort at startup.
3125 struct GeometryExecuteSerials {
3126 static constexpr unsigned kCapacity = 32; // a replay has not been seen nested this deep
3127 std::uint64_t serials[kCapacity]{};
3128 unsigned count{};
3129 unsigned skipped{}; // replays begun while the stack was full: the innermost, ended first
3130 };
3131 static GeometryExecuteSerials& geometry_execute_serials() {
3132 thread_local GeometryExecuteSerials serials;
2719 return serials; 3133 return serials;
2720 } 3134 }
2721 void geometry_execute_begin() { 3135 void geometry_execute_begin() {
2722 if (!geometry.cap()) return; 3136 if (!geometry.cap()) return;
2723 geometry_execute_serials().push_back(geometry.execute_begin()); 3137 auto& serials = geometry_execute_serials();
3138 if (serials.count == GeometryExecuteSerials::kCapacity) {
3139 static std::atomic<bool> logged{false};
3140 if (!logged.exchange(true))
3141 std::fprintf(stderr, "[rt] d3d12: ExecuteCommandLists nested more than %u deep; a geometry view retired "
3142 "in the extra replay is not deferred to it\n",
3143 GeometryExecuteSerials::kCapacity);
3144 ++serials.skipped;
3145 return;
3146 }
3147 serials.serials[serials.count++] = geometry.execute_begin();
2724 } 3148 }
2725 void geometry_execute_end() { 3149 void geometry_execute_end() {
3150 if (!geometry.cap()) return;
2726 auto& serials = geometry_execute_serials(); 3151 auto& serials = geometry_execute_serials();
2727 if (!geometry.cap() || serials.empty()) return; 3152 if (serials.skipped != 0) {
2728 const std::uint64_t serial = serials.back(); 3153 --serials.skipped;
2729 serials.pop_back(); 3154 return;
3155 }
3156 if (serials.count == 0) return;
3157 const std::uint64_t serial = serials.serials[--serials.count];
2730 geometry.execute_end(serial, [this] { return context->submitted_retire_ticket(); }); 3158 geometry.execute_end(serial, [this] { return context->submitted_retire_ticket(); });
2731 } 3159 }
2732 static rt::d3d12::GeometryCopy copy_geometry(std::uint8_t* to, const std::uint8_t* from, std::size_t size) { 3160 static rt::d3d12::GeometryCopy copy_geometry(std::uint8_t* to, const std::uint8_t* from, std::size_t size) {
@@ -2818,7 +3246,8 @@ struct DeviceState {
2818 std::uint8_t* mapped{}; 3246 std::uint8_t* mapped{};
2819 if (arena_allocate(size, kTitleWindowAlign, offset, arena_buffer)) { 3247 if (arena_allocate(size, kTitleWindowAlign, offset, arena_buffer)) {
2820 mapped = arena.mapped + offset; 3248 mapped = arena.mapped + offset;
2821 } else if (stream_windows() && external_windows.allocate(*this, size, offset, mapped)) { 3249 } else if (leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::windows);
3250 stream_windows() && external_windows.allocate(*this, size, offset, mapped)) {
2822 external_window_made.store(true, std::memory_order_release); 3251 external_window_made.store(true, std::memory_order_release);
2823 } else { 3252 } else {
2824 ++title_window_refusals; 3253 ++title_window_refusals;
@@ -2840,6 +3269,93 @@ struct DeviceState {
2840 return offset; 3269 return offset;
2841 } 3270 }
2842 3271
3272 // A binding of the title's memory reached for the coming submission: keep its range for the copy back after it.
3273 // Over-inclusive on purpose (a read-only view costs a copy, a write is never missed: a V# has no read/write bit).
3274 void note_title_write(std::uint64_t va, std::uint64_t bytes) {
3275 static const bool on = [] {
3276 char value[2] = {};
3277 std::size_t length = 0;
3278 return getenv_s(&length, value, sizeof(value), "LEONIDA_TITLE_WRITEBACK") != 0 || value[0] != '0';
3279 }();
3280 if (!on || !va || !bytes) return;
3281 std::uint64_t lo = 0, hi = 0;
3282 if (!leonida::title_va_aliases().title_memory(va, lo, hi) || va >= hi) return;
3283 const std::uint64_t end = va + std::min(bytes, hi - va);
3284 std::lock_guard lock(title_write_back_mutex);
3285 auto it = title_write_back.lower_bound(va);
3286 if (it != title_write_back.begin()) {
3287 auto previous = std::prev(it);
3288 if (previous->second >= va) {
3289 if (previous->second < end) previous->second = end;
3290 return;
3291 }
3292 }
3293 if (it != title_write_back.end() && it->first <= end) {
3294 it->second = std::max(it->second, end);
3295 return;
3296 }
3297 if (title_write_back.size() >= kTitleWriteBackRanges || title_write_back_bytes >= kTitleWriteBackBytes) {
3298 if (!title_write_back_refused++)
3299 log_once("past LEONIDA_TITLE_WRITEBACK's caps: reached ranges are not copied back this submission; "
3300 "ranges refused:",
3301 1);
3302 return;
3303 }
3304 title_write_back_bytes += end - va;
3305 title_write_back.emplace(va, end);
3306 }
3307
3308 // What the GPU wrote into those copies goes back to the title's pages, so a later read by the title or the next
3309 // forward copy sees it. Only once the submission that wrote them has completed: a batch carries the ticket of the
3310 // submission after it (a submission's commands are recorded before it exists), and is copied back when the
3311 // context reports that ticket done. Runs at the start of a refresh, under shadow_mutex and before the forward
3312 // copies, so a page the title wrote again is copied forward over the result.
3313 void write_back_titles() {
3314 if (!&context) return;
3315 const std::uint64_t done = context->completed_retire_ticket();
3316 std::vector<std::pair<uint64_t, std::uint64_t>> finished; // one entry per range, collected under the lock
3317 {
3318 std::lock_guard lock(title_write_back_mutex);
3319 if (!title_write_back.empty()) {
3320 // The ranges of the submission about to execute, which is the next ticket.
3321 title_write_back_pending.push_back({context->submitted_retire_ticket() + 1,
3322 std::move(title_write_back)});
3323 title_write_back.clear();
3324 title_write_back_bytes = 0;
3325 }
3326 bool forced = false;
3327 while (!title_write_back_pending.empty() &&
3328 (title_write_back_pending.front().first <= done ||
3329 title_write_back_pending.size() > kTitleWriteBackBatches)) {
3330 forced = forced || title_write_back_pending.front().first > done;
3331 for (const auto& [begin, end] : title_write_back_pending.front().second)
3332 finished.push_back({begin, end});
3333 title_write_back_pending.pop_front();
3334 }
3335 // A queue held deep (console ordering) can leave batches waiting: the oldest go back anyway, once each.
3336 if (forced && !title_write_back_unfenced++)
3337 log_once("more than 64 title write-back batches wait on their submissions: the oldest are copied "
3338 "back without their ticket; batches:",
3339 1);
3340 }
3341 if (finished.empty()) return;
3342 std::uint64_t written = 0, ranges = 0;
3343 for (const auto& [begin, end] : finished)
3344 for (const ShadowPagesPtr& s : shadows)
3345 if (end > s->first() && begin < s->last()) {
3346 const std::uint64_t bytes = s->write_back(begin, end);
3347 written += bytes;
3348 ranges += bytes != 0;
3349 }
3350 title_write_back_total += written;
3351 if (!written) return;
3352 if (++title_write_back_calls <= 4 || !(title_write_back_calls & (title_write_back_calls - 1)))
3353 std::fprintf(stderr, "[rt] d3d12: %llu KiB of the GPU's writes in %llu reached range(s) went back to the "
3354 "title's pages (%llu KiB so far)\n",
3355 static_cast<unsigned long long>(written >> 10), static_cast<unsigned long long>(ranges),
3356 static_cast<unsigned long long>(title_write_back_total >> 10));
3357 }
3358
2843 // A stream pool's address (a CPU view paired with a GPU-only alias). Rule B 3359 // A stream pool's address (a CPU view paired with a GPU-only alias). Rule B
2844 // first: the CPU view is where the host reads the frames, so that is what the copy is made from; the GPU-only 3360 // first: the CPU view is where the host reads the frames, so that is what the copy is made from; the GPU-only
2845 // pages are the same frames through the title's queue slot 31 and are read only when the CPU view is not 3361 // pages are the same frames through the title's queue slot 31 and are read only when the CPU view is not
@@ -3199,8 +3715,8 @@ struct DeviceState {
3199 for (auto& t : b.triangles) { 3715 for (auto& t : b.triangles) {
3200 const std::uint64_t triangles = (t.index_type ? t.index_count : t.vertex_count) / 3; 3716 const std::uint64_t triangles = (t.index_type ? t.index_count : t.vertex_count) / 3;
3201 if (!triangles) continue; 3717 if (!triangles) continue;
3202 // Unindexed: three vertices a triangle. Indexed: the VertexCount the title declared (indices past 3718 // Unindexed: three vertices a triangle. Indexed: the VertexCount the title declared (an index past
3203 // it read past the buffer, as on the console). 3719 // it is not read: xdxr_build.comp vertex() makes its triangle inactive).
3204 const std::uint64_t vertices = t.index_type ? t.vertex_count : 3 * triangles; 3720 const std::uint64_t vertices = t.index_type ? t.vertex_count : 3 * triangles;
3205 const std::uint64_t element = t.vertex_format == VK_FORMAT_R32G32_SFLOAT ? 8 : 12; 3721 const std::uint64_t element = t.vertex_format == VK_FORMAT_R32G32_SFLOAT ? 8 : 12;
3206 const std::uint64_t vertex_bytes = vertices ? (vertices - 1) * t.vertex_stride + element : 0; 3722 const std::uint64_t vertex_bytes = vertices ? (vertices - 1) * t.vertex_stride + element : 0;
@@ -3485,36 +4001,67 @@ struct DeviceState {
3485 } 4001 }
3486 4002
3487 // Indexed by actual Vulkan address, never by a placed buffer's CPU address. 4003 // Indexed by actual Vulkan address, never by a placed buffer's CPU address.
3488 static bool filter_heap_releases() {
3489 static const bool on = [] {
3490 const auto* v = std::getenv("LEONIDA_CONSOLE_RELEASE_FILTER");
3491 return v && std::strcmp(v, "1") == 0;
3492 }();
3493 return on;
3494 }
3495 leonida::DescriptorRangeChanges backing_changes;
3496 std::atomic<uint64_t> released_backings{};
3497 std::atomic<uint64_t> backing_generation{}; // every add and release 4004 std::atomic<uint64_t> backing_generation{}; // every add and release
3498 std::mutex backing_mutex; 4005 std::mutex backing_mutex;
3499 leonida::BufferVaIndex<uint64_t> gpu_backings; 4006 leonida::BufferVaIndex<uint64_t> gpu_backings;
4007
4008 // What changed for the console heaps' slot records (ConsoleHeap::records) since the last submission: backings and
4009 // copies released or added, alias ranges removed or added, title memory added. Unbounded: every change is applied
4010 // at the next refresh_console_heaps, which takes the whole list. Written from any thread, under the lock of what
4011 // changed (backing_mutex, the alias table's); slot_change_mutex is taken last and nothing is taken under it.
4012 // Nothing is kept before a console resource heap with a CPU copy exists (no slot has a record then).
4013 std::mutex slot_change_mutex;
4014 std::vector<leonida::SlotChange> slot_changes;
4015 std::atomic<bool> slot_records_live{false};
4016 void note_slot_change(leonida::SlotChange::Kind kind, std::uint64_t lo, std::uint64_t bytes) {
4017 if (!bytes || !slot_records_live.load(std::memory_order_acquire)) return;
4018 const std::uint64_t hi = lo + bytes < lo ? UINT64_MAX : lo + bytes;
4019 std::lock_guard lock(slot_change_mutex);
4020 slot_changes.push_back({kind, lo, hi});
4021 }
4022 // A device range [address, address + bytes) as the V# bases that name it directly: arena offsets in the V#'s 48
4023 // bits (a buffer below the arena, as sign-extended offsets, vsharp_address). Nothing for a range no V# reaches.
4024 void note_slot_source_added(VkDeviceAddress address, std::uint64_t bytes) {
4025 constexpr std::uint64_t mask = (1ull << 48) - 1;
4026 const std::uint64_t offset = address - arena.address;
4027 if (offset <= mask) note_slot_change(leonida::SlotChange::source_added, offset, bytes);
4028 else if (offset >= ~(mask >> 1)) note_slot_change(leonida::SlotChange::source_added, offset & mask, bytes);
4029 }
4030 // The alias table's changes (TitleVaAliases::add_listener), under its lock.
4031 static void alias_changed(void* device, leonida::TitleVaAliases::Change change, std::uint64_t title_va,
4032 std::uint64_t bytes, std::uint64_t shader_va) {
4033 auto& self = *static_cast<DeviceState*>(device);
4034 using Change = leonida::TitleVaAliases::Change;
4035 if (change == Change::removed) {
4036 // What resolved through the range (by its base), and what names its copy (by the copy's address).
4037 self.note_slot_change(leonida::SlotChange::source_gone, title_va, bytes);
4038 self.note_slot_change(leonida::SlotChange::target_gone, self.arena.address + shader_va, bytes);
4039 } else {
4040 self.note_slot_change(leonida::SlotChange::source_added, title_va, bytes);
4041 }
4042 }
4043
3500 // A title-window or geometry-copy block was destroyed (TitleBufferWindows::destroy_block; its GPU work completed): 4044 // A title-window or geometry-copy block was destroyed (TitleBufferWindows::destroy_block; its GPU work completed):
3501 // as for a released backing, the backed table cuts it and the key entries and heap slots answering into it go at 4045 // as for a released backing, the backed table cuts it and the key entries and heap slots answering into it go at
3502 // the next refresh, so no table names the freed memory. 4046 // the next refresh, so no table names the freed memory.
3503 void title_block_gone(VkDeviceAddress address, VkDeviceSize bytes) { 4047 void title_block_gone(VkDeviceAddress address, VkDeviceSize bytes) {
3504 std::lock_guard lock(backing_mutex); 4048 std::lock_guard lock(backing_mutex);
3505 if (filter_heap_releases()) backing_changes.record(address, bytes);
3506 backing_generation.fetch_add(1, std::memory_order_relaxed); 4049 backing_generation.fetch_add(1, std::memory_order_relaxed);
3507 released_backings.fetch_add(1, std::memory_order_release); 4050 note_slot_change(leonida::SlotChange::target_gone, address, bytes);
3508 if (heap_gpu) released_ranges.emplace_back(address - arena.address, bytes); 4051 if (heap_gpu) released_ranges.emplace_back(address - arena.address, bytes);
3509 } 4052 }
3510 void backing(VkDeviceAddress address, uint64_t bytes, uint64_t id, bool add) { 4053 void backing(VkDeviceAddress address, uint64_t bytes, uint64_t id, bool add) {
3511 std::lock_guard lock(backing_mutex); 4054 std::lock_guard lock(backing_mutex);
3512 if (filter_heap_releases()) backing_changes.record(address, bytes);
3513 backing_generation.fetch_add(1, std::memory_order_relaxed); 4055 backing_generation.fetch_add(1, std::memory_order_relaxed);
3514 if (add) gpu_backings.insert(address, bytes, id); 4056 if (add) {
3515 else { 4057 gpu_backings.insert(address, bytes, id);
4058 // A V# that named this range before it was backed, directly or through an alias, can resolve now.
4059 note_slot_change(leonida::SlotChange::target_added, address, bytes);
4060 note_slot_source_added(address, bytes);
4061 } else {
3516 gpu_backings.erase(address, id); 4062 gpu_backings.erase(address, id);
3517 released_backings.fetch_add(1, std::memory_order_release); 4063 // The heap slots whose copy names it are fixed again at the next refresh.
4064 note_slot_change(leonida::SlotChange::target_gone, address, bytes);
3518 // LEONIDA_CONSOLE_HEAP_GPU: the key entries answering into it go at the next refresh. 4065 // LEONIDA_CONSOLE_HEAP_GPU: the key entries answering into it go at the next refresh.
3519 if (heap_gpu) released_ranges.emplace_back(address - arena.address, bytes); 4066 if (heap_gpu) released_ranges.emplace_back(address - arena.address, bytes);
3520 } 4067 }
@@ -3523,8 +4070,11 @@ struct DeviceState {
3523 enum class VsharpPath { table, shadow, scratch }; 4070 enum class VsharpPath { table, shadow, scratch };
3524 enum class VsharpResult { unchanged, rebased, empty }; 4071 enum class VsharpResult { unchanged, rebased, empty };
3525 4072
4073 // `refused` (when given): for an answer of 0, the copy an alias range named that was not backed (0: none), so the
4074 // console heap's slot record is found again when a backing is added there.
3526 uint64_t vsharp_address(uint64_t base, uint64_t bytes, leonida::TitleVaAliases::Kind kind = leonida::TitleVaAliases::created_view, 4075 uint64_t vsharp_address(uint64_t base, uint64_t bytes, leonida::TitleVaAliases::Kind kind = leonida::TitleVaAliases::created_view,
3527 bool make_window = true, bool try_geometry = false) { 4076 bool make_window = true, bool try_geometry = false, uint64_t* refused = nullptr) {
4077 if (refused) *refused = 0;
3528 if (!base || !bytes) return 0; 4078 if (!base || !bytes) return 0;
3529 auto& aliases = leonida::title_va_aliases(); 4079 auto& aliases = leonida::title_va_aliases();
3530 constexpr uint64_t mask = (1ull << 48) - 1; 4080 constexpr uint64_t mask = (1ull << 48) - 1;
@@ -3551,7 +4101,10 @@ struct DeviceState {
3551 const auto path = [this](unsigned p) { vsharp_paths[p].fetch_add(1, std::memory_order_relaxed); }; 4101 const auto path = [this](unsigned p) { vsharp_paths[p].fetch_add(1, std::memory_order_relaxed); };
3552 uint64_t to{}, room{}; 4102 uint64_t to{}, room{};
3553 if (aliases.range_of(base, to, room)) { 4103 if (aliases.range_of(base, to, room)) {
3554 if (!to || room < bytes || !backed(to)) return path(1), 0; 4104 if (!to || room < bytes || !backed(to)) {
4105 if (refused) *refused = to;
4106 return path(1), 0;
4107 }
3555 aliases.note_translation(kind); 4108 aliases.note_translation(kind);
3556 return path(0), to; 4109 return path(0), to;
3557 } 4110 }
@@ -3571,6 +4124,7 @@ struct DeviceState {
3571 uint64_t mapped{}; 4124 uint64_t mapped{};
3572 if (to && aliases.range_of(base, mapped, room) && mapped == to && room >= bytes && backed(to)) 4125 if (to && aliases.range_of(base, mapped, room) && mapped == to && room >= bytes && backed(to))
3573 return path(4), to; 4126 return path(4), to;
4127 if (refused) *refused = to;
3574 } 4128 }
3575 return path(5), 0; 4129 return path(5), 0;
3576 } 4130 }
@@ -3578,7 +4132,51 @@ struct DeviceState {
3578 static constexpr unsigned kVsharpPathCount = 6; 4132 static constexpr unsigned kVsharpPathCount = 6;
3579 std::array<std::atomic<std::uint64_t>, kVsharpPathCount> vsharp_paths{}; 4133 std::array<std::atomic<std::uint64_t>, kVsharpPathCount> vsharp_paths{};
3580 4134
3581 VsharpResult fix_vsharp(uint32_t* w, VsharpPath path) { 4135 // LEONIDA_UNBACKED_VSHARP=1 (diagnostic): the buffer V#s fix_vsharp writes empty because nothing backs their base.
4136 // One line for each of the first 120 distinct bases (span and stride), and every 8192 such V#s a summary by 4 GiB
4137 // range of the base, so the address ranges the world's data comes from can be compared with the title memory.
4138 static void note_unbacked_vsharp(uint64_t base, uint64_t span, uint32_t stride, const uint32_t* w) {
4139 static const bool on = [] {
4140 const char* v = std::getenv("LEONIDA_UNBACKED_VSHARP");
4141 return v && *v == '1';
4142 }();
4143 if (!on) return;
4144 static std::mutex mutex;
4145 static std::unordered_map<uint64_t, uint64_t> seen; // base -> span
4146 static std::map<uint64_t, uint64_t> by_range; // base >> 32 -> distinct bases
4147 static uint64_t count = 0;
4148 std::lock_guard lock(mutex);
4149 ++count;
4150 if (seen.emplace(base, span).second) {
4151 ++by_range[base >> 32];
4152 if (seen.size() <= 120)
4153 std::fprintf(stderr,
4154 "[rt] unbacked-vsharp: #%zu base 0x%llx span %llu stride %u words %08x %08x %08x %08x\n",
4155 seen.size(), static_cast<unsigned long long>(base), static_cast<unsigned long long>(span),
4156 stride, w[0], w[1], w[2], w[3]);
4157 }
4158 if (!(count % 8192)) {
4159 std::vector<std::pair<uint64_t, uint64_t>> top;
4160 for (const auto& [range, n] : by_range) top.emplace_back(n, range);
4161 std::sort(top.rbegin(), top.rend());
4162 std::string text;
4163 char item[64];
4164 for (std::size_t i = 0; i < top.size() && i < 10; ++i) {
4165 std::snprintf(item, sizeof(item), "%s0x%llx00000000 x%llu", i ? "; " : "",
4166 static_cast<unsigned long long>(top[i].second), static_cast<unsigned long long>(top[i].first));
4167 text += item;
4168 }
4169 std::fprintf(stderr, "[rt] unbacked-vsharp: %llu empty V#s, %zu distinct bases; by 4 GiB range: %s\n",
4170 static_cast<unsigned long long>(count), seen.size(), text.c_str());
4171 }
4172 }
4173
4174 // What fix_vsharp resolved a V# to, for a console heap's slot record (ConsoleHeapSlotRecords::set).
4175 struct VsharpRecord {
4176 leonida::ConsoleHeapSlotRecords::State state = leonida::ConsoleHeapSlotRecords::none;
4177 uint64_t base = 0, span = 0, target = 0;
4178 };
4179 VsharpResult fix_vsharp(uint32_t* w, VsharpPath path, VsharpRecord* record = nullptr) {
3582 if ((w[3] >> 30) || !w[2]) return VsharpResult::unchanged; // image, empty slot or raw pointer 4180 if ((w[3] >> 30) || !w[2]) return VsharpResult::unchanged; // image, empty slot or raw pointer
3583 const uint64_t base = uint64_t(w[0]) | (uint64_t(w[1] & 0xffff) << 32); 4181 const uint64_t base = uint64_t(w[0]) | (uint64_t(w[1] & 0xffff) << 32);
3584 const uint32_t stride = (w[1] >> 16) & 0x3fffu; 4182 const uint32_t stride = (w[1] >> 16) & 0x3fffu;
@@ -3587,8 +4185,16 @@ struct DeviceState {
3587 leonida::gfx10::Buffer desc{}; 4185 leonida::gfx10::Buffer desc{};
3588 const bool copy_geometry = leonida::gfx10::decode(words, desc) && 4186 const bool copy_geometry = leonida::gfx10::decode(words, desc) &&
3589 (path != VsharpPath::scratch || span <= kTitleWindowMax || (desc.format && leonida::gfx10::encode(desc) == words)); 4187 (path != VsharpPath::scratch || span <= kTitleWindowMax || (desc.format && leonida::gfx10::encode(desc) == words));
4188 uint64_t refused = 0;
3590 const auto to = vsharp_address(base, span, leonida::TitleVaAliases::table_view, 4189 const auto to = vsharp_address(base, span, leonida::TitleVaAliases::table_view,
3591 path != VsharpPath::scratch, copy_geometry); 4190 path != VsharpPath::scratch, copy_geometry, &refused);
4191 if (record) {
4192 // The copy's device address (mod 2^64: a buffer below the arena has a negative offset).
4193 record->state = to ? leonida::ConsoleHeapSlotRecords::resolved : leonida::ConsoleHeapSlotRecords::waiting;
4194 record->base = base;
4195 record->span = span;
4196 record->target = to ? arena.address + to : refused ? arena.address + refused : 0;
4197 }
3592 if (!to) { 4198 if (!to) {
3593 static std::atomic_flag noted[3]{}; 4199 static std::atomic_flag noted[3]{};
3594 if (!noted[unsigned(path)].test_and_set(std::memory_order_relaxed)) { 4200 if (!noted[unsigned(path)].test_and_set(std::memory_order_relaxed)) {
@@ -3597,6 +4203,7 @@ struct DeviceState {
3597 std::fprintf(stderr, "[rt] d3d12: %s V# at 0x%llx (%llu bytes) has no GPU backing; zero records\n", 4203 std::fprintf(stderr, "[rt] d3d12: %s V# at 0x%llx (%llu bytes) has no GPU backing; zero records\n",
3598 where, (unsigned long long)base, (unsigned long long)span); 4204 where, (unsigned long long)base, (unsigned long long)span);
3599 } 4205 }
4206 note_unbacked_vsharp(base, span, stride, w);
3600 w[0] = w[1] = w[2] = 0; 4207 w[0] = w[1] = w[2] = 0;
3601 return VsharpResult::empty; 4208 return VsharpResult::empty;
3602 } 4209 }
@@ -3792,13 +4399,13 @@ struct DeviceState {
3792 [](const PoolSpan& span) { return span.geometry; }); 4399 [](const PoolSpan& span) { return span.geometry; });
3793 std::fprintf(stderr, 4400 std::fprintf(stderr,
3794 "[rt] d3d12: title memory: %zu windows (%llu KiB of a %llu MiB budget, %llu refused), %zu " 4401 "[rt] d3d12: title memory: %zu windows (%llu KiB of a %llu MiB budget, %llu refused), %zu "
3795 "stream-pool extents (one mapping each, %llu KiB; %lld by geometry copy), %llu addresses " 4402 "stream-pool extents (one mapping each, %llu KiB; %lld by geometry copy, %llu retired with "
3796 "given a zero-size view\n", 4403 "their copy), %llu addresses given a zero-size view\n",
3797 title_windows.size(), static_cast<unsigned long long>(title_window_bytes >> 10), 4404 title_windows.size(), static_cast<unsigned long long>(title_window_bytes >> 10),
3798 static_cast<unsigned long long>(title_window_cap >> 20), 4405 static_cast<unsigned long long>(title_window_cap >> 20),
3799 static_cast<unsigned long long>(title_window_refusals), pool_spans.size(), 4406 static_cast<unsigned long long>(title_window_refusals), pool_spans.size(),
3800 static_cast<unsigned long long>(pool_span_bytes >> 10), 4407 static_cast<unsigned long long>(pool_span_bytes >> 10),
3801 static_cast<long long>(geometry_spans), 4408 static_cast<long long>(geometry_spans), static_cast<unsigned long long>(pool_spans_retired),
3802 static_cast<unsigned long long>(unbacked_requests)); 4409 static_cast<unsigned long long>(unbacked_requests));
3803 } 4410 }
3804 } 4411 }
@@ -3813,7 +4420,7 @@ struct DeviceState {
3813 backing(arena.address + offset, bytes, offset, false); 4420 backing(arena.address + offset, bytes, offset, false);
3814 arena.in_use -= bytes; 4421 arena.in_use -= bytes;
3815 arena.use_in_use[use] -= bytes; 4422 arena.use_in_use[use] -= bytes;
3816 // A heap copy re-fixes its slots when a backing has gone (released_backings): the range is no view's. 4423 // A heap copy re-fixes the slots that named a backing that has gone (slot_changes): the range is no view's.
3817 backing(arena.address + offset, bytes, offset, false); 4424 backing(arena.address + offset, bytes, offset, false);
3818 } 4425 }
3819 if (fault != leonida::ArenaBlocks::Fault::none && arena_report_due()) { 4426 if (fault != leonida::ArenaBlocks::Fault::none && arena_report_due()) {
@@ -3875,25 +4482,17 @@ struct DeviceState {
3875 VkDeviceMemory memory = VK_NULL_HANDLE; 4482 VkDeviceMemory memory = VK_NULL_HANDLE;
3876 std::uint64_t pin = 0; // the imported pages' leonida::kernel_writes pin while `memory` lives 4483 std::uint64_t pin = 0; // the imported pages' leonida::kernel_writes pin while `memory` lives
3877 std::size_t scan_at = 0; // the next slot the T# scan reads 4484 std::size_t scan_at = 0; // the next slot the T# scan reads
3878 uint64_t checked_generation{}, alias_generation{}, backing_cursor{}, alias_cursor{};
3879 uint64_t release_sweeps{}, release_candidates{}, release_fixes{}, release_rebases{}, release_full{};
3880 // copy 4485 // copy
3881 bool identity = false; 4486 bool identity = false;
3882 ShadowPagesPtr pages; 4487 ShadowPagesPtr pages;
3883 std::vector<std::uint8_t> mirror; // the title's bytes as the tracker last copied them 4488 std::vector<std::uint8_t> mirror; // the title's bytes as the tracker last copied them
3884 std::vector<std::uint8_t> made; // the title's bytes each arena slot was last made from 4489 std::vector<std::uint8_t> made; // the title's bytes each arena slot was last made from
3885 std::vector<std::uint8_t> retry; // per slot: not settled yet (fix_console_slot), in `retries` 4490 std::vector<std::uint8_t> retry; // per slot: not settled yet (fix_console_slot), in `retries`
3886 leonida::ConsoleHeapVsharpSlots live_vsharps; // slots whose GPU copy holds a live buffer V# 4491 // A resource heap's V# halves: what each resolved to (fix_console_slot), so a change of the address space
4492 // re-fixes the slots it touches (apply_slot_changes), and a V# whose buffer comes later is fixed when it does.
4493 leonida::ConsoleHeapSlotRecords records;
3887 std::vector<std::uint32_t> retries; 4494 std::vector<std::uint32_t> retries;
3888 std::set<std::uint32_t> empty_slots;
3889 std::uint32_t next_empty = 0;
3890 std::size_t retry_at = 0; // where retry_console_slots goes on 4495 std::size_t retry_at = 0; // where retry_console_slots goes on
3891 // V#s naming an address nothing backs that is not the title's memory: null in the copy, and looked at again a
3892 // few times (kUnmappedTries, at most kUnmappedRetrySlots a submission) in case their buffer is made after the
3893 // descriptor.
3894 std::vector<std::uint8_t> unmapped_tries; // per slot: 0, or the looks so far (it is in `unmapped`)
3895 std::vector<std::uint32_t> unmapped;
3896 std::size_t unmapped_at = 0;
3897 // fix_console_slots' budget, for the current refresh, and the slots it nulled since the last log line 4496 // fix_console_slots' budget, for the current refresh, and the slots it nulled since the last log line
3898 std::chrono::steady_clock::time_point fix_start{}; 4497 std::chrono::steady_clock::time_point fix_start{};
3899 bool fix_over = false; 4498 bool fix_over = false;
@@ -3908,10 +4507,11 @@ struct DeviceState {
3908 double ms = 0, pages_ms = 0, fix_ms = 0, retry_ms = 0; // ms: all; the others its parts 4507 double ms = 0, pages_ms = 0, fix_ms = 0, retry_ms = 0; // ms: all; the others its parts
3909 // Changed slots by class (before the fix budget), since the last log line: all-zero, V# pair, T#, other 4508 // Changed slots by class (before the fix budget), since the last log line: all-zero, V# pair, T#, other
3910 // words; V# halves whose 16 bytes were seen before (a direct-mapped memo of 65536 keys, so a lower bound of 4509 // words; V# halves whose 16 bytes were seen before (a direct-mapped memo of 65536 keys, so a lower bound of
3911 // how often an exact-key translation would be found again); rescans after a backing release and their cost. 4510 // how often an exact-key translation would be found again); the slot records' work: changes applied, index
4511 // entries looked at, slots fixed again, and its time.
3912 std::uint64_t changed[4] = {}, vsharp_halves = 0, vsharp_repeats = 0; 4512 std::uint64_t changed[4] = {}, vsharp_halves = 0, vsharp_repeats = 0;
3913 std::uint64_t rescans = 0, rescanned = 0; 4513 std::uint64_t record_changes = 0, record_looked = 0, record_refixed = 0;
3914 double rescan_ms = 0; 4514 double record_ms = 0;
3915 std::vector<std::array<std::uint32_t, 4>> seen_keys; 4515 std::vector<std::array<std::uint32_t, 4>> seen_keys;
3916 // LEONIDA_CONSOLE_HEAP_GPU (DeviceState::attach_console_heap_gpu): the translation pass's index of this heap 4516 // LEONIDA_CONSOLE_HEAP_GPU (DeviceState::attach_console_heap_gpu): the translation pass's index of this heap
3917 // (-1: fixed on the CPU), the import of `input` the pass reads, the slots holding a V# pair (translated again 4517 // (-1: fixed on the CPU), the import of `input` the pass reads, the slots holding a V# pair (translated again
@@ -3987,38 +4587,31 @@ struct DeviceState {
3987 return true; 4587 return true;
3988 } 4588 }
3989 4589
3990 // Slot `slot` of a heap copy, as the title wrote it, fixed up as described above. True when it is settled: not a 4590 // Slot `slot` of a heap copy, as the title wrote it, fixed up as described above, and the only writer of a
3991 // T# whose texture is still to come, nor a V# into the title's memory that got no copy. `unmapped` (when given) is 4591 // resource heap's slot records. True when it is settled: not a T# whose texture is still to come. A sampler heap
3992 // set for a V# written null because its base is neither the title's memory nor anything of the device's: settled, 4592 // holds S#s: copied as written.
3993 // but its buffer may still be made (the round-robin probe in refresh_console_heap). A sampler heap holds S#s: 4593 bool fix_console_slot(ConsoleHeap& heap, std::size_t slot) {
3994 // copied as written.
3995 bool fix_console_slot(ConsoleHeap& heap, std::size_t slot, bool* unmapped = nullptr) {
3996 std::uint32_t w[kDescriptorSize / 4]; 4594 std::uint32_t w[kDescriptorSize / 4];
3997 std::memcpy(w, heap.previous + slot * kDescriptorSize, kDescriptorSize); 4595 std::memcpy(w, heap.previous + slot * kDescriptorSize, kDescriptorSize);
3998 bool settled = true, empty = false; 4596 bool settled = true, vsharp = false;
3999 if (unmapped) *unmapped = false; 4597 VsharpRecord halves[2];
4000 const VsharpPath path = heap.scratch ? VsharpPath::scratch : VsharpPath::shadow; 4598 const VsharpPath path = heap.scratch ? VsharpPath::scratch : VsharpPath::shadow;
4001 if (!heap.resource_heap || !(w[0] | w[1] | w[2] | w[3])) { 4599 if (!heap.resource_heap || !(w[0] | w[1] | w[2] | w[3])) {
4002 // A sampler heap holds S#s (copied as written); an all-zero slot stays null. 4600 // A sampler heap holds S#s (copied as written); an all-zero slot stays null.
4003 } else if (!(w[3] >> 30)) { 4601 } else if (!(w[3] >> 30)) {
4004 // A buffer V#: rewritten to the address its bytes are backed at (fix_vsharp: the console shadow, or the 4602 // A buffer V#: rewritten to the address its bytes are backed at (fix_vsharp: the console shadow, or the
4005 // console scratch an imported heap rewrites). A base nothing backs is written with no base and no records, 4603 // console scratch an imported heap rewrites). A base nothing backs is written with no base and no records
4006 // settled, and left for the bounded round-robin probe in refresh_console_heap in case its buffer is made 4604 // and recorded as waiting: a backing, alias range or title memory added over it fixes the slot again
4007 // after the descriptor. 4605 // (apply_slot_changes).
4008 const VsharpResult result = fix_vsharp(w, path); 4606 vsharp = true;
4607 const VsharpResult result = fix_vsharp(w, path, &halves[0]);
4009 if (result == VsharpResult::rebased) ++heap.vsharps; 4608 if (result == VsharpResult::rebased) ++heap.vsharps;
4010 if (result == VsharpResult::empty) { 4609 // Only the GPU copy changes; the title's bytes (heap.previous) stay as written.
4011 // Only the GPU copy changes; the title's bytes (heap.previous) stay as written. 4610 if (result == VsharpResult::empty) ++heap.unbacked;
4012 ++heap.unbacked;
4013 empty = true;
4014 }
4015 // The slot's second V# is a UAV counter (raw, 4 bytes, in the descriptor's upper 16 bytes): a store to it at 4611 // The slot's second V# is a UAV counter (raw, 4 bytes, in the descriptor's upper 16 bytes): a store to it at
4016 // heap_base + a raw title address loses the device just as one through the buffer V# does. A counter with 4612 // heap_base + a raw title address loses the device just as one through the buffer V# does. A counter with
4017 // no backing is nulled and left to retry_console_slots. 4613 // no backing is nulled and waits as the buffer V# does.
4018 if (fix_vsharp(w + 4, path) == VsharpResult::empty) { 4614 if (fix_vsharp(w + 4, path, &halves[1]) == VsharpResult::empty) ++heap.unbacked;
4019 ++heap.unbacked;
4020 empty = true;
4021 }
4022 } else { 4615 } else {
4023 leonida::gfx10::ImageWords words; 4616 leonida::gfx10::ImageWords words;
4024 std::memcpy(words.data(), w, sizeof(words)); 4617 std::memcpy(words.data(), w, sizeof(words));
@@ -4037,15 +4630,20 @@ struct DeviceState {
4037 // Neither a buffer V# (TYPE is not 0) nor a T# the layer can decode: data the title keeps in the slot. 4630 // Neither a buffer V# (TYPE is not 0) nor a T# the layer can decode: data the title keeps in the slot.
4038 // No image is found by these words (the bindless lookup misses, as for a null T#), but a shader that 4631 // No image is found by these words (the bindless lookup misses, as for a null T#), but a shader that
4039 // takes the slot as a V# (an index from data, or one past what the title filled) adds heap_base to 4632 // takes the slot as a V# (an index from data, or one past what the title filled) adds heap_base to
4040 // words that name nothing: in the GPU copy the slot is null, and left to retry_console_slots. 4633 // words that name nothing: in the GPU copy the slot is null.
4041 ++heap.images[unsigned(TitleImage::not_tsharp)]; 4634 ++heap.images[unsigned(TitleImage::not_tsharp)];
4042 std::memset(w, 0, 16); 4635 std::memset(w, 0, 16);
4043 } 4636 }
4044 } 4637 }
4045 if (empty) heap.empty_slots.insert(std::uint32_t(slot));
4046 else if (!heap.empty_slots.empty()) heap.empty_slots.erase(std::uint32_t(slot));
4047 std::memcpy(heap.copy + slot * kDescriptorSize, w, kDescriptorSize); 4638 std::memcpy(heap.copy + slot * kDescriptorSize, w, kDescriptorSize);
4048 heap.live_vsharps.set(slot, leonida::ConsoleHeapVsharpSlots::is_live_vsharp(w)); 4639 if (heap.resource_heap) {
4640 if (vsharp)
4641 for (unsigned half = 0; half < 2; ++half)
4642 heap.records.set(slot, half, halves[half].state, halves[half].base, halves[half].span,
4643 halves[half].target);
4644 else
4645 heap.records.clear(slot);
4646 }
4049 return settled; 4647 return settled;
4050 } 4648 }
4051 4649
@@ -4100,14 +4698,19 @@ struct DeviceState {
4100 const std::size_t slot = at / kDescriptorSize; 4698 const std::size_t slot = at / kDescriptorSize;
4101 if (!std::memcmp(heap.previous + at, heap.input + at, kDescriptorSize)) continue; 4699 if (!std::memcmp(heap.previous + at, heap.input + at, kDescriptorSize)) continue;
4102 std::memcpy(heap.previous + at, heap.input + at, kDescriptorSize); 4700 std::memcpy(heap.previous + at, heap.input + at, kDescriptorSize);
4103 if (heap.unmapped_tries[slot]) heap.unmapped_tries[slot] = 1; // new words: their looks start over
4104 note_changed_slot(heap, heap.previous + at); 4701 note_changed_slot(heap, heap.previous + at);
4105 if (budget_us && !heap.fix_over && !(++heap.fix_count & 15) && 4702 if (budget_us && !heap.fix_over && !(++heap.fix_count & 15) &&
4106 std::chrono::steady_clock::now() - heap.fix_start >= std::chrono::microseconds(budget_us)) 4703 std::chrono::steady_clock::now() - heap.fix_start >= std::chrono::microseconds(budget_us))
4107 heap.fix_over = true; 4704 heap.fix_over = true;
4108 if (heap.fix_over) { 4705 // Buffer V#s (!(w3 >> 30)) only rebase address offsets, so they are fast and must never be
4706 // deferred or nulled: at the first world frame lib_cs_01144 reads its loop bound from a buffer
4707 // slot; nulling it causes an infinite loop and device loss. Only image T#s are deferred past budget.
4708 std::uint32_t w3 = 0;
4709 std::memcpy(&w3, heap.previous + at + 12, sizeof(w3));
4710 const bool is_buffer_vsharp = !(w3 >> 30);
4711 if (heap.fix_over && !is_buffer_vsharp) {
4109 std::memset(heap.copy + at, 0, kDescriptorSize); 4712 std::memset(heap.copy + at, 0, kDescriptorSize);
4110 heap.live_vsharps.clear(slot); 4713 heap.records.clear(slot);
4111 ++heap.deferred_fixes; 4714 ++heap.deferred_fixes;
4112 if (!heap.retry[slot]) { 4715 if (!heap.retry[slot]) {
4113 heap.retry[slot] = 1; 4716 heap.retry[slot] = 1;
@@ -4115,49 +4718,34 @@ struct DeviceState {
4115 } 4718 }
4116 continue; 4719 continue;
4117 } 4720 }
4118 bool unmapped = false; 4721 if (fix_console_slot(heap, slot)) {
4119 if (fix_console_slot(heap, slot, &unmapped)) {
4120 heap.retry[slot] = 0; 4722 heap.retry[slot] = 0;
4121 } else if (!heap.retry[slot]) { 4723 } else if (!heap.retry[slot]) {
4122 heap.retry[slot] = 1; 4724 heap.retry[slot] = 1;
4123 heap.retries.push_back(std::uint32_t(slot)); 4725 heap.retries.push_back(std::uint32_t(slot));
4124 } 4726 }
4125 if (unmapped && !heap.unmapped_tries[slot]) {
4126 heap.unmapped_tries[slot] = 1;
4127 heap.unmapped.push_back(std::uint32_t(slot));
4128 }
4129 }
4130 }
4131
4132 // The V#s fix_console_slot wrote null because nothing backs their base: looked at again, round robin, at most
4133 // kUnmappedRetrySlots a submission, each kUnmappedTries times at most. A descriptor the title wrote before making
4134 // its buffer (or a buffer another thread registers just after) then gets its base back; one that stays unmapped
4135 // drops out of the list, so data the title keeps in its heap does not cost a lookup at every submission.
4136 static constexpr std::size_t kUnmappedRetrySlots = 2048;
4137 static constexpr std::uint8_t kUnmappedTries = 4;
4138 void retry_unmapped_slots(ConsoleHeap& heap) {
4139 std::size_t i = heap.unmapped_at;
4140 // Each entry once a submission at most: the looks are a submission apart.
4141 const std::size_t visits = std::min(kUnmappedRetrySlots, heap.unmapped.size());
4142 for (std::size_t visited = 0; visited < visits && !heap.unmapped.empty(); ++visited) {
4143 if (i >= heap.unmapped.size()) i = 0;
4144 const std::uint32_t slot = heap.unmapped[i];
4145 // Zeroed since (unmapped_tries reset), reachable now, or out of looks: out of the list.
4146 bool done = !heap.unmapped_tries[slot];
4147 if (!done) {
4148 bool unmapped = false;
4149 fix_console_slot(heap, slot, &unmapped);
4150 done = !unmapped || ++heap.unmapped_tries[slot] > kUnmappedTries;
4151 }
4152 if (done) {
4153 heap.unmapped_tries[slot] = 0;
4154 heap.unmapped[i] = heap.unmapped.back();
4155 heap.unmapped.pop_back();
4156 } else {
4157 ++i;
4158 }
4159 } 4727 }
4160 heap.unmapped_at = i; 4728 }
4729
4730 // The changes since the last submission (slot_changes), applied to a resource heap's copy: each slot whose record
4731 // a change touches is fixed again - a V# whose backing, copy or alias range went, so the copy never names freed
4732 // memory, and a waiting V# over which a backing, alias range or title memory was added. Only the slots near the
4733 // changed ranges are looked at (ConsoleHeapSlotRecords::touched); nothing reads the copy.
4734 std::vector<std::uint32_t> slot_change_scratch; // console_heap_mutex
4735 void apply_slot_changes(ConsoleHeap& heap, const std::vector<leonida::SlotChange>& changes) {
4736 if (!heap.resource_heap || changes.empty()) return;
4737 const auto start = std::chrono::steady_clock::now();
4738 const std::uint64_t looked = heap.records.looked_at();
4739 heap.records.touched(changes.data(), changes.size(), slot_change_scratch);
4740 heap.record_changes += changes.size();
4741 heap.record_looked += heap.records.looked_at() - looked;
4742 heap.record_refixed += slot_change_scratch.size();
4743 for (const std::uint32_t slot : slot_change_scratch)
4744 if (!fix_console_slot(heap, slot) && !heap.retry[slot]) {
4745 heap.retry[slot] = 1;
4746 heap.retries.push_back(slot);
4747 }
4748 heap.record_ms += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count();
4161 } 4749 }
4162 4750
4163 // The slots of a heap copy not settled yet: fixed again, and kept while they are still not. Round robin, for at 4751 // The slots of a heap copy not settled yet: fixed again, and kept while they are still not. Round robin, for at
@@ -4199,7 +4787,9 @@ struct DeviceState {
4199 unbound_tsharp_tracker().note(heap.console_va, offset, words, why); 4787 unbound_tsharp_tracker().note(heap.console_va, offset, words, why);
4200 } 4788 }
4201 4789
4202 void refresh_console_heap(ConsoleHeap& heap) { // console_heap_mutex held 4790 // `changes`: what changed since the last submission (refresh_console_heaps took it from slot_changes), or null for
4791 // a heap's first refresh, which has no records yet.
4792 void refresh_console_heap(ConsoleHeap& heap, const std::vector<leonida::SlotChange>* changes) { // console_heap_mutex held
4203 if (heap.imported) return; // directly imported sampler heap 4793 if (heap.imported) return; // directly imported sampler heap
4204 if (heap.gpu >= 0) return refresh_console_heap_gpu(heap); 4794 if (heap.gpu >= 0) return refresh_console_heap_gpu(heap);
4205 using clock = std::chrono::steady_clock; 4795 using clock = std::chrono::steady_clock;
@@ -4213,90 +4803,20 @@ struct DeviceState {
4213 std::memset(heap.previous + offset, 0, bytes); 4803 std::memset(heap.previous + offset, 0, bytes);
4214 const auto first = std::uint32_t(offset / kDescriptorSize); 4804 const auto first = std::uint32_t(offset / kDescriptorSize);
4215 const auto end = std::uint32_t((offset + bytes) / kDescriptorSize); 4805 const auto end = std::uint32_t((offset + bytes) / kDescriptorSize);
4216 heap.empty_slots.erase(heap.empty_slots.lower_bound(first), heap.empty_slots.lower_bound(end)); 4806 for (auto slot = first; slot < end; ++slot) heap.retry[slot] = 0;
4217 for (auto slot = first; slot < end; ++slot) { 4807 if (heap.resource_heap) heap.records.clear_range(first, end);
4218 heap.retry[slot] = 0;
4219 heap.unmapped_tries[slot] = 0;
4220 }
4221 heap.live_vsharps.clear_range(first, end);
4222 }); 4808 });
4223 const auto t1 = clock::now(); 4809 const auto t1 = clock::now();
4224 heap.fix_start = t1; 4810 heap.fix_start = t1;
4225 heap.fix_over = false; 4811 heap.fix_over = false;
4226 heap.fix_count = 0; 4812 heap.fix_count = 0;
4227 heap.pages->for_each_copied([&](std::size_t offset, std::size_t bytes) { fix_console_slots(heap, offset, bytes); }); 4813 heap.pages->for_each_copied([&](std::size_t offset, std::size_t bytes) { fix_console_slots(heap, offset, bytes); });
4228 const auto generation = released_backings.load(std::memory_order_acquire); 4814 // Even an unchanged title slot may name a buffer released since the last submission: the slots the changes
4229 const auto alias_generation = leonida::title_va_aliases().invalidations(); 4815 // touch are fixed again, found by their records.
4230 if (heap.resource_heap && (generation != heap.checked_generation || alias_generation != heap.alias_generation)) { 4816 if (changes) apply_slot_changes(heap, *changes);
4231 heap.alias_generation = alias_generation;
4232 heap.checked_generation = generation;
4233 leonida::DescriptorRanges backing, aliases;
4234 bool filtered = filter_heap_releases();
4235 if (filtered) {
4236 {
4237 std::lock_guard lock(backing_mutex);
4238 filtered = backing_changes.read(heap.backing_cursor, backing);
4239 }
4240 filtered &= leonida::title_va_aliases().changed_ranges(heap.alias_cursor, aliases);
4241 backing.merge();
4242 aliases.merge();
4243 }
4244 ++heap.release_sweeps;
4245 heap.release_full += !filtered;
4246 const auto bda = [&](uint64_t base) {
4247 if (signed_vsharp_offsets() && (base & (1ull << 47))) base |= ~((1ull << 48)-1);
4248 return arena.address + base;
4249 };
4250 const auto affected = [&](const uint32_t* src, const uint32_t* dst) {
4251 if ((src[3] >> 30) || !src[2]) return false;
4252 const uint64_t base = uint64_t(src[0]) | (uint64_t(src[1] & 0xffff) << 32);
4253 const uint64_t fixed = uint64_t(dst[0]) | (uint64_t(dst[1] & 0xffff) << 32);
4254 const auto stride = (src[1] >> 16) & 0x3fff;
4255 const uint64_t bytes = uint64_t(src[2]) * (stride ? stride : 1);
4256 return aliases.overlaps(base, 1) || backing.overlaps(bda(base), bytes) ||
4257 (dst[2] && backing.overlaps(bda(fixed), bytes));
4258 };
4259 const auto before = heap.vsharps;
4260 ++heap.rescans;
4261 const auto rescan_start = clock::now();
4262 // Even an unchanged title slot may name a buffer released since the last submission.
4263 // Walk the host-RAM V# bitset instead of reading every slot of `heap.copy` (which may be uncached WC VRAM).
4264 heap.live_vsharps.for_each([&](std::size_t slot) {
4265 ++heap.release_candidates;
4266 if (filtered) {
4267 const auto at = slot * kDescriptorSize;
4268 const auto* src = reinterpret_cast<const uint32_t*>(heap.previous + at);
4269 const auto* dst = reinterpret_cast<const uint32_t*>(heap.copy + at);
4270 if (!affected(src, dst) && !affected(src + 4, dst + 4)) return;
4271 }
4272 ++heap.release_fixes;
4273 ++heap.rescanned;
4274 if (!fix_console_slot(heap, slot) && !heap.retry[slot]) {
4275 heap.retry[slot] = 1;
4276 heap.retries.push_back(uint32_t(slot));
4277 }
4278 });
4279 heap.release_rebases += heap.vsharps - before;
4280 heap.rescan_ms += ms(rescan_start, clock::now());
4281 }
4282 const auto t2 = clock::now(); 4817 const auto t2 = clock::now();
4283 // A settled zero can acquire GPU backing without a CPU map event. Probe at most eight in 4818 // T#s whose texture is not there yet, and slots the fix budget deferred.
4284 // round-robin order every 32 submissions. Keep texture and copy-budget retries independent.
4285 if ((heap.refreshes & 31) == 31 && !heap.empty_slots.empty()) {
4286 auto it = heap.empty_slots.lower_bound(heap.next_empty);
4287 const auto count = (std::min)(std::size_t{8}, heap.empty_slots.size());
4288 for (std::size_t n = 0; n < count && !heap.empty_slots.empty(); ++n) {
4289 if (it == heap.empty_slots.end()) it = heap.empty_slots.begin();
4290 const auto slot = *it++;
4291 heap.next_empty = slot + 1;
4292 if (!heap.retry[slot]) {
4293 fix_console_slot(heap, slot);
4294 ++heap.retried;
4295 }
4296 }
4297 }
4298 if (!heap.retries.empty()) retry_console_slots(heap); 4819 if (!heap.retries.empty()) retry_console_slots(heap);
4299 if (!heap.unmapped.empty()) retry_unmapped_slots(heap);
4300 const auto t3 = clock::now(); 4820 const auto t3 = clock::now();
4301 heap.pages_ms += ms(t0, t1); 4821 heap.pages_ms += ms(t0, t1);
4302 heap.fix_ms += ms(t1, t2); 4822 heap.fix_ms += ms(t1, t2);
@@ -4316,9 +4836,16 @@ struct DeviceState {
4316 if (on) state.console_heap_gpu_end(); 4836 if (on) state.console_heap_gpu_end();
4317 } 4837 }
4318 } gpu_end{*this, heap_pass}; 4838 } gpu_end{*this, heap_pass};
4839 // Every change since the last submission, for every heap; one made from now on (by another thread, or by a
4840 // fix below making a window) is applied at the next submission.
4841 std::vector<leonida::SlotChange> changes;
4842 {
4843 std::lock_guard taken(slot_change_mutex);
4844 changes.swap(slot_changes);
4845 }
4319 for (const auto& heap : console_heaps) { 4846 for (const auto& heap : console_heaps) {
4320 const auto start = std::chrono::steady_clock::now(); 4847 const auto start = std::chrono::steady_clock::now();
4321 refresh_console_heap(*heap); 4848 refresh_console_heap(*heap, &changes);
4322 heap->ms += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count(); 4849 heap->ms += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count();
4323 ++heap->refreshes; 4850 ++heap->refreshes;
4324 // A line at the first and 64th submission, then every 10 s (a crawl logs as often as a fast run). 4851 // A line at the first and 64th submission, then every 10 s (a crawl logs as often as a fast run).
@@ -4333,7 +4860,7 @@ struct DeviceState {
4333 "in %.3f ms on average (pages %.3f, fixing copied slots %.3f, %llu left to retries past the " 4860 "in %.3f ms on average (pages %.3f, fixing copied slots %.3f, %llu left to retries past the "
4334 "budget, retrying %.3f: %.1f slots a " 4861 "budget, retrying %.3f: %.1f slots a "
4335 "submission, %zu waiting), %llu write faults; %llu title V#s rebased, %llu with no copy given " 4862 "submission, %zu waiting), %llu write faults; %llu title V#s rebased, %llu with no copy given "
4336 "no records (%zu naming nothing waiting for another look), T#s %llu known, %llu bound, %llu " 4863 "no records (%zu V# halves waiting for a backing), T#s %llu known, %llu bound, %llu "
4337 "naming no texture, %llu refused, %llu words that are no V# or T# (data, null in the copy)\n", 4864 "naming no texture, %llu refused, %llu words that are no V# or T# (data, null in the copy)\n",
4338 static_cast<unsigned long long>(heap->console_va), heap->imported ? "imported" : "copy", 4865 static_cast<unsigned long long>(heap->console_va), heap->imported ? "imported" : "copy",
4339 static_cast<unsigned long long>(heap->refreshes), "copied", 4866 static_cast<unsigned long long>(heap->refreshes), "copied",
@@ -4343,41 +4870,41 @@ struct DeviceState {
4343 double(heap->retried) / count, heap->retries.size(), 4870 double(heap->retried) / count, heap->retries.size(),
4344 static_cast<unsigned long long>(heap->pages ? heap->pages->faults() : 0), 4871 static_cast<unsigned long long>(heap->pages ? heap->pages->faults() : 0),
4345 static_cast<unsigned long long>(heap->vsharps), 4872 static_cast<unsigned long long>(heap->vsharps),
4346 static_cast<unsigned long long>(heap->unbacked), heap->empty_slots.size(), 4873 static_cast<unsigned long long>(heap->unbacked), heap->records.waiting_count(),
4347 static_cast<unsigned long long>(heap->images[unsigned(TitleImage::known)]), 4874 static_cast<unsigned long long>(heap->images[unsigned(TitleImage::known)]),
4348 static_cast<unsigned long long>(heap->images[unsigned(TitleImage::bound)]), 4875 static_cast<unsigned long long>(heap->images[unsigned(TitleImage::bound)]),
4349 static_cast<unsigned long long>(heap->images[unsigned(TitleImage::unknown)]), 4876 static_cast<unsigned long long>(heap->images[unsigned(TitleImage::unknown)]),
4350 static_cast<unsigned long long>(heap->images[unsigned(TitleImage::refused)]), 4877 static_cast<unsigned long long>(heap->images[unsigned(TitleImage::refused)]),
4351 static_cast<unsigned long long>(heap->images[unsigned(TitleImage::not_tsharp)])); 4878 static_cast<unsigned long long>(heap->images[unsigned(TitleImage::not_tsharp)]));
4352 if (heap->release_sweeps && filter_heap_releases())
4353 std::fprintf(stderr, "[rt] CPU release filter: %llu sweeps, %llu live slots, %llu fixes, %llu rebases, %llu full fallbacks\n",
4354 (unsigned long long)heap->release_sweeps, (unsigned long long)heap->release_candidates,
4355 (unsigned long long)heap->release_fixes, (unsigned long long)heap->release_rebases,
4356 (unsigned long long)heap->release_full);
4357 heap->release_sweeps = heap->release_candidates = heap->release_fixes = heap->release_rebases = heap->release_full = 0;
4358 if (heap->resource_heap) { 4879 if (heap->resource_heap) {
4359 std::uint64_t paths[kVsharpPathCount]; 4880 std::uint64_t paths[kVsharpPathCount];
4360 for (unsigned i = 0; i < kVsharpPathCount; ++i) 4881 for (unsigned i = 0; i < kVsharpPathCount; ++i)
4361 paths[i] = vsharp_paths[i].exchange(0, std::memory_order_relaxed); 4882 paths[i] = vsharp_paths[i].exchange(0, std::memory_order_relaxed);
4362 std::fprintf(stderr, 4883 std::fprintf(stderr,
4363 "[rt] d3d12: console descriptor heap 0x%llx changed slots per submission: %.1f zero, %.1f " 4884 "[rt] d3d12: console descriptor heap 0x%llx changed slots per submission: %.1f zero, %.1f "
4364 "V# pairs, %.1f T#s, %.1f other; V# halves %.1f, %.1f%% seen before; rescans %llu (%.1f " 4885 "V# pairs, %.1f T#s, %.1f other; V# halves %.1f, %.1f%% seen before; V# resolutions since "
4365 "V# slots and %.3f ms each); V# resolutions since the last line: alias %llu, alias " 4886 "the last line: alias %llu, alias refused %llu, arena %llu, geometry %llu, window %llu, "
4366 "refused %llu, arena %llu, geometry %llu, window %llu, none %llu\n", 4887 "none %llu\n",
4367 static_cast<unsigned long long>(heap->console_va), double(heap->changed[0]) / count, 4888 static_cast<unsigned long long>(heap->console_va), double(heap->changed[0]) / count,
4368 double(heap->changed[1]) / count, double(heap->changed[2]) / count, 4889 double(heap->changed[1]) / count, double(heap->changed[2]) / count,
4369 double(heap->changed[3]) / count, double(heap->vsharp_halves) / count, 4890 double(heap->changed[3]) / count, double(heap->vsharp_halves) / count,
4370 heap->vsharp_halves ? 100.0 * double(heap->vsharp_repeats) / double(heap->vsharp_halves) 4891 heap->vsharp_halves ? 100.0 * double(heap->vsharp_repeats) / double(heap->vsharp_halves)
4371 : 0.0, 4892 : 0.0,
4372 static_cast<unsigned long long>(heap->rescans),
4373 heap->rescans ? double(heap->rescanned) / double(heap->rescans) : 0.0,
4374 heap->rescans ? heap->rescan_ms / double(heap->rescans) : 0.0,
4375 static_cast<unsigned long long>(paths[0]), static_cast<unsigned long long>(paths[1]), 4893 static_cast<unsigned long long>(paths[0]), static_cast<unsigned long long>(paths[1]),
4376 static_cast<unsigned long long>(paths[2]), static_cast<unsigned long long>(paths[3]), 4894 static_cast<unsigned long long>(paths[2]), static_cast<unsigned long long>(paths[3]),
4377 static_cast<unsigned long long>(paths[4]), static_cast<unsigned long long>(paths[5])); 4895 static_cast<unsigned long long>(paths[4]), static_cast<unsigned long long>(paths[5]));
4896 // What releases, alias changes and additions cost: per submission, the changes taken, the record
4897 // entries looked at to find their slots, and the slots fixed again (apply_slot_changes).
4898 std::fprintf(stderr,
4899 "[rt] d3d12: console descriptor heap 0x%llx slot records per submission: %.1f changes, "
4900 "%.1f slots looked at, %.1f fixed again, %.3f ms; %zu V# halves recorded\n",
4901 static_cast<unsigned long long>(heap->console_va), double(heap->record_changes) / count,
4902 double(heap->record_looked) / count, double(heap->record_refixed) / count,
4903 heap->record_ms / count, heap->records.recorded());
4378 for (auto& n : heap->changed) n = 0; 4904 for (auto& n : heap->changed) n = 0;
4379 heap->vsharp_halves = heap->vsharp_repeats = heap->rescans = heap->rescanned = 0; 4905 heap->vsharp_halves = heap->vsharp_repeats = 0;
4380 heap->rescan_ms = 0; 4906 heap->record_changes = heap->record_looked = heap->record_refixed = 0;
4907 heap->record_ms = 0;
4381 } 4908 }
4382 if (heap->gpu >= 0) log_console_heap_gpu(*heap, count); 4909 if (heap->gpu >= 0) log_console_heap_gpu(*heap, count);
4383 std::string refused_breakdown; 4910 std::string refused_breakdown;
@@ -4582,8 +5109,11 @@ struct DeviceState {
4582 heap->previous = heap->made.data(); 5109 heap->previous = heap->made.data();
4583 } 5110 }
4584 heap->retry.assign(std::size_t(bytes / kDescriptorSize), 0); 5111 heap->retry.assign(std::size_t(bytes / kDescriptorSize), 0);
4585 heap->live_vsharps.reset(std::size_t(bytes / kDescriptorSize)); 5112 if (resource_heap) {
4586 heap->unmapped_tries.assign(std::size_t(bytes / kDescriptorSize), 0); 5113 heap->records.reset(std::size_t(bytes / kDescriptorSize));
5114 // Changes are kept from now on, before the first refresh writes a record.
5115 slot_records_live.store(true, std::memory_order_release);
5116 }
4587 heap->pages = make_shadow_pages(reinterpret_cast<const std::uint8_t*>(static_cast<std::uintptr_t>(console_va)), 5117 heap->pages = make_shadow_pages(reinterpret_cast<const std::uint8_t*>(static_cast<std::uintptr_t>(console_va)),
4588 heap->input, std::size_t(bytes)); 5118 heap->input, std::size_t(bytes));
4589 } 5119 }
@@ -4597,7 +5127,7 @@ struct DeviceState {
4597 { 5127 {
4598 std::lock_guard lock(console_heap_mutex); 5128 std::lock_guard lock(console_heap_mutex);
4599 if (heap->gpu >= 0) gpu_heaps[std::size_t(heap->gpu)] = heap.get(); 5129 if (heap->gpu >= 0) gpu_heaps[std::size_t(heap->gpu)] = heap.get();
4600 if (!imported) refresh_console_heap(*heap); 5130 if (!imported) refresh_console_heap(*heap, nullptr);
4601 if (heap->copy) { 5131 if (heap->copy) {
4602 std::unique_lock ranges(console_copy_ranges_mutex); 5132 std::unique_lock ranges(console_copy_ranges_mutex);
4603 console_copy_ranges.emplace_back(heap->console_va, heap->bytes); 5133 console_copy_ranges.emplace_back(heap->console_va, heap->bytes);
@@ -4742,17 +5272,15 @@ struct DeviceState {
4742 std::vector<std::uint32_t> gpu_queue_scratch; 5272 std::vector<std::uint32_t> gpu_queue_scratch;
4743 bool gpu_rescan = false, gpu_rescan_after_resolve = false; 5273 bool gpu_rescan = false, gpu_rescan_after_resolve = false;
4744 std::chrono::steady_clock::time_point gpu_rescan_asked{}; 5274 std::chrono::steady_clock::time_point gpu_rescan_asked{};
4745 // LEONIDA_CONSOLE_GPU_FILTER=1 (default: LEONIDA_CONSOLE_RELEASE_FILTER's value): a release, an alias range that 5275 // LEONIDA_CONSOLE_GPU_FILTER=1 (default off): a release, an alias range that went or a word answered since asks
4746 // went or a word answered since asks for a rescan of the slots it touches (the release filter's interval rule, 5276 // for a rescan of the slots it touches (an interval rule, 8a22e92c8) instead of every V# slot: the GPU passes over
4747 // 8a22e92c8) instead of every V# slot: the GPU passes over the rest on its device-local metadata. 5277 // the rest on its device-local metadata.
4748 // gpu_filter_shader: shader-VA spans (released backings, alias copies that went); gpu_filter_title: title VAs 5278 // gpu_filter_shader: shader-VA spans (released backings, alias copies that went); gpu_filter_title: title VAs
4749 // (words backed since). Overflows and key resets still rescan everything. 5279 // (words backed since). Overflows and key resets still rescan everything.
4750 static bool gpu_filter_enabled() { 5280 static bool gpu_filter_enabled() {
4751 static const bool on = [] { 5281 static const bool on = [] {
4752 char text[8] = {}; 5282 char text[8] = {};
4753 if (GetEnvironmentVariableA("LEONIDA_CONSOLE_GPU_FILTER", text, sizeof(text)) && text[0]) 5283 return GetEnvironmentVariableA("LEONIDA_CONSOLE_GPU_FILTER", text, sizeof(text)) && text[0] == '1';
4754 return text[0] == '1';
4755 return GetEnvironmentVariableA("LEONIDA_CONSOLE_RELEASE_FILTER", text, sizeof(text)) && text[0] == '1';
4756 }(); 5284 }();
4757 return on; 5285 return on;
4758 } 5286 }
@@ -5426,6 +5954,148 @@ struct DeviceState {
5426 gpu_counts.backed_ms += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count(); 5954 gpu_counts.backed_ms += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count();
5427 } 5955 }
5428 5956
5957 // LEONIDA_ADDRESS_GUARD=1 (docs/d3d12_vulkan.md, "Address guard"): the page table the guarded shaders read, a
5958 // host-visible buffer of its own whose address minus heap_base is in the guard header at arena offset
5959 // kGuardHeader. Built from the same backings as the console heap pass's backed table (gpu_backings, the
5960 // geometry copies' blocks and the separate window buffers), but whole and at once: a backing made since the last
5961 // submission must not read 0.
5962 struct AddressGuard {
5963 VkBuffer buffer = VK_NULL_HANDLE;
5964 VkDeviceMemory memory = VK_NULL_HANDLE;
5965 std::uint32_t* words = nullptr;
5966 std::unique_ptr<leonida::address_guard::AddressGuardTable> table;
5967 std::uint64_t generation = ~0ull, blocks = ~0ull, heaps = ~0ull; // heaps: the console heaps' ranges, hashed
5968 std::uint32_t refused_logged = 0, overflow_logged = 0;
5969 std::uint64_t updates = 0, words_written = 0;
5970 std::chrono::steady_clock::time_point logged{};
5971 std::mutex mutex;
5972 } guard;
5973
5974 // Make the page table and write the header (called once the arena is mapped). False leaves the guard off: the
5975 // header keeps no magic, so guarded shaders check nothing.
5976 bool create_address_guard() {
5977 namespace ag = leonida::address_guard;
5978 if (!context || !arena.mapped || arena.size < ag::kGuardEnd) return false;
5979 auto& vk = context->vk;
5980 guard.table = std::make_unique<ag::AddressGuardTable>();
5981 VkBufferCreateInfo create{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
5982 create.size = guard.table->bytes();
5983 create.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT;
5984 create.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
5985 if (vk.vkCreateBuffer(info.device, &create, nullptr, &guard.buffer) != VK_SUCCESS) {
5986 guard.buffer = VK_NULL_HANDLE;
5987 return false;
5988 }
5989 VkMemoryRequirements requirements{};
5990 vk.vkGetBufferMemoryRequirements(info.device, guard.buffer, &requirements);
5991 guard.memory = allocate(requirements, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
5992 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, nullptr, true);
5993 void* mapped = nullptr;
5994 if (!guard.memory || vk.vkBindBufferMemory(info.device, guard.buffer, guard.memory, 0) != VK_SUCCESS ||
5995 vk.vkMapMemory(info.device, guard.memory, 0, VK_WHOLE_SIZE, 0, &mapped) != VK_SUCCESS) {
5996 destroy_address_guard();
5997 return false;
5998 }
5999 guard.words = static_cast<std::uint32_t*>(mapped);
6000 std::memcpy(guard.words, guard.table->words().data(), guard.table->bytes());
6001 VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO};
6002 address.buffer = guard.buffer;
6003 const VkDeviceAddress table = vk.vkGetBufferDeviceAddress(info.device, &address);
6004 auto* header = reinterpret_cast<ag::AddressGuardHeader*>(arena.mapped + ag::kGuardHeader);
6005 std::memset(arena.mapped + ag::kGuardHeader, 0, std::size_t(ag::kGuardEnd - ag::kGuardHeader));
6006 header->limit = arena.size;
6007 header->table = table - arena.address;
6008 std::atomic_thread_fence(std::memory_order_release);
6009 header->magic = ag::magic(); // last: a shader that sees it sees the rest
6010 std::fprintf(stderr, "[rt] d3d12: address guard on (LEONIDA_ADDRESS_GUARD): %llu KiB page table, header at "
6011 "heap_base + 0x%llx; shaders translated with --address-guard read 0 from memory nothing "
6012 "backs and drop their stores there\n",
6013 static_cast<unsigned long long>(guard.table->bytes() >> 10),
6014 static_cast<unsigned long long>(ag::kGuardHeader));
6015 return true;
6016 }
6017 void destroy_address_guard() {
6018 if (!context) return;
6019 auto& vk = context->vk;
6020 if (guard.buffer) vk.vkDestroyBuffer(info.device, guard.buffer, nullptr);
6021 if (guard.memory) vk.vkFreeMemory(info.device, guard.memory, nullptr);
6022 guard.buffer = VK_NULL_HANDLE;
6023 guard.memory = VK_NULL_HANDLE;
6024 guard.words = nullptr;
6025 }
6026
6027 // Before each submission: the page table says exactly what is backed now, and refusals since the last line are
6028 // logged (at most once a second). Rebuilt only when a backing came or went; only changed words are written.
6029 void update_address_guard() {
6030 namespace ag = leonida::address_guard;
6031 if (!guard.words) return;
6032 // A console descriptor heap whose GPU copy lies outside the arena (an import of the title's pages, which
6033 // shaders read at shader_va = its device address minus heap_base) is read through heap_base + VA like a
6034 // buffer, but no gpu_backing names it: its bytes and the null guard after them are entered here. Without
6035 // this the guard refused every descriptor-table load from such a heap (run 28: a 38 MB imported heap at
6036 // shader VA 0x87e00000, past a 2 GiB arena). Collected before guard.mutex, in console_heap_mutex's order.
6037 std::vector<std::pair<std::uint64_t, std::uint64_t>> heap_spans;
6038 std::uint64_t heap_signature = 0xcbf29ce484222325ull;
6039 {
6040 std::lock_guard heaps(console_heap_mutex);
6041 for (const auto& h : console_heaps) {
6042 if (!h || !h->bytes) continue;
6043 const std::uint64_t begin = h->shader_va, end = h->shader_va + h->bytes + h->guard;
6044 heap_signature = (heap_signature ^ begin) * 0x100000001b3ull;
6045 heap_signature = (heap_signature ^ end) * 0x100000001b3ull;
6046 if (!(begin < arena.size && end <= arena.size)) heap_spans.emplace_back(begin, end);
6047 }
6048 }
6049 std::lock_guard lock(guard.mutex);
6050 const std::uint64_t generation = backing_generation.load(std::memory_order_relaxed);
6051 const std::uint64_t blocks = geometry.pool().layout_generation() + external_windows.layout_generation();
6052 if (generation != guard.generation || blocks != guard.blocks || heap_signature != guard.heaps) {
6053 guard.generation = generation;
6054 guard.blocks = blocks;
6055 guard.heaps = heap_signature;
6056 std::vector<std::pair<std::uint64_t, std::uint64_t>> spans = heap_spans;
6057 {
6058 std::lock_guard backing_lock(backing_mutex);
6059 gpu_backings.for_each([&](std::uint64_t va, std::uint64_t bytes) {
6060 const std::uint64_t offset = va - arena.address;
6061 // The arena's own ranges pass on the limit compare; only what lies outside needs pages.
6062 if (bytes && !(offset < arena.size && bytes <= arena.size - offset))
6063 spans.emplace_back(offset, offset + bytes);
6064 });
6065 }
6066 const auto block = [&](VkDeviceAddress address, VkDeviceSize bytes) {
6067 const std::uint64_t offset = address - arena.address;
6068 if (address && bytes) spans.emplace_back(offset, offset + bytes);
6069 };
6070 geometry.pool().for_each_block(block);
6071 external_windows.for_each_block(block);
6072 guard.words_written += guard.table->assign(spans, [&](std::size_t i, std::uint32_t v) {
6073 std::atomic_ref(guard.words[i]).store(v, std::memory_order_relaxed);
6074 });
6075 ++guard.updates;
6076 if (guard.table->overflowed() != guard.overflow_logged) {
6077 guard.overflow_logged = guard.table->overflowed();
6078 std::fprintf(stderr, "[rt] d3d12: address guard: %u 4 GiB chunk(s) of backings past the page table's "
6079 "%u blocks are not checked\n",
6080 guard.overflow_logged, guard.table->blocks_used());
6081 }
6082 }
6083 auto* header = reinterpret_cast<ag::AddressGuardHeader*>(arena.mapped + ag::kGuardHeader);
6084 const std::uint32_t refused = std::atomic_ref(header->refused).load(std::memory_order_relaxed);
6085 const auto now = std::chrono::steady_clock::now();
6086 if (refused != guard.refused_logged && now - guard.logged >= std::chrono::seconds(1)) {
6087 guard.logged = now;
6088 std::fprintf(stderr, "[rt] d3d12: address guard: %u access(es) refused so far (+%u), the last at heap "
6089 "offset 0x%llx by module 0x%08x; %llu table update(s), %llu word(s) written\n",
6090 refused, refused - guard.refused_logged,
6091 static_cast<unsigned long long>(header->last_refused),
6092 std::atomic_ref(header->last_module).load(std::memory_order_relaxed),
6093 static_cast<unsigned long long>(guard.updates),
6094 static_cast<unsigned long long>(guard.words_written));
6095 guard.refused_logged = refused;
6096 }
6097 }
6098
5429 // The ask table: the title's memory and both addresses of its GPU-window pairs. A V# base outside them that the 6099 // The ask table: the title's memory and both addresses of its GPU-window pairs. A V# base outside them that the
5430 // other tables do not answer is one vsharp_address could only answer 0 for. 6100 // other tables do not answer is one vsharp_address could only answer 0 for.
5431 void update_gpu_ask() { 6101 void update_gpu_ask() {
@@ -6572,7 +7242,9 @@ struct DeviceState {
6572 7242
6573 // Gives the T# `words` a view in set 0 and an entry in the hash table, unless it has them. `storage`: shaders 7243 // Gives the T# `words` a view in set 0 and an entry in the hash table, unless it has them. `storage`: shaders
6574 // write through it too (an unordered-access view), so it also goes into the storage arrays, which are 7244 // write through it too (an unordered-access view), so it also goes into the storage arrays, which are
6575 // shorter. False when set 0 cannot show the image; the descriptor then finds the fallback at index 0. 7245 // shorter. False when set 0 cannot show the image; the descriptor then finds the fallback at index 0. `why`, when
7246 // given, is set to the reason when it is that set 0 has no room (or no array) for the image's dimension, and left
7247 // alone otherwise (no view could be made for the T#).
6576 bool bind_image(const leonida::gfx10::ImageWords& words, const leonida::gfx10::Image& image, VkImage vk_image, 7248 bool bind_image(const leonida::gfx10::ImageWords& words, const leonida::gfx10::Image& image, VkImage vk_image,
6577 VkFormat image_format, VkImageAspectFlags aspects, bool storage, 7249 VkFormat image_format, VkImageAspectFlags aspects, bool storage,
6578 bool allow_channel_cast = false, VkFormat uint_backed = VK_FORMAT_UNDEFINED) { 7250 bool allow_channel_cast = false, VkFormat uint_backed = VK_FORMAT_UNDEFINED) {
@@ -6582,7 +7254,8 @@ struct DeviceState {
6582 } 7254 }
6583 bool bind_image_locked(const leonida::gfx10::ImageWords& words, const leonida::gfx10::Image& image, 7255 bool bind_image_locked(const leonida::gfx10::ImageWords& words, const leonida::gfx10::Image& image,
6584 VkImage vk_image, VkFormat image_format, VkImageAspectFlags aspects, bool storage, 7256 VkImage vk_image, VkFormat image_format, VkImageAspectFlags aspects, bool storage,
6585 bool allow_channel_cast = false, VkFormat uint_backed = VK_FORMAT_UNDEFINED) { 7257 bool allow_channel_cast = false, VkFormat uint_backed = VK_FORMAT_UNDEFINED,
7258 const char** why = nullptr) {
6586 namespace g = leonida::gfx10; 7259 namespace g = leonida::gfx10;
6587 if (!bindless) return false; 7260 if (!bindless) return false;
6588 auto pending = pending_image_keys.find(vk_image); 7261 auto pending = pending_image_keys.find(vk_image);
@@ -6627,7 +7300,7 @@ struct DeviceState {
6627 const bool sampled_only = uint_backed || (view_format != image_format && view_format != VK_FORMAT_UNDEFINED); 7300 const bool sampled_only = uint_backed || (view_format != image_format && view_format != VK_FORMAT_UNDEFINED);
6628 return bind_image_views_locked(words, image, vk_image, view_format, channels_format, 7301 return bind_image_views_locked(words, image, vk_image, view_format, channels_format,
6629 uint_backed ? image_format : view_format, aspects, true, storage, {}, 7302 uint_backed ? image_format : view_format, aspects, true, storage, {},
6630 sampled_only); 7303 sampled_only, why);
6631 } 7304 }
6632 // The same for a view whose formats the caller has worked out: `view_format` of the sampled view (made when 7305 // The same for a view whose formats the caller has worked out: `view_format` of the sampled view (made when
6633 // `sampled`), `channels_format` whose channels the T#'s swizzle selects from, `storage_format` of the storage view. 7306 // `sampled`), `channels_format` whose channels the T#'s swizzle selects from, `storage_format` of the storage view.
@@ -6641,7 +7314,7 @@ struct DeviceState {
6641 bool bind_image_views_locked(const leonida::gfx10::ImageWords& words, const leonida::gfx10::Image& image, 7314 bool bind_image_views_locked(const leonida::gfx10::ImageWords& words, const leonida::gfx10::Image& image,
6642 VkImage vk_image, VkFormat view_format, VkFormat channels_format, 7315 VkImage vk_image, VkFormat view_format, VkFormat channels_format,
6643 VkFormat storage_format, VkImageAspectFlags aspects, bool sampled, bool storage, 7316 VkFormat storage_format, VkImageAspectFlags aspects, bool sampled, bool storage,
6644 VolumeSlices slices, bool sampled_only) { 7317 VolumeSlices slices, bool sampled_only, const char** why = nullptr) {
6645 namespace g = leonida::gfx10; 7318 namespace g = leonida::gfx10;
6646 if (!bindless) { 7319 if (!bindless) {
6647 if (storage) log_once("unordered-access view needs the Vulkan bindless set; type", int(image.type)); 7320 if (storage) log_once("unordered-access view needs the Vulkan bindless set; type", int(image.type));
@@ -6796,24 +7469,37 @@ struct DeviceState {
6796 vk.vkDestroyImageView(info.device, entry.mirror_storage, nullptr); 7469 vk.vkDestroyImageView(info.device, entry.mirror_storage, nullptr);
6797 entry.mirror_storage = VK_NULL_HANDLE; 7470 entry.mirror_storage = VK_NULL_HANDLE;
6798 } 7471 }
6799 if (first_diagnostic("a bindless image array is full; dimension", int(dimension))) { 7472 using Refusal = leonida::BindlessSet::ImageRefusal;
7473 const Refusal refusal = bindless->image_refusal(dimension, entry.storage != VK_NULL_HANDLE, sampled_class);
7474 if (why)
7475 *why = refusal == Refusal::no_array ? "set 0 has no array for the T#'s dimension"
7476 : refusal == Refusal::storage_full ? "the bindless storage arrays of the T#'s dimension are full"
7477 : "the bindless array of the T#'s dimension is full";
7478 if (refusal != Refusal::no_array &&
7479 first_diagnostic("a bindless image array is full; dimension", int(dimension))) {
6800 // Whether the array holds live textures or stale views: the T#s it holds, the textures they name, 7480 // Whether the array holds live textures or stale views: the T#s it holds, the textures they name,
6801 // and the most T#s of one texture (a texture whose T#s keep changing, a streamed mip clamp say, 7481 // the most T#s of one texture (a texture whose T#s keep changing, a streamed mip clamp say, keeps an
6802 // keeps an index for each until it goes). 7482 // index for each until it goes), and how many of those textures are still the one registered at
6803 std::size_t entries = 0, replaced = 0, most = 0; 7483 // their address (a texture leaves the set when the one registered there goes: forget_image).
7484 std::size_t entries = 0, replaced = 0, most = 0, registered = 0;
6804 std::map<std::uint64_t, std::size_t> per_texture; 7485 std::map<std::uint64_t, std::size_t> per_texture;
6805 for (const auto& [key, held] : image_entries) 7486 for (const auto& [key, held] : image_entries)
6806 if (held.dimension == dimension) { 7487 if (held.dimension == dimension) {
6807 ++entries; 7488 ++entries;
6808 most = std::max(most, ++per_texture[held.address]); 7489 most = std::max(most, ++per_texture[held.address]);
6809 } 7490 }
7491 for (const auto& texture : per_texture) registered += images_by_address.count(texture.first);
6810 for (const auto& held : replaced_images) replaced += held.dimension == dimension; 7492 for (const auto& held : replaced_images) replaced += held.dimension == dimension;
7493 constexpr const char* names[] = {"2D", "2D array", "3D", "1D", "1D array", "2D MS", "2D MS array"};
6811 std::fprintf(stderr, 7494 std::fprintf(stderr,
6812 "[rt] d3d12: a bindless image array is full; dimension %d: %u indices, %zu T#s of %zu " 7495 "[rt] d3d12: a bindless image array is full; dimension %d (%s)%s: %u indices, %u in the "
6813 "textures (at most %zu T#s of one), %zu replaced views kept; further T#s of this " 7496 "storage arrays, %zu T#s of %zu textures (%zu registered at their address, at most %zu "
6814 "dimension read the fallback\n", 7497 "T#s of one), %zu replaced views kept; further T#s of this dimension read the "
6815 int(dimension), bindless->image_capacity(dimension), entries, per_texture.size(), most, 7498 "fallback\n",
6816 replaced); 7499 int(dimension), names[int(dimension)],
7500 refusal == Refusal::storage_full ? ", its storage range" : "",
7501 bindless->image_capacity(dimension), bindless->storage_capacity(dimension), entries,
7502 per_texture.size(), registered, most, replaced);
6817 } 7503 }
6818 if (entry.sampled) vk.vkDestroyImageView(info.device, entry.sampled, nullptr); 7504 if (entry.sampled) vk.vkDestroyImageView(info.device, entry.sampled, nullptr);
6819 if (entry.storage) vk.vkDestroyImageView(info.device, entry.storage, nullptr); 7505 if (entry.storage) vk.vkDestroyImageView(info.device, entry.storage, nullptr);
@@ -7079,6 +7765,12 @@ struct DeviceState {
7079 return nullptr; 7765 return nullptr;
7080 } 7766 }
7081}; 7767};
7768// TitleBufferWindows::system_memory_types reads the memory types through these (LEONIDA_GEOMETRY_HOST): without them
7769// it would leave every type allowed, the BAR included.
7770static_assert(requires(const DeviceState& d) {
7771 d.memory.memoryTypes[0].propertyFlags;
7772 d.memory.memoryTypeCount;
7773});
7082 7774
7083// The Vulkan format for a texture this layer can create, with the D24 fallback; VK_FORMAT_UNDEFINED, after a log 7775// The Vulkan format for a texture this layer can create, with the D24 fallback; VK_FORMAT_UNDEFINED, after a log
7084// line, when it cannot. Committed and placed textures share it so both refuse the same formats for the same reason. 7776// line, when it cannot. Committed and placed textures share it so both refuse the same formats for the same reason.
@@ -7848,6 +8540,8 @@ public:
7848 if (heap_.Type == D3D12_HEAP_TYPE_READBACK) host_preferred = VK_MEMORY_PROPERTY_HOST_CACHED_BIT; 8540 if (heap_.Type == D3D12_HEAP_TYPE_READBACK) host_preferred = VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
7849 if (heap_.Type == D3D12_HEAP_TYPE_UPLOAD && device_.upload_in_vram) 8541 if (heap_.Type == D3D12_HEAP_TYPE_UPLOAD && device_.upload_in_vram)
7850 host_preferred = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; 8542 host_preferred = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
8543 leonida::memory_breakdown::Owner owner(host ? leonida::memory_breakdown::Consumer::upload
8544 : leonida::memory_breakdown::current_owner());
7851 memory_ = host ? device_.allocate(requirements, 8545 memory_ = host ? device_.allocate(requirements,
7852 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, 8546 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
7853 host_preferred, &memory_flags_, addressable || need_bda) 8547 host_preferred, &memory_flags_, addressable || need_bda)
@@ -8166,6 +8860,7 @@ public:
8166 vk.vkGetBufferMemoryRequirements(device_.info.device, buffer_, &requirements); 8860 vk.vkGetBufferMemoryRequirements(device_.info.device, buffer_, &requirements);
8167 // As an upload buffer (D3D-96): the CPU writes it at every submission and the GPU reads it, so VRAM through 8861 // As an upload buffer (D3D-96): the CPU writes it at every submission and the GPU reads it, so VRAM through
8168 // Resizable BAR where there is one, system memory otherwise. 8862 // Resizable BAR where there is one, system memory otherwise.
8863 leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::windows);
8169 memory_ = device_.allocate(requirements, 8864 memory_ = device_.allocate(requirements,
8170 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, 8865 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
8171 device_.upload_in_vram ? VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT : 0, &memory_flags_, 8866 device_.upload_in_vram ? VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT : 0, &memory_flags_,
@@ -8701,6 +9396,7 @@ private:
8701 vk.vkBindImageMemory, vk.vkDestroyImage, vk.vkFreeMemory, [&](VkDeviceSize size, std::uint32_t& type) { 9396 vk.vkBindImageMemory, vk.vkDestroyImage, vk.vkFreeMemory, [&](VkDeviceSize size, std::uint32_t& type) {
8702 auto page = pool_requirements; 9397 auto page = pool_requirements;
8703 page.size = size; 9398 page.size = size;
9399 leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::image_blocks);
8704 return device_.allocate(page, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, nullptr, false, &type); 9400 return device_.allocate(page, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, nullptr, false, &type);
8705 }); 9401 });
8706 if (pooled_image_) memory_flags_ = device_.memory.memoryTypes[pooled_image_->page->type].propertyFlags; 9402 if (pooled_image_) memory_flags_ = device_.memory.memoryTypes[pooled_image_->page->type].propertyFlags;
@@ -9303,8 +9999,12 @@ private:
9303 }; 9999 };
9304 VkMemoryRequirements requirements{}; 10000 VkMemoryRequirements requirements{};
9305 vk.vkGetBufferMemoryRequirements(dev, staging.buffer, &requirements); 10001 vk.vkGetBufferMemoryRequirements(dev, staging.buffer, &requirements);
9306 memory = device_.allocate(requirements, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, 10002 {
9307 write ? 0 : VK_MEMORY_PROPERTY_HOST_CACHED_BIT); 10003 leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::staging);
10004 memory = device_.allocate(requirements,
10005 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
10006 write ? 0 : VK_MEMORY_PROPERTY_HOST_CACHED_BIT);
10007 }
9308 if (!memory || vk.vkBindBufferMemory(dev, staging.buffer, memory, 0) != VK_SUCCESS || 10008 if (!memory || vk.vkBindBufferMemory(dev, staging.buffer, memory, 0) != VK_SUCCESS ||
9309 vk.vkMapMemory(dev, memory, 0, VK_WHOLE_SIZE, 0, &mapped) != VK_SUCCESS) 10009 vk.vkMapMemory(dev, memory, 0, VK_WHOLE_SIZE, 0, &mapped) != VK_SUCCESS)
9310 return release(E_OUTOFMEMORY); 10010 return release(E_OUTOFMEMORY);
@@ -10978,10 +11678,13 @@ public:
10978 // D24_UNORM_S8_UINT stored as D32_SFLOAT_S8_UINT (no D24 on the GPU): the pixel stage writes the depth D24 11678 // D24_UNORM_S8_UINT stored as D32_SFLOAT_S8_UINT (no D24 on the GPU): the pixel stage writes the depth D24
10979 // would hold, biased in D24 units and quantised (src/depth24_fragment.h, D3D-309), and the rasterizer's own 11679 // would hold, biased in D24 units and quantised (src/depth24_fragment.h, D3D-309), and the rasterizer's own
10980 // bias is turned off. Multisampled targets keep the old path: a FragDepth write is per pixel. 11680 // bias is turned off. Multisampled targets keep the old path: a FragDepth write is per pixel.
10981 const bool d24_as_float = desc.DSVFormat != DXGI_FORMAT_UNKNOWN && 11681 const VkFormat dsv_vk = desc.DSVFormat != DXGI_FORMAT_UNKNOWN
10982 vulkan_format(desc.DSVFormat, true).format == VK_FORMAT_D24_UNORM_S8_UINT && 11682 ? vulkan_format(desc.DSVFormat, true).format
11683 : VK_FORMAT_UNDEFINED;
11684 const bool d24_as_float = dsv_vk == VK_FORMAT_D24_UNORM_S8_UINT &&
10983 !device_.depth_usable(VK_FORMAT_D24_UNORM_S8_UINT); 11685 !device_.depth_usable(VK_FORMAT_D24_UNORM_S8_UINT);
10984 const bool packed16_fallback=desc.DSVFormat==xbox_d16s8 && device_.depth_backing(VK_FORMAT_D16_UNORM_S8_UINT)!=VK_FORMAT_D16_UNORM_S8_UINT; 11686 const bool packed16_fallback = dsv_vk == VK_FORMAT_D16_UNORM_S8_UINT &&
11687 device_.depth_backing(VK_FORMAT_D16_UNORM_S8_UINT) != VK_FORMAT_D16_UNORM_S8_UINT;
10985 if(packed16_fallback && samples>1 && desc.DepthStencilState.DepthEnable) return E_NOTIMPL; 11688 if(packed16_fallback && samples>1 && desc.DepthStencilState.DepthEnable) return E_NOTIMPL;
10986 bool depth24_fragment = (d24_as_float || packed16_fallback) && desc.DepthStencilState.DepthEnable; 11689 bool depth24_fragment = (d24_as_float || packed16_fallback) && desc.DepthStencilState.DepthEnable;
10987 if (depth24_fragment && samples > 1) { 11690 if (depth24_fragment && samples > 1) {
@@ -11298,8 +12001,11 @@ public:
11298 log_once("conservative rasterization needs enabled VK_EXT_conservative_rasterization and Tier 1 precision", 1); 12001 log_once("conservative rasterization needs enabled VK_EXT_conservative_rasterization and Tier 1 precision", 1);
11299 return E_INVALIDARG; 12002 return E_INVALIDARG;
11300 } 12003 }
11301 if (r.FillMode != D3D12_FILL_MODE_SOLID || 12004 // A mesh pipeline has no input assembler, so its stream need not set the topology type: what is rasterized
11302 topology_type != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) return E_INVALIDARG; 12005 // is the module's output, and it has to be triangles as well.
12006 if (r.FillMode != D3D12_FILL_MODE_SOLID) return E_INVALIDARG;
12007 if (mesh ? !leonida::conservative_raster::mesh_outputs_triangles(stages[0].words)
12008 : topology_type != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) return E_INVALIDARG;
11303 // Target-independent rasterization is a separate pipeline path; do not silently ignore its count. 12009 // Target-independent rasterization is a separate pipeline path; do not silently ignore its count.
11304 if (r.ForcedSampleCount) 12010 if (r.ForcedSampleCount)
11305 return stream_unsupported("target-independent rasterization; forced sample count", int(r.ForcedSampleCount)); 12011 return stream_unsupported("target-independent rasterization; forced sample count", int(r.ForcedSampleCount));
@@ -12181,7 +12887,11 @@ private:
12181 const leonida::dev_status::Build dev_build(r.mesh ? "mesh pipeline" : "graphics pipeline"); 12887 const leonida::dev_status::Build dev_build(r.mesh ? "mesh pipeline" : "graphics pipeline");
12182 const leonida::pipeline_profile::DriverCall profile(r.mesh ? "ms" : "vs", lazy_ ? "lazy" : "eager", 12888 const leonida::pipeline_profile::DriverCall profile(r.mesh ? "ms" : "vs", lazy_ ? "lazy" : "eager",
12183 program, fragment, unbound); 12889 program, fragment, unbound);
12184 const auto result = device_.context->vk.vkCreateGraphicsPipelines(device_.info.device, cache, 1, &info, nullptr, &pipeline); 12890 const auto result = device_.create_pipeline(flags, [&](VkPipelineCache with, VkPipelineCreateFlags f) {
12891 info.flags = f;
12892 pipeline = VK_NULL_HANDLE;
12893 return device_.context->vk.vkCreateGraphicsPipelines(device_.info.device, with, 1, &info, nullptr, &pipeline);
12894 });
12185 if (status) *status = result; 12895 if (status) *status = result;
12186 profile.finish(int(result)); 12896 profile.finish(int(result));
12187 trace.end(trigger, profile_shaders_.c_str(), unbound, bytes, result); 12897 trace.end(trigger, profile_shaders_.c_str(), unbound, bytes, result);
@@ -12997,6 +13707,57 @@ void DeviceState::drain_titles_gone() {
12997// these words, as write_image_descriptor does. Every field the layer does not encode (tiling, compression, 13707// these words, as write_image_descriptor does. Every field the layer does not encode (tiling, compression,
12998// performance hints) only makes the key differ, so a title-built T# still finds its texture. Checked against the 13708// performance hints) only makes the key differ, so a title-built T# still finds its texture. Checked against the
12999// texture first: a view of mips, layers or a dimension it lacks would be an invalid Vulkan view. 13709// texture first: a view of mips, layers or a dimension it lacks would be an invalid Vulkan view.
13710// LEONIDA_UNKNOWN_TSHARP=1 (diagnostic): one line for each distinct base address a title-written T# names with no
13711// texture there (its shape, the tiling bits SW_MODE = dword 3 bits 20..24 by the GFX10 layout, unverified, and whether
13712// the address is title memory), up to 300 addresses, and every 8192 such lookups a summary by format, type and tiling.
13713// What a texture made from the T# on its first read would have to create.
13714void note_unknown_tsharp(const leonida::gfx10::ImageWords& words, const leonida::gfx10::Image& image) {
13715 static const bool on = [] {
13716 const char* v = std::getenv("LEONIDA_UNKNOWN_TSHARP");
13717 return v && *v == '1';
13718 }();
13719 if (!on) return;
13720 struct Shape {
13721 std::uint32_t format, type, sw, width, height, depth, mips, layers;
13722 };
13723 static std::mutex mutex;
13724 static std::unordered_map<std::uint64_t, Shape> seen;
13725 static std::map<std::string, std::uint64_t> by_shape;
13726 static std::uint64_t lookups = 0, in_title = 0;
13727 const Shape s{image.format, std::uint32_t(image.type), (words[3] >> 20) & 0x1f, image.width, image.height,
13728 image.depth, image.resource_mips, image.layer_count};
13729 std::uint64_t lo = 0, hi = 0;
13730 const bool title = leonida::title_va_aliases().title_memory(image.address, lo, hi);
13731 std::lock_guard lock(mutex);
13732 ++lookups;
13733 if (seen.emplace(image.address, s).second) {
13734 in_title += title;
13735 char key[64];
13736 std::snprintf(key, sizeof(key), "fmt %u type %u sw %u", s.format, s.type, s.sw);
13737 ++by_shape[key];
13738 if (seen.size() <= 300)
13739 std::fprintf(stderr,
13740 "[rt] unknown-tsharp: #%zu base 0x%llx fmt %u type %u sw %u %ux%ux%u mips %u layers %u%s\n",
13741 seen.size(), static_cast<unsigned long long>(image.address), s.format, s.type, s.sw, s.width,
13742 s.height, s.depth, s.mips, s.layers, title ? " (title memory)" : " (not title memory)");
13743 if (seen.size() <= 24)
13744 std::fprintf(stderr, "[rt] unknown-tsharp: #%zu words %08x %08x %08x %08x %08x %08x %08x %08x\n", seen.size(),
13745 words[0], words[1], words[2], words[3], words[4], words[5], words[6], words[7]);
13746 }
13747 if (!(lookups % 8192)) {
13748 std::vector<std::pair<std::uint64_t, std::string>> top;
13749 for (const auto& [k, n] : by_shape) top.emplace_back(n, k);
13750 std::sort(top.rbegin(), top.rend());
13751 std::string text;
13752 for (std::size_t i = 0; i < top.size() && i < 10; ++i)
13753 text += (i ? "; " : "") + top[i].second + " x" + std::to_string(top[i].first);
13754 std::fprintf(stderr,
13755 "[rt] unknown-tsharp: %llu lookups, %zu distinct addresses (%llu in title memory); by shape: %s\n",
13756 static_cast<unsigned long long>(lookups), seen.size(), static_cast<unsigned long long>(in_title),
13757 text.c_str());
13758 }
13759}
13760
13000TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWords& words, const char** why) { 13761TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWords& words, const char** why) {
13001 namespace g = leonida::gfx10; 13762 namespace g = leonida::gfx10;
13002 const auto refuse = [why](const char* reason) { 13763 const auto refuse = [why](const char* reason) {
@@ -13030,6 +13791,7 @@ TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWord
13030 } 13791 }
13031 if (!owner) { 13792 if (!owner) {
13032 if (why) *why = "no texture at T# address"; 13793 if (why) *why = "no texture at T# address";
13794 note_unknown_tsharp(words, image);
13033 return TitleImage::unknown; 13795 return TitleImage::unknown;
13034 } 13796 }
13035 const Resource& r = *owner; 13797 const Resource& r = *owner;
@@ -13053,9 +13815,10 @@ TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWord
13053 return refuse("T# names layers the texture lacks"); 13815 return refuse("T# names layers the texture lacks");
13054 const bool storage = (d.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && !msaa && 13816 const bool storage = (d.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && !msaa &&
13055 r.aspects() == VK_IMAGE_ASPECT_COLOR_BIT; 13817 r.aspects() == VK_IMAGE_ASPECT_COLOR_BIT;
13818 const char* unbound = "no view for the T#'s format or range"; // unless set 0 has no room (bind_image)
13056 if (!device.bind_image_locked(words, image, r.descriptor_image(), r.format(), r.aspects(), storage, 13819 if (!device.bind_image_locked(words, image, r.descriptor_image(), r.format(), r.aspects(), storage,
13057 r.has_view_format_list(), r.uint_backed())) 13820 r.has_view_format_list(), r.uint_backed(), &unbound))
13058 return refuse("no view for the T#'s format or range"); 13821 return refuse(unbound);
13059 r.note_shader_view(); // Include descriptors written directly into title heaps. 13822 r.note_shader_view(); // Include descriptors written directly into title heaps.
13060 if (r.sparse_image()) sparse = r.id(); 13823 if (r.sparse_image()) sparse = r.id();
13061 } 13824 }
@@ -13708,6 +14471,8 @@ public:
13708 const phases::Scope timed(phases::geometry); 14471 const phases::Scope timed(phases::geometry);
13709 state_.geometry.refresh(DeviceState::copy_geometry); 14472 state_.geometry.refresh(DeviceState::copy_geometry);
13710 } 14473 }
14474 // Last, once the heap refresh, the windows and the geometry copies have made what this submission reads.
14475 state_.update_address_guard();
13711 const phases::Scope timed(phases::textures); 14476 const phases::Scope timed(phases::textures);
13712 if (async_texture_refresh()) { 14477 if (async_texture_refresh()) {
13713 if (!t_in_title_textures) { 14478 if (!t_in_title_textures) {
@@ -13750,12 +14515,18 @@ public:
13750 [](void* device, std::uint64_t table, std::uint32_t descriptors) { 14515 [](void* device, std::uint64_t table, std::uint32_t descriptors) {
13751 static_cast<DeviceState*>(device)->scan_title_table(table, descriptors); 14516 static_cast<DeviceState*>(device)->scan_title_table(table, descriptors);
13752 }); 14517 });
14518 leonida::title_va_aliases().set_noter([](void* device, std::uint64_t va, std::uint64_t bytes) {
14519 static_cast<DeviceState*>(device)->note_title_write(va, bytes);
14520 });
14521 // Every device, hooks or not: its console heaps' slot records follow the alias table's changes.
14522 leonida::title_va_aliases().add_listener(&state_, &DeviceState::alias_changed);
13753 state_.image_memory = std::make_unique<leonida::ImageMemory>( 14523 state_.image_memory = std::make_unique<leonida::ImageMemory>(
13754 [device = info.device, make = state_.context->vk.vkAllocateMemory](std::uint32_t type, std::uint64_t bytes) { 14524 [device = info.device, make = state_.context->vk.vkAllocateMemory](std::uint32_t type, std::uint64_t bytes) {
13755 VkMemoryAllocateInfo block{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; 14525 VkMemoryAllocateInfo block{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
13756 block.allocationSize = bytes; 14526 block.allocationSize = bytes;
13757 block.memoryTypeIndex = type; 14527 block.memoryTypeIndex = type;
13758 VkDeviceMemory out = VK_NULL_HANDLE; 14528 VkDeviceMemory out = VK_NULL_HANDLE;
14529 leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::image_blocks);
13759 return make(device, &block, nullptr, &out) == VK_SUCCESS ? out : VkDeviceMemory(VK_NULL_HANDLE); 14530 return make(device, &block, nullptr, &out) == VK_SUCCESS ? out : VkDeviceMemory(VK_NULL_HANDLE);
13760 }, 14531 },
13761 [device = info.device, free = state_.context->vk.vkFreeMemory](VkDeviceMemory block) { 14532 [device = info.device, free = state_.context->vk.vkFreeMemory](VkDeviceMemory block) {
@@ -13859,6 +14630,21 @@ public:
13859 (unsigned long long)shadows, leonida::fsdraw::pipeline_count()); 14630 (unsigned long long)shadows, leonida::fsdraw::pipeline_count());
13860 return std::string(text); 14631 return std::string(text);
13861 }; 14632 };
14633 facts.share = [this] {
14634 leonida::memory_breakdown::DeviceShare share;
14635 DeviceState& d = state_;
14636 if (d.arena.buffer) {
14637 share.arena = true;
14638 std::lock_guard lock(d.arena.mutex);
14639 share.arena_reserved = d.arena.size;
14640 share.arena_bound = d.arena.size; // one allocation behind the whole range
14641 share.arena_in_use = d.arena.in_use;
14642 for (std::size_t i = 0; i < share.arena_use.size(); ++i) share.arena_use[i] = d.arena.use_in_use[i];
14643 }
14644 std::lock_guard lock(d.descriptor_mutex); // the bindless set's lock (ExecuteCommandLists' flush)
14645 if (const auto* bindless = d.bindless.get()) share.bindless_table_bytes = bindless->table_buffer_bytes();
14646 return share;
14647 };
13862 leonida::mem_probe::start(std::move(facts)); 14648 leonida::mem_probe::start(std::move(facts));
13863 } 14649 }
13864 if (info.conditional_rendering) { 14650 if (info.conditional_rendering) {
@@ -13895,6 +14681,7 @@ public:
13895 state_.context->enable_copy_scratch( 14681 state_.context->enable_copy_scratch(
13896 get_device, 14682 get_device,
13897 [this, index_scratch](const VkMemoryRequirements& requirements) { 14683 [this, index_scratch](const VkMemoryRequirements& requirements) {
14684 leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::staging);
13898 return state_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, nullptr, index_scratch); 14685 return state_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, nullptr, index_scratch);
13899 }, 14686 },
13900 scratch_extra, state_.families); 14687 scratch_extra, state_.families);
@@ -14322,8 +15109,11 @@ public:
14322 "device's %s\n", 15109 "device's %s\n",
14323 static_cast<unsigned long long>(size.bytes >> 20), 15110 static_cast<unsigned long long>(size.bytes >> 20),
14324 static_cast<unsigned long long>(size.requested >> 20), leonida::arena_cap_name(size.capped)); 15111 static_cast<unsigned long long>(size.requested >> 20), leonida::arena_cap_name(size.capped));
14325 arena.memory = state_.allocate(requirements, leonida::kArenaRequiredMemory, leonida::kArenaPreferredMemory, 15112 {
14326 nullptr, true, &arena.memory_type); 15113 leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::arena);
15114 arena.memory = state_.allocate(requirements, leonida::kArenaRequiredMemory,
15115 leonida::kArenaPreferredMemory, nullptr, true, &arena.memory_type);
15116 }
14327 void* mapped = nullptr; 15117 void* mapped = nullptr;
14328 if (!arena.memory || vk.vkBindBufferMemory(state_.info.device, arena.buffer, arena.memory, 0) != VK_SUCCESS || 15118 if (!arena.memory || vk.vkBindBufferMemory(state_.info.device, arena.buffer, arena.memory, 0) != VK_SUCCESS ||
14329 vk.vkMapMemory(state_.info.device, arena.memory, 0, VK_WHOLE_SIZE, 0, &mapped) != VK_SUCCESS) { 15119 vk.vkMapMemory(state_.info.device, arena.memory, 0, VK_WHOLE_SIZE, 0, &mapped) != VK_SUCCESS) {
@@ -14376,14 +15166,20 @@ public:
14376 // Under the arena's lock: an insert rebalances the tree and rewrites child links, which a walk on 15166 // Under the arena's lock: an insert rebalances the tree and rewrites child links, which a walk on
14377 // another thread must not see half done. 15167 // another thread must not see half done.
14378 std::lock_guard lock(arena.mutex); 15168 std::lock_guard lock(arena.mutex);
14379 arena.blocks.reset(null_bytes + kArenaReserved, arena.size); 15169 // LEONIDA_ADDRESS_GUARD: the guard header and sinks at [0x70000, 0x80000) are never handed out either
14380 arena.first = null_bytes + kArenaReserved; 15170 // (inside the null region when there is one, else just past the quad indices).
15171 arena.first = std::max<VkDeviceSize>(null_bytes + kArenaReserved,
15172 address_guard_enabled() ? leonida::address_guard::kGuardEnd : 0);
15173 arena.blocks.reset(arena.first, arena.size);
14381 char check[2] = {}; 15174 char check[2] = {};
14382 size_t check_length = 0; 15175 size_t check_length = 0;
14383 arena.check_all = getenv_s(&check_length, check, "LEONIDA_ARENA_CHECK") == 0 && check_length > 1 && 15176 arena.check_all = getenv_s(&check_length, check, "LEONIDA_ARENA_CHECK") == 0 && check_length > 1 &&
14384 check[0] != '0'; 15177 check[0] != '0';
14385 } 15178 }
14386 arena.peak_end = null_bytes + kArenaReserved; 15179 arena.peak_end = arena.first;
15180 if (address_guard_enabled() && !state_.create_address_guard())
15181 std::fprintf(stderr, "[rt] d3d12: LEONIDA_ADDRESS_GUARD=1 but the address guard could not be set up; "
15182 "guarded shaders check nothing\n");
14387 char log[4] = {}; 15183 char log[4] = {};
14388 length = 0; 15184 length = 0;
14389 arena.log = getenv_s(&length, log, "LEONIDA_ARENA_LOG") == 0 && length > 1 && log[0] != '0'; 15185 arena.log = getenv_s(&length, log, "LEONIDA_ARENA_LOG") == 0 && length > 1 && log[0] != '0';
@@ -14452,6 +15248,7 @@ public:
14452 compiler_use_.release(); 15248 compiler_use_.release();
14453 } 15249 }
14454 leonida::title_va_aliases().clear_hooks(&state_); 15250 leonida::title_va_aliases().clear_hooks(&state_);
15251 leonida::title_va_aliases().remove_listener(&state_);
14455 { 15252 {
14456 std::lock_guard lock(state_.title_window_mutex); 15253 std::lock_guard lock(state_.title_window_mutex);
14457 for (const auto& window : state_.title_windows) 15254 for (const auto& window : state_.title_windows)
@@ -14490,12 +15287,14 @@ public:
14490 state_.bindless.reset(); 15287 state_.bindless.reset();
14491 } 15288 }
14492 state_.report_arena(); 15289 state_.report_arena();
15290 state_.destroy_address_guard();
14493 if (state_.context && state_.arena.buffer) { 15291 if (state_.context && state_.arena.buffer) {
14494 leonida::fsdraw::forget_arena(state_.arena.mapped); 15292 leonida::fsdraw::forget_arena(state_.arena.mapped);
14495 auto& vk = state_.context->vk; 15293 auto& vk = state_.context->vk;
14496 vk.vkDestroyBuffer(state_.info.device, state_.arena.buffer, nullptr); 15294 vk.vkDestroyBuffer(state_.info.device, state_.arena.buffer, nullptr);
14497 if (state_.arena.memory) vk.vkFreeMemory(state_.info.device, state_.arena.memory, nullptr); 15295 if (state_.arena.memory) vk.vkFreeMemory(state_.info.device, state_.arena.memory, nullptr);
14498 } 15296 }
15297 state_.finish_heavy_cache();
14499 if (state_.pipeline_cache_handle) { 15298 if (state_.pipeline_cache_handle) {
14500 // Nothing should be building into the cache now (the compiler's jobs for this device are gone, and so 15299 // Nothing should be building into the cache now (the compiler's jobs for this device are gone, and so
14501 // is every PSO). If something is, its pipelines are half in the cache: keep the previous session file. 15300 // is every PSO). If something is, its pipelines are half in the cache: keep the previous session file.
@@ -15621,6 +16420,8 @@ private:
15621 const bool guard = check_pages_before_read(); 16420 const bool guard = check_pages_before_read();
15622 if (!guard && !t.memory.pending()) return true; 16421 if (!guard && !t.memory.pending()) return true;
15623 const bool mapped = t.mapped && refresh_mapped_pages(); 16422 const bool mapped = t.mapped && refresh_mapped_pages();
16423 if (!title_pass_ && guard && !mapped)
16424 t.memory.sync_map(title_map_generation_, static_cast<std::uintptr_t>(t.cpu), t.layout.layout.size);
15624 const auto commit = mapped ? leonida::kernel_writes::state().committer.load(std::memory_order_acquire) : nullptr; 16425 const auto commit = mapped ? leonida::kernel_writes::state().committer.load(std::memory_order_acquire) : nullptr;
15625 const bool waited = t.memory.pending(); 16426 const bool waited = t.memory.pending();
15626 // The answer is kept (generation 0) until a map change over the texture, a write into it or the periodic 16427 // The answer is kept (generation 0) until a map change over the texture, a write into it or the periodic
@@ -17927,7 +18728,7 @@ public:
17927 // imported, or a shadow copied from them before every submission) and kept until the device goes, up to 18728 // imported, or a shadow copied from them before every submission) and kept until the device goes, up to
17928 // LEONIDA_TITLE_BUFFERS_MB (512 by default). 18729 // LEONIDA_TITLE_BUFFERS_MB (512 by default).
17929 void make_title_buffer(std::uint64_t va, std::uint64_t bytes) { 18730 void make_title_buffer(std::uint64_t va, std::uint64_t bytes) {
17930 if (!state_.context) return; 18731 if (!&context()) return;
17931 static const bool check_size = [] { 18732 static const bool check_size = [] {
17932 wchar_t flag[2]{}; 18733 wchar_t flag[2]{};
17933 return !(GetEnvironmentVariableW(L"LEONIDA_TITLE_BUFFER_COVERAGE", flag, 2) == 1 && flag[0] == L'0'); 18734 return !(GetEnvironmentVariableW(L"LEONIDA_TITLE_BUFFER_COVERAGE", flag, 2) == 1 && flag[0] == L'0');
@@ -19933,9 +20734,10 @@ bool stop_pipeline_compiles(unsigned wait_ms) {
19933 return idle; 20734 return idle;
19934} 20735}
19935 20736
19936// How long an exit save waits for the write itself (save_session_pipeline_cache): a 77 MiB cache was measured at about 20737// How long an exit save waits for the write itself (save_session_pipeline_cache). Measured fill and publish: a 77 MiB
19937// 36 ms (fill and publish), so this only bounds a driver that blocks the read. 20738// cache about 36 ms; 1.87 GB 1.4 s and 2.9 GB 1.3-1.6 s (NVIDIA, Windows 11, NVMe), so about 2.2 s at the 4 GiB
19938constexpr unsigned kExitCacheWriteMs = 3000; 20739// default limit. The wait ends with the write; the bound only covers a driver or disk that blocks.
20740constexpr unsigned kExitCacheWriteMs = 6000;
19939 20741
19940bool save_pipeline_caches_at_exit(unsigned wait_ms) { 20742bool save_pipeline_caches_at_exit(unsigned wait_ms) {
19941 if (exit_cache_saved.exchange(true)) return false; // once: a crash during the normal exit's save does not redo it 20743 if (exit_cache_saved.exchange(true)) return false; // once: a crash during the normal exit's save does not redo it
@@ -21017,8 +21819,12 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin
21017 v13.compute_full_subgroups, info.subgroup); 21819 v13.compute_full_subgroups, info.subgroup);
21018 const char* compile_mode = std::getenv("LEONIDA_PIPELINE_COMPILE"); 21820 const char* compile_mode = std::getenv("LEONIDA_PIPELINE_COMPILE");
21019 const auto mode = compile_mode ? std::string_view(compile_mode) : std::string_view{}; 21821 const auto mode = compile_mode ? std::string_view(compile_mode) : std::string_view{};
21020 v13.enable_pipeline_cache_control = mode == "cache-only" && v13.core && v13.pipeline_cache_control; 21822 // pipelineCreationCacheControl: for LEONIDA_PIPELINE_COMPILE=cache-only, and for the heavy pipeline cache unless
21021 info.cold_graphics_compile = v13.enable_pipeline_cache_control; 21823 // LEONIDA_HEAVY_PIPELINE_CACHE_MS=0 turns it off.
21824 v13.enable_pipeline_cache_control =
21825 (mode == "cache-only" || heavy_pipeline_cache_ms()) && v13.core && v13.pipeline_cache_control;
21826 info.cold_graphics_compile = mode == "cache-only" && v13.enable_pipeline_cache_control;
21827 info.heavy_pipeline_cache = heavy_pipeline_cache_ms() && v13.enable_pipeline_cache_control;
21022 info.prepare_on_bind = mode == "on-demand"; 21828 info.prepare_on_bind = mode == "on-demand";
21023 void* v13_chain = v13.enable(ext_chain); 21829 void* v13_chain = v13.enable(ext_chain);
21024 // D3D-78 uses the core robustness and format-feature flags. Leave the Vulkan 1.2 extension path unchanged. 21830 // D3D-78 uses the core robustness and format-feature flags. Leave the Vulkan 1.2 extension path unchanged.
@@ -21681,10 +22487,10 @@ public:
21681 DeviceState& state() { return *device_; } 22487 DeviceState& state() { return *device_; }
21682 const leonida::ShaderLibrary* library() const { return library_; } 22488 const leonida::ShaderLibrary* library() const { return library_; }
21683 22489
21684 // Why create_compute would refuse the entry, or null. 22490 // Why create_compute could not build the entry on this device, or null. LEONIDA_SKIP_COMPUTE is not a reason here:
22491 // it drops a program's dispatches at play, and each caller decides whether it also keeps the program unbuilt.
21685 const char* unbuildable(const leonida::ShaderEntry& entry, std::size_t bytes) const { 22492 const char* unbuildable(const leonida::ShaderEntry& entry, std::size_t bytes) const {
21686 if (!bytes) return "no .spv"; 22493 if (!bytes) return "no .spv";
21687 if (skip_compute(entry.name)) return "LEONIDA_SKIP_COMPUTE";
21688 if (entry.binding_count && !with_set0_) return "set-0 bindings and no bindless set"; 22494 if (entry.binding_count && !with_set0_) return "set-0 bindings and no bindless set";
21689 if (entry.lds_bytes && max_shared_ && entry.lds_bytes > max_shared_) return "workgroup memory over the limit"; 22495 if (entry.lds_bytes && max_shared_ && entry.lds_bytes > max_shared_) return "workgroup memory over the limit";
21690 return nullptr; 22496 return nullptr;
@@ -21716,13 +22522,15 @@ int precompile_compute_pipelines(const PrecompileOptions& options) {
21716 if (!host.open()) return 1; 22522 if (!host.open()) return 1;
21717 const leonida::ShaderLibrary* library = host.library(); 22523 const leonida::ShaderLibrary* library = host.library();
21718 22524
21719 // What to build: every compute entry the runtime could create a pipeline for. 22525 // What to build: every compute entry the runtime could create a pipeline for. LEONIDA_SKIP_COMPUTE is a setting
22526 // for play (the game drops the listed programs' dispatches); the journal is kept for every program unless
22527 // --skip-listed asks to leave them out too, so a later run without the list finds them built.
21720 struct Job { 22528 struct Job {
21721 const leonida::ShaderEntry* entry; 22529 const leonida::ShaderEntry* entry;
21722 std::size_t bytes; 22530 std::size_t bytes;
21723 }; 22531 };
21724 std::vector<Job> jobs; 22532 std::vector<Job> jobs;
21725 std::size_t not_buildable = 0, filtered = 0; 22533 std::size_t not_buildable = 0, filtered = 0, listed = 0, listed_left_out = 0;
21726 for (const leonida::ShaderEntry* entry : library->stage_entries("cs")) { 22534 for (const leonida::ShaderEntry* entry : library->stage_entries("cs")) {
21727 if (!options.filters.empty() && 22535 if (!options.filters.empty() &&
21728 std::none_of(options.filters.begin(), options.filters.end(), 22536 std::none_of(options.filters.begin(), options.filters.end(),
@@ -21735,6 +22543,15 @@ int precompile_compute_pipelines(const PrecompileOptions& options) {
21735 ++filtered; 22543 ++filtered;
21736 continue; 22544 continue;
21737 } 22545 }
22546 if (skip_compute(entry->name)) {
22547 ++listed;
22548 if (options.skip_listed) {
22549 ++listed_left_out;
22550 std::fprintf(stderr, "[precompile] %s: not built (LEONIDA_SKIP_COMPUTE, --skip-listed)\n",
22551 entry->name.c_str());
22552 continue;
22553 }
22554 }
21738 if (const char* why = host.unbuildable(*entry, bytes)) { 22555 if (const char* why = host.unbuildable(*entry, bytes)) {
21739 ++not_buildable; 22556 ++not_buildable;
21740 std::fprintf(stderr, "[precompile] %s: not built (%s)\n", entry->name.c_str(), why); 22557 std::fprintf(stderr, "[precompile] %s: not built (%s)\n", entry->name.c_str(), why);
@@ -21745,14 +22562,22 @@ int precompile_compute_pipelines(const PrecompileOptions& options) {
21745 std::stable_sort(jobs.begin(), jobs.end(), [&](const Job& a, const Job& b) { 22562 std::stable_sort(jobs.begin(), jobs.end(), [&](const Job& a, const Job& b) {
21746 return options.smallest_first ? a.bytes < b.bytes : a.bytes > b.bytes; 22563 return options.smallest_first ? a.bytes < b.bytes : a.bytes > b.bytes;
21747 }); 22564 });
21748 if (options.limit && jobs.size() > options.limit) jobs.resize(options.limit); 22565 if (options.limit && jobs.size() > options.limit) {
22566 filtered += jobs.size() - options.limit;
22567 jobs.resize(options.limit);
22568 }
21749 std::uint64_t total_bytes = 0; 22569 std::uint64_t total_bytes = 0;
21750 for (const Job& job : jobs) total_bytes += job.bytes; 22570 for (const Job& job : jobs) total_bytes += job.bytes;
21751 const unsigned threads = (std::max)(1u, options.threads); 22571 const unsigned threads = (std::max)(1u, options.threads);
21752 const unsigned big_threads = options.big_threads ? (std::min)(options.big_threads, threads) : threads; 22572 const unsigned big_threads = options.big_threads ? (std::min)(options.big_threads, threads) : threads;
21753 std::fprintf(stderr, "[precompile] %zu compute entries to build (%.1f MB of SPIR-V; %zu filtered out, %zu not " 22573 if (listed && !options.skip_listed)
21754 "buildable), %s first, %u thread(s), at most %u on modules over %zu bytes; journal %ls\n", 22574 std::fprintf(stderr, "[precompile] LEONIDA_SKIP_COMPUTE names %zu of the entries: built anyway, since the list "
21755 jobs.size(), double(total_bytes) / 1e6, filtered, not_buildable, 22575 "drops their dispatches at play only (--skip-listed leaves them out of this run)\n",
22576 listed);
22577 std::fprintf(stderr, "[precompile] %zu compute entries to build (%.1f MB of SPIR-V; %zu filtered out, %zu left "
22578 "out by --skip-listed, %zu not buildable), %s first, %u thread(s), at most %u on modules over "
22579 "%zu bytes; journal %ls\n",
22580 jobs.size(), double(total_bytes) / 1e6, filtered, listed_left_out, not_buildable,
21756 options.smallest_first ? "smallest" : "largest", threads, big_threads, options.big_bytes, 22581 options.smallest_first ? "smallest" : "largest", threads, big_threads, options.big_bytes,
21757 pipeline_journal_dir().c_str()); 22582 pipeline_journal_dir().c_str());
21758 if (options.dry_run) { 22583 if (options.dry_run) {
@@ -21762,7 +22587,7 @@ int precompile_compute_pipelines(const PrecompileOptions& options) {
21762 22587
21763 std::atomic<std::size_t> next{0}; 22588 std::atomic<std::size_t> next{0};
21764 std::mutex progress_mutex; 22589 std::mutex progress_mutex;
21765 std::size_t done = 0, compiled = 0, skipped = 0, hits = 0, failed = 0; 22590 std::size_t done = 0, compiled = 0, skipped = 0, hits = 0, failed = 0, journaled = 0, elsewhere = 0;
21766 std::uint64_t done_bytes = 0; 22591 std::uint64_t done_bytes = 0;
21767 std::mutex big_mutex; 22592 std::mutex big_mutex;
21768 std::condition_variable big_free; 22593 std::condition_variable big_free;
@@ -21801,8 +22626,8 @@ int precompile_compute_pipelines(const PrecompileOptions& options) {
21801 ++done; 22626 ++done;
21802 done_bytes += job.bytes; 22627 done_bytes += job.bytes;
21803 const char* what = "failed"; 22628 const char* what = "failed";
21804 if (build.skipped) ++skipped, what = "journaled already"; 22629 if (build.skipped) ++skipped, ++journaled, what = "journaled already";
21805 else if (build.busy) ++skipped, what = "being built by another process"; 22630 else if (build.busy) ++skipped, ++elsewhere, what = "being built by another process";
21806 else if (build.result != VK_SUCCESS || (!build.pipeline && !build.skipped)) ++failed; 22631 else if (build.result != VK_SUCCESS || (!build.pipeline && !build.skipped)) ++failed;
21807 else if (build.journal_hit || build.from_shared) ++hits, what = "found in a cache"; 22632 else if (build.journal_hit || build.from_shared) ++hits, what = "found in a cache";
21808 else ++compiled, what = build.journaled ? "compiled and journaled" : "compiled (not journaled)"; 22633 else ++compiled, what = build.journaled ? "compiled and journaled" : "compiled (not journaled)";
@@ -21819,8 +22644,12 @@ int precompile_compute_pipelines(const PrecompileOptions& options) {
21819 std::vector<std::thread> pool; 22644 std::vector<std::thread> pool;
21820 for (unsigned t = 0; t < threads; ++t) pool.emplace_back(worker); 22645 for (unsigned t = 0; t < threads; ++t) pool.emplace_back(worker);
21821 for (std::thread& t : pool) t.join(); 22646 for (std::thread& t : pool) t.join();
21822 std::fprintf(stderr, "[precompile] done: %zu compiled, %zu from a cache, %zu journaled already, %zu failed, %zu " 22647 // One line for the whole run: what was built, what was there already, and what was left out and why.
21823 "not buildable, in %.0f s\n", compiled, hits, skipped, failed, not_buildable, 22648 std::fprintf(stderr, "[precompile] done: %zu built (%zu compiled, %zu from a cache), %zu journaled already, %zu "
22649 "being built by another process, %zu failed; left out: %zu of %zu listed in "
22650 "LEONIDA_SKIP_COMPUTE%s, %zu not buildable, %zu filtered out; in %.0f s\n",
22651 compiled + hits, compiled, hits, journaled, elsewhere, failed, listed_left_out, listed,
22652 options.skip_listed ? " (--skip-listed)" : "", not_buildable, filtered,
21824 std::chrono::duration<double>(Clock::now() - began).count()); 22653 std::chrono::duration<double>(Clock::now() - began).count());
21825 return failed ? 2 : 0; 22654 return failed ? 2 : 0;
21826} 22655}
@@ -21939,6 +22768,7 @@ int compile_server(const CompileServerOptions& options) {
21939 const leonida::ShaderEntry* entry = it == by_name.end() ? nullptr : it->second; 22768 const leonida::ShaderEntry* entry = it == by_name.end() ? nullptr : it->second;
21940 const std::size_t bytes = entry ? library->spirv_bytes(*entry) : 0; 22769 const std::size_t bytes = entry ? library->spirv_bytes(*entry) : 0;
21941 if (!entry) failure = "no compute entry of that name in this library"; 22770 if (!entry) failure = "no compute entry of that name in this library";
22771 else if (skip_compute(entry->name)) failure = "LEONIDA_SKIP_COMPUTE"; // the game drops its dispatches
21942 else if (const char* why = host.unbuildable(*entry, bytes)) failure = why; 22772 else if (const char* why = host.unbuildable(*entry, bytes)) failure = why;
21943 // LOCAL FIX (compile helper: the journal name was checked after the build): the name is hashed from the 22773 // LOCAL FIX (compile helper: the journal name was checked after the build): the name is hashed from the
21944 // module and this device's environment, which costs no driver call. A request from a game whose environment 22774 // module and this device's environment, which costs no driver call. A request from a game whose environment
@@ -22063,7 +22893,7 @@ int compile_server(const CompileServerOptions& options) {
22063 return; 22893 return;
22064 } 22894 }
22065 const leonida::ShaderEntry& entry = *fill_order[i]; 22895 const leonida::ShaderEntry& entry = *fill_order[i];
22066 if (host.unbuildable(entry, fill_bytes[i])) continue; 22896 if (skip_compute(entry.name) || host.unbuildable(entry, fill_bytes[i])) continue;
22067 std::error_code stat; 22897 std::error_code stat;
22068 const auto spv = library->spirv_file(entry); 22898 const auto spv = library->spirv_file(entry);
22069 const long long mtime = static_cast<long long>(std::filesystem::last_write_time(spv, stat).time_since_epoch().count()); 22899 const long long mtime = static_cast<long long>(std::filesystem::last_write_time(spv, stat).time_since_epoch().count());
diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp
index 87cc26dd3..c5f12dc05 100644
--- a/runtime/shims/d3d12_xs_device.cpp
+++ b/runtime/shims/d3d12_xs_device.cpp
@@ -2289,6 +2289,12 @@ HRESULT queue_copy_page_mappings(ChildProxy* self, UINT count, const xmem::PageB
2289 if (!map && rt::xmem::copy_page_mappings_fn) map = &copy_page_mappings_default; 2289 if (!map && rt::xmem::copy_page_mappings_fn) map = &copy_page_mappings_default;
2290 if (!map || !count) return S_OK; 2290 if (!map || !count) return S_OK;
2291 if (!batches || flags) return E_INVALIDARG; 2291 if (!batches || flags) return E_INVALIDARG;
2292 // Which implementation remaps, once: a boot's read-fault reports belong to that route's tests.
2293 static std::atomic<bool> route_logged{false};
2294 if (!route_logged.exchange(true, std::memory_order_relaxed))
2295 std::fprintf(stderr, "[rt] d3d12_xs: CopyPageMappingsBatchX remaps through %s\n",
2296 map == &copy_page_mappings_default ? "xmem's range callback (copy_page_mappings_fn)"
2297 : "the installed batch hook (set_copy_page_mappings_hook)");
2292 auto* queue = reinterpret_cast<ID3D12CommandQueue*>(self->real); 2298 auto* queue = reinterpret_cast<ID3D12CommandQueue*>(self->real);
2293 using clock = std::chrono::steady_clock; 2299 using clock = std::chrono::steady_clock;
2294 const auto t0 = clock::now(); 2300 const auto t0 = clock::now();
@@ -2840,6 +2846,32 @@ struct UploadArena {
2840 2846
2841constexpr std::size_t kUploadChunkMin = 8 << 20; // one chunk serves a title's whole frame of uploads 2847constexpr std::size_t kUploadChunkMin = 8 << 20; // one chunk serves a title's whole frame of uploads
2842 2848
2849// LEONIDA_UPLOAD_LOG=1 (diagnostic): each upload chunk (its CPU base, device address and size), and the first 96 and
2850// then every 8192nd AllocateUploadMemory result as an offset into its chunk, so the addresses the title builds
2851// descriptors from can be matched with the memory it was handed.
2852inline bool upload_log() {
2853 static const bool on = [] {
2854 const char* v = std::getenv("LEONIDA_UPLOAD_LOG");
2855 return v && *v == '1';
2856 }();
2857 return on;
2858}
2859inline void log_upload_result(const UploadChunk* chunk, std::uint64_t result, std::uint64_t size,
2860 std::uint64_t alignment) {
2861 if (!upload_log() || !chunk) return;
2862 static std::atomic<std::uint64_t> calls{0};
2863 const std::uint64_t n = ++calls;
2864 if (n > 96 && (n % 8192)) return;
2865 const std::uint64_t base = reinterpret_cast<std::uint64_t>(chunk->cpu_base);
2866 std::fprintf(stderr,
2867 "[rt] upload-log: #%llu result 0x%llx = chunk 0x%llx + offset 0x%llx (size %llu, alignment %llu; "
2868 "chunk device address 0x%llx)\n",
2869 static_cast<unsigned long long>(n), static_cast<unsigned long long>(result),
2870 static_cast<unsigned long long>(base), static_cast<unsigned long long>(result - base),
2871 static_cast<unsigned long long>(size), static_cast<unsigned long long>(alignment),
2872 static_cast<unsigned long long>(chunk->gpu_base));
2873}
2874
2843UploadChunk* upload_chunk_new(DeviceProxy* device, std::size_t size) { 2875UploadChunk* upload_chunk_new(DeviceProxy* device, std::size_t size) {
2844 auto* chunk = new (std::nothrow) UploadChunk{}; 2876 auto* chunk = new (std::nothrow) UploadChunk{};
2845 if (!chunk) return nullptr; 2877 if (!chunk) return nullptr;
@@ -2865,6 +2897,24 @@ UploadChunk* upload_chunk_new(DeviceProxy* device, std::size_t size) {
2865 chunk->resource = resource; 2897 chunk->resource = resource;
2866 chunk->cpu_base = static_cast<std::uint8_t*>(cpu); 2898 chunk->cpu_base = static_cast<std::uint8_t*>(cpu);
2867 chunk->gpu_base = resource->GetGPUVirtualAddress(); 2899 chunk->gpu_base = resource->GetGPUVirtualAddress();
2900 // LEONIDA_UPLOAD_ALIAS=1 (experiment): the title takes the pointer AllocateUploadMemory hands it for a GPU
2901 // address too (the console's memory is unified) and writes it into the descriptors it builds itself. Entered in
2902 // the title VA table, the chunk's CPU range answers with the chunk's console VA (its device address minus
2903 // heap_base), so a V# the title wrote with such a pointer is rewritten to the chunk instead of left empty. A
2904 // chunk below the arena has a negative console VA, usable in a V# only with LEONIDA_IMPORT_BELOW_ARENA=1.
2905 static const bool alias = [] {
2906 const char* v = std::getenv("LEONIDA_UPLOAD_ALIAS");
2907 return v && *v == '1';
2908 }();
2909 if (alias) {
2910 const bool added = leonida::title_va_aliases().add(reinterpret_cast<std::uint64_t>(chunk->cpu_base),
2911 chunk->size, chunk->gpu_base);
2912 std::fprintf(stderr, "[rt] d3d12_xs: upload chunk 0x%llx (%llu bytes) entered as an alias of console VA "
2913 "0x%llx: %s\n",
2914 static_cast<unsigned long long>(reinterpret_cast<std::uint64_t>(chunk->cpu_base)),
2915 static_cast<unsigned long long>(chunk->size), static_cast<unsigned long long>(chunk->gpu_base),
2916 added ? "ok" : "refused");
2917 }
2868 return chunk; 2918 return chunk;
2869 } 2919 }
2870 if (resource) resource->Release(); 2920 if (resource) resource->Release();
@@ -2912,7 +2962,9 @@ std::uint64_t upload_alloc(DeviceProxy* device, std::uint64_t size, std::uint64_
2912 const std::size_t aligned = (chunk->used + (alignment - 1)) & ~(static_cast<std::size_t>(alignment) - 1); 2962 const std::size_t aligned = (chunk->used + (alignment - 1)) & ~(static_cast<std::size_t>(alignment) - 1);
2913 if (aligned >= chunk->used && aligned <= chunk->size && need <= chunk->size - aligned) { 2963 if (aligned >= chunk->used && aligned <= chunk->size && need <= chunk->size - aligned) {
2914 chunk->used = aligned + need; 2964 chunk->used = aligned + need;
2915 return reinterpret_cast<std::uint64_t>(chunk->cpu_base + aligned); 2965 const std::uint64_t result = reinterpret_cast<std::uint64_t>(chunk->cpu_base + aligned);
2966 log_upload_result(chunk, result, size, alignment);
2967 return result;
2916 } 2968 }
2917 } 2969 }
2918 const std::size_t chunk_size = need + alignment > kUploadChunkMin ? need + alignment : kUploadChunkMin; 2970 const std::size_t chunk_size = need + alignment > kUploadChunkMin ? need + alignment : kUploadChunkMin;
@@ -2926,7 +2978,14 @@ std::uint64_t upload_alloc(DeviceProxy* device, std::uint64_t size, std::uint64_
2926 arena->chunks = chunk; 2978 arena->chunks = chunk;
2927 const std::size_t aligned = (alignment - 1) & ~(static_cast<std::size_t>(alignment) - 1); // 0-based 2979 const std::size_t aligned = (alignment - 1) & ~(static_cast<std::size_t>(alignment) - 1); // 0-based
2928 chunk->used = aligned + need; 2980 chunk->used = aligned + need;
2929 return reinterpret_cast<std::uint64_t>(chunk->cpu_base + aligned); 2981 if (upload_log())
2982 std::fprintf(stderr, "[rt] upload-log: new chunk at 0x%llx, device address 0x%llx, %llu bytes (%s)\n",
2983 static_cast<unsigned long long>(reinterpret_cast<std::uint64_t>(chunk->cpu_base)),
2984 static_cast<unsigned long long>(chunk->gpu_base), static_cast<unsigned long long>(chunk->size),
2985 chunk->resource ? "mapped upload buffer" : "VirtualAlloc fallback");
2986 const std::uint64_t result = reinterpret_cast<std::uint64_t>(chunk->cpu_base + aligned);
2987 log_upload_result(chunk, result, size, alignment);
2988 return result;
2930} 2989}
2931 2990
2932// An address inside an upload chunk becomes the chunk's device address plus the offset; anything else — a 2991// An address inside an upload chunk becomes the chunk's device address plus the offset; anything else — a
@@ -2949,6 +3008,9 @@ void destroy_upload_state(void* upload_state) {
2949 for (UploadChunk* chunk = arena->chunks; chunk;) { 3008 for (UploadChunk* chunk = arena->chunks; chunk;) {
2950 UploadChunk* next = chunk->next; 3009 UploadChunk* next = chunk->next;
2951 if (chunk->resource) { 3010 if (chunk->resource) {
3011 const char* alias = std::getenv("LEONIDA_UPLOAD_ALIAS");
3012 if (alias && *alias == '1')
3013 leonida::title_va_aliases().remove(reinterpret_cast<std::uint64_t>(chunk->cpu_base), chunk->gpu_base);
2952 chunk->resource->Unmap(0, nullptr); 3014 chunk->resource->Unmap(0, nullptr);
2953 chunk->resource->Release(); 3015 chunk->resource->Release();
2954 } else { 3016 } else {
diff --git a/runtime/shims/d3d12_xs_list_values.h b/runtime/shims/d3d12_xs_list_values.h
index e49eefa98..b4f24bbbb 100644
--- a/runtime/shims/d3d12_xs_list_values.h
+++ b/runtime/shims/d3d12_xs_list_values.h
@@ -31,8 +31,10 @@
31// - The thread that signals a gate runs the work the layer held behind it (QueueHolds: the held lists' submission, 31// - The thread that signals a gate runs the work the layer held behind it (QueueHolds: the held lists' submission,
32// the shadow refresh, a deferred Present). That is the releaser, a second thread: the pump only decides, so 32// the shadow refresh, a deferred Present). That is the releaser, a second thread: the pump only decides, so
33// writes keep landing and other gates keep timing out while held work runs. 33// writes keep landing and other gates keep timing out while held work runs.
34// Bounded: a gate is signalled after LEONIDA_VALUE_WAIT_TIMEOUT_MS (default 200 ms) whatever memory holds, counted 34// Bounded: a gate is signalled after LEONIDA_VALUE_WAIT_TIMEOUT_MS (default 200 ms) of idle wait time, counted from
35// from when the gates before it on its queue opened, and logged once per address. Short timeouts (4 ms) go to an 35// when the gates before it on its queue opened and paused (up to a finite cap scaled with the gate's own budget) while
36// the releaser is running held work, while an acyclic matching producer write is in flight, or while unrelated
37// unblocked GPU work is running (src/list_value_wait_budget.h); logged once per address. Short timeouts (4 ms) go to an
36// address that timed out three times in a row, and, once four gates in a row timed out (the title waits for values 38// address that timed out three times in a row, and, once four gates in a row timed out (the title waits for values
37// no modelled write stores, a new address each frame), to every wait whose address was never met: a frame then pays 39// no modelled write stores, a new address each frame), to every wait whose address was never met: a frame then pays
38// a few milliseconds, not the full timeout, per such wait. A wait cut short is watched for the rest of the full 40// a few milliseconds, not the full timeout, per such wait. A wait cut short is watched for the rest of the full
@@ -56,10 +58,12 @@
56#include <memory> 58#include <memory>
57#include <mutex> 59#include <mutex>
58#include <new> 60#include <new>
61#include <span>
59#include <utility> 62#include <utility>
60#include <vector> 63#include <vector>
61 64
62#include "d3d12_xs_device.h" // console_value_met, ListValueStats 65#include "d3d12_xs_device.h" // console_value_met, ListValueStats
66#include "../src/list_value_wait_budget.h" // leonida::list_value_wait: work-aware timeout clock & producer graph
63#include "../src/title_page_watch.h" // leonida::kernel_writes::store 67#include "../src/title_page_watch.h" // leonida::kernel_writes::store
64#include "../src/value_write_sink.h" // leonida::value_sink: the arena and xmem's PAGE_NOACCESS pages 68#include "../src/value_write_sink.h" // leonida::value_sink: the arena and xmem's PAGE_NOACCESS pages
65 69
@@ -362,7 +366,8 @@ public:
362 if (writes.empty() || exiting_.load(std::memory_order_relaxed)) return; // stop(): see there 366 if (writes.empty() || exiting_.load(std::memory_order_relaxed)) return; // stop(): see there
363 { 367 {
364 std::lock_guard lock(mutex_); 368 std::lock_guard lock(mutex_);
365 writes_.push_back({std::move(queue), value, std::move(writes)}); 369 const std::uint64_t after_gate = max_pending_gate_locked(queue.get());
370 writes_.push_back({std::move(queue), value, std::move(writes), after_gate});
366 } 371 }
367 start_or_settle(); 372 start_or_settle();
368 } 373 }
@@ -396,7 +401,7 @@ public:
396 gate.value = value; 401 gate.value = value;
397 gate.started = true; 402 gate.started = true;
398 gate.since = Clock::now(); 403 gate.since = Clock::now();
399 gate.deadline = Clock::time_point::max(); 404 gate.last_tick = gate.since;
400 gate.after = after; 405 gate.after = after;
401 gate.action = std::move(action); 406 gate.action = std::move(action);
402 gates_.push_back(std::move(gate)); 407 gates_.push_back(std::move(gate));
@@ -502,13 +507,15 @@ private:
502 std::shared_ptr<QueueValues> queue; 507 std::shared_ptr<QueueValues> queue;
503 std::uint64_t value; 508 std::uint64_t value;
504 std::vector<Write> writes; 509 std::vector<Write> writes;
510 std::uint64_t after_gate = 0; // highest pending gate value on `queue` ahead of this write group
505 }; 511 };
506 struct Gate { 512 struct Gate {
507 std::shared_ptr<QueueValues> queue; 513 std::shared_ptr<QueueValues> queue;
508 std::uint64_t value = 0; 514 std::uint64_t value = 0;
509 std::vector<Wait> waits; 515 std::vector<Wait> waits;
510 Clock::time_point deadline; // set by start_gate 516 leonida::list_value_wait::GateTimeoutState timeout{}; // work-aware timeout clock (set by start_gate)
511 Clock::time_point since; 517 Clock::time_point last_tick{};
518 Clock::time_point since{};
512 bool started = false; // the gates before it on its queue have opened: its time runs 519 bool started = false; // the gates before it on its queue have opened: its time runs
513 bool cut_short = false; // given the short timeout 520 bool cut_short = false; // given the short timeout
514 std::uint64_t after = 0; // action gates: the queue's `written` value the action runs behind 521 std::uint64_t after = 0; // action gates: the queue's `written` value the action runs behind
@@ -632,12 +639,21 @@ private:
632 releasing_ = true; 639 releasing_ = true;
633 } 640 }
634 SetEvent(wake_); // the pump may be in an untimed wait: it watches the Signals from here on 641 SetEvent(wake_); // the pump may be in an untimed wait: it watches the Signals from here on
642 struct PendingReleaseGuard {
643 std::atomic<std::size_t>* count;
644 std::size_t remaining;
645 ~PendingReleaseGuard() {
646 if (remaining) count->fetch_sub(remaining, std::memory_order_release);
647 }
648 } pending_guard{&pending_releases_, batch.size()};
635 for (Release& release : batch) { 649 for (Release& release : batch) {
636 if (stop_.load(std::memory_order_relaxed)) break; 650 if (stop_.load(std::memory_order_relaxed)) break;
637 signal_value_.store(release.value, std::memory_order_relaxed); 651 signal_value_.store(release.value, std::memory_order_relaxed);
638 signal_since_ms_.store(GetTickCount64() | 1, std::memory_order_relaxed); // never 0 while inside 652 signal_since_ms_.store(GetTickCount64() | 1, std::memory_order_relaxed); // never 0 while inside
639 signal(release); 653 signal(release);
640 signal_since_ms_.store(0, std::memory_order_relaxed); 654 signal_since_ms_.store(0, std::memory_order_relaxed);
655 pending_releases_.fetch_sub(1, std::memory_order_release);
656 --pending_guard.remaining;
641 } 657 }
642 std::lock_guard lock(release_mutex_); 658 std::lock_guard lock(release_mutex_);
643 releasing_ = false; 659 releasing_ = false;
@@ -721,36 +737,114 @@ private:
721 writes_.swap(rest); 737 writes_.swap(rest);
722 } 738 }
723 739
724 // The gates whose waits are met, whose time is up or whose action's turn has come, taken off the list in each 740 // Highest pending gate value currently in `gates_` for `queue` (0 if none). Called with mutex_ held.
741 std::uint64_t max_pending_gate_locked(const QueueValues* queue) const {
742 std::uint64_t highest = 0;
743 for (const Gate& g : gates_)
744 if (g.queue.get() == queue && g.value > highest) highest = g.value;
745 return highest;
746 }
747
748 // The gates whose waits are met, whose idle time is up or whose action's turn has come, taken off the list in each
725 // queue's order (a queue's gate values rise in submission order, so a later one must not be signalled first: it 749 // queue's order (a queue's gate values rise in submission order, so a later one must not be signalled first: it
726 // would open the earlier one too). `force` (no threads): every gate, now. Called with mutex_ held. 750 // would open the earlier one too). A memory gate's timeout clock pauses while held work is being released, while
727 void take_open(bool force, std::vector<Release>& opening) { 751 // an acyclic matching producer write is in flight, or (up to a cap) while unrelated unblocked GPU work is running
728 std::vector<const QueueValues*> blocked; 752 // (src/list_value_wait_budget.h). `force` (no threads): every gate, now. Called with mutex_ held.
753 void take_open(bool force, bool landed_any, std::vector<Release>& opening) {
754 if (gates_.empty()) return;
729 const auto now = Clock::now(); 755 const auto now = Clock::now();
730 for (auto it = gates_.begin(); it != gates_.end();) { 756 namespace lvw = leonida::list_value_wait;
731 const QueueValues* queue = it->queue.get(); 757
732 if (std::find(blocked.begin(), blocked.end(), queue) != blocked.end()) { 758 // Build the lightweight producer/gate dependency view lazily only if a started memory gate is still unmet.
733 ++it; 759 bool graph_built = false;
734 continue; 760 std::vector<lvw::PendingWrite> flat_writes;
761 std::vector<lvw::PendingWriteGroup> view_writes;
762 std::vector<lvw::WaitPredicate> flat_waits;
763 std::vector<lvw::PendingGate> view_gates;
764 std::vector<std::pair<std::size_t, std::size_t>> gate_wait_ranges; // (offset, count) into flat_waits
765 const auto ensure_graph = [&] {
766 if (graph_built) return;
767 graph_built = true;
768 std::size_t total_writes = 0;
769 for (const WriteGroup& wg : writes_) total_writes += wg.writes.size();
770 flat_writes.reserve(total_writes);
771 view_writes.reserve(writes_.size());
772 for (const WriteGroup& wg : writes_) {
773 const std::size_t start = flat_writes.size();
774 for (const Write& w : wg.writes)
775 flat_writes.push_back({w.address, w.value, w.bytes, w.kind != WriteKind::value});
776 view_writes.push_back({wg.queue.get(), wg.after_gate,
777 std::span<const lvw::PendingWrite>(flat_writes).subspan(start, wg.writes.size())});
778 }
779 std::size_t total_waits = 0;
780 for (const Gate& g : gates_)
781 if (!g.action) total_waits += g.waits.size();
782 flat_waits.reserve(total_waits);
783 gate_wait_ranges.reserve(gates_.size());
784 for (const Gate& g : gates_) {
785 const std::size_t start = flat_waits.size();
786 if (!g.action) {
787 for (const Wait& w : g.waits)
788 if (!met_now(w)) flat_waits.push_back({w.address, w.reference, w.comparison, w.wide});
789 }
790 gate_wait_ranges.emplace_back(start, flat_waits.size() - start);
791 }
792 view_gates.reserve(gates_.size());
793 for (std::size_t i = 0; i < gates_.size(); ++i) {
794 const auto [off, cnt] = gate_wait_ranges[i];
795 view_gates.push_back({gates_[i].queue.get(), gates_[i].value, static_cast<bool>(gates_[i].action),
796 std::span<const lvw::WaitPredicate>(flat_waits).subspan(off, cnt)});
735 } 797 }
798 };
799
800 std::vector<const QueueValues*> blocked;
801 std::vector<bool> opened(gates_.size(), false);
802 for (std::size_t idx = 0; idx < gates_.size(); ++idx) {
803 Gate& gate = gates_[idx];
804 const QueueValues* queue = gate.queue.get();
805 if (std::find(blocked.begin(), blocked.end(), queue) != blocked.end()) continue;
736 bool open = force; 806 bool open = force;
737 if (it->action) { 807 if (gate.action) {
738 open = open || queue->written->GetCompletedValue() >= it->after; 808 open = open || queue->written->GetCompletedValue() >= gate.after;
739 } else { 809 } else {
740 if (!it->started) start_gate(*it, now); 810 if (!gate.started) start_gate(gate, now);
741 bool met = true; 811 bool met = true;
742 for (const Wait& wait : it->waits) met = met && met_now(wait); 812 for (const Wait& wait : gate.waits) met = met && met_now(wait);
743 open = open || met || now >= it->deadline; 813 bool timed_out = false;
744 if (open) note_outcome(*it, met || force); 814 if (!open && !met) {
815 const std::uint64_t dt_us =
816 now > gate.last_tick
817 ? static_cast<std::uint64_t>(
818 std::chrono::duration_cast<std::chrono::microseconds>(now - gate.last_tick).count())
819 : 0u;
820 gate.last_tick = now;
821 const bool releaser_busy =
822 landed_any || !opening.empty() || pending_releases_.load(std::memory_order_acquire) != 0;
823 lvw::PauseReason reason = lvw::PauseReason::releaser_busy;
824 if (!releaser_busy) {
825 ensure_graph();
826 reason = lvw::pause_reason(false, view_writes, view_gates, idx, console_value_met);
827 }
828 timed_out = gate.timeout.advance(dt_us, reason);
829 } else {
830 gate.last_tick = now;
831 }
832 open = open || met || timed_out;
833 if (open) note_outcome(gate, met || force, now);
745 } 834 }
746 if (open) { 835 if (open) {
747 opening.push_back({std::move(it->queue), it->value, std::move(it->action)}); 836 opening.push_back({std::move(gate.queue), gate.value, std::move(gate.action)});
748 it = gates_.erase(it); 837 opened[idx] = true;
749 } else { 838 } else {
750 blocked.push_back(queue); 839 blocked.push_back(queue);
751 ++it;
752 } 840 }
753 } 841 }
842 if (!opening.empty()) {
843 std::deque<Gate> rest;
844 for (std::size_t idx = 0; idx < gates_.size(); ++idx)
845 if (!opened[idx]) rest.push_back(std::move(gates_[idx]));
846 gates_.swap(rest);
847 }
754 } 848 }
755 849
756 // Writes landed, then gates opened: the pump's one step. `force` runs on the caller's thread when the threads do 850 // Writes landed, then gates opened: the pump's one step. `force` runs on the caller's thread when the threads do
@@ -763,12 +857,15 @@ private:
763 busy_ = true; 857 busy_ = true;
764 take_landed(force, landing); 858 take_landed(force, landing);
765 } 859 }
860 const bool landed_any = !landing.empty();
766 for (const WriteGroup& group : landing) land(group); 861 for (const WriteGroup& group : landing) land(group);
767 std::vector<Release> opening; 862 std::vector<Release> opening;
768 { 863 {
769 std::lock_guard lock(mutex_); 864 std::lock_guard lock(mutex_);
770 watch_late(); 865 watch_late();
771 take_open(force, opening); 866 take_open(force, landed_any, opening);
867 if (!force && !opening.empty())
868 pending_releases_.fetch_add(opening.size(), std::memory_order_release);
772 } 869 }
773 if (!opening.empty()) { 870 if (!opening.empty()) {
774 if (force) { 871 if (force) {
@@ -919,7 +1016,10 @@ private:
919 gate.started = true; 1016 gate.started = true;
920 gate.cut_short = cut_short; 1017 gate.cut_short = cut_short;
921 gate.since = now; 1018 gate.since = now;
922 gate.deadline = now + std::chrono::milliseconds(cut_short ? kDemotedTimeoutMs : full); 1019 gate.last_tick = now;
1020 const unsigned gate_ms = cut_short ? kDemotedTimeoutMs : full;
1021 const auto caps = leonida::list_value_wait::default_pause_caps(gate_ms, cut_short);
1022 gate.timeout.reset(static_cast<std::uint64_t>(gate_ms) * 1000u, caps.active_us, caps.max_us);
923 } 1023 }
924 1024
925 // A wait for `address` was met (in time, or late): the address has met history and its timeouts in a row end. 1025 // A wait for `address` was met (in time, or late): the address has met history and its timeouts in a row end.
@@ -961,15 +1061,15 @@ private:
961 } 1061 }
962 1062
963 // Called with mutex_ held. 1063 // Called with mutex_ held.
964 void note_outcome(const Gate& gate, bool met) { 1064 void note_outcome(const Gate& gate, bool met, Clock::time_point now) {
965 if (met) { 1065 if (met) {
966 bump(counters().gates_met); 1066 bump(counters().gates_met);
967 timeouts_in_a_row_ = 0; 1067 timeouts_in_a_row_ = 0;
968 for (const Wait& wait : gate.waits) note_met(wait.address); 1068 for (const Wait& wait : gate.waits) note_met(wait.address);
969 if (gate.cut_short && !gate.waits.empty()) lift_demotion(gate.waits.front().address); 1069 if (gate.cut_short && !gate.waits.empty()) lift_demotion(gate.waits.front().address);
970 if (logged_met_ < 4) { // the first few, to show the model at work in a boot log 1070 if (logged_met_ < 4 && !gate.waits.empty()) { // the first few, to show the model at work in a boot log
971 ++logged_met_; 1071 ++logged_met_;
972 const double ms = std::chrono::duration<double, std::milli>(Clock::now() - gate.since).count(); 1072 const double ms = std::chrono::duration<double, std::milli>(now - gate.since).count();
973 std::fprintf(stderr, "[rt] d3d12_xs: a queue's wait for 0x%llx was met after %.2f ms\n", 1073 std::fprintf(stderr, "[rt] d3d12_xs: a queue's wait for 0x%llx was met after %.2f ms\n",
974 static_cast<unsigned long long>(gate.waits.front().address), ms); 1074 static_cast<unsigned long long>(gate.waits.front().address), ms);
975 } 1075 }
@@ -990,14 +1090,14 @@ private:
990 for (const Wait& wait : gate.waits) { 1090 for (const Wait& wait : gate.waits) {
991 if (met_now(wait)) continue; 1091 if (met_now(wait)) continue;
992 if (gate.cut_short && !watched && late_.size() < kMaxLate) { 1092 if (gate.cut_short && !watched && late_.size() < kMaxLate) {
993 late_.push_back({wait, gate.since + std::chrono::milliseconds(full)}); 1093 late_.push_back({wait, now + std::chrono::milliseconds(full)});
994 watched = true; 1094 watched = true;
995 } 1095 }
996 Streak* streak = find_streak(wait.address); 1096 Streak* streak = find_streak(wait.address);
997 if (!streak) streak = add_streak(wait.address); 1097 if (!streak) streak = add_streak(wait.address);
998 ++streak->timeouts; 1098 ++streak->timeouts;
999 std::uint64_t now = 0; 1099 std::uint64_t current = 0;
1000 read_value(wait.address, wait.wide, now); 1100 read_value(wait.address, wait.wide, current);
1001 if (!streak->logged) { 1101 if (!streak->logged) {
1002 streak->logged = true; 1102 streak->logged = true;
1003 static std::atomic<unsigned> addresses{0}; 1103 static std::atomic<unsigned> addresses{0};
@@ -1008,7 +1108,7 @@ private:
1008 gate.cut_short ? kDemotedTimeoutMs : full, 1108 gate.cut_short ? kDemotedTimeoutMs : full,
1009 static_cast<unsigned long long>(wait.address), wait.wide ? 64u : 32u, 1109 static_cast<unsigned long long>(wait.address), wait.wide ? 64u : 32u,
1010 wait.comparison, static_cast<unsigned long long>(wait.reference), 1110 wait.comparison, static_cast<unsigned long long>(wait.reference),
1011 static_cast<unsigned long long>(now)); 1111 static_cast<unsigned long long>(current));
1012 } 1112 }
1013 if (streak->timeouts == kDemoteAfter) { 1113 if (streak->timeouts == kDemoteAfter) {
1014 static std::atomic<unsigned> demoted{0}; 1114 static std::atomic<unsigned> demoted{0};
@@ -1041,6 +1141,7 @@ private:
1041 std::condition_variable release_ready_; 1141 std::condition_variable release_ready_;
1042 std::deque<Release> releases_; 1142 std::deque<Release> releases_;
1043 bool releasing_ = false; 1143 bool releasing_ = false;
1144 std::atomic<std::size_t> pending_releases_{0}; // queued + active releases, read lock-free in take_open()
1044 std::atomic<std::uint64_t> signal_since_ms_{0}; // GetTickCount64 when the releaser's current Signal began, or 0 1145 std::atomic<std::uint64_t> signal_since_ms_{0}; // GetTickCount64 when the releaser's current Signal began, or 0
1045 std::atomic<std::uint64_t> signal_value_{0}; 1146 std::atomic<std::uint64_t> signal_value_{0};
1046 std::atomic<DWORD> releaser_tid_{0}; 1147 std::atomic<DWORD> releaser_tid_{0};
diff --git a/runtime/shims/dstorage.cpp b/runtime/shims/dstorage.cpp
index fe800fe68..103a5c9df 100644
--- a/runtime/shims/dstorage.cpp
+++ b/runtime/shims/dstorage.cpp
@@ -10,6 +10,8 @@
10// it has. Completion is therefore in queue order, as the API guarantees. 10// it has. Completion is therefore in queue order, as the API guarantees.
11// - Compressed requests stage RFC 1950 inflate, BCPack BC block reconstruction and DirectStorage 11// - Compressed requests stage RFC 1950 inflate, BCPack BC block reconstruction and DirectStorage
12// macro-unshuffle before publishing the destination. Physical page numbers resolve in xmem at execution. 12// macro-unshuffle before publishing the destination. Physical page numbers resolve in xmem at execution.
13// - A queue half full submits itself, but a read into physical pages and everything enqueued behind it wait for
14// the title's own Submit: the title may fill the page list only then (hold_pages below).
13// Nothing here goes online or touches the GPU. 15// Nothing here goes online or touches the GPU.
14#include <windows.h> 16#include <windows.h>
15#include <d3d12.h> 17#include <d3d12.h>
@@ -38,6 +40,7 @@
38#include "../src/shader_directory.h" 40#include "../src/shader_directory.h"
39#include "../src/dstorage_swizzle.h" 41#include "../src/dstorage_swizzle.h"
40#include "../src/dstorage_trace.h" 42#include "../src/dstorage_trace.h"
43#include "../src/dstorage_hold.h"
41#include "dstorage_xs_abi.h" 44#include "dstorage_xs_abi.h"
42#include "dstorage_staging.h" 45#include "dstorage_staging.h"
43#include "startup_trace.h" 46#include "startup_trace.h"
@@ -542,6 +545,47 @@ HRESULT read_file_range(HANDLE handle, uint64_t offset, void* destination, uint3
542 return S_OK; 545 return S_OK;
543} 546}
544 547
548// ---- Reads into physical pages wait for the title's Submit -------------------------------------------------------
549//
550// A request into physical pages names them through a pointer into the title's own page-number table, and a title may
551// fill that table for a batch only in its submit path, right before Submit. A queue that submits itself at half its
552// capacity then starts such a read early: it finds page 0 and fails, or finds the number the slot held before and
553// writes the data into a page that now belongs to something else, with no error at all. So a self-submit stops at
554// the first read into physical pages: that read and every entry behind it (the queue completes in order) wait for
555// the title's Submit. A full queue still submits everything, since the title cannot call Submit while it waits in an
556// enqueue, and Close does as before. The idea is from VIctory (Marvisak/VIctory eddde73, carried in
557// fxceless/victory-fork 79cfdd9); the code here is written anew for this queue.
558//
559// LEONIDA_DSTORAGE_HOLD_PAGES=0 restores the old self-submit of everything. A hold has a time limit, so that a
560// title path that never calls Submit and counted on the self-submit cannot stall for good: held entries that have
561// waited LEONIDA_DSTORAGE_HOLD_MS milliseconds (2000 unless set) are submitted, page lists as they are, and counted
562// as a timed release. 0 is no limit: they wait for Submit, however long. Both are read when a queue is created.
563constexpr uint32_t kDefaultHoldMs = 2000;
564
565uint32_t environment_number(const wchar_t* name, uint32_t fallback) {
566 wchar_t value[16]{};
567 const DWORD n = GetEnvironmentVariableW(name, value, 16);
568 if (n == 0 || n >= 16) return fallback;
569 wchar_t* end = nullptr;
570 const unsigned long parsed = std::wcstoul(value, &end, 10);
571 return end && *end == 0 ? static_cast<uint32_t>(parsed) : fallback;
572}
573
574// One line with every counter, at each power of two of the counter that moved: countable in a truncated log
575// without a line per event.
576void log_hold(const char* event, uint64_t n, unsigned capacity, size_t held_now) {
577 if (n & (n - 1)) return;
578 const auto& h = leonida::dstorage::hold_stats();
579 std::lock_guard lock(log_mutex());
580 std::fprintf(stderr, "[rt] ds-hold event=%s self_submits=%llu held_reads=%llu full_releases=%llu "
581 "timed_releases=%llu page0_entries=%llu capacity=%u held_now=%zu\n", event,
582 static_cast<unsigned long long>(h.self_submits.load()),
583 static_cast<unsigned long long>(h.held_reads.load()),
584 static_cast<unsigned long long>(h.full_releases.load()),
585 static_cast<unsigned long long>(h.timed_releases.load()),
586 static_cast<unsigned long long>(h.page0_entries.load()), capacity, held_now);
587}
588
545// ---- Queues ------------------------------------------------------------------------------------------------------- 589// ---- Queues -------------------------------------------------------------------------------------------------------
546 590
547// Only sampled when request tracing is enabled. Times include work done by the file/decode worker. 591// Only sampled when request tracing is enabled. Times include work done by the file/decode worker.
@@ -576,7 +620,10 @@ struct Entry {
576 620
577class Queue final : public IDStorageQueueX2 { 621class Queue final : public IDStorageQueueX2 {
578public: 622public:
579 explicit Queue(const DSTORAGE_QUEUE_DESC1& desc) : desc_(desc) { 623 explicit Queue(const DSTORAGE_QUEUE_DESC1& desc)
624 : desc_(desc),
625 hold_pages_(environment_number(L"LEONIDA_DSTORAGE_HOLD_PAGES", 1) != 0),
626 hold_release_ms_(environment_number(L"LEONIDA_DSTORAGE_HOLD_MS", kDefaultHoldMs)) {
580 error_event_ = CreateEventW(nullptr, TRUE, FALSE, nullptr); 627 error_event_ = CreateEventW(nullptr, TRUE, FALSE, nullptr);
581 clear_record_locked(); 628 clear_record_locked();
582 std::lock_guard lock(stats().mutex); 629 std::lock_guard lock(stats().mutex);
@@ -781,15 +828,64 @@ private:
781 bool auto_submit() const { return !desc_.Options.AutoSubmitDisabled; } 828 bool auto_submit() const { return !desc_.Options.AutoSubmitDisabled; }
782 size_t used_locked() const { return entries_.size() + in_flight_; } 829 size_t used_locked() const { return entries_.size() + in_flight_; }
783 830
831 // A read into physical pages: its page list may not be filled before the title's Submit (hold_pages above).
832 static bool into_pages(const Entry& e) {
833 return e.type == Entry::Type::Request && (e.request.Options.AsUINT64 & options::kDestinationPages) != 0;
834 }
835
836 // The queue has reached half its capacity and holds nothing yet. Submits up to the first read into physical
837 // pages, which waits with everything behind it for the title's Submit.
838 void self_submit_locked() {
839 auto& h = leonida::dstorage::hold_stats();
840 if (!hold_pages_) {
841 log_hold("self-submit", ++h.self_submits, desc_.Capacity, 0);
842 submit_locked();
843 return;
844 }
845 size_t end = submitted_;
846 while (end < entries_.size() && !into_pages(entries_[end])) ++end;
847 if (end < entries_.size()) {
848 uint64_t reads = 0;
849 for (size_t i = end; i < entries_.size(); ++i) reads += into_pages(entries_[i]);
850 h.held_reads += reads;
851 holding_ = true;
852 hold_warned_ = false;
853 held_since_ = std::chrono::steady_clock::now();
854 }
855 const size_t held_now = entries_.size() - end;
856 const bool hold = holding_; // submit_locked ends a hold when it submits everything
857 submit_locked(end);
858 holding_ = hold;
859 if (holding_) work_.notify_one(); // the worker starts timing the hold
860 log_hold("self-submit", ++h.self_submits, desc_.Capacity, held_now);
861 }
862
784 void enqueue(Entry&& e) { 863 void enqueue(Entry&& e) {
785 { 864 {
786 std::unique_lock lock(mutex_); 865 std::unique_lock lock(mutex_);
787 // A full queue waits for the worker to free a slot. With auto-submit on, half the queue is always 866 // A full queue waits for the worker to free a slot. With auto-submit on, half the queue was submitted
788 // submitted by then; with it off, only a Submit from another thread frees one (as the reference warns). 867 // by then, except what is held for the title's Submit: the title cannot make that call while it waits
789 space_.wait(lock, [&] { return closing_ || used_locked() < usable(); }); 868 // here, so a full queue submits the held entries too, page lists as they are. With auto-submit off,
869 // only a Submit from another thread frees a slot (as the reference warns).
870 space_.wait(lock, [&] {
871 if (closing_ || used_locked() < usable()) return true;
872 if (holding_) {
873 const size_t held_now = entries_.size() - submitted_;
874 submit_locked();
875 log_hold("full-queue", ++leonida::dstorage::hold_stats().full_releases, desc_.Capacity, held_now);
876 log_once("full-hold", "a full queue submitted reads into physical pages before the title's "
877 "Submit (their page lists may not be filled yet)");
878 }
879 return false;
880 });
790 if (!closing_) { 881 if (!closing_) {
791 entries_.push_back(std::move(e)); 882 entries_.push_back(std::move(e));
792 if (auto_submit() && entries_.size() - submitted_ >= half()) submit_locked(); 883 if (holding_) {
884 // Behind a held read: it waits with it, whatever it is. No second self-submit until the hold ends.
885 if (into_pages(entries_.back())) ++leonida::dstorage::hold_stats().held_reads;
886 } else if (auto_submit() && entries_.size() - submitted_ >= half()) {
887 self_submit_locked();
888 }
793 return; 889 return;
794 } 890 }
795 } 891 }
@@ -801,10 +897,16 @@ private:
801 release_references(e); 897 release_references(e);
802 } 898 }
803 899
804 void submit_locked() { 900 // Submits the entries before "end". Without one it submits all of them and ends a hold: the title's Submit, a
901 // full queue, Close, a hold that ran out of time.
902 void submit_locked(size_t end = SIZE_MAX) {
903 if (end >= entries_.size()) {
904 end = entries_.size();
905 holding_ = false;
906 }
805 uint32_t requests = 0; 907 uint32_t requests = 0;
806 uint64_t source_bytes = 0, destination_bytes = 0; 908 uint64_t source_bytes = 0, destination_bytes = 0;
807 for (size_t i = submitted_; i < entries_.size(); ++i) { 909 for (size_t i = submitted_; i < end; ++i) {
808 Entry& e = entries_[i]; 910 Entry& e = entries_[i];
809 if (e.file) e.file_counted = e.file->add_pending(); 911 if (e.file) e.file_counted = e.file->add_pending();
810 if (e.counted) { 912 if (e.counted) {
@@ -820,12 +922,49 @@ private:
820 p.TotalRequestSourceByteCount += source_bytes; 922 p.TotalRequestSourceByteCount += source_bytes;
821 p.TotalRequestDestinationByteCount += destination_bytes; 923 p.TotalRequestDestinationByteCount += destination_bytes;
822 } 924 }
823 if (entries_.size() > submitted_) { 925 if (end > submitted_) {
824 submitted_ = entries_.size(); 926 submitted_ = end;
825 work_.notify_one(); 927 work_.notify_one();
826 } 928 }
827 } 929 }
828 930
931 // How long the worker sleeps before it looks at a hold again: until the time limit runs out, a quarter of a
932 // second at most (and exactly that without a limit, for the five-second line).
933 std::chrono::milliseconds hold_wait_locked() const {
934 long long ms = 250;
935 if (hold_release_ms_) {
936 const auto waited = std::chrono::duration_cast<std::chrono::milliseconds>(
937 std::chrono::steady_clock::now() - held_since_).count();
938 ms = std::clamp<long long>(static_cast<long long>(hold_release_ms_) - waited, 1, 250);
939 }
940 return std::chrono::milliseconds(ms);
941 }
942
943 // On the worker while entries are held: a hold with a time limit ends when it runs out (a timed release), and
944 // one without says once that it has lasted five seconds (a title that never calls Submit would show up as this
945 // line and nothing after it).
946 void hold_tick_locked() {
947 if (!holding_) return;
948 const auto waited = std::chrono::duration_cast<std::chrono::milliseconds>(
949 std::chrono::steady_clock::now() - held_since_).count();
950 const size_t held_now = entries_.size() - submitted_;
951 if (hold_release_ms_ && waited >= static_cast<long long>(hold_release_ms_)) {
952 submit_locked();
953 log_hold("timed", ++leonida::dstorage::hold_stats().timed_releases, desc_.Capacity, held_now);
954 log_once("timed-hold", "timed release: reads into physical pages held for the title's Submit were "
955 "submitted after LEONIDA_DSTORAGE_HOLD_MS without one (their page lists may "
956 "not be filled; the ds-hold line counts these)");
957 } else if (waited >= 5000 && !hold_warned_) {
958 hold_warned_ = true;
959 std::lock_guard lock(log_mutex());
960 std::fprintf(stderr, "[rt] dstorage: %zu entries behind a read into physical pages have waited %lld ms "
961 "for the title's Submit (queue %p, capacity %u; LEONIDA_DSTORAGE_HOLD_MS=<n> "
962 "submits them after n ms, LEONIDA_DSTORAGE_HOLD_PAGES=0 never holds)\n",
963 held_now, static_cast<long long>(waited), static_cast<void*>(this),
964 unsigned(desc_.Capacity));
965 }
966 }
967
829 struct Prepared { 968 struct Prepared {
830 Entry& entry; 969 Entry& entry;
831 HRESULT result = S_OK; 970 HRESULT result = S_OK;
@@ -859,7 +998,11 @@ private:
859 bool paired = false; 998 bool paired = false;
860 { 999 {
861 std::unique_lock lock(mutex_); 1000 std::unique_lock lock(mutex_);
862 work_.wait(lock, [&] { return submitted_ > 0 || closed_; }); 1001 while (!(submitted_ > 0 || closed_)) {
1002 if (!holding_) work_.wait(lock);
1003 else if (work_.wait_for(lock, hold_wait_locked()) == std::cv_status::timeout)
1004 hold_tick_locked();
1005 }
863 if (submitted_ == 0) return; 1006 if (submitted_ == 0) return;
864 head = std::move(entries_.front()); 1007 head = std::move(entries_.front());
865 entries_.pop_front(); 1008 entries_.pop_front();
@@ -1088,6 +1231,10 @@ private:
1088 std::vector<uint64_t> numbers(1 + (buffer.size() - 1 + offset) / 65536); 1231 std::vector<uint64_t> numbers(1 + (buffer.size() - 1 + offset) / 65536);
1089 if (!guarded_move(numbers.data(), pages, numbers.size() * sizeof(numbers[0]))) 1232 if (!guarded_move(numbers.data(), pages, numbers.size() * sizeof(numbers[0])))
1090 return E_DSTORAGE_ACCESS_VIOLATION; 1233 return E_DSTORAGE_ACCESS_VIOLATION;
1234 // Page 0 is never a title page: a destination list that names it was not filled when its request ran, and
1235 // the request fails below. Counted, since each one is data the title asked for and did not get.
1236 if (write && std::find(numbers.begin(), numbers.end(), uint64_t{0}) != numbers.end())
1237 log_hold("page0", ++leonida::dstorage::hold_stats().page0_entries, 0, 0);
1091 if (rt::xmem::transfer_physical(numbers, offset, buffer, write)) return S_OK; 1238 if (rt::xmem::transfer_physical(numbers, offset, buffer, write)) return S_OK;
1092 return HRESULT_FROM_WIN32(GetLastError()); 1239 return HRESULT_FROM_WIN32(GetLastError());
1093 } 1240 }
@@ -1305,6 +1452,11 @@ private:
1305 std::condition_variable work_, space_, idle_; 1452 std::condition_variable work_, space_, idle_;
1306 std::deque<Entry> entries_; 1453 std::deque<Entry> entries_;
1307 size_t submitted_ = 0; // the first submitted_ entries are submitted 1454 size_t submitted_ = 0; // the first submitted_ entries are submitted
1455 const bool hold_pages_; // LEONIDA_DSTORAGE_HOLD_PAGES
1456 const uint32_t hold_release_ms_; // LEONIDA_DSTORAGE_HOLD_MS (kDefaultHoldMs unless set); 0: no time limit
1457 bool holding_ = false; // under mutex_: a self-submit left entries for the title's Submit
1458 bool hold_warned_ = false; // under mutex_: this hold's five-second line was written
1459 std::chrono::steady_clock::time_point held_since_{}; // under mutex_
1308 size_t in_flight_ = 0; 1460 size_t in_flight_ = 0;
1309 bool closing_ = false; 1461 bool closing_ = false;
1310 bool closed_ = false; 1462 bool closed_ = false;
diff --git a/runtime/shims/gameinput.cpp b/runtime/shims/gameinput.cpp
index fa5889d6a..c989daff4 100644
--- a/runtime/shims/gameinput.cpp
+++ b/runtime/shims/gameinput.cpp
@@ -1887,7 +1887,9 @@ void update_keyboard_pad() {
1887 clip_cursor(active && g_raw_ready && g_cursor_pos.load() == system_cursor_pos && foreground_is_ours()); 1887 clip_cursor(active && g_raw_ready && g_cursor_pos.load() == system_cursor_pos && foreground_is_ours());
1888 for (const auto& b : kKeyBindings) SDL_SetJoystickVirtualButton(g_keyboard.js, b.sdl_button, down[b.sdl_button]); 1888 for (const auto& b : kKeyBindings) SDL_SetJoystickVirtualButton(g_keyboard.js, b.sdl_button, down[b.sdl_button]);
1889 // LEONIDA_INPUT_SCRIPT="a@70,a@85,start@120" (with LEONIDA_KEYBOARD_PAD=always): timed presses on the keyboard 1889 // LEONIDA_INPUT_SCRIPT="a@70,a@85,start@120" (with LEONIDA_KEYBOARD_PAD=always): timed presses on the keyboard
1890 // pad, in seconds since the pad's first update, each held 300 ms. For unattended boots: the title's first prompt 1890 // pad, in seconds since the pad's first update, each held 300 ms or its own button@seconds:hold, and then until the
1891 // title has read the pads kReads times since it began (never past kMaxHold seconds, or the hold if it is longer, so
1892 // a title that stops reading does not keep the button). For unattended boots: the title's first prompt
1891 // waits for a button with no timeout (docs/re/notes/firstframe.md, step 5). The parser, the timeline and the 1893 // waits for a button with no timeout (docs/re/notes/firstframe.md, step 5). The parser, the timeline and the
1892 // button names are gameinput_script.h's, shared with the scripted pad of a build without SDL3. 1894 // button names are gameinput_script.h's, shared with the scripted pad of a build without SDL3.
1893 namespace script = rt::gameinput::script; 1895 namespace script = rt::gameinput::script;
@@ -1899,7 +1901,21 @@ void update_keyboard_pad() {
1899 s.presses.size(), s.rejected); 1901 s.presses.size(), s.rejected);
1900 return s; 1902 return s;
1901 }(); 1903 }();
1902 if (!scripted.empty()) { 1904 // LEONIDA_INPUT_FILE=<path> (local, for headless runs whose display takes no keyboard input): every line appended
1905 // to the file names one button of gameinput_script.h's table ("a", "down", ...) and becomes a press at once, held
1906 // like a scripted one (300 ms and six readings, at most 5 s). The file is read again at most every 250 ms.
1907 struct FilePress {
1908 uint32_t bit;
1909 double at;
1910 uint64_t began;
1911 bool started;
1912 };
1913 static std::vector<FilePress> file_presses;
1914 static const std::string input_file = [] {
1915 const char* v = std::getenv("LEONIDA_INPUT_FILE");
1916 return std::string(v ? v : "");
1917 }();
1918 if (!scripted.empty() || !input_file.empty()) {
1903 static const ULONGLONG origin = GetTickCount64(); 1919 static const ULONGLONG origin = GetTickCount64();
1904 const double now = (GetTickCount64() - origin) / 1000.0; 1920 const double now = (GetTickCount64() - origin) / 1000.0;
1905 script::Held held{}; 1921 script::Held held{};
@@ -1908,15 +1924,51 @@ void update_keyboard_pad() {
1908 static std::vector<uint64_t> began(scripted.presses.size(), 0); 1924 static std::vector<uint64_t> began(scripted.presses.size(), 0);
1909 static std::vector<char> started(scripted.presses.size(), 0); 1925 static std::vector<char> started(scripted.presses.size(), 0);
1910 const uint64_t calls = g_reading_calls.load(std::memory_order_relaxed); 1926 const uint64_t calls = g_reading_calls.load(std::memory_order_relaxed);
1927 if (!input_file.empty()) {
1928 static ULONGLONG last_read = 0;
1929 static std::size_t lines_done = 0;
1930 const ULONGLONG tick = GetTickCount64();
1931 if (tick - last_read >= 250) {
1932 last_read = tick;
1933 if (FILE* f = std::fopen(input_file.c_str(), "r")) {
1934 char line[64];
1935 std::size_t n = 0;
1936 while (std::fgets(line, sizeof(line), f)) {
1937 if (++n <= lines_done) continue;
1938 lines_done = n;
1939 std::string name(line);
1940 while (!name.empty() && (name.back() == '\n' || name.back() == '\r' || name.back() == ' '))
1941 name.pop_back();
1942 bool known = false;
1943 for (const script::Button& b : script::kButtons)
1944 if (name == b.name) {
1945 file_presses.push_back({b.bit, now, 0, false});
1946 known = true;
1947 }
1948 std::fprintf(stderr, "[rt] gameinput: input file line %zu \"%s\" at %.1f s%s\n", n,
1949 name.c_str(), now, known ? "" : " (unknown button, ignored)");
1950 }
1951 std::fclose(f);
1952 }
1953 }
1954 for (auto& p : file_presses) {
1955 if (now < p.at || now >= p.at + kMaxHold) continue;
1956 if (!p.started) {
1957 p.started = true;
1958 p.began = calls;
1959 }
1960 if (now < p.at + 0.3 || calls - p.began < kReads) held.buttons |= p.bit;
1961 }
1962 }
1911 for (std::size_t i = 0; i < scripted.presses.size(); ++i) { 1963 for (std::size_t i = 0; i < scripted.presses.size(); ++i) {
1912 const auto& press = scripted.presses[i]; 1964 const auto& press = scripted.presses[i];
1913 bool active = false; 1965 bool active = false;
1914 if (now >= press.at && now < press.at + kMaxHold) { 1966 if (now >= press.at && now < press.at + std::max(press.hold, kMaxHold)) {
1915 if (!started[i]) { 1967 if (!started[i]) {
1916 started[i] = 1; 1968 started[i] = 1;
1917 began[i] = calls; 1969 began[i] = calls;
1918 } 1970 }
1919 active = now < press.at + 0.3 || calls - began[i] < kReads; 1971 active = now < press.at + press.hold || calls - began[i] < kReads;
1920 } 1972 }
1921 if (!active) continue; 1973 if (!active) continue;
1922 if (press.stick) held.stick = press.stick; 1974 if (press.stick) held.stick = press.stick;
@@ -1924,7 +1976,7 @@ void update_keyboard_pad() {
1924 } 1976 }
1925 if (held.stick) right_y = held.stick > 0 ? -kStickFull : kStickFull; // SDL's +Y is down 1977 if (held.stick) right_y = held.stick > 0 ? -kStickFull : kStickFull; // SDL's +Y is down
1926 for (const script::Button& b : script::kButtons) { 1978 for (const script::Button& b : script::kButtons) {
1927 if (!(scripted.named & b.bit)) continue; 1979 if (!(scripted.named & b.bit) && input_file.empty()) continue;
1928 const auto button = static_cast<SDL_GamepadButton>(b.sdl); 1980 const auto button = static_cast<SDL_GamepadButton>(b.sdl);
1929 SDL_SetJoystickVirtualButton(g_keyboard.js, button, (held.buttons & b.bit) || down[button]); 1981 SDL_SetJoystickVirtualButton(g_keyboard.js, button, (held.buttons & b.bit) || down[button]);
1930 } 1982 }
@@ -2443,13 +2495,13 @@ public:
2443 struct Stats { 2495 struct Stats {
2444 std::mutex mu; 2496 std::mutex mu;
2445 uint64_t calls[3][3] = {}; // method x (null, aggregate, a device) 2497 uint64_t calls[3][3] = {}; // method x (null, aggregate, a device)
2446 uint64_t found[3] = {}, pressed[3] = {}; 2498 uint64_t found[3] = {}, pressed[3] = {}, a_pressed[3] = {};
2447 std::map<std::string, std::pair<uint64_t, uint64_t>> by_device; // name -> (readings, with buttons) 2499 std::map<std::string, std::pair<uint64_t, uint64_t>> by_device; // name -> (readings, with buttons)
2448 uint64_t since = 0; 2500 uint64_t since = 0;
2449 }; 2501 };
2450 static Stats st; 2502 static Stats st;
2451 std::string name; 2503 std::string name;
2452 bool buttons = false; 2504 bool buttons = false, a_button = false;
2453 if (SUCCEEDED(hr) && got) { 2505 if (SUCCEEDED(hr) && got) {
2454 IGameInputDevice* d = nullptr; 2506 IGameInputDevice* d = nullptr;
2455 got->GetDevice(&d); 2507 got->GetDevice(&d);
@@ -2458,7 +2510,10 @@ public:
2458 d->Release(); 2510 d->Release();
2459 } 2511 }
2460 GameInputGamepadState g{}; 2512 GameInputGamepadState g{};
2461 if (got->GetGamepadState(&g)) buttons = g.buttons != 0; 2513 if (got->GetGamepadState(&g)) {
2514 buttons = g.buttons != 0;
2515 a_button = (g.buttons & GameInputGamepadA) != 0;
2516 }
2462 } 2517 }
2463 const int arg = !asked ? 0 : as_device(asked)->info.deviceFamily == GameInputFamilyAggregate ? 1 : 2; 2518 const int arg = !asked ? 0 : as_device(asked)->info.deviceFamily == GameInputFamilyAggregate ? 1 : 2;
2464 std::lock_guard lock(st.mu); 2519 std::lock_guard lock(st.mu);
@@ -2466,6 +2521,7 @@ public:
2466 if (SUCCEEDED(hr) && got) { 2521 if (SUCCEEDED(hr) && got) {
2467 ++st.found[method]; 2522 ++st.found[method];
2468 st.pressed[method] += buttons; 2523 st.pressed[method] += buttons;
2524 st.a_pressed[method] += a_button;
2469 auto& e = st.by_device[name]; 2525 auto& e = st.by_device[name];
2470 ++e.first; 2526 ++e.first;
2471 e.second += buttons; 2527 e.second += buttons;
@@ -2477,10 +2533,10 @@ public:
2477 std::string line; 2533 std::string line;
2478 for (int m = 0; m < 3; ++m) { 2534 for (int m = 0; m < 3; ++m) {
2479 char t[200]; 2535 char t[200];
2480 std::snprintf(t, sizeof(t), " %s %llu/%llu/%llu found %llu pressed %llu;", methods[m], 2536 std::snprintf(t, sizeof(t), " %s %llu/%llu/%llu found %llu pressed %llu A %llu;", methods[m],
2481 (unsigned long long)st.calls[m][0], (unsigned long long)st.calls[m][1], 2537 (unsigned long long)st.calls[m][0], (unsigned long long)st.calls[m][1],
2482 (unsigned long long)st.calls[m][2], (unsigned long long)st.found[m], 2538 (unsigned long long)st.calls[m][2], (unsigned long long)st.found[m],
2483 (unsigned long long)st.pressed[m]); 2539 (unsigned long long)st.pressed[m], (unsigned long long)st.a_pressed[m]);
2484 line += t; 2540 line += t;
2485 } 2541 }
2486 for (const auto& [n, c] : st.by_device) { 2542 for (const auto& [n, c] : st.by_device) {
@@ -2493,6 +2549,7 @@ public:
2493 std::memset(st.calls, 0, sizeof(st.calls)); 2549 std::memset(st.calls, 0, sizeof(st.calls));
2494 std::memset(st.found, 0, sizeof(st.found)); 2550 std::memset(st.found, 0, sizeof(st.found));
2495 std::memset(st.pressed, 0, sizeof(st.pressed)); 2551 std::memset(st.pressed, 0, sizeof(st.pressed));
2552 std::memset(st.a_pressed, 0, sizeof(st.a_pressed));
2496 st.by_device.clear(); 2553 st.by_device.clear();
2497 st.since = now; 2554 st.since = now;
2498 } 2555 }
diff --git a/runtime/shims/gameinput_no_sdl.cpp b/runtime/shims/gameinput_no_sdl.cpp
index 77b7ebccf..7d8c7b6ee 100644
--- a/runtime/shims/gameinput_no_sdl.cpp
+++ b/runtime/shims/gameinput_no_sdl.cpp
@@ -16,8 +16,10 @@
16// title waits at its first "press A" prompt forever. The pad is an Xbox One gamepad that is connected from the 16// title waits at its first "press A" prompt forever. The pad is an Xbox One gamepad that is connected from the
17// first GameInputCreate on: device enumeration through RegisterDeviceCallback (blocking, async, and through a 17// first GameInputCreate on: device enumeration through RegisterDeviceCallback (blocking, async, and through a
18// dispatcher), GetCurrentReading, GetNextReading and GetPreviousReading, and readings whose GetGamepadState and 18// dispatcher), GetCurrentReading, GetNextReading and GetPreviousReading, and readings whose GetGamepadState and
19// GetUiNavigationState follow the script. A reading is taken when the title asks for one, so no thread runs; 19// GetUiNavigationState follow the script. Readings are taken when the title asks for one, so no thread runs,
20// reading callbacks, aggregate devices, rumble and every other device still need SDL3. Controllers and the 20// but each one first adds a reading for every change the script made since the last, stamped with the script's
21// own time: a press that starts and ends between two reads still reaches the history for GetNextReading.
22// Reading callbacks, aggregate devices, rumble and every other device still need SDL3. Controllers and the
21// keyboard pad need SDL3 too. 23// keyboard pad need SDL3 too.
22#include <windows.h> 24#include <windows.h>
23 25
@@ -101,6 +103,8 @@ constexpr uint32_t kAxisCount = 6; // LX, LY, RX, RY, LT, RT, as the SDL3 sh
101constexpr uint32_t kButtonCount = 15; // SDL's standard gamepad buttons, numbered as the script's Button::sdl 103constexpr uint32_t kButtonCount = 15; // SDL's standard gamepad buttons, numbered as the script's Button::sdl
102constexpr size_t kHistoryCap = 64; // readings kept for GetNextReading/GetPreviousReading; one per change 104constexpr size_t kHistoryCap = 64; // readings kept for GetNextReading/GetPreviousReading; one per change
103constexpr char kPadName[] = "Scripted pad (Leonida)"; 105constexpr char kPadName[] = "Scripted pad (Leonida)";
106std::atomic<bool> g_trace_readings{false};
107std::atomic<uint64_t> g_gamepad_state_queries{0};
104 108
105uint64_t qpc_now_us() { 109uint64_t qpc_now_us() {
106 static const LARGE_INTEGER freq = [] { LARGE_INTEGER f; QueryPerformanceFrequency(&f); return f; }(); 110 static const LARGE_INTEGER freq = [] { LARGE_INTEGER f; QueryPerformanceFrequency(&f); return f; }();
@@ -151,7 +155,14 @@ public:
151 return r; 155 return r;
152 } 156 }
153 157
154 uint32_t STDMETHODCALLTYPE GetInputKind() override { return kKinds; } 158 uint32_t STDMETHODCALLTYPE GetInputKind() override {
159 static std::atomic<uint64_t> queries{0};
160 const uint64_t query = queries.fetch_add(1, std::memory_order_relaxed) + 1;
161 if (g_trace_readings.load(std::memory_order_relaxed) && query <= 8)
162 std::fprintf(stderr, "[rt] gameinput: GetInputKind #%llu seq=%llu kinds=0x%08x\n",
163 static_cast<unsigned long long>(query), static_cast<unsigned long long>(seq_), kKinds);
164 return kKinds;
165 }
155 uint64_t STDMETHODCALLTYPE GetSequenceNumber(uint32_t) override { return seq_; } 166 uint64_t STDMETHODCALLTYPE GetSequenceNumber(uint32_t) override { return seq_; }
156 uint64_t STDMETHODCALLTYPE GetTimestamp() override { return ts_; } 167 uint64_t STDMETHODCALLTYPE GetTimestamp() override { return ts_; }
157 void STDMETHODCALLTYPE GetDevice(IGameInputDevice** device) override; 168 void STDMETHODCALLTYPE GetDevice(IGameInputDevice** device) override;
@@ -168,6 +179,11 @@ public:
168 state_.leftTrigger, state_.rightTrigger}; 179 state_.leftTrigger, state_.rightTrigger};
169 const uint32_t n = std::min(count, kAxisCount); 180 const uint32_t n = std::min(count, kAxisCount);
170 std::memcpy(out, axes, n * sizeof(float)); 181 std::memcpy(out, axes, n * sizeof(float));
182 static std::atomic<uint64_t> queries{0};
183 const uint64_t query = queries.fetch_add(1, std::memory_order_relaxed) + 1;
184 if (g_trace_readings.load(std::memory_order_relaxed) && query <= 8)
185 std::fprintf(stderr, "[rt] gameinput: GetControllerAxisState #%llu seq=%llu count=%u returned=%u\n",
186 static_cast<unsigned long long>(query), static_cast<unsigned long long>(seq_), count, n);
171 return n; 187 return n;
172 } 188 }
173 uint32_t STDMETHODCALLTYPE GetControllerButtonCount() override { return kButtonCount; } 189 uint32_t STDMETHODCALLTYPE GetControllerButtonCount() override { return kButtonCount; }
@@ -177,6 +193,12 @@ public:
177 for (const script::Button& b : script::kButtons) buttons[b.sdl] = (state_.buttons & b.bit) != 0; 193 for (const script::Button& b : script::kButtons) buttons[b.sdl] = (state_.buttons & b.bit) != 0;
178 const uint32_t n = std::min(count, kButtonCount); 194 const uint32_t n = std::min(count, kButtonCount);
179 std::memcpy(out, buttons, n * sizeof(bool)); 195 std::memcpy(out, buttons, n * sizeof(bool));
196 static std::atomic<uint64_t> queries{0};
197 const uint64_t query = queries.fetch_add(1, std::memory_order_relaxed) + 1;
198 if (g_trace_readings.load(std::memory_order_relaxed) && query <= 8)
199 std::fprintf(stderr, "[rt] gameinput: GetControllerButtonState #%llu seq=%llu count=%u returned=%u buttons=0x%08x\n",
200 static_cast<unsigned long long>(query), static_cast<unsigned long long>(seq_), count, n,
201 state_.buttons);
180 return n; 202 return n;
181 } 203 }
182 uint32_t STDMETHODCALLTYPE GetControllerSwitchCount() override { return 0; } 204 uint32_t STDMETHODCALLTYPE GetControllerSwitchCount() override { return 0; }
@@ -192,12 +214,21 @@ public:
192 bool STDMETHODCALLTYPE GetGamepadState(GameInputGamepadState* state) override { 214 bool STDMETHODCALLTYPE GetGamepadState(GameInputGamepadState* state) override {
193 if (!state) return false; 215 if (!state) return false;
194 *state = state_; 216 *state = state_;
217 const uint64_t query = g_gamepad_state_queries.fetch_add(1, std::memory_order_relaxed) + 1;
218 if (g_trace_readings.load(std::memory_order_relaxed) && (query == 1 || state_.buttons || query % 1000 == 0))
219 std::fprintf(stderr, "[rt] gameinput: GetGamepadState #%llu seq=%llu buttons=0x%08x\n",
220 static_cast<unsigned long long>(query), static_cast<unsigned long long>(seq_), state_.buttons);
195 return true; 221 return true;
196 } 222 }
197 bool STDMETHODCALLTYPE GetRacingWheelState(void*) override { return false; } 223 bool STDMETHODCALLTYPE GetRacingWheelState(void*) override { return false; }
198 bool STDMETHODCALLTYPE GetUiNavigationState(GameInputUiNavigationState* state) override { 224 bool STDMETHODCALLTYPE GetUiNavigationState(GameInputUiNavigationState* state) override {
199 if (!state) return false; 225 if (!state) return false;
200 state->buttons = script::ui_navigation(state_); 226 state->buttons = script::ui_navigation(state_);
227 static std::atomic<uint64_t> queries{0};
228 const uint64_t query = queries.fetch_add(1, std::memory_order_relaxed) + 1;
229 if (g_trace_readings.load(std::memory_order_relaxed) && query <= 8)
230 std::fprintf(stderr, "[rt] gameinput: GetUiNavigationState #%llu seq=%llu buttons=0x%08x\n",
231 static_cast<unsigned long long>(query), static_cast<unsigned long long>(seq_), state->buttons);
201 return true; 232 return true;
202 } 233 }
203 234
@@ -278,7 +309,13 @@ public:
278 ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } 309 ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; }
279 ULONG STDMETHODCALLTYPE Release() override { return release_floor(refs_); } 310 ULONG STDMETHODCALLTYPE Release() override { return release_floor(refs_); }
280 311
281 const GameInputDeviceInfo* STDMETHODCALLTYPE GetDeviceInfo() override { return &info_; } 312 const GameInputDeviceInfo* STDMETHODCALLTYPE GetDeviceInfo() override {
313 static std::atomic<bool> logged{false};
314 if (g_trace_readings.load(std::memory_order_relaxed) && !logged.exchange(true, std::memory_order_relaxed))
315 std::fprintf(stderr, "[rt] gameinput: GetDeviceInfo family=%d input=0x%08x status=0x%08x\n",
316 info_.deviceFamily, info_.supportedInput, kConnectedStatus);
317 return &info_;
318 }
282 uint32_t STDMETHODCALLTYPE GetDeviceStatus() override { return kConnectedStatus; } 319 uint32_t STDMETHODCALLTYPE GetDeviceStatus() override { return kConnectedStatus; }
283 void STDMETHODCALLTYPE GetBatteryState(GameInputBatteryState* state) override { 320 void STDMETHODCALLTYPE GetBatteryState(GameInputBatteryState* state) override {
284 if (state) *state = {0, 0, 0, 0, GameInputBatteryUnknown}; 321 if (state) *state = {0, 0, 0, 0, GameInputBatteryUnknown};
@@ -355,8 +392,11 @@ struct State {
355 std::atomic<DWORD> delivering_thread{0}; 392 std::atomic<DWORD> delivering_thread{0};
356 script::Script script; 393 script::Script script;
357 uint64_t origin_us = 0; // the script's clock starts at the first GameInputCreate 394 uint64_t origin_us = 0; // the script's clock starts at the first GameInputCreate
395 double updated_s = -1; // the script time of the last update; its changes up to here are in the history
358 bool log_presses = true; // LEONIDA_INPUT_LOG 396 bool log_presses = true; // LEONIDA_INPUT_LOG
397 bool trace_reads = false; // LEONIDA_INPUT_TRACE
359 uint32_t logged_held = 0; // what log_scripted saw last 398 uint32_t logged_held = 0; // what log_scripted saw last
399 uint64_t reading_queries = 0;
360 std::deque<Reading*> history; // one reference each, oldest first; the newest is the current reading 400 std::deque<Reading*> history; // one reference each, oldest first; the newest is the current reading
361 uint64_t evicted_seq = 0; // sequence number of the newest reading dropped from history 401 uint64_t evicted_seq = 0; // sequence number of the newest reading dropped from history
362 uint64_t seq = 0; 402 uint64_t seq = 0;
@@ -372,10 +412,9 @@ State& g() {
372 return *s; 412 return *s;
373} 413}
374 414
375// Takes a reading when the script's state at `now` differs from the current one. Under g().mu. 415// Takes a reading when the script's state `seconds` into it differs from the current one. Under g().mu.
376void update(uint64_t now) { 416void take_reading(double seconds, uint64_t timestamp) {
377 State& s = g(); 417 State& s = g();
378 const double seconds = now > s.origin_us ? (now - s.origin_us) / 1e6 : 0.0;
379 const script::Held held = script::held_at(s.script, seconds); 418 const script::Held held = script::held_at(s.script, seconds);
380 GameInputGamepadState state{}; 419 GameInputGamepadState state{};
381 state.buttons = held.buttons; 420 state.buttons = held.buttons;
@@ -387,7 +426,7 @@ void update(uint64_t now) {
387 if (s.log_presses && last) 426 if (s.log_presses && last)
388 script::log_presses(state.buttons & ~last->state().buttons, last->state().rightThumbstickY, 427 script::log_presses(state.buttons & ~last->state().buttons, last->state().rightThumbstickY,
389 state.rightThumbstickY, seconds, kPadName); 428 state.rightThumbstickY, seconds, kPadName);
390 s.history.push_back(new Reading(state, ++s.seq, now)); 429 s.history.push_back(new Reading(state, ++s.seq, timestamp));
391 while (s.history.size() > kHistoryCap) { 430 while (s.history.size() > kHistoryCap) {
392 s.evicted_seq = s.history.front()->seq(); 431 s.evicted_seq = s.history.front()->seq();
393 s.history.front()->Release(); 432 s.history.front()->Release();
@@ -395,7 +434,39 @@ void update(uint64_t now) {
395 } 434 }
396} 435}
397 436
437// Brings the history up to `now`: one reading for every start and end of a press the script made since the last
438// update, at the time the script made it, then the state at `now`. The title may read its pad only every few seconds
439// (at world-start frame rates it does); a press that began and ended in between is still in the history, where
440// GetNextReading finds it, and the readings are the same however often the title reads. Under g().mu.
441void update(uint64_t now) {
442 State& s = g();
443 const double seconds = now > s.origin_us ? (now - s.origin_us) / 1e6 : 0.0;
444 if (seconds > s.updated_s) {
445 std::vector<double> edges;
446 for (const script::Press& p : s.script.presses)
447 for (const double edge : {p.at, p.at + p.hold})
448 if (edge > s.updated_s && edge < seconds) edges.push_back(edge);
449 std::sort(edges.begin(), edges.end());
450 edges.erase(std::unique(edges.begin(), edges.end()), edges.end());
451 for (const double edge : edges) take_reading(edge, s.origin_us + static_cast<uint64_t>(edge * 1e6 + 0.5));
452 s.updated_s = seconds;
453 }
454 take_reading(seconds, now);
455}
456
457void trace_reading(State& s, const char* api, uint32_t kind, const Reading* reading) {
458 const uint64_t query = ++s.reading_queries;
459 const uint32_t buttons = reading ? reading->state().buttons : 0;
460 if (s.trace_reads && (query <= 128 || buttons || query % 1000 == 0))
461 std::fprintf(stderr, "[rt] gameinput: %s #%llu kind=0x%08x seq=%llu buttons=0x%08x\n", api,
462 static_cast<unsigned long long>(query), kind,
463 static_cast<unsigned long long>(reading ? reading->seq() : 0), buttons);
464}
465
398void call_device(const Callback& c, uint64_t timestamp) { 466void call_device(const Callback& c, uint64_t timestamp) {
467 if (g().trace_reads)
468 std::fprintf(stderr, "[rt] gameinput: device callback token=%llu timestamp=%llu status=0x%08x\n",
469 static_cast<unsigned long long>(c.token), static_cast<unsigned long long>(timestamp), kConnectedStatus);
399 reinterpret_cast<GameInputDeviceCallback>(c.fn)(c.token, c.context, &pad(), timestamp, kConnectedStatus, 470 reinterpret_cast<GameInputDeviceCallback>(c.fn)(c.token, c.context, &pad(), timestamp, kConnectedStatus,
400 GameInputDeviceNoStatus); 471 GameInputDeviceNoStatus);
401} 472}
@@ -504,6 +575,8 @@ HRESULT find_reading(IGameInputReading* ref, uint32_t kind, IGameInputReading**
504 std::lock_guard lock(s.mu); 575 std::lock_guard lock(s.mu);
505 update(now_us()); 576 update(now_us());
506 const uint64_t r = static_cast<Reading*>(ref)->seq(); 577 const uint64_t r = static_cast<Reading*>(ref)->seq();
578 trace_reading(s, forward ? "GetNextReading" : "GetPreviousReading", kind,
579 s.history.empty() ? nullptr : s.history.back());
507 if (forward ? s.evicted_seq > r : s.evicted_seq >= r) return GAMEINPUT_E_REFERENCE_READING_TOO_OLD; 580 if (forward ? s.evicted_seq > r : s.evicted_seq >= r) return GAMEINPUT_E_REFERENCE_READING_TOO_OLD;
508 Reading* best = nullptr; 581 Reading* best = nullptr;
509 for (Reading* c : s.history) { 582 for (Reading* c : s.history) {
@@ -547,6 +620,7 @@ public:
547 std::lock_guard lock(s.mu); 620 std::lock_guard lock(s.mu);
548 update(now_us()); 621 update(now_us());
549 Reading* r = s.history.back(); 622 Reading* r = s.history.back();
623 trace_reading(s, "GetCurrentReading", kind, r);
550 r->AddRef(); 624 r->AddRef();
551 *out = r; 625 *out = r;
552 return S_OK; 626 return S_OK;
@@ -595,6 +669,10 @@ public:
595 later = true; 669 later = true;
596 } 670 }
597 } 671 }
672 if (s.trace_reads)
673 std::fprintf(stderr,
674 "[rt] gameinput: RegisterDeviceCallback kind=0x%08x filter=0x%08x enumeration=%d report=%d\n",
675 kind, status_filter, static_cast<int>(enumeration), report ? 1 : 0);
598 if (token) *token = c.token; 676 if (token) *token = c.token;
599 // Blocking enumeration: the pad is reported before this returns, on the caller's thread. 677 // Blocking enumeration: the pad is reported before this returns, on the caller's thread.
600 if (report && enumeration == GameInputBlockingEnumeration) call_device(c, now_us()); 678 if (report && enumeration == GameInputBlockingEnumeration) call_device(c, now_us());
@@ -683,6 +761,8 @@ ScriptedInput* scripted() {
683 std::lock_guard lock(s.mu); 761 std::lock_guard lock(s.mu);
684 s.script = script::parse(text); 762 s.script = script::parse(text);
685 s.log_presses = script::env_lower("LEONIDA_INPUT_LOG") != "0"; 763 s.log_presses = script::env_lower("LEONIDA_INPUT_LOG") != "0";
764 s.trace_reads = script::env_lower("LEONIDA_INPUT_TRACE") == "1";
765 g_trace_readings = s.trace_reads;
686 s.wait_event = CreateEventW(nullptr, FALSE, FALSE, nullptr); 766 s.wait_event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
687 s.origin_us = now_us(); 767 s.origin_us = now_us();
688 update(s.origin_us); // the first reading: nothing held unless the script presses at 0 s 768 update(s.origin_us); // the first reading: nothing held unless the script presses at 0 s
diff --git a/runtime/shims/gameinput_script.h b/runtime/shims/gameinput_script.h
index 759506750..5be554424 100644
--- a/runtime/shims/gameinput_script.h
+++ b/runtime/shims/gameinput_script.h
@@ -5,10 +5,13 @@
5// 5//
6// LEONIDA_INPUT_SCRIPT="a@70,a@85,start@120" 6// LEONIDA_INPUT_SCRIPT="a@70,a@85,start@120"
7// 7//
8// Each entry is button@seconds, the seconds counted from the shim's first update. A press is held for kHoldSeconds, 8// Each entry is button@seconds[:hold], the seconds counted from the shim's first update. A press is held for `hold`
9// then released. Buttons: a b x y start back lb rb up down left right; rsup and rsdown throw the right stick fully up 9// seconds (kHoldSeconds when the entry has none), then released: a longer hold reaches a title that reads its pad
10// or down for the same time (they replay the stick throws the press log writes). Spaces around an entry are allowed; 10// only every few seconds, as the retail title does at world-start frame rates. Buttons: a b x y start back lb rb
11// empty entries, unknown buttons and invalid times (negative, non-finite, trailing text) are counted as rejected. 11// up down left right; rsup and rsdown throw the right stick fully up or down for the same time (they replay the
12// stick throws the press log writes). Spaces around an entry are allowed; empty entries, unknown buttons, invalid
13// times (negative, non-finite, trailing text) and invalid holds (zero, negative, non-finite, more than
14// kMaxHoldSeconds) are counted as rejected.
12#pragma once 15#pragma once
13#include <algorithm> 16#include <algorithm>
14#include <cctype> 17#include <cctype>
@@ -24,6 +27,7 @@
24namespace rt::gameinput::script { 27namespace rt::gameinput::script {
25 28
26constexpr double kHoldSeconds = 0.3; 29constexpr double kHoldSeconds = 0.3;
30constexpr double kMaxHoldSeconds = 600; // a typo such as b@10:1100 should not hold B for the whole run
27 31
28// One scriptable button: its name in the script and the press log, its GameInput gamepad bit, and its SDL3 32// One scriptable button: its name in the script and the press log, its GameInput gamepad bit, and its SDL3
29// SDL_GamepadButton number, which the "scripted press of button <n>" line has always carried (tools/stage_timeline.py 33// SDL_GamepadButton number, which the "scripted press of button <n>" line has always carried (tools/stage_timeline.py
@@ -46,6 +50,7 @@ struct Press {
46 uint32_t button = 0; // a GameInput gamepad bit, or 0 for a stick throw 50 uint32_t button = 0; // a GameInput gamepad bit, or 0 for a stick throw
47 int stick = 0; // +1 rsup, -1 rsdown (GameInput's +Y is up) 51 int stick = 0; // +1 rsup, -1 rsdown (GameInput's +Y is up)
48 double at = 0; // seconds 52 double at = 0; // seconds
53 double hold = kHoldSeconds;
49}; 54};
50 55
51struct Script { 56struct Script {
@@ -72,17 +77,22 @@ inline Script parse(std::string text) {
72 const char* time = item.c_str() + sep + 1; 77 const char* time = item.c_str() + sep + 1;
73 char* tail; 78 char* tail;
74 const double seconds = std::strtod(time, &tail); 79 const double seconds = std::strtod(time, &tail);
75 if (tail == time || !std::isfinite(seconds) || seconds < 0 || 80 if (tail == time || !std::isfinite(seconds) || seconds < 0) continue;
76 item.find_first_not_of(whitespace, static_cast<size_t>(tail - item.c_str())) != std::string::npos) 81 double hold = kHoldSeconds;
77 continue; 82 if (*tail == ':') {
83 const char* hold_text = tail + 1;
84 hold = std::strtod(hold_text, &tail);
85 if (tail == hold_text || !std::isfinite(hold) || hold <= 0 || hold > kMaxHoldSeconds) continue;
86 }
87 if (item.find_first_not_of(whitespace, static_cast<size_t>(tail - item.c_str())) != std::string::npos) continue;
78 const auto is = [&](const char* name) { return item.compare(first, sep - first, name) == 0; }; 88 const auto is = [&](const char* name) { return item.compare(first, sep - first, name) == 0; };
79 if (is("rsup") || is("rsdown")) { 89 if (is("rsup") || is("rsdown")) {
80 out.presses.push_back({0, is("rsup") ? 1 : -1, seconds}); 90 out.presses.push_back({0, is("rsup") ? 1 : -1, seconds, hold});
81 continue; 91 continue;
82 } 92 }
83 for (const Button& b : kButtons) { 93 for (const Button& b : kButtons) {
84 if (is(b.name)) { 94 if (is(b.name)) {
85 out.presses.push_back({b.bit, 0, seconds}); 95 out.presses.push_back({b.bit, 0, seconds, hold});
86 out.named |= b.bit; 96 out.named |= b.bit;
87 break; 97 break;
88 } 98 }
@@ -102,7 +112,7 @@ struct Held {
102inline Held held_at(const Script& script, double seconds) { 112inline Held held_at(const Script& script, double seconds) {
103 Held h; 113 Held h;
104 for (const Press& p : script.presses) { 114 for (const Press& p : script.presses) {
105 if (seconds < p.at || seconds >= p.at + kHoldSeconds) continue; 115 if (seconds < p.at || seconds >= p.at + p.hold) continue;
106 if (p.stick) h.stick = p.stick; 116 if (p.stick) h.stick = p.stick;
107 else h.buttons |= p.button; 117 else h.buttons |= p.button;
108 } 118 }
diff --git a/runtime/shims/process.cpp b/runtime/shims/process.cpp
index 08023ea78..2c37292e2 100644
--- a/runtime/shims/process.cpp
+++ b/runtime/shims/process.cpp
@@ -11,8 +11,9 @@
11// shares with gta6rt. exit() runs it newest first, as the CRT does, before the run ends; _exit(), _Exit(), 11// shares with gta6rt. exit() runs it newest first, as the CRT does, before the run ends; _exit(), _Exit(),
12// quick_exit(), ExitProcess() and abort() do not. _cexit() runs it and returns, _c_exit() returns. A second 12// quick_exit(), ExitProcess() and abort() do not. _cexit() runs it and returns, _c_exit() returns. A second
13// thread that calls exit(), _exit(), _Exit() or quick_exit() while the first is leaving waits, as with the 13// thread that calls exit(), _exit(), _Exit() or quick_exit() while the first is leaving waits, as with the
14// CRT's exit lock. Not covered yet: at_quick_exit() handlers (quick_exit() runs none) and the thread-local 14// CRT's exit lock. Not covered yet: at_quick_exit() handlers (quick_exit() runs none).
15// destructor callback (_register_thread_local_exe_atexit_callback); both still reach the host CRT. 15// - the EXE's thread-local destructor callback (_register_thread_local_exe_atexit_callback) is kept here too:
16// exit() and _cexit() call it before the atexit handlers, as the UCRT does (see game_exit below).
16// Covered CRTs: the Universal CRT (api-ms-win-crt-runtime-l1-1-0.dll / ucrtbase.dll, what MSVC links; ucrtbased.dll in Debug) and 17// Covered CRTs: the Universal CRT (api-ms-win-crt-runtime-l1-1-0.dll / ucrtbase.dll, what MSVC links; ucrtbased.dll in Debug) and
17// msvcrt.dll (MinGW). Calls made inside host DLLs, not through the game's imports, are not seen here. 18// msvcrt.dll (MinGW). Calls made inside host DLLs, not through the game's imports, are not seen here.
18// The loader matches imports by exact DLL name, so GetCommandLineA/W and ExitProcess are served under every name a 19// The loader matches imports by exact DLL name, so GetCommandLineA/W and ExitProcess are served under every name a
@@ -142,6 +143,28 @@ OnexitFn __cdecl game_onexit(OnexitFn fn) {
142 return fn && register_atexit(reinterpret_cast<AtexitFn>(fn)) ? fn : nullptr; 143 return fn && register_atexit(reinterpret_cast<AtexitFn>(fn)) ? fn : nullptr;
143} 144}
144 145
146// ---- the EXE's thread-local destructors
147// An MSVC EXE's startup passes vcruntime's TLS destructor callback, which its TLS directory also lists, to
148// _register_thread_local_exe_atexit_callback (UCRT process.h: void __cdecl (_tls_callback_type), where
149// _tls_callback_type is void (__stdcall*)(void*, unsigned long, void*)). The UCRT calls it as
150// (nullptr, DLL_PROCESS_DETACH, nullptr) when exit() or _cexit() starts, before the atexit table: the leaving thread's
151// thread_local objects end before the static ones, as C++ requires. Other threads' end through the loader's
152// thread-detach notification, which calls the same function from the TLS directory, so it is not called here then.
153// The host CRT cannot take it: the UCRT accepts one per process and fast-fails the second (gta6rt's own startup
154// registers the first, so the title stopped at boot on Windows), and Wine's ucrtbase replaces gta6rt's own and never
155// calls the title's, because the run ends through end_run.
156using TlsCallback = void(__stdcall*)(void*, unsigned long, void*);
157std::atomic<TlsCallback> g_thread_local_exit_callback{nullptr};
158
159void __cdecl game_register_thread_local_exe_atexit_callback(TlsCallback callback) {
160 g_thread_local_exit_callback.store(callback);
161}
162// Once per run, like the UCRT's exit path: a later exit() after _cexit() finds nothing left to run.
163void run_thread_local_exe_atexit_callback() {
164 if (const TlsCallback callback = g_thread_local_exit_callback.exchange(nullptr))
165 callback(nullptr, DLL_PROCESS_DETACH, nullptr);
166}
167
145// ---- the way out 168// ---- the way out
146// The CRT's exit lock, which exit(), _exit(), _Exit() and quick_exit() all take: the first thread to leave owns it 169// The CRT's exit lock, which exit(), _exit(), _Exit() and quick_exit() all take: the first thread to leave owns it
147// and ends the run; any other thread that tries to leave waits forever. The owner may leave again from a handler 170// and ends the run; any other thread that tries to leave waits forever. The owner may leave again from a handler
@@ -157,7 +180,10 @@ bool take_exit_lock() {
157} 180}
158// exit(): the game's handlers and static destructors, then the end of the run. 181// exit(): the game's handlers and static destructors, then the end of the run.
159void __cdecl game_exit(int code) { 182void __cdecl game_exit(int code) {
160 if (take_exit_lock()) run_atexit_handlers(); 183 if (take_exit_lock()) {
184 run_thread_local_exe_atexit_callback();
185 run_atexit_handlers();
186 }
161 end_run(code); 187 end_run(code);
162} 188}
163// _exit(), _Exit(), quick_exit(): the end of the run without the atexit handlers. 189// _exit(), _Exit(), quick_exit(): the end of the run without the atexit handlers.
@@ -167,6 +193,7 @@ void __cdecl game_quick_exit(int code) {
167} 193}
168// _cexit() runs the handlers and flushes the streams, then returns; _c_exit() only returns. 194// _cexit() runs the handlers and flushes the streams, then returns; _c_exit() only returns.
169void __cdecl game_cexit() { 195void __cdecl game_cexit() {
196 run_thread_local_exe_atexit_callback();
170 run_atexit_handlers(); 197 run_atexit_handlers();
171 std::fflush(nullptr); 198 std::fflush(nullptr);
172} 199}
@@ -493,6 +520,8 @@ using namespace rt::process;
493 {dll, "_crt_atexit", reinterpret_cast<void*>(&game_crt_atexit)}, \ 520 {dll, "_crt_atexit", reinterpret_cast<void*>(&game_crt_atexit)}, \
494 {dll, "_cexit", reinterpret_cast<void*>(&game_cexit)}, {dll, "_c_exit", reinterpret_cast<void*>(&game_c_exit)}, \ 521 {dll, "_cexit", reinterpret_cast<void*>(&game_cexit)}, {dll, "_c_exit", reinterpret_cast<void*>(&game_c_exit)}, \
495 {dll, "abort", reinterpret_cast<void*>(&game_abort)}, {dll, "__p___argc", reinterpret_cast<void*>(&game_p_argc)}, \ 522 {dll, "abort", reinterpret_cast<void*>(&game_abort)}, {dll, "__p___argc", reinterpret_cast<void*>(&game_p_argc)}, \
523 {dll, "_register_thread_local_exe_atexit_callback", \
524 reinterpret_cast<void*>(&game_register_thread_local_exe_atexit_callback)}, \
496 {dll, "__p___argv", reinterpret_cast<void*>(&game_p_argv)}, \ 525 {dll, "__p___argv", reinterpret_cast<void*>(&game_p_argv)}, \
497 {dll, "__p___wargv", reinterpret_cast<void*>(&game_p_wargv)}, \ 526 {dll, "__p___wargv", reinterpret_cast<void*>(&game_p_wargv)}, \
498 {dll, "_configure_narrow_argv", reinterpret_cast<void*>(&game_configure_narrow_argv)}, \ 527 {dll, "_configure_narrow_argv", reinterpret_cast<void*>(&game_configure_narrow_argv)}, \
diff --git a/runtime/shims/xapu_chad.cpp b/runtime/shims/xapu_chad.cpp
index 35bda2b72..e46a61c97 100644
--- a/runtime/shims/xapu_chad.cpp
+++ b/runtime/shims/xapu_chad.cpp
@@ -1,24 +1,8 @@
1// xapu.dll and chad.dll: the console's audio processing unit (APU) and audio DSP command queues. No PC has either, 1// chad.dll: the console's audio DSP command queue. No PC has one, so this gives the title a connection whose calls
2// so these give the title connections whose calls succeed, a zeroed shared buffer, a result for each stream open and 2// succeed and zeroed DSP status: nothing the title submits is processed. xapu.dll, the APU command queue, is in
3// close, and zeroed DSP status: the audio the APU would render stays silent, and nothing the title submits is processed. 3// xapu_queue.cpp.
4// 4//
5// Read from the executable's call sites (counts in docs/runtime_imports.md), statically, never run: 5// Read from the executable's call sites (counts in docs/runtime_imports.md), statically, never run:
6// XApuConnect(block24*, out16*, handle*) 1 site; success is SUCCEEDED(hr). The first qword of the 16-byte
7// output is read later as the base of a CPU-visible buffer: per-stream
8// input at base + slot * 0x280 and output at base + 0x14000 +
9// slot * 0x1E00. The first argument is a 24-byte global of the title
10// that other title code also addresses; whether it is an input or an
11// output is not known, so it is left untouched.
12// XApuEnqueueCommand(handle, cmd*, 0) 4 sites; the return value is never read. cmd's first dword is a type
13// (1, 2 and 3 seen), the second a stream slot.
14// XApuGetResultCount(handle, 0) 1 site; 0 skips the loop that dequeues.
15// XApuDequeueResult(handle, out*) 1 site, called count times into a zeroed 0x50-byte local; a negative
16// HRESULT skips that result. The loop reads a type at +0, a stream slot
17// at +4 and a dword at +0x34. Its per-slot state machine takes a type 1
18// result as "opened" and returns the slot to the title's free list only
19// on a type 2 result, after the title enqueued a type 2 command.
20// XApuDisconnect(handle, 0x20) 1 site; the return value is never read. The constant second
21// argument is not declared here: nothing reads it.
22// XDspConnectWithMaximumStreamLimit(buffer, u32, u32, 0x80, 1, handle*) 1 site; success is a return of 0. The 6// XDspConnectWithMaximumStreamLimit(buffer, u32, u32, 0x80, 1, handle*) 1 site; success is a return of 0. The
23// buffer comes from the title's XMemAlloc and stays the title's. 7// buffer comes from the title's XMemAlloc and stays the title's.
24// XDspActivate(handle, desc*, out*, out*) 1 site; success is a return of 0, else the caller returns -1. The two 8// XDspActivate(handle, desc*, out*, out*) 1 site; success is a return of 0, else the caller returns -1. The two
@@ -30,12 +14,6 @@
30// at +4 equals *id. 14// at +4 equals *id.
31// XDspDeactivate, XDspDisconnect 1 site each, tail calls: the caller returns what they return. 15// XDspDeactivate, XDspDisconnect 1 site each, tail calls: the caller returns what they return.
32// 16//
33// HYPOTHESIS: the shared buffer is 0x14000 + 128 * 0x1E00 bytes. 128 slots is what fits 0x14000 at the 0x280 input
34// stride, and the DSP connect passes 0x80 as its stream limit; no call site shows a bound. The 16-byte output is
35// written as {base, size}; only the base is measured.
36// HYPOTHESIS: a type 1 (open) or type 2 (close) command produces one result of the same type for the same slot; the
37// title's state machine fits that, the console is not measured. Without the close result the title's 256 stream ids
38// run out. Only the two dwords are written; other command types are accepted with S_OK and produce no result.
39// HYPOTHESIS: XDspActivate's outputs point at zeroed memory owned by the connection. XDspSubmitCommand leaves *id at 17// HYPOTHESIS: XDspActivate's outputs point at zeroed memory owned by the connection. XDspSubmitCommand leaves *id at
40// the title's 0, so the zeroed status reads as "command 0 done, no error" and the title does not wait. 18// the title's 0, so the zeroed status reads as "command 0 done, no error" and the title does not wait.
41#include <windows.h> 19#include <windows.h>
@@ -43,7 +21,6 @@
43 21
44#include <cstdint> 22#include <cstdint>
45#include <cstring> 23#include <cstring>
46#include <deque>
47#include <mutex> 24#include <mutex>
48#include <new> 25#include <new>
49#include <set> 26#include <set>
@@ -54,30 +31,13 @@
54 31
55namespace { 32namespace {
56 33
57constexpr size_t kApuBufferSize = 0x14000 + 128 * 0x1E00;
58
59// shortcut: results past this cap are dropped (each leaks one stream id); raise it if a title that never dequeues
60// must still work.
61constexpr size_t kMaxResults = 4096;
62
63struct ApuResult {
64 uint32_t type;
65 uint32_t slot;
66};
67
68struct ApuConnection {
69 void* buffer;
70 std::mutex mutex;
71 std::deque<ApuResult> results;
72};
73
74struct DspConnection { 34struct DspConnection {
75 uint8_t status[256]; 35 uint8_t status[256];
76 uint8_t stream[256]; 36 uint8_t stream[256];
77}; 37};
78 38
79// gta6rt --trace FILE: the first call of each function and the first XApuEnqueueCommand of each command type, with 39// gta6rt --trace FILE: the first call of each function, with the caller, so the first boot shows what the title sends
80// the caller, so the first boot shows what the title sends without a line per call. 40// without a line per call.
81void note(const char* api, uint64_t value, const void* caller) { 41void note(const char* api, uint64_t value, const void* caller) {
82 if (!rt::startup_trace::enabled()) return; 42 if (!rt::startup_trace::enabled()) return;
83 static std::mutex mutex; 43 static std::mutex mutex;
@@ -92,71 +52,6 @@ void note(const char* api, uint64_t value, const void* caller) {
92 rt::startup_trace::quote(rt::startup_trace::where(reinterpret_cast<uint64_t>(caller)))); 52 rt::startup_trace::quote(rt::startup_trace::where(reinterpret_cast<uint64_t>(caller))));
93} 53}
94 54
95HRESULT __stdcall XApuConnect(void* block24, void* out16, void** handle) {
96 note("XApuConnect", 0, _ReturnAddress());
97 if (!handle) return E_INVALIDARG;
98 *handle = nullptr;
99 void* buffer = VirtualAlloc(nullptr, kApuBufferSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); // zeroed
100 if (!buffer) return E_OUTOFMEMORY;
101 auto* c = new (std::nothrow) ApuConnection; // a throwing new would unwind into the title
102 if (!c) {
103 VirtualFree(buffer, 0, MEM_RELEASE);
104 return E_OUTOFMEMORY;
105 }
106 c->buffer = buffer;
107 *handle = c;
108 (void)block24;
109 if (out16) {
110 const uint64_t info[2] = {reinterpret_cast<uint64_t>(buffer), kApuBufferSize};
111 std::memcpy(out16, info, sizeof info);
112 }
113 return S_OK;
114}
115
116HRESULT __stdcall XApuDisconnect(void* handle) {
117 note("XApuDisconnect", 0, _ReturnAddress());
118 auto* c = static_cast<ApuConnection*>(handle);
119 if (!c) return E_INVALIDARG;
120 VirtualFree(c->buffer, 0, MEM_RELEASE);
121 delete c;
122 return S_OK;
123}
124
125HRESULT __stdcall XApuEnqueueCommand(void* handle, const uint32_t* command, uint64_t flags) {
126 note("XApuEnqueueCommand", command ? command[0] : ~0ull, _ReturnAddress());
127 (void)flags;
128 auto* c = static_cast<ApuConnection*>(handle);
129 if (!c || !command) return E_INVALIDARG;
130 if (command[0] == 1 || command[0] == 2) {
131 try {
132 const std::lock_guard lock(c->mutex);
133 if (c->results.size() < kMaxResults) c->results.push_back({command[0], command[1]});
134 } catch (...) { // out of memory: the result is lost, nothing may unwind into the title
135 }
136 }
137 return S_OK;
138}
139
140uint32_t __stdcall XApuGetResultCount(void* handle, uint64_t flags) {
141 note("XApuGetResultCount", 0, _ReturnAddress());
142 (void)flags;
143 auto* c = static_cast<ApuConnection*>(handle);
144 if (!c) return 0;
145 const std::lock_guard lock(c->mutex);
146 return static_cast<uint32_t>(c->results.size());
147}
148
149HRESULT __stdcall XApuDequeueResult(void* handle, void* result) {
150 note("XApuDequeueResult", 0, _ReturnAddress());
151 auto* c = static_cast<ApuConnection*>(handle);
152 if (!c || !result) return E_INVALIDARG;
153 const std::lock_guard lock(c->mutex);
154 if (c->results.empty()) return E_FAIL;
155 std::memcpy(result, &c->results.front(), sizeof(ApuResult)); // the rest stays as the caller zeroed it
156 c->results.pop_front();
157 return S_OK;
158}
159
160HRESULT __stdcall XDspConnectWithMaximumStreamLimit(void* buffer, uint32_t a, uint32_t b, uint32_t max_streams, 55HRESULT __stdcall XDspConnectWithMaximumStreamLimit(void* buffer, uint32_t a, uint32_t b, uint32_t max_streams,
161 uint32_t flags, void** handle) { 56 uint32_t flags, void** handle) {
162 note("XDspConnectWithMaximumStreamLimit", max_streams, _ReturnAddress()); 57 note("XDspConnectWithMaximumStreamLimit", max_streams, _ReturnAddress());
@@ -199,14 +94,6 @@ HRESULT __stdcall XDspSubmitCommand(void*, void*, uint32_t*) {
199 94
200} // namespace 95} // namespace
201 96
202SHIM_TABLE(xapu,
203 {"xapu.dll", "XApuConnect", reinterpret_cast<void*>(&XApuConnect)},
204 {"xapu.dll", "XApuDequeueResult", reinterpret_cast<void*>(&XApuDequeueResult)},
205 {"xapu.dll", "XApuDisconnect", reinterpret_cast<void*>(&XApuDisconnect)},
206 {"xapu.dll", "XApuEnqueueCommand", reinterpret_cast<void*>(&XApuEnqueueCommand)},
207 {"xapu.dll", "XApuGetResultCount", reinterpret_cast<void*>(&XApuGetResultCount)},
208);
209
210SHIM_TABLE(chad, 97SHIM_TABLE(chad,
211 {"chad.dll", "XDspActivate", reinterpret_cast<void*>(&XDspActivate)}, 98 {"chad.dll", "XDspActivate", reinterpret_cast<void*>(&XDspActivate)},
212 {"chad.dll", "XDspConnectWithMaximumStreamLimit", reinterpret_cast<void*>(&XDspConnectWithMaximumStreamLimit)}, 99 {"chad.dll", "XDspConnectWithMaximumStreamLimit", reinterpret_cast<void*>(&XDspConnectWithMaximumStreamLimit)},
diff --git a/runtime/shims/xapu_queue.cpp b/runtime/shims/xapu_queue.cpp
new file mode 100644
index 000000000..e754376ba
--- /dev/null
+++ b/runtime/shims/xapu_queue.cpp
@@ -0,0 +1,438 @@
1// xapu.dll: the console's audio processing unit (APU) command queue. No PC has one, so this keeps the queue the title
2// talks to - one result per accepted command, in command order, with the console's error codes. With
3// runtime/opus_decoder built (LEONIDA_HAVE_OPUS_DECODER) a process command decodes its Opus packet to PCM; without
4// it the result carries the frame count its table-of-contents byte gives and silence in its output.
5//
6// Read from the executable's call sites (counts in docs/runtime_imports.md, shapes in docs/audio_hal_exe_calls.md),
7// statically, never run:
8// XApuConnect(input24*, out16*, handle*) 1 site; success is SUCCEEDED(hr). The first qword of the 16-byte
9// output is read later as the base of a CPU-visible buffer: per-stream
10// input at base + slot * 0x280 and output at base + 0x14000 +
11// slot * 0x1E00. The first argument is a 24-byte global of the title
12// that other title code also addresses.
13// XApuEnqueueCommand(handle, cmd*, 0) 4 sites; the return value is never read. cmd's first dword is a type
14// (1, 2 and 3 seen), the second a stream slot.
15// XApuGetResultCount(handle, 0) 1 site; 0 skips the loop that dequeues.
16// XApuDequeueResult(handle, out*) 1 site, called count times into a zeroed 0x50-byte local; a negative
17// HRESULT skips that result. The loop reads a type at +0, a stream slot
18// at +4 and a dword at +0x34. Its per-slot state machine takes a type 1
19// result as "opened" and returns the slot to the title's free list only
20// on a type 2 result, after the title enqueued a type 2 command.
21// XApuDisconnect(handle, 0x20) 1 site; the return value is never read.
22//
23// Where the layouts come from. The signatures, structure layouts, command kinds, option bits and error codes below
24// are facts recorded by Marvisak/VIctory (GPL-3.0-or-later, crates/victory-hle/src/modules/apu.rs at commit ffe310e),
25// whose runtime runs the retail executable through these calls; see docs/related_projects.md. Nothing of its code is
26// copied; this file is written from those facts. They agree with every shape above: the first argument of
27// XApuConnect is an input, the dword the title reads at +0x34 of a result is its output byte count, and a type 1
28// (activate) or type 2 (deactivate) command gives a result of the same kind for the same stream.
29// HRESULT XApuConnect(const ConnectInput*, ConnectOutput*, Connection** out)
30// HRESULT XApuDisconnect(Connection*, uint32_t) the second argument is not read
31// HRESULT XApuEnqueueCommand(Connection*, const void* command, uint32_t* accepted_so_far) may be null
32// HRESULT XApuDequeueResult(Connection*, Result* out) 0x8AC81001 while no result is ready
33// uint32_t XApuGetResultCount(Connection*, uint32_t* dequeued_so_far) may be null; returns the results ready
34// A connection is for one kind of processing; kind 1 is Opus decoding to 32-bit float PCM at 48 kHz, and any other
35// kind is E_NOTIMPL. Every command starts with the 24-byte CommandId. A command refused at once (unknown kind,
36// stream out of range, or the stream already holding `commands_per_stream` results not dequeued) gives no result;
37// every other command gives one, with its error, if any, in the result.
38//
39// Without runtime/opus_decoder a process command's frame count comes from the Opus packet's table-of-contents byte
40// (RFC 6716, section 3.1), clipped from first_frame, to frame_count and to what output_bytes holds, and that output
41// range is written with zeros, so the title sees streams advance at the right rate and the audio stays silent. With
42// the crate, fill() decodes the packet and writes its PCM instead.
43#include <windows.h>
44#include <intrin.h>
45
46#include <cstddef>
47#include <cstdint>
48#include <cstdio>
49#include <cstring>
50#include <deque>
51#include <mutex>
52#include <new>
53#include <set>
54#include <string>
55#include <vector>
56
57#if defined(LEONIDA_HAVE_OPUS_DECODER)
58#include "leonida_opus_decoder.h"
59#endif
60
61#include "shims.h"
62#include "startup_trace.h"
63
64namespace {
65
66constexpr HRESULT kNotImpl = static_cast<HRESULT>(rt::shims::kENotImpl);
67constexpr HRESULT kQueueFull = static_cast<HRESULT>(0x8AC81000u);
68constexpr HRESULT kNoResult = static_cast<HRESULT>(0x8AC81001u);
69constexpr HRESULT kInvalidCommand = static_cast<HRESULT>(0x8AC81002u);
70constexpr HRESULT kInvalidStream = static_cast<HRESULT>(0x8AC81003u);
71constexpr HRESULT kAlreadyActive = static_cast<HRESULT>(0x8AC81005u);
72constexpr HRESULT kBadPacket = static_cast<HRESULT>(0x8AC81008u);
73
74constexpr uint32_t kDecodeOpus = 1; // ConnectInput::processing
75
76constexpr uint32_t kActivate = 1; // CommandId::kind
77constexpr uint32_t kDeactivate = 2;
78constexpr uint32_t kProcess = 3;
79constexpr uint32_t kReset = 5; // 4 is notify; neither carries anything to do while nothing is decoded
80
81constexpr uint32_t kSignalWhenDone = 0x1; // CommandId::options: set the result event when the result is ready
82constexpr uint32_t kResultEvent = 0x8; // ConnectInput::options: create an auto-reset event and hand it out
83constexpr uint32_t kDeinterleavedOutput = 0x4; // ConnectInput::options: split stereo into two planes
84constexpr uint32_t kOpusSampleRate = 48000;
85
86constexpr uint32_t kMaxStreams = 500;
87constexpr uint32_t kMaxCommandsPerStream = 16;
88constexpr uint32_t kMaxFrames = 5760; // 120 ms at 48 kHz, the longest Opus packet (RFC 6716, section 3.2.5)
89
90#pragma pack(push, 1)
91struct ConnectInput {
92 uint32_t processing;
93 uint32_t streams;
94 uint32_t commands_per_stream;
95 uint32_t memory_bytes;
96 uint32_t frames_per_output; // 0 for decoding
97 uint32_t options;
98};
99struct ConnectOutput {
100 void* memory; // zeroed, for the title's packets and output
101 HANDLE result_event;
102};
103struct CommandId {
104 uint32_t kind;
105 uint32_t stream;
106 uint32_t sequence;
107 uint32_t options;
108 uint64_t context;
109};
110struct ActivateCommand {
111 CommandId id;
112 uint32_t channels; // 1 or 2
113 uint32_t init_bytes;
114 const void* init;
115 float start_pitch;
116 uint32_t processing_bytes;
117 void* processing;
118};
119struct ProcessCommand {
120 CommandId id;
121 float pitch_ramp;
122 float target_pitch;
123 uint32_t first_frame;
124 uint32_t frame_count;
125 uint32_t input_bytes;
126 const uint8_t* input;
127 uint32_t output_bytes;
128 uint8_t* output;
129};
130struct Result {
131 CommandId id;
132 uint32_t state;
133 uint64_t state_data;
134 uint64_t usec;
135 HRESULT error;
136 uint32_t frames;
137 uint32_t output_bytes;
138 uint8_t* output;
139 float pitch;
140 uint32_t input_bytes;
141 const uint8_t* input;
142};
143#pragma pack(pop)
144static_assert(sizeof(ConnectInput) == 24, "six dwords");
145static_assert(sizeof(ConnectOutput) == 16, "memory and event");
146static_assert(sizeof(CommandId) == 24, "kind, stream, sequence, options, context");
147static_assert(sizeof(ActivateCommand) == 56, "CommandId and the activate fields");
148static_assert(sizeof(ProcessCommand) == 64, "CommandId and the process fields");
149static_assert(sizeof(Result) == 0x50, "the result the title dequeues");
150static_assert(offsetof(Result, state) == 0x18 && offsetof(Result, error) == 0x2C &&
151 offsetof(Result, output_bytes) == 0x34 && offsetof(Result, pitch) == 0x40 &&
152 offsetof(Result, input) == 0x48,
153 "the offsets the title and the layout agree on");
154
155struct Stream {
156 bool active = false;
157 uint32_t channels = 0;
158 uint32_t pending = 0; // results queued and not dequeued
159#if defined(LEONIDA_HAVE_OPUS_DECODER)
160 LeonidaOpusDecoder* decoder = nullptr;
161#endif
162};
163
164struct Connection {
165 void* memory = nullptr;
166 HANDLE event = nullptr;
167 uint32_t commands_per_stream = 0;
168 bool deinterleaved = false;
169 std::mutex mutex;
170 std::vector<Stream> streams;
171 std::deque<Result> results;
172 uint32_t accepted = 0;
173 uint32_t dequeued = 0;
174};
175
176// gta6rt --trace FILE: the first call of each function and the first XApuEnqueueCommand of each command kind, with
177// the caller, so the first boot shows what the title sends without a line per call.
178void note(const char* api, uint64_t value, const void* caller) {
179 if (!rt::startup_trace::enabled()) return;
180 static std::mutex mutex;
181 static std::set<std::pair<std::string, uint64_t>> seen;
182 {
183 const std::lock_guard lock(mutex);
184 if (!seen.insert({api, value}).second) return;
185 }
186 rt::startup_trace::event(
187 "audio_queue", std::string("\"api\":") + rt::startup_trace::quote(api) +
188 ",\"value\":" + rt::startup_trace::quote(rt::startup_trace::hex(value)) + ",\"caller\":" +
189 rt::startup_trace::quote(rt::startup_trace::where(reinterpret_cast<uint64_t>(caller))));
190}
191
192// Samples per channel at 48 kHz in one Opus packet, from its table-of-contents byte and frame count code (RFC 6716,
193// section 3.1); 0 for a packet that is not valid. The no-decoder path counts frames this way.
194uint32_t opus_packet_frames(const uint8_t* packet, uint32_t bytes) {
195 if (!packet || bytes == 0) return 0;
196 static constexpr uint32_t kSilk[4] = {480, 960, 1920, 2880}; // 10, 20, 40, 60 ms
197 static constexpr uint32_t kHybrid[2] = {480, 960}; // 10, 20 ms
198 static constexpr uint32_t kCelt[4] = {120, 240, 480, 960}; // 2.5, 5, 10, 20 ms
199 const uint32_t config = packet[0] >> 3;
200 const uint32_t per_frame = config < 12 ? kSilk[config & 3] : config < 16 ? kHybrid[config & 1] : kCelt[config & 3];
201 uint32_t count = 0;
202 switch (packet[0] & 3) {
203 case 0: count = 1; break;
204 case 1:
205 case 2: count = 2; break;
206 default:
207 if (bytes < 2) return 0;
208 count = packet[1] & 0x3F;
209 break;
210 }
211 if (count == 0 || count * per_frame > kMaxFrames) return 0;
212 return count * per_frame;
213}
214
215// Fills a process command's result: the packet's PCM when runtime/opus_decoder is built, silence (with the frame
216// count from the table-of-contents byte) otherwise.
217void fill(Connection& connection, Stream& stream, const ProcessCommand& c, Result& r) {
218 r.input = c.input;
219 r.input_bytes = c.input_bytes;
220 r.output = c.output;
221 if (!c.input || !c.output || c.input_bytes == 0) {
222 r.error = E_INVALIDARG;
223 return;
224 }
225#if defined(LEONIDA_HAVE_OPUS_DECODER)
226 if (stream.decoder) {
227 const uint32_t channels = leonida_opus_decoder_channels(stream.decoder);
228 if (channels == 0) {
229 r.error = kInvalidStream;
230 return;
231 }
232 std::vector<float> pcm;
233 try {
234 pcm.resize(size_t(kMaxFrames) * channels);
235 } catch (...) {
236 r.error = E_OUTOFMEMORY;
237 return;
238 }
239 uint32_t decoded = 0;
240 if (leonida_opus_decode_packet(stream.decoder, c.input, c.input_bytes, pcm.data(), kMaxFrames, &decoded) !=
241 LEONIDA_OPUS_OK) {
242 r.error = kBadPacket;
243 return;
244 }
245 const uint32_t first = c.first_frame < decoded ? c.first_frame : decoded;
246 uint32_t frames = decoded - first;
247 if (frames > c.frame_count) frames = c.frame_count;
248 const uint32_t room = c.output_bytes / (4 * channels);
249 if (frames > room) frames = room;
250 const uint32_t bytes = frames * channels * 4;
251 if (connection.deinterleaved && channels == 2) {
252 float* out = reinterpret_cast<float*>(c.output);
253 for (uint32_t i = 0; i < frames; ++i) {
254 out[i] = pcm[(first + i) * 2];
255 out[frames + i] = pcm[(first + i) * 2 + 1];
256 }
257 } else if (bytes != 0) {
258 std::memcpy(c.output, pcm.data() + first * channels, bytes);
259 }
260 r.frames = frames;
261 r.output_bytes = bytes;
262 return;
263 }
264#endif
265 const uint32_t decoded = opus_packet_frames(c.input, c.input_bytes);
266 if (decoded == 0) {
267 r.error = kBadPacket;
268 return;
269 }
270 const uint32_t first = c.first_frame < decoded ? c.first_frame : decoded;
271 uint32_t frames = decoded - first;
272 if (frames > c.frame_count) frames = c.frame_count;
273 const uint32_t room = c.output_bytes / (4 * stream.channels);
274 if (frames > room) frames = room;
275 const uint32_t bytes = frames * stream.channels * 4;
276 std::memset(c.output, 0, bytes); // interleaved or not, silence is zeros
277 r.frames = frames;
278 r.output_bytes = bytes;
279}
280
281HRESULT __stdcall XApuConnect(const ConnectInput* input, ConnectOutput* output, Connection** out) {
282 note("XApuConnect", input ? input->processing : ~0ull, _ReturnAddress());
283 if (!input || !output || !out) return E_INVALIDARG;
284 *out = nullptr;
285 ConnectInput in;
286 std::memcpy(&in, input, sizeof(in));
287 if (in.streams == 0 || in.streams > kMaxStreams || in.commands_per_stream == 0 ||
288 in.commands_per_stream > kMaxCommandsPerStream || in.memory_bytes == 0)
289 return E_INVALIDARG;
290 if (in.processing != kDecodeOpus) {
291 std::fprintf(stderr, "[rt] xapu: XApuConnect for processing kind %u: only Opus decoding (1); E_NOTIMPL\n",
292 in.processing);
293 return kNotImpl;
294 }
295 if (in.frames_per_output != 0) return E_INVALIDARG;
296
297 auto* c = new (std::nothrow) Connection; // a throwing new would unwind into the title
298 if (!c) return E_OUTOFMEMORY;
299 try {
300 c->streams.resize(in.streams);
301 } catch (...) {
302 delete c;
303 return E_OUTOFMEMORY;
304 }
305 c->memory = VirtualAlloc(nullptr, in.memory_bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); // zeroed
306 if (!c->memory) {
307 delete c;
308 return E_OUTOFMEMORY;
309 }
310 if (in.options & kResultEvent) {
311 c->event = CreateEventW(nullptr, FALSE, FALSE, nullptr); // auto-reset
312 if (!c->event) {
313 const HRESULT hr = HRESULT_FROM_WIN32(GetLastError());
314 VirtualFree(c->memory, 0, MEM_RELEASE);
315 delete c;
316 return hr;
317 }
318 }
319 c->commands_per_stream = in.commands_per_stream;
320 c->deinterleaved = (in.options & kDeinterleavedOutput) != 0;
321 const ConnectOutput o{c->memory, c->event};
322 std::memcpy(output, &o, sizeof(o));
323 *out = c;
324#if defined(LEONIDA_HAVE_OPUS_DECODER)
325 std::fprintf(stderr, "[rt] xapu: connected for Opus decoding, %u streams; packets decoded\n", in.streams);
326#else
327 std::fprintf(stderr, "[rt] xapu: connected for Opus decoding, %u streams; packets counted, not decoded\n",
328 in.streams);
329#endif
330 return S_OK;
331}
332
333HRESULT __stdcall XApuDisconnect(Connection* c, uint32_t /*0x20 at the measured site*/) {
334 note("XApuDisconnect", 0, _ReturnAddress());
335 if (!c) return E_INVALIDARG;
336#if defined(LEONIDA_HAVE_OPUS_DECODER)
337 for (Stream& s : c->streams)
338 if (s.decoder) leonida_opus_decoder_destroy(s.decoder);
339#endif
340 if (c->event) CloseHandle(c->event);
341 VirtualFree(c->memory, 0, MEM_RELEASE);
342 delete c;
343 return S_OK;
344}
345
346HRESULT __stdcall XApuEnqueueCommand(Connection* c, const void* command, uint32_t* accepted_so_far) {
347 if (!c || !command) return E_INVALIDARG;
348 CommandId id;
349 std::memcpy(&id, command, sizeof(id));
350 note("XApuEnqueueCommand", id.kind, _ReturnAddress());
351 if (id.kind < kActivate || id.kind > kReset) return kInvalidCommand;
352
353 const std::lock_guard lock(c->mutex);
354 if (id.stream >= c->streams.size()) return kInvalidStream;
355 Stream& stream = c->streams[id.stream];
356 if (stream.pending >= c->commands_per_stream) return kQueueFull;
357
358 Result r{};
359 r.id = id;
360 r.pitch = 1.0f;
361 if (id.kind == kActivate) {
362 ActivateCommand a;
363 std::memcpy(&a, command, sizeof(a));
364 if (stream.active) {
365 r.error = kAlreadyActive;
366 } else if (a.channels < 1 || a.channels > 2) {
367 r.error = E_INVALIDARG;
368 } else {
369 stream.active = true;
370 stream.channels = a.channels;
371#if defined(LEONIDA_HAVE_OPUS_DECODER)
372 if (leonida_opus_decoder_create(kOpusSampleRate, a.channels, &stream.decoder) != LEONIDA_OPUS_OK) {
373 stream.active = false;
374 stream.channels = 0;
375 r.error = E_INVALIDARG;
376 }
377#endif
378 }
379 } else if (id.kind == kDeactivate) {
380 stream.active = false;
381#if defined(LEONIDA_HAVE_OPUS_DECODER)
382 if (stream.decoder) {
383 leonida_opus_decoder_destroy(stream.decoder);
384 stream.decoder = nullptr;
385 }
386#endif
387 } else if (id.kind == kReset) {
388#if defined(LEONIDA_HAVE_OPUS_DECODER)
389 if (stream.decoder) leonida_opus_decoder_reset(stream.decoder);
390#endif
391 } else if (id.kind == kProcess) {
392 ProcessCommand p;
393 std::memcpy(&p, command, sizeof(p));
394 if (!stream.active) r.error = kInvalidStream;
395 else fill(*c, stream, p, r);
396 }
397 try {
398 c->results.push_back(r);
399 } catch (...) { // out of memory: refuse the command, nothing may unwind into the title
400 return E_OUTOFMEMORY;
401 }
402 ++stream.pending;
403 ++c->accepted;
404 if (accepted_so_far) *accepted_so_far = c->accepted;
405 if ((id.options & kSignalWhenDone) && c->event) SetEvent(c->event);
406 return S_OK;
407}
408
409HRESULT __stdcall XApuDequeueResult(Connection* c, Result* out) {
410 note("XApuDequeueResult", 0, _ReturnAddress());
411 if (!c || !out) return E_INVALIDARG;
412 const std::lock_guard lock(c->mutex);
413 if (c->results.empty()) return kNoResult;
414 const Result r = c->results.front();
415 c->results.pop_front();
416 --c->streams[r.id.stream].pending;
417 ++c->dequeued;
418 std::memcpy(out, &r, sizeof(r));
419 return S_OK;
420}
421
422uint32_t __stdcall XApuGetResultCount(Connection* c, uint32_t* dequeued_so_far) {
423 note("XApuGetResultCount", 0, _ReturnAddress());
424 if (!c) return 0;
425 const std::lock_guard lock(c->mutex);
426 if (dequeued_so_far) *dequeued_so_far = c->dequeued;
427 return static_cast<uint32_t>(c->results.size());
428}
429
430} // namespace
431
432SHIM_TABLE(xapu,
433 {"xapu.dll", "XApuConnect", reinterpret_cast<void*>(&XApuConnect)},
434 {"xapu.dll", "XApuDequeueResult", reinterpret_cast<void*>(&XApuDequeueResult)},
435 {"xapu.dll", "XApuDisconnect", reinterpret_cast<void*>(&XApuDisconnect)},
436 {"xapu.dll", "XApuEnqueueCommand", reinterpret_cast<void*>(&XApuEnqueueCommand)},
437 {"xapu.dll", "XApuGetResultCount", reinterpret_cast<void*>(&XApuGetResultCount)},
438);
diff --git a/runtime/shims/xgameruntime_gamesave.cpp b/runtime/shims/xgameruntime_gamesave.cpp
index 7ba8ab645..b29475778 100644
--- a/runtime/shims/xgameruntime_gamesave.cpp
+++ b/runtime/shims/xgameruntime_gamesave.cpp
@@ -326,23 +326,30 @@ struct BlobRead {
326 326
327size_t align8(size_t n) { return (n + 7) & ~size_t{7}; } 327size_t align8(size_t n) { return (n + 7) & ~size_t{7}; }
328 328
329size_t packed_size(const std::vector<BlobRead>& blobs) { 329// The layout the blobs are packed in: 8-byte aligned data and names when the buffer has room for that, packed back
330 size_t n = align8(blobs.size() * sizeof(XGameSaveBlob)); 330// to back otherwise. A title sizes the buffer as the sum of sizeof(XGameSaveBlob), the data and the name with its NUL
331 for (const BlobRead& b : blobs) n += align8(b.data.size()) + align8(b.name.size() + 1); 331// for each blob, so the minimum is the unaligned size.
332size_t packed_size(const std::vector<BlobRead>& blobs, bool aligned) {
333 const auto a = [aligned](size_t n) { return aligned ? align8(n) : n; };
334 size_t n = a(blobs.size() * sizeof(XGameSaveBlob));
335 for (const BlobRead& b : blobs) n += a(b.data.size()) + a(b.name.size() + 1);
332 return n; 336 return n;
333} 337}
338size_t packed_size(const std::vector<BlobRead>& blobs) { return packed_size(blobs, false); }
334 339
335void pack(const std::vector<BlobRead>& blobs, void* buffer) { 340void pack(const std::vector<BlobRead>& blobs, void* buffer, size_t buffer_size) {
341 const bool aligned = buffer_size >= packed_size(blobs, true);
342 const auto a = [aligned](size_t n) { return aligned ? align8(n) : n; };
336 auto* base = static_cast<uint8_t*>(buffer); 343 auto* base = static_cast<uint8_t*>(buffer);
337 auto* entries = static_cast<XGameSaveBlob*>(buffer); 344 auto* entries = static_cast<XGameSaveBlob*>(buffer);
338 size_t at = align8(blobs.size() * sizeof(XGameSaveBlob)); 345 size_t at = a(blobs.size() * sizeof(XGameSaveBlob));
339 for (size_t i = 0; i < blobs.size(); ++i) { 346 for (size_t i = 0; i < blobs.size(); ++i) {
340 uint8_t* data = base + at; 347 uint8_t* data = base + at;
341 if (!blobs[i].data.empty()) std::memcpy(data, blobs[i].data.data(), blobs[i].data.size()); 348 if (!blobs[i].data.empty()) std::memcpy(data, blobs[i].data.data(), blobs[i].data.size());
342 at += align8(blobs[i].data.size()); 349 at += a(blobs[i].data.size());
343 char* name = reinterpret_cast<char*>(base + at); 350 char* name = reinterpret_cast<char*>(base + at);
344 std::memcpy(name, blobs[i].name.c_str(), blobs[i].name.size() + 1); 351 std::memcpy(name, blobs[i].name.c_str(), blobs[i].name.size() + 1);
345 at += align8(blobs[i].name.size() + 1); 352 at += a(blobs[i].name.size() + 1);
346 entries[i].info.name = name; 353 entries[i].info.name = name;
347 entries[i].info.size = static_cast<uint32_t>(blobs[i].data.size()); 354 entries[i].info.size = static_cast<uint32_t>(blobs[i].data.size());
348 entries[i].data = data; 355 entries[i].data = data;
@@ -642,7 +649,7 @@ HRESULT CALLBACK job_provider(XAsyncOp op, const XAsyncProviderData* data) {
642 } 649 }
643 if (job->identity == &kReadIdentity) { 650 if (job->identity == &kReadIdentity) {
644 if (data->bufferSize < packed_size(job->blobs)) return E_GS_PROVIDED_BUFFER_TOO_SMALL; 651 if (data->bufferSize < packed_size(job->blobs)) return E_GS_PROVIDED_BUFFER_TOO_SMALL;
645 pack(job->blobs, data->buffer); 652 pack(job->blobs, data->buffer, data->bufferSize);
646 t_read_count = static_cast<uint32_t>(job->blobs.size()); 653 t_read_count = static_cast<uint32_t>(job->blobs.size());
647 return S_OK; 654 return S_OK;
648 } 655 }
@@ -840,7 +847,7 @@ HRESULT STDMETHODCALLTYPE save_read(void*, XGameSaveContainerHandle c, const cha
840 const HRESULT hr = read_blobs(c, names, names ? *count : 0, blobs); 847 const HRESULT hr = read_blobs(c, names, names ? *count : 0, blobs);
841 if (FAILED(hr)) return hr; 848 if (FAILED(hr)) return hr;
842 if (size < packed_size(blobs)) return E_GS_PROVIDED_BUFFER_TOO_SMALL; 849 if (size < packed_size(blobs)) return E_GS_PROVIDED_BUFFER_TOO_SMALL;
843 pack(blobs, out); 850 pack(blobs, out, size);
844 *count = static_cast<uint32_t>(blobs.size()); 851 *count = static_cast<uint32_t>(blobs.size());
845 return S_OK; 852 return S_OK;
846} 853}
diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp
index 44c6f140b..fca6f6f47 100644
--- a/runtime/shims/xmem.cpp
+++ b/runtime/shims/xmem.cpp
@@ -1033,6 +1033,7 @@ constexpr size_t kUnmapRecords = 1024;
1033UnmapRecord g_unmaps[kUnmapRecords]; 1033UnmapRecord g_unmaps[kUnmapRecords];
1034uint64_t g_unmap_count = 0; 1034uint64_t g_unmap_count = 0;
1035thread_local const char* t_unmap_cause = "unmap"; 1035thread_local const char* t_unmap_cause = "unmap";
1036
1036struct UnmapCause { 1037struct UnmapCause {
1037 const char* was; 1038 const char* was;
1038 explicit UnmapCause(const char* cause) : was(std::exchange(t_unmap_cause, cause)) {} 1039 explicit UnmapCause(const char* cause) : was(std::exchange(t_unmap_cause, cause)) {}
@@ -1576,7 +1577,7 @@ LONG CALLBACK physical_page_fault(EXCEPTION_POINTERS* info) {
1576 MEMORY_BASIC_INFORMATION seen{}; // the page as the decision saw it 1577 MEMORY_BASIC_INFORMATION seen{}; // the page as the decision saw it
1577 char read_note[1024]; 1578 char read_note[1024];
1578 DWORD read_note_size = 0; 1579 DWORD read_note_size = 0;
1579 bool plant_read = false, promote = false; 1580 bool plant_read = false, promote = false, from_title = false;
1580 bool queried = false; 1581 bool queried = false;
1581 { 1582 {
1582 const FaultLockShared lock; 1583 const FaultLockShared lock;
@@ -1595,7 +1596,8 @@ LONG CALLBACK physical_page_fault(EXCEPTION_POINTERS* info) {
1595 if (where != kNoReservation || access == 1) 1596 if (where != kNoReservation || access == 1)
1596 queried = VirtualQuery(reinterpret_cast<const void*>(accessed), &seen, sizeof(seen)) != 0; 1597 queried = VirtualQuery(reinterpret_cast<const void*>(accessed), &seen, sizeof(seen)) != 0;
1597 const auto pc = reinterpret_cast<uintptr_t>(record->ExceptionAddress); 1598 const auto pc = reinterpret_cast<uintptr_t>(record->ExceptionAddress);
1598 if (access == 0 && result == PageCommit::not_ours && title_code(pc)) { 1599 from_title = access == 0 && result == PageCommit::not_ours && title_code(pc);
1600 if (from_title) {
1599 if (!queried) queried = VirtualQuery(reinterpret_cast<const void*>(accessed), &seen, sizeof(seen)) != 0; 1601 if (!queried) queried = VirtualQuery(reinterpret_cast<const void*>(accessed), &seen, sizeof(seen)) != 0;
1600 read_note_size = describe_read(read_note, pc, accessed, seen); 1602 read_note_size = describe_read(read_note, pc, accessed, seen);
1601 plant_read = where == kInWindow && g_pool_zero_pages; 1603 plant_read = where == kInWindow && g_pool_zero_pages;
@@ -1671,7 +1673,8 @@ LONG CALLBACK physical_page_fault(EXCEPTION_POINTERS* info) {
1671 exit = FaultExit::committed; 1673 exit = FaultExit::committed;
1672 } else if (answered) { 1674 } else if (answered) {
1673 exit = FaultExit::answered; 1675 exit = FaultExit::answered;
1674 } else if (result == PageCommit::committed_before && !escalated) { 1676 } else if ((result == PageCommit::committed_before && !escalated) ||
1677 (title_page && access == 0 && result == PageCommit::not_ours && !from_title)) {
1675 exit = FaultExit::passed_guarded; // a guard's (the D3D12 layer's), routine: not noted 1678 exit = FaultExit::passed_guarded; // a guard's (the D3D12 layer's), routine: not noted
1676 } else if (title_page || reserved_write) { 1679 } else if (title_page || reserved_write) {
1677 note_fault(kRefused, accessed, access, result, where, seen); 1680 note_fault(kRefused, accessed, access, result, where, seen);
@@ -1970,6 +1973,7 @@ BOOL WINAPI XMemMapPhysicalPagesScatter(void* const* addresses, uint32_t page_co
1970 return scatter_refused(ScatterFailure::unaligned, address, ERROR_INVALID_PARAMETER); 1973 return scatter_refused(ScatterFailure::unaligned, address, ERROR_INVALID_PARAMETER);
1971 } 1974 }
1972 const uint64_t page = page_array ? page_array[i] : 0; 1975 const uint64_t page = page_array ? page_array[i] : 0;
1976 const UnmapCause cause(page ? "XMemMapPhysicalPagesScatter (remap)" : "XMemMapPhysicalPagesScatter (unmap)");
1973 if (page == 0) { 1977 if (page == 0) {
1974 if (!unmap_page(address)) return scatter_refused(ScatterFailure::unmap, address, GetLastError()); 1978 if (!unmap_page(address)) return scatter_refused(ScatterFailure::unmap, address, GetLastError());
1975 continue; 1979 continue;
@@ -1992,6 +1996,34 @@ BOOL WINAPI XMemMapPhysicalPagesScatter(void* const* addresses, uint32_t page_co
1992// calls with the same page make them. Every source page is looked up before any destination page changes, so a source 1996// calls with the same page make them. Every source page is looked up before any destination page changes, so a source
1993// range that overlaps the destination maps what was there before the call. A destination in a GPU-only range is mapped 1997// range that overlaps the destination maps what was there before the call. A destination in a GPU-only range is mapped
1994// at its paired CPU range too (title_gpu_views), and a source page missing at a GPU-only address is looked up there. 1998// at its paired CPU range too (title_gpu_views), and a source page missing at a GPU-only address is looked up there.
1999// A page of that CPU range the title mapped itself is the title's (title_mapped_twin): the copy leaves it as it is.
2000
2001// With g_phys_mutex held. True when the paired CPU page at `address` holds a mapping of the title's own: its
2002// XMemMapPhysicalPages or XMemMapPhysicalPagesScatter call, or a slot-31 copy onto that address. The console's
2003// CopyPageMappingsBatchX changes only the GPU-only range's page table, so such a page keeps what the title put
2004// there; only a page the copy mirrored there itself (MapOwner::mirror), a zero plant, or a page with no mapping
2005// follows the GPU-only range. Each page kept is counted, and the first ones logged.
2006bool title_mapped_twin(uintptr_t address, uintptr_t gpu, bool unmap) {
2007 MapOwner owner;
2008 {
2009 const FaultLockShared faults;
2010 uintptr_t base = 0;
2011 const View* const view = covering_view(address, base);
2012 if (!view || view->zero || view->owner == MapOwner::mirror) return false;
2013 owner = view->owner;
2014 }
2015 static std::atomic<uint64_t> kept{0};
2016 const uint64_t n = kept.fetch_add(1, std::memory_order_relaxed) + 1;
2017 if (n <= 8 || (n & (n - 1)) == 0)
2018 std::fprintf(stderr,
2019 "[rt] xmem: slot-31 %s at 0x%llx left the title's %s mapping at its paired CPU page 0x%llx "
2020 "(%llu such pages so far)\n",
2021 unmap ? "unmap" : "copy", static_cast<unsigned long long>(gpu),
2022 owner == MapOwner::scatter ? "scatter" : owner == MapOwner::slot31 ? "slot-31" : "physical",
2023 static_cast<unsigned long long>(address), static_cast<unsigned long long>(n));
2024 return true;
2025}
2026
1995bool copy_page_mappings(void* destination, const void* source, uint64_t pages, bool repeat_first) { 2027bool copy_page_mappings(void* destination, const void* source, uint64_t pages, bool repeat_first) {
1996 const uintptr_t to = reinterpret_cast<uintptr_t>(destination); 2028 const uintptr_t to = reinterpret_cast<uintptr_t>(destination);
1997 const uintptr_t from = reinterpret_cast<uintptr_t>(source); 2029 const uintptr_t from = reinterpret_cast<uintptr_t>(source);
@@ -2012,8 +2044,14 @@ bool copy_page_mappings(void* destination, const void* source, uint64_t pages, b
2012 const Window* const cpu_window = cpu_to != to ? find_window(cpu_to, pages * kPhysicalPageSize) : nullptr; 2044 const Window* const cpu_window = cpu_to != to ? find_window(cpu_to, pages * kPhysicalPageSize) : nullptr;
2013 if (!source) { 2045 if (!source) {
2014 for (uint64_t i = 0; i < pages; ++i) { 2046 for (uint64_t i = 0; i < pages; ++i) {
2015 if (!unmap_page(to + i * kPhysicalPageSize)) return false; 2047 const uintptr_t gpu = to + i * kPhysicalPageSize, cpu = cpu_to + i * kPhysicalPageSize;
2016 if (cpu_window && !unmap_page(cpu_to + i * kPhysicalPageSize)) return false; 2048 {
2049 const UnmapCause cause("CopyPageMappingsBatchX (unmap)");
2050 if (!unmap_page(gpu)) return false;
2051 }
2052 if (!cpu_window || title_mapped_twin(cpu, gpu, true)) continue;
2053 const UnmapCause cause("CopyPageMappingsBatchX (unmap paired CPU page)");
2054 if (!unmap_page(cpu)) return false;
2017 } 2055 }
2018 return true; 2056 return true;
2019 } 2057 }
@@ -2036,8 +2074,11 @@ bool copy_page_mappings(void* destination, const void* source, uint64_t pages, b
2036 const DWORD cpu_protect = cpu_window ? view_protect(*cpu_window) : 0; 2074 const DWORD cpu_protect = cpu_window ? view_protect(*cpu_window) : 0;
2037 for (uint64_t i = 0; i < pages; ++i) { 2075 for (uint64_t i = 0; i < pages; ++i) {
2038 const uint64_t page = found[static_cast<size_t>(i)]; 2076 const uint64_t page = found[static_cast<size_t>(i)];
2039 if (!map_page(to + i * kPhysicalPageSize, page, protect, MapOwner::slot31)) return false; 2077 const uintptr_t gpu = to + i * kPhysicalPageSize, cpu = cpu_to + i * kPhysicalPageSize;
2040 if (cpu_window && !map_page(cpu_to + i * kPhysicalPageSize, page, cpu_protect, MapOwner::mirror)) return false; 2078 const UnmapCause cause(page ? "CopyPageMappingsBatchX (remap)" : "CopyPageMappingsBatchX (hole)");
2079 if (!map_page(gpu, page, protect, MapOwner::slot31)) return false;
2080 if (cpu_window && !title_mapped_twin(cpu, gpu, false) && !map_page(cpu, page, cpu_protect, MapOwner::mirror))
2081 return false;
2041 } 2082 }
2042 return true; 2083 return true;
2043} 2084}
diff --git a/runtime/shims/xmem.h b/runtime/shims/xmem.h
index 96fb89e7e..6e0017f2b 100644
--- a/runtime/shims/xmem.h
+++ b/runtime/shims/xmem.h
@@ -55,7 +55,7 @@ enum class FaultExit : int {
55 answered, // a mapped page committed, or found committed and allowed (another thread's map or commit) 55 answered, // a mapped page committed, or found committed and allowed (another thread's map or commit)
56 planted, // a window page the title never mapped, backed by a zero page 56 planted, // a window page the title never mapped, backed by a zero page
57 committed, // a section page in the title's reservation with no view of xmem's, committed 57 committed, // a section page in the title's reservation with no view of xmem's, committed
58 passed_guarded, // a committed page of xmem's views whose protection refuses the access: its guard's to answer 58 passed_guarded, // a committed page whose protection refuses the access, or a host guarded read of an unmapped page
59 passed_foreign, // memory that is not the title's reservation and not only reserved: someone else's fault 59 passed_foreign, // memory that is not the title's reservation and not only reserved: someone else's fault
60 left_to_title, // the title's reservation, or a write into memory that is only reserved: noted (FaultNote) 60 left_to_title, // the title's reservation, or a write into memory that is only reserved: noted (FaultNote)
61 count 61 count