upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime
diff options
context:
space:
mode:
authorDimitar Pavlov <360593571+azsekazvamdimitar@users.noreply.github.com>2026-11-25 15:39:43 +0200
committerDimitar Pavlov <360593571+azsekazvamdimitar@users.noreply.github.com>2026-11-26 11:18:19 +0200
commit49a0b69fcdb80db1f2a44ce7ca0ab8dfdec1e403 (patch)
treedd53c9909834cbfeec85e7cbd188595c8a2d9931 /runtime
parenta73a57e1339be072baf5522351c8ec7f1482b56b (diff)
d3d12: slot-133 shadows guard aliased title pages at every address instead of copying them each submission (RT-SHADOW-ALIAS-GUARD)
A page xmem maps at two addresses was copied whole at every refresh, since a guard on one view doesn't fault a write through the other: about 1 GB a submission after the story load on a retail boot. ShadowPages now arms the geometry watch's cells of each aliased 64 KiB block at every address it is mapped and copies a block only when a cell's version moved. xmem tells the cells of a mapping change after updating the peers, and of list value writes made through the section. AI-assisted; tested under WineHQ 11.22 and GE-Proton11-14 on an RTX 3090 (NVIDIA 590.48.01).
Diffstat (limited to 'runtime')
-rw-r--r--runtime/README.md2
-rw-r--r--runtime/shims/d3d12_vulkan_device.cpp181
-rw-r--r--runtime/shims/xmem.cpp19
-rw-r--r--runtime/src/title_page_watch.h3
-rw-r--r--runtime/test/d3d12_existing_heap_test.cpp80
5 files changed, 241 insertions, 44 deletions
diff --git a/runtime/README.md b/runtime/README.md
index 23a7811ab..28304408f 100644
--- a/runtime/README.md
+++ b/runtime/README.md
@@ -378,7 +378,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w
378| `LEONIDA_LOCAL_SPEECH` | unset | `1` forwards the title's speech-synthesis calls to the host's installed `xgameruntime.dll` where there is one. Unset, and wherever that library is missing, the silent voice answers. No profile sets it. | 378| `LEONIDA_LOCAL_SPEECH` | unset | `1` forwards the title's speech-synthesis calls to the host's installed `xgameruntime.dll` where there is one. Unset, and wherever that library is missing, the silent voice answers. No profile sets it. |
379| `LEONIDA_CONSOLE_FIX_US` | `0` | Microseconds one submission may spend fixing the changed slots of a console descriptor heap's copy; `0` sets no limit. Past it, each further changed slot is written as a null descriptor and queued for `LEONIDA_CONSOLE_RETRY_US`, so a shader reads it as empty until its turn comes: a limit changes results, and can hang the GPU. | 379| `LEONIDA_CONSOLE_FIX_US` | `0` | Microseconds one submission may spend fixing the changed slots of a console descriptor heap's copy; `0` sets no limit. Past it, each further changed slot is written as a null descriptor and queued for `LEONIDA_CONSOLE_RETRY_US`, so a shader reads it as empty until its turn comes: a limit changes results, and can hang the GPU. |
380| `LEONIDA_CONSOLE_RETRY_US` | `500` | Microseconds one submission may spend retrying, round robin, the console heap slots not settled yet (a T# whose texture does not exist yet, or one deferred by `LEONIDA_CONSOLE_FIX_US`). `0` retries all of them at every submission. | 380| `LEONIDA_CONSOLE_RETRY_US` | `500` | Microseconds one submission may spend retrying, round robin, the console heap slots not settled yet (a T# whose texture does not exist yet, or one deferred by `LEONIDA_CONSOLE_FIX_US`). `0` retries all of them at every submission. |
381| `LEONIDA_SHADOW_ALIAS_MS` | `0` | The shortest time, in milliseconds, between two copies of the title-memory pages that XMem maps at two addresses (no write guard can watch them) into the slot-133 shadows and title windows. `0` copies them at every submission; a larger value lets a GPU read of them be up to that many milliseconds behind the title's writes. | 381| `LEONIDA_SHADOW_ALIAS_MS` | `0` | The shortest time, in milliseconds, between two copies of the title-memory pages that XMem maps at two addresses into the slot-133 shadows and title windows: pages a write reached since they were guarded at every address, or every time while they can't be (a page pinned for a kernel write). `0` copies them at every submission; a larger value lets a GPU read of them be up to that many milliseconds behind the title's writes. |
382| `LEONIDA_REFRESH_PER_FRAME` | `0` | Trades correctness for speed. `1`: the slot-133 shadows, title windows and geometry copies are brought up to date only by the first submission after each present, not by every submission; `2`: the console descriptor heaps too. A GPU read of them can then be a frame behind the title's writes (wrong pixels). `0` refreshes all of them at every submission. | 382| `LEONIDA_REFRESH_PER_FRAME` | `0` | Trades correctness for speed. `1`: the slot-133 shadows, title windows and geometry copies are brought up to date only by the first submission after each present, not by every submission; `2`: the console descriptor heaps too. A GPU read of them can then be a frame behind the title's writes (wrong pixels). `0` refreshes all of them at every submission. |
383| `LEONIDA_GEOMETRY_ASYNC` | unset | Trades correctness for speed. `1` refreshes the geometry copies (`shims/d3d12_geometry_views.h`) on a worker thread of the layer, started at submission and not waited for, instead of on the title's submitting thread. A draw may read a copy the worker is still writing: wrong vertices for a frame. | 383| `LEONIDA_GEOMETRY_ASYNC` | unset | Trades correctness for speed. `1` refreshes the geometry copies (`shims/d3d12_geometry_views.h`) on a worker thread of the layer, started at submission and not waited for, instead of on the title's submitting thread. A draw may read a copy the worker is still writing: wrong vertices for a frame. |
384| `LEONIDA_GEOMETRY_WHOLE_VIEWS` | unset | A geometry copy that is already filled copies only the 64 KiB tiles of title memory written since the last refresh (`shims/d3d12_geometry_views.h`). Any value other than `0` copies every view over a written tile whole, as before. | 384| `LEONIDA_GEOMETRY_WHOLE_VIEWS` | unset | A geometry copy that is already filled copies only the 64 KiB tiles of title memory written since the last refresh (`shims/d3d12_geometry_views.h`). Any value other than `0` copies every view over a written tile whole, as before. |
diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp
index 1fb36401e..ca25ccc9e 100644
--- a/runtime/shims/d3d12_vulkan_device.cpp
+++ b/runtime/shims/d3d12_vulkan_device.cpp
@@ -301,8 +301,10 @@ void copy_run(std::uint8_t* to, const std::uint8_t* from, std::size_t bytes, boo
301// - other readable pages (read-only or copy-on-write pages of the title's own, pages another tracker protected) 301// - other readable pages (read-only or copy-on-write pages of the title's own, pages another tracker protected)
302// can't be watched: copied every time, as before; 302// can't be watched: copied every time, as before;
303// - pages not committed, or not readable, are zero in the copies (written once); 303// - pages not committed, or not readable, are zero in the copies (written once);
304// - pages xmem reports mapped at another address too (title_page_watch.h) are copied every time: a write 304// - pages xmem reports mapped at another address too (title_page_watch.h): a write through the other address
305// through the other address doesn't fault here; 305// doesn't fault here, so their 64 KiB blocks are guarded at every address by the geometry watch's cells
306// (update_aliased) and copied when a cell's version moved. Without the other addresses (no xmem), or while a
307// cell can't be armed, they are copied every time;
306// - pages a file shim pinned for a kernel write (ReadFile into title memory, which fails with ERROR_NOACCESS on a 308// - pages a file shim pinned for a kernel write (ReadFile into title memory, which fails with ERROR_NOACCESS on a
307// read-only page instead of faulting) are left writable and copied every time until the pin ends. 309// read-only page instead of faulting) are left writable and copied every time until the pin ends.
308// If the protection can't be changed (VirtualProtect refuses, or the fault handler couldn't be installed), those 310// If the protection can't be changed (VirtualProtect refuses, or the fault handler couldn't be installed), those
@@ -369,6 +371,8 @@ public:
369 if (std::any_of(state_.begin(), state_.end(), [](std::uint8_t s) { return s & kProtected; })) 371 if (std::any_of(state_.begin(), state_.end(), [](std::uint8_t s) { return s & kProtected; }))
370 reopen_locked(first_, last_); 372 reopen_locked(first_, last_);
371 ReleaseSRWLockExclusive(&lock_); 373 ReleaseSRWLockExclusive(&lock_);
374 for (auto& [va, block] : aliased_blocks_) release_cells(va, block);
375 aliased_blocks_.clear();
372 } 376 }
373 ShadowPages(const ShadowPages&) = delete; 377 ShadowPages(const ShadowPages&) = delete;
374 ShadowPages& operator=(const ShadowPages&) = delete; 378 ShadowPages& operator=(const ShadowPages&) = delete;
@@ -411,11 +415,11 @@ public:
411 const auto walk_start = std::chrono::steady_clock::now(); 415 const auto walk_start = std::chrono::steady_clock::now();
412 pieces_ = {}; 416 pieces_ = {};
413 copy_aliased_ = copy_aliased; 417 copy_aliased_ = copy_aliased;
418 update_aliased();
414 jobs_.clear(); 419 jobs_.clear();
415 zeroed_.clear(); 420 zeroed_.clear();
416 copy_bytes_ = {}; 421 copy_bytes_ = {};
417 std::uint64_t queries = 0; 422 std::uint64_t queries = 0;
418 const std::uint64_t generation = leonida::title_page_aliases::generation();
419 // LEONIDA_SHADOW_FULL_WALK=1 queries every page at every refresh, as before the generation skip. 423 // LEONIDA_SHADOW_FULL_WALK=1 queries every page at every refresh, as before the generation skip.
420 static const bool always_full_walk = [] { 424 static const bool always_full_walk = [] {
421 char value[8] = {}; 425 char value[8] = {};
@@ -438,15 +442,7 @@ public:
438 })) 442 }))
439 full_walk = true; 443 full_walk = true;
440 refresh_walked_all_ = full_walk; 444 refresh_walked_all_ = full_walk;
441 refresh_protects_ = 0; 445 refresh_protects_ = alias_arms_;
442 if (generation != alias_generation_) {
443 alias_generation_ = generation;
444 for (std::uint8_t& s : state_) s &= ~kAliased;
445 leonida::title_page_aliases::for_each_in(first_, last_, [&](std::uintptr_t va) {
446 const std::uintptr_t from = std::max(va, first_), to = std::min(va + kBlock, last_);
447 for (std::uintptr_t p = from; p < to; p += kPage) state_[(p - first_) / kPage] |= kAliased;
448 });
449 }
450 if (pinned_) { 446 if (pinned_) {
451 for (std::uint8_t& s : state_) s &= ~kPinned; 447 for (std::uint8_t& s : state_) s &= ~kPinned;
452 pinned_ = false; 448 pinned_ = false;
@@ -502,13 +498,16 @@ public:
502 // passed over like unchanged ones and queried at the next such refresh: a mapping change over them is in 498 // passed over like unchanged ones and queried at the next such refresh: a mapping change over them is in
503 // the journal (kRequery) anyway. speed-16/17/18: 730-820 VirtualQuery calls a refresh, ~19 us each under 499 // the journal (kRequery) anyway. speed-16/17/18: 730-820 VirtualQuery calls a refresh, ~19 us each under
504 // Wine (NtQueryVirtualMemory waits for Wine's virtual-memory lock, which the mapping threads hold), a 500 // Wine (NtQueryVirtualMemory waits for Wine's virtual-memory lock, which the mapping threads hold), a
505 // fifth of the submitting thread's time. 501 // fifth of the submitting thread's time. So are aliased pages whose cells no write reached (aliased_clean):
506 const auto skip = [&](std::uint8_t s) { 502 // a mapping, commitment or protection change over a cell moves its version too.
507 return unchanged(s) || (!copy_aliased_ && (s == kAliased || s == kZero || s == (kZero | kAliased))); 503 const auto skip = [&](std::size_t i) {
504 const std::uint8_t s = state_[i];
505 return unchanged(s) || ((s & ~(kZero | kProtected)) == kAliased && aliased_clean(i)) ||
506 (!copy_aliased_ && (s == kAliased || s == kZero || s == (kZero | kAliased)));
508 }; 507 };
509 if (!full_walk && skip(state_[i0])) { 508 if (!full_walk && skip(i0)) {
510 std::size_t i = i0 + 1; 509 std::size_t i = i0 + 1;
511 while (i < state_.size() && skip(state_[i])) ++i; 510 while (i < state_.size() && skip(i)) ++i;
512 at = first_ + i * kPage; 511 at = first_ + i * kPage;
513 continue; 512 continue;
514 } 513 }
@@ -688,6 +687,7 @@ public:
688 leonida::title_write_watch::merge_reader(reader_, other.reader_); 687 leonida::title_write_watch::merge_reader(reader_, other.reader_);
689 } 688 }
690 watch_generation_ = ~std::uint64_t(0); 689 watch_generation_ = ~std::uint64_t(0);
690 alias_generation_ = ~std::uint64_t(0);
691 pinned_ |= other.pinned_; 691 pinned_ |= other.pinned_;
692 watch_ = watch_ && other.watch_; 692 watch_ = watch_ && other.watch_;
693 faults_.fetch_add(other.faults(), std::memory_order_relaxed); 693 faults_.fetch_add(other.faults(), std::memory_order_relaxed);
@@ -704,6 +704,7 @@ public:
704 targets_.push_back({begin, end, shadow}); 704 targets_.push_back({begin, end, shadow});
705 for (std::uintptr_t p = begin & ~(kPage - 1); p < end; p += kPage) ++cover_[(p - first_) / kPage]; 705 for (std::uintptr_t p = begin & ~(kPage - 1); p < end; p += kPage) ++cover_[(p - first_) / kPage];
706 index_targets(); 706 index_targets();
707 alias_generation_ = ~std::uint64_t(0); // the aliased blocks the copies read
707 ReleaseSRWLockExclusive(&lock_); 708 ReleaseSRWLockExclusive(&lock_);
708 } 709 }
709 710
@@ -751,6 +752,7 @@ public:
751 targets_.erase(it); 752 targets_.erase(it);
752 index_targets(); 753 index_targets();
753 watch_generation_ = ~std::uint64_t(0); // recounts the write-watched pages covered 754 watch_generation_ = ~std::uint64_t(0); // recounts the write-watched pages covered
755 alias_generation_ = ~std::uint64_t(0); // and the aliased blocks the copies read
754 ReleaseSRWLockExclusive(&lock_); 756 ReleaseSRWLockExclusive(&lock_);
755 return true; 757 return true;
756 } 758 }
@@ -887,7 +889,11 @@ private:
887 const bool unwatched = state_[i] & (kAliased | kPinned); 889 const bool unwatched = state_[i] & (kAliased | kPinned);
888 std::size_t j = i + 1; 890 std::size_t j = i + 1;
889 while (j < i1 && bool(state_[j] & (kAliased | kPinned)) == unwatched) ++j; 891 while (j < i1 && bool(state_[j] & (kAliased | kPinned)) == unwatched) ++j;
890 for (std::size_t k = i; k < j; ++k) state_[k] &= ~(kZero | kProtected); 892 for (std::size_t k = i; k < j; ++k) {
893 state_[k] &= ~(kZero | kProtected);
894 // Writable with no write seen: its cells must be armed again (update_aliased).
895 if (aliased_clean(k) && (rearm_.empty() || rearm_.back() != block_of(k))) rearm_.push_back(block_of(k));
896 }
891 if (!unwatched && watch_) protect(i, j, current); 897 if (!unwatched && watch_) protect(i, j, current);
892 if (unwatched && !copy_aliased_ && (state_[i] & kAliased)) { 898 if (unwatched && !copy_aliased_ && (state_[i] & kAliased)) {
893 i = j; 899 i = j;
@@ -901,13 +907,18 @@ private:
901 } 907 }
902 } 908 }
903 909
904 // Guarded pages [i, j) of a read-only region: pages this tracker protected are as the last refresh left them; 910 // Guarded pages [i, j) of a read-only region: pages this tracker protected, and aliased pages whose cells no write
905 // any other is copied again. 911 // reached, are as the last refresh left them; any other is copied again.
906 void guard_read_only(std::size_t i0, std::size_t i1, bool streaming) { 912 void guard_read_only(std::size_t i0, std::size_t i1, bool streaming) {
913 const auto clean_at = [&](std::size_t k) {
914 const std::uint8_t s = state_[k];
915 return (s & (kProtected | kAliased | kPinned)) == kProtected ||
916 ((s & (kAliased | kPinned)) == kAliased && aliased_clean(k));
917 };
907 for (std::size_t i = i0; i < i1;) { 918 for (std::size_t i = i0; i < i1;) {
908 const bool clean = (state_[i] & (kProtected | kAliased | kPinned)) == kProtected; 919 const bool clean = clean_at(i);
909 std::size_t j = i + 1; 920 std::size_t j = i + 1;
910 while (j < i1 && ((state_[j] & (kProtected | kAliased | kPinned)) == kProtected) == clean) ++j; 921 while (j < i1 && clean_at(j) == clean) ++j;
911 if (!clean && !(!copy_aliased_ && (state_[i] & kAliased))) { 922 if (!clean && !(!copy_aliased_ && (state_[i] & kAliased))) {
912 for (std::size_t k = i; k < j; ++k) state_[k] &= ~kZero; 923 for (std::size_t k = i; k < j; ++k) state_[k] &= ~kZero;
913 add_job(i, j, streaming, 924 add_job(i, j, streaming,
@@ -919,6 +930,99 @@ private:
919 } 930 }
920 } 931 }
921 932
933 // An aliased block's cell, its other addresses' cells, and their mapping and version when it was last armed.
934 struct AliasedBlock {
935 leonida::geometry_writes::Cell* cell = nullptr;
936 Vector<std::pair<std::uintptr_t, leonida::geometry_writes::Cell*>> peers;
937 std::uint64_t mapping = 0, version = 0;
938 bool armed = false;
939 };
940
941 // The 64 KiB block of page i, and whether update_aliased found no write reached it.
942 std::uintptr_t block_of(std::size_t i) const { return (first_ + i * kPage) & ~(kBlock - 1); }
943 bool aliased_clean(std::size_t i) const {
944 return !clean_.empty() && clean_[((first_ & (kBlock - 1)) + i * kPage) / kBlock];
945 }
946
947 // At the start of refresh(), outside lock_ (the cells' lock is the write-fault handler's, and the other addresses
948 // are asked for on the process heap). Each aliased block the copies read is guarded at every address xmem maps it
949 // by a cell of the geometry watch, whose faults shadow_write_fault answers: a write through any of the addresses,
950 // a remap or a protection change moves a cell's version. A block whose cells kept their versions since they were
951 // armed is clean (clean_); any other is armed again before the walk copies it, so a write after the arming is
952 // copied at the next refresh. A block is copied every time while its cells can't be armed: no other address
953 // known, a page pinned for a kernel write, or the refreshes that leave aliased pages alone (copy_aliased_).
954 void update_aliased() {
955 namespace watch = leonida::geometry_writes;
956 const std::uint64_t generation = leonida::title_page_aliases::generation();
957 AcquireSRWLockExclusive(&lock_);
958 if (generation != alias_generation_) {
959 alias_generation_ = generation;
960 aliased_list_.clear();
961 for (std::uint8_t& s : state_) s &= ~kAliased;
962 leonida::title_page_aliases::for_each_in(first_, last_, [&](std::uintptr_t va) {
963 const std::uintptr_t from = std::max(va, first_), to = std::min(va + kBlock, last_);
964 bool read = false;
965 for (std::uintptr_t p = from; p < to; p += kPage) {
966 state_[(p - first_) / kPage] |= kAliased;
967 read |= cover_[(p - first_) / kPage] != 0;
968 }
969 if (read) aliased_list_.push_back(va);
970 });
971 }
972 Vector<std::uintptr_t> rearm;
973 rearm.swap(rearm_);
974 ReleaseSRWLockExclusive(&lock_);
975 const std::uintptr_t base = first_ & ~(kBlock - 1);
976 clean_.assign(aliased_list_.empty() ? 0 : (last_ - base + kBlock - 1) / kBlock, 0);
977 alias_arms_ = 0;
978 const auto aliases = watch::aliases.load(std::memory_order_acquire);
979 const bool guard = aliases && watch_;
980 for (auto it = aliased_blocks_.begin(); it != aliased_blocks_.end();) {
981 if (guard && std::binary_search(aliased_list_.begin(), aliased_list_.end(), it->first)) {
982 ++it;
983 continue;
984 }
985 release_cells(it->first, it->second);
986 it = aliased_blocks_.erase(it);
987 }
988 if (!guard) return;
989 for (const std::uintptr_t va : rearm)
990 if (const auto it = aliased_blocks_.find(va); it != aliased_blocks_.end()) it->second.armed = false;
991 for (const std::uintptr_t va : aliased_list_) {
992 AliasedBlock& b = aliased_blocks_[va];
993 if (!b.cell) b.cell = watch::acquire(va);
994 std::uint64_t version = b.cell->version.load(std::memory_order_acquire);
995 const std::uint64_t mapping = b.cell->mapping.load(std::memory_order_acquire);
996 if (mapping != b.mapping) {
997 std::vector<std::uintptr_t> others;
998 if (aliases) aliases(va, others);
999 auto old = std::move(b.peers);
1000 b.peers.clear();
1001 for (const std::uintptr_t other : others) b.peers.emplace_back(other, watch::acquire(other));
1002 for (const auto& [other, cell] : old) watch::release(other);
1003 b.mapping = mapping;
1004 b.armed = false;
1005 }
1006 for (const auto& [other, cell] : b.peers)
1007 version = std::max(version, cell->version.load(std::memory_order_acquire));
1008 if (b.armed && version == b.version) {
1009 clean_[(va - base) / kBlock] = 1;
1010 continue;
1011 }
1012 b.armed = false;
1013 if (!copy_aliased_ || b.peers.empty()) continue;
1014 b.armed = watch::arm(va, *b.cell);
1015 for (const auto& [other, cell] : b.peers) b.armed = watch::arm(other, *cell) && b.armed;
1016 alias_arms_ += 1 + b.peers.size();
1017 b.version = version;
1018 }
1019 }
1020 static void release_cells(std::uintptr_t va, AliasedBlock& b) {
1021 if (b.cell) leonida::geometry_writes::release(va);
1022 for (const auto& [other, cell] : b.peers) leonida::geometry_writes::release(other);
1023 b = {};
1024 }
1025
922 // With the lock held, when this tracker opens a new write-watch reader: no page is clean until that reader has 1026 // With the lock held, when this tracker opens a new write-watch reader: no page is clean until that reader has
923 // asked and the walk has copied it. The runs may have closed (their reservation released) and come back over a 1027 // asked and the walk has copied it. The runs may have closed (their reservation released) and come back over a
924 // reservation made at the same address since, which a page's watched mark alone doesn't tell (re-review of #61). 1028 // reservation made at the same address since, which a page's watched mark alone doesn't tell (re-review of #61).
@@ -1129,6 +1233,13 @@ private:
1129 Vector<std::uintptr_t> reach_; // see index_targets 1233 Vector<std::uintptr_t> reach_; // see index_targets
1130 std::size_t target_bytes_ = 0; 1234 std::size_t target_bytes_ = 0;
1131 std::uint64_t alias_generation_ = ~std::uint64_t(0); 1235 std::uint64_t alias_generation_ = ~std::uint64_t(0);
1236 // Aliased blocks (update_aliased), refresh() only: those the copies read, in address order; their cells; per 64 KiB
1237 // block from first_ rounded down, whether no write reached it; and the clean blocks the walk found writable.
1238 Vector<std::uintptr_t> aliased_list_;
1239 leonida::host_heap::map<std::uintptr_t, AliasedBlock> aliased_blocks_;
1240 Vector<std::uint8_t> clean_;
1241 Vector<std::uintptr_t> rearm_;
1242 std::uint64_t alias_arms_ = 0; // arm() calls of the last update_aliased()
1132 std::uint64_t map_generation_ = ~std::uint64_t(0); 1243 std::uint64_t map_generation_ = ~std::uint64_t(0);
1133 bool pinned_ = false; // some page has kPinned 1244 bool pinned_ = false; // some page has kPinned
1134 Vector<Job> jobs_; // refresh() only, which DeviceState::shadow_mutex serializes 1245 Vector<Job> jobs_; // refresh() only, which DeviceState::shadow_mutex serializes
@@ -1162,15 +1273,6 @@ leonida::host_heap::vector<ShadowPages*>& shadow_pages_list() {
1162 return *list; 1273 return *list;
1163} 1274}
1164 1275
1165// A write to a page a shadow made read-only: the page is made writable again and the write retried. First in the
1166// handler chain, so a startup trace doesn't log these as exceptions; any other access violation goes on down it.
1167// Whatever thread wrote: the title's, or a host thread of the runtime's (a DirectStorage queue's copy).
1168//
1169// A physical page xmem maps at two addresses (a stream pool's CPU view and its GPU-only twin) has a protection per
1170// address: a guard on one view never faults a write through the other, which the shadows see by copying aliased
1171// pages at every submission (title_page_aliases), so the guard to look for is the faulting address's own. When none
1172// answers for it (each guard reopens only what it protected), xmem makes the page writable again if its window is
1173// (kernel_writes' unguarder): a read-only page nobody reopens would fault that write, and every later one, for good.
1174// A title write into a committed, private, read-only page of title memory that no guard owns (the geometry watch, 1276// A title write into a committed, private, read-only page of title memory that no guard owns (the geometry watch,
1175// the slot-133 shadows and the kernel-write unguarder all declined it): a guard of ours left behind, since the title 1277// the slot-133 shadows and the kernel-write unguarder all declined it): a guard of ours left behind, since the title
1176// never writes memory it made read-only itself on the console. Said for the first 32 pages, with whether a shadow's 1278// never writes memory it made read-only itself on the console. Said for the first 32 pages, with whether a shadow's
@@ -1214,6 +1316,16 @@ bool stray_read_only(EXCEPTION_POINTERS* info, std::uintptr_t address) {
1214 return ok; 1316 return ok;
1215} 1317}
1216 1318
1319// A write to a page a shadow made read-only: the page is made writable again and the write retried. First in the
1320// handler chain, so a startup trace doesn't log these as exceptions; any other access violation goes on down it.
1321// Whatever thread wrote: the title's, or a host thread of the runtime's (a DirectStorage queue's copy).
1322//
1323// A physical page xmem maps at two addresses (a stream pool's CPU view and its GPU-only twin) has a protection per
1324// address: a guard on one view never faults a write through the other, which the shadows see through the geometry
1325// watch's cells they arm at every address of an aliased page (ShadowPages::update_aliased), so the guard to look for
1326// is the faulting address's own. When none answers for it (each guard reopens only what it protected), xmem makes the
1327// page writable again if its window is (kernel_writes' unguarder): a read-only page nobody reopens would fault that
1328// write, and every later one, for good.
1217LONG CALLBACK shadow_write_fault(EXCEPTION_POINTERS* info) { 1329LONG CALLBACK shadow_write_fault(EXCEPTION_POINTERS* info) {
1218 const EXCEPTION_RECORD* record = info ? info->ExceptionRecord : nullptr; 1330 const EXCEPTION_RECORD* record = info ? info->ExceptionRecord : nullptr;
1219 if (!record || record->ExceptionCode != EXCEPTION_ACCESS_VIOLATION || record->NumberParameters < 2 || 1331 if (!record || record->ExceptionCode != EXCEPTION_ACCESS_VIOLATION || record->NumberParameters < 2 ||
@@ -2438,9 +2550,10 @@ struct DeviceState {
2438 std::lock_guard lock(shadow_mutex); 2550 std::lock_guard lock(shadow_mutex);
2439 if (shadows.empty()) return; 2551 if (shadows.empty()) return;
2440 const auto start = clock::now(); 2552 const auto start = clock::now();
2441 // LEONIDA_SHADOW_ALIAS_MS (0 by default: every submission): pages xmem maps at two addresses, which no guard 2553 // LEONIDA_SHADOW_ALIAS_MS (0 by default: every submission): pages xmem maps at two addresses that a write
2442 // can watch, are copied at most this often. After the story load they were 59 MiB a submission (speed-6); a 2554 // reached, or whose cells can't be armed (ShadowPages::update_aliased), are copied at most this often. After
2443 // GPU read of them is at most this many milliseconds behind the title's writes. 2555 // the story load they were 59 MiB a submission (speed-6), copied every time; a GPU read of them is at most
2556 // this many milliseconds behind the title's writes.
2444 static const auto alias_period = std::chrono::milliseconds([] { 2557 static const auto alias_period = std::chrono::milliseconds([] {
2445 char text[16] = {}; 2558 char text[16] = {};
2446 const DWORD n = GetEnvironmentVariableA("LEONIDA_SHADOW_ALIAS_MS", text, sizeof(text)); 2559 const DWORD n = GetEnvironmentVariableA("LEONIDA_SHADOW_ALIAS_MS", text, sizeof(text));
diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp
index 384f7bd27..44c6f140b 100644
--- a/runtime/shims/xmem.cpp
+++ b/runtime/shims/xmem.cpp
@@ -543,8 +543,8 @@ using AddressList = std::vector<uintptr_t, leonida::host_heap::Allocator<uintptr
543HostUnorderedMap<uintptr_t, AddressList> g_alias_peers; 543HostUnorderedMap<uintptr_t, AddressList> g_alias_peers;
544 544
545// With g_phys_mutex held. Keeps leonida::title_page_aliases in step: a page mapped at two or more addresses is 545// With g_phys_mutex held. Keeps leonida::title_page_aliases in step: a page mapped at two or more addresses is
546// aliased at each of them (the D3D12 layer's slot-133 shadows copy those pages at every submission instead of 546// aliased at each of them (the D3D12 layer's slot-133 shadows guard those pages at every address, since a write
547// waiting for a write fault, which a write through another address doesn't raise). 547// through one address doesn't fault a guard on another).
548void note_mapping(uint64_t page, uintptr_t address, bool mapped) { 548void note_mapping(uint64_t page, uintptr_t address, bool mapped) {
549 auto& addresses = g_page_addresses[page]; 549 auto& addresses = g_page_addresses[page];
550 if (mapped) { 550 if (mapped) {
@@ -553,12 +553,6 @@ void note_mapping(uint64_t page, uintptr_t address, bool mapped) {
553 addresses.erase(address); 553 addresses.erase(address);
554 leonida::title_page_aliases::set(address, false); 554 leonida::title_page_aliases::set(address, false);
555 } 555 }
556 using namespace leonida::geometry_writes;
557 if (state().count.load(std::memory_order_acquire)) {
558 notify(address, address + kPhysicalPageSize, Event::mapping);
559 for (auto other : addresses)
560 if (other != address) notify(other, other + kPhysicalPageSize, Event::mapping);
561 }
562 const bool aliased = addresses.size() > 1; 556 const bool aliased = addresses.size() > 1;
563 for (const uintptr_t at : addresses) leonida::title_page_aliases::set(at, aliased); 557 for (const uintptr_t at : addresses) leonida::title_page_aliases::set(at, aliased);
564 const std::unique_lock aliases(g_alias_lock); 558 const std::unique_lock aliases(g_alias_lock);
@@ -573,6 +567,13 @@ void note_mapping(uint64_t page, uintptr_t address, bool mapped) {
573 for (const uintptr_t other : addresses) 567 for (const uintptr_t other : addresses)
574 if (other != at) peers.push_back(other); 568 if (other != at) peers.push_back(other);
575 } 569 }
570 // After the peers: a cell's watcher that sees the new mapping asks geometry_aliases for the addresses again.
571 using namespace leonida::geometry_writes;
572 if (state().count.load(std::memory_order_acquire)) {
573 notify(address, address + kPhysicalPageSize, Event::mapping);
574 for (auto other : addresses)
575 if (other != address) notify(other, other + kPhysicalPageSize, Event::mapping);
576 }
576 if (addresses.empty()) g_page_addresses.erase(page); 577 if (addresses.empty()) g_page_addresses.erase(page);
577} 578}
578 579
@@ -2726,6 +2727,8 @@ bool write_title_bytes(const void* address, const void* bytes, std::size_t size)
2726 std::memcpy(host + offset, static_cast<const std::uint8_t*>(bytes) + done, chunk); 2727 std::memcpy(host + offset, static_cast<const std::uint8_t*>(bytes) + done, chunk);
2727 done += chunk; 2728 done += chunk;
2728 } 2729 }
2730 // Through the section, not the title's views: no fault tells a guard of them (a shadow's cells) of the write.
2731 leonida::geometry_writes::notify(start, start + size, leonida::geometry_writes::Event::write);
2729 return true; 2732 return true;
2730} 2733}
2731 2734
diff --git a/runtime/src/title_page_watch.h b/runtime/src/title_page_watch.h
index 9d0a2ccfc..44a19cb1b 100644
--- a/runtime/src/title_page_watch.h
+++ b/runtime/src/title_page_watch.h
@@ -9,7 +9,8 @@
9// 9//
10// 1. Aliases (title_page_aliases). xmem maps one physical page at as many VAs as the title asks 10// 1. Aliases (title_page_aliases). xmem maps one physical page at as many VAs as the title asks
11// (XMemMapPhysicalPages): a write through one VA changes what the others read without touching them. xmem 11// (XMemMapPhysicalPages): a write through one VA changes what the others read without touching them. xmem
12// reports each 64 KiB page mapped at more than one address; a shadow copies those at every submission. 12// reports each 64 KiB page mapped at more than one address; a shadow guards those at every address with the
13// geometry watch's cells (title_geometry_watch.h), or copies them at every submission while it can't.
13// 14//
14// 2. Kernel writes (kernel_writes). A read-only page makes ReadFile fail with ERROR_NOACCESS instead of faulting 15// 2. Kernel writes (kernel_writes). A read-only page makes ReadFile fail with ERROR_NOACCESS instead of faulting
15// into a user-mode handler. The file shims (read_file and the rest, below) pin the destination before the kernel 16// into a user-mode handler. The file shims (read_file and the rest, below) pin the destination before the kernel
diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp
index 25fa1f654..7848ac864 100644
--- a/runtime/test/d3d12_existing_heap_test.cpp
+++ b/runtime/test/d3d12_existing_heap_test.cpp
@@ -13,6 +13,7 @@
13#include "host_wine.h" 13#include "host_wine.h"
14#include "../shims/d3d12_com.h" 14#include "../shims/d3d12_com.h"
15#include "../src/title_page_watch.h" 15#include "../src/title_page_watch.h"
16#include "../src/title_geometry_watch.h"
16#include "../src/gfx10_descriptors.h" 17#include "../src/gfx10_descriptors.h"
17#include "../src/deferred_image_binding.h" 18#include "../src/deferred_image_binding.h"
18#include <dxgi1_4.h> 19#include <dxgi1_4.h>
@@ -922,6 +923,84 @@ int check_aliased_write(ID3D12Device* device) {
922 return 0; 923 return 0;
923} 924}
924 925
926// The same page, guarded at both addresses instead of copied at every submission. With the other address known (what
927// xmem answers through leonida::geometry_writes::aliases), the shadow at A arms the geometry watch's cells of the
928// aliased 64 KiB at A and at B: both read-only between submissions, and a submission that follows no write copies
929// nothing of it. The control: a write through a third view nobody reported doesn't fault, so it stays stale until a
930// write through B (which faults) marks the block; then both arrive. Each view commits its pages itself: Wine shows a
931// page of a SEC_RESERVE view as committed only in the view that committed it.
932std::uintptr_t g_alias_a, g_alias_b;
933void aliases_of_test_views(std::uintptr_t va, std::vector<std::uintptr_t>& others) {
934 if (va >= g_alias_a && va < g_alias_a + 4 * 0x10000) others.push_back(va - g_alias_a + g_alias_b);
935 if (va >= g_alias_b && va < g_alias_b + 4 * 0x10000) others.push_back(va - g_alias_b + g_alias_a);
936}
937
938int check_aliased_guard(ID3D12Device* device) {
939 const char* who = "vulkan slot-133 aliased page, guarded";
940 constexpr SIZE_T size = 4 * 0x10000;
941 constexpr UINT64 committed = size / 2, block = 0x10000, at = 0x11000;
942 HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE | SEC_RESERVE, 0, DWORD(size),
943 nullptr);
944 EXPECT(section != nullptr);
945 std::uint8_t* views[3]{};
946 for (auto& view : views) {
947 view = static_cast<std::uint8_t*>(MapViewOfFile(section, FILE_MAP_ALL_ACCESS, 0, 0, size));
948 EXPECT(view != nullptr && VirtualAlloc(view, committed, MEM_COMMIT, PAGE_READWRITE) == view);
949 }
950 std::uint8_t *a = views[0], *b = views[1], *c = views[2];
951 g_alias_a = reinterpret_cast<std::uintptr_t>(a);
952 g_alias_b = reinterpret_cast<std::uintptr_t>(b);
953 leonida::geometry_writes::aliases.store(&aliases_of_test_views, std::memory_order_release);
954 leonida::title_page_aliases::set(g_alias_a + block, true);
955 leonida::title_page_aliases::set(g_alias_b + block, true);
956 long long unreported = -1, faulted = -1;
957 DWORD at_a = 0, at_b = 0, b_written = 0;
958 {
959 Ref<ID3D12Resource> buffer;
960 buffer.p = place_shadow(device, a, size);
961 EXPECT(buffer.p != nullptr);
962 GpuReader reader;
963 if (reader.init(device, size)) return 1;
964 std::vector<std::uint8_t> want(size, 0), got;
965 for (UINT64 i = 0; i < committed; ++i) want[i] = a[i] = pattern_byte(i, 23);
966 EXPECT(reader.read(buffer.p, got) == 0);
967 EXPECT(first_difference(got, want) == -1);
968 at_a = protection_of(a + at);
969 at_b = protection_of(b + at);
970 EXPECT((at_a & 0xff) == PAGE_READONLY);
971 EXPECT((at_b & 0xff) == PAGE_READONLY);
972 // Nothing written: the block is not copied, so a write the cells can't see is not either.
973 for (UINT64 i = at; i < at + 64; ++i) want[i] = c[i] = 0x5a;
974 EXPECT(reader.read(buffer.p, got) == 0);
975 unreported = first_difference(got, want);
976 // Through B: faults, and the block is copied again (the write through C with it).
977 for (UINT64 i = at + 0x800; i < at + 0x1000; ++i) want[i] = b[i] = pattern_byte(i, 151);
978 b_written = protection_of(b + at);
979 EXPECT(reader.read(buffer.p, got) == 0);
980 faulted = first_difference(got, want);
981 EXPECT((protection_of(b + at) & 0xff) == PAGE_READONLY);
982 // Through A, the shadow's own address.
983 for (UINT64 i = at; i < at + 16; ++i) want[i] = a[i] = 0xc3;
984 EXPECT(reader.read(buffer.p, got) == 0);
985 EXPECT(first_difference(got, want) == -1);
986 }
987 // Released: both addresses are writable again.
988 EXPECT((protection_of(a + at) & 0xff) == PAGE_READWRITE);
989 EXPECT((protection_of(b + at) & 0xff) == PAGE_READWRITE);
990 leonida::title_page_aliases::set(g_alias_a + block, false);
991 leonida::title_page_aliases::set(g_alias_b + block, false);
992 leonida::geometry_writes::aliases.store(nullptr, std::memory_order_release);
993 for (auto* view : views) UnmapViewOfFile(view);
994 CloseHandle(section);
995 std::printf("%s: protection between submissions 0x%lx at A, 0x%lx at B (0x%lx after the write through B); an "
996 "unreported view's write: first stale byte at %lld (expected 69632); after a write through B: %s\n",
997 who, at_a, at_b, b_written, unreported, faulted == -1 ? "arrives" : "STILL STALE");
998 EXPECT(unreported == static_cast<long long>(at));
999 EXPECT((b_written & 0xff) == PAGE_READWRITE);
1000 EXPECT(faulted == -1);
1001 return 0;
1002}
1003
925// Kernel writes into a watched page. ReadFile writes from kernel mode, so a page a shadow made read-only fails it 1004// Kernel writes into a watched page. ReadFile writes from kernel mode, so a page a shadow made read-only fails it
926// with ERROR_NOACCESS instead of faulting into the layer: the plain call fails (the control). Through the file shims' 1005// with ERROR_NOACCESS instead of faulting into the layer: the plain call fails (the control). Through the file shims'
927// path (leonida::kernel_writes::read_file, what the title's ReadFile import resolves to), the destination is pinned 1006// path (leonida::kernel_writes::read_file, what the title's ReadFile import resolves to), the destination is pinned
@@ -1960,6 +2039,7 @@ int check_written_pages_all(ID3D12Device* device) {
1960 failures += check_concurrent_writes(device, false); 2039 failures += check_concurrent_writes(device, false);
1961 if (leonida::title_write_watch::enabled()) failures += check_concurrent_writes(device, true); 2040 if (leonida::title_write_watch::enabled()) failures += check_concurrent_writes(device, true);
1962 failures += check_aliased_write(device); 2041 failures += check_aliased_write(device);
2042 failures += check_aliased_guard(device);
1963 failures += check_kernel_write(device); 2043 failures += check_kernel_write(device);
1964 failures += check_shared_pages(device); 2044 failures += check_shared_pages(device);
1965 return failures; 2045 return failures;