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:
authorDadaCap <167002618+DadaCap@users.noreply.github.com>2026-11-26 00:46:03 +0100
committerDadaCap <167002618+DadaCap@users.noreply.github.com>2026-11-26 01:22:14 +0100
commit0ebd4286ea80b5de20dbf7adf7bf6b970c7492df (patch)
tree351ecd034823d3274e316d056cd570da3e9c3518 /runtime
parent33bd07cf86bb42236635c27341359b3fe841d1d5 (diff)
d3d12: a slot-133 shadow keeps the GPU's writes where the title's bytes did not change (LEONIDA_SHADOW_KEEP)
ShadowPages copies pages that carry no sign of a title write (aliased, unguarded, reopened with their 64 KiB block, write-watched or pinned) at every refresh, and that copy overwrote what a shader had stored in the shadow with the title's unchanged bytes. A value a compute program writes for the next frame then read back as the title's old bytes every other frame. Each tracker now keeps a 64-bit sum per 256-byte piece of the bytes it copied last (runtime/src/shadow_keep.h) and copies a piece only when the title's bytes differ. Zeroed pages forget their sums. LEONIDA_SHADOW_KEEP=0 copies every job whole, as before. New CPU-only test shadow_keep. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Gt9hwRYcpySx4P4ncQ3wD5
Diffstat (limited to 'runtime')
-rw-r--r--runtime/CMakeLists.txt6
-rw-r--r--runtime/README.md1
-rw-r--r--runtime/shims/d3d12_vulkan_device.cpp57
-rw-r--r--runtime/src/shadow_keep.h72
-rw-r--r--runtime/test/shadow_keep_test.cpp141
5 files changed, 271 insertions, 6 deletions
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt
index 283ed202a..3fb277356 100644
--- a/runtime/CMakeLists.txt
+++ b/runtime/CMakeLists.txt
@@ -4503,6 +4503,12 @@ if(TARGET Vulkan::Headers)
4503 target_compile_options(console_heap_vsharp_slots_test PRIVATE /W4 /permissive- /utf-8) 4503 target_compile_options(console_heap_vsharp_slots_test PRIVATE /W4 /permissive- /utf-8)
4504 endif() 4504 endif()
4505 add_test(NAME console_heap_vsharp_slots COMMAND console_heap_vsharp_slots_test) 4505 add_test(NAME console_heap_vsharp_slots COMMAND console_heap_vsharp_slots_test)
4506 # A slot-133 shadow keeps a GPU write until the title's bytes under it change (src/shadow_keep.h).
4507 add_executable(shadow_keep_test test/shadow_keep_test.cpp)
4508 if(WIN32 AND MSVC)
4509 target_compile_options(shadow_keep_test PRIVATE /W4 /permissive- /utf-8)
4510 endif()
4511 add_test(NAME shadow_keep COMMAND shadow_keep_test)
4506 # Queue construction cleans its Vulkan handles if holder registration runs out of host memory. 4512 # Queue construction cleans its Vulkan handles if holder registration runs out of host memory.
4507 add_executable(vk_host_texture_order_test test/vk_host_texture_order_test.cpp) 4513 add_executable(vk_host_texture_order_test test/vk_host_texture_order_test.cpp)
4508 target_link_libraries(vk_host_texture_order_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) 4514 target_link_libraries(vk_host_texture_order_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS})
diff --git a/runtime/README.md b/runtime/README.md
index 2af9dc215..62a59bd8e 100644
--- a/runtime/README.md
+++ b/runtime/README.md
@@ -376,6 +376,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w
376| `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. | 376| `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. |
377| `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. | 377| `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. |
378| `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. | 378| `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. |
379| `LEONIDA_SHADOW_KEEP` | on | The slot-133 shadows and title windows copy a page only in the 256-byte pieces where the title's bytes changed since the last copy, so what a shader stored in the copy stays, also on pages copied without a sign that the title wrote them (aliased, unguarded, pinned). A title writing the same bytes again to reset such a value is not seen. `0` copies those pages whole, as before, overwriting the GPU's writes. |
379| `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. | 380| `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. |
380| `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. | 381| `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. |
381| `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. | 382| `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 938e8372d..59edde074 100644
--- a/runtime/shims/d3d12_vulkan_device.cpp
+++ b/runtime/shims/d3d12_vulkan_device.cpp
@@ -52,6 +52,7 @@
52#include "../src/resource_detile.h" 52#include "../src/resource_detile.h"
53#include "../src/console_texture_layout.h" 53#include "../src/console_texture_layout.h"
54#include "../src/shader_library.h" 54#include "../src/shader_library.h"
55#include "../src/shadow_keep.h"
55#include "../src/dstorage_trace.h" 56#include "../src/dstorage_trace.h"
56#include "../src/title_page_watch.h" 57#include "../src/title_page_watch.h"
57#include "../src/guarded_copy.h" 58#include "../src/guarded_copy.h"
@@ -335,6 +336,7 @@ public:
335 last_ = (end_ + kPage - 1) & ~(kPage - 1); 336 last_ = (end_ + kPage - 1) & ~(kPage - 1);
336 state_.assign((last_ - first_) / kPage, 0); 337 state_.assign((last_ - first_) / kPage, 0);
337 idle_.assign(state_.size(), 0); 338 idle_.assign(state_.size(), 0);
339 sums_.assign(state_.size() * kPieces, 0);
338 cover_.assign(state_.size(), 1); 340 cover_.assign(state_.size(), 1);
339 targets_.push_back({begin_, end_, shadow}); 341 targets_.push_back({begin_, end_, shadow});
340 index_targets(); 342 index_targets();
@@ -511,6 +513,7 @@ public:
511 if (state_[i] & kZero) continue; 513 if (state_[i] & kZero) continue;
512 const auto [offset, bytes] = span_of(i, i + 1); 514 const auto [offset, bytes] = span_of(i, i + 1);
513 zero_targets(offset, bytes); 515 zero_targets(offset, bytes);
516 leonida::shadow_keep::forget(sums_.data(), first_, begin_ + offset, begin_ + offset + bytes);
514 if (!zeroed_.empty() && zeroed_.back().offset + zeroed_.back().bytes == offset) 517 if (!zeroed_.empty() && zeroed_.back().offset + zeroed_.back().bytes == offset)
515 zeroed_.back().bytes += bytes; 518 zeroed_.back().bytes += bytes;
516 else 519 else
@@ -564,12 +567,15 @@ public:
564 // The copies run without the lock: a write that faults meanwhile is let through and copied next time. 567 // The copies run without the lock: a write that faults meanwhile is let through and copied next time.
565 std::size_t copied = 0; 568 std::size_t copied = 0;
566 for (const Job& job : jobs_) 569 for (const Job& job : jobs_)
567 for_each_target(begin_ + job.offset, begin_ + job.offset + job.bytes, 570 if (keep_gpu_writes())
568 [&](const Target& t, std::uintptr_t from, std::uintptr_t to) { 571 copied += copy_changed(job);
569 copy_run(t.shadow + (from - t.begin), reinterpret_cast<const std::uint8_t*>(from), 572 else
570 to - from, job.streaming); 573 for_each_target(begin_ + job.offset, begin_ + job.offset + job.bytes,
571 copied += to - from; 574 [&](const Target& t, std::uintptr_t from, std::uintptr_t to) {
572 }); 575 copy_run(t.shadow + (from - t.begin), reinterpret_cast<const std::uint8_t*>(from),
576 to - from, job.streaming);
577 copied += to - from;
578 });
573 refresh_queries_ = queries; 579 refresh_queries_ = queries;
574 return copied; 580 return copied;
575 } 581 }
@@ -583,12 +589,14 @@ public:
583 const std::size_t n = (first_ - first) / kPage; 589 const std::size_t n = (first_ - first) / kPage;
584 state_.insert(state_.begin(), n, std::uint8_t(0)); 590 state_.insert(state_.begin(), n, std::uint8_t(0));
585 idle_.insert(idle_.begin(), n, std::uint8_t(0)); 591 idle_.insert(idle_.begin(), n, std::uint8_t(0));
592 sums_.insert(sums_.begin(), n * kPieces, std::uint64_t(0));
586 cover_.insert(cover_.begin(), n, 0u); 593 cover_.insert(cover_.begin(), n, 0u);
587 first_ = first; 594 first_ = first;
588 } 595 }
589 if (last > last_) { 596 if (last > last_) {
590 state_.resize((last - first_) / kPage, 0); 597 state_.resize((last - first_) / kPage, 0);
591 idle_.resize(state_.size(), 0); 598 idle_.resize(state_.size(), 0);
599 sums_.resize(state_.size() * kPieces, 0);
592 cover_.resize(state_.size(), 0); 600 cover_.resize(state_.size(), 0);
593 last_ = last; 601 last_ = last;
594 } 602 }
@@ -608,6 +616,8 @@ public:
608 state_[at + i] |= other.state_[i]; 616 state_[at + i] |= other.state_[i];
609 cover_[at + i] += other.cover_[i]; 617 cover_[at + i] += other.cover_[i];
610 idle_[at + i] = other.idle_[i]; 618 idle_[at + i] = other.idle_[i];
619 std::copy_n(other.sums_.begin() + std::ptrdiff_t(i * kPieces), kPieces,
620 sums_.begin() + std::ptrdiff_t((at + i) * kPieces));
611 } 621 }
612 targets_.insert(targets_.end(), other.targets_.begin(), other.targets_.end()); 622 targets_.insert(targets_.end(), other.targets_.begin(), other.targets_.end());
613 if (other.map_generation_ != map_generation_) map_generation_ = ~std::uint64_t(0); 623 if (other.map_generation_ != map_generation_) map_generation_ = ~std::uint64_t(0);
@@ -944,6 +954,40 @@ private:
944 jobs_.push_back({offset, bytes, streaming}); 954 jobs_.push_back({offset, bytes, streaming});
945 } 955 }
946 956
957 // LEONIDA_SHADOW_KEEP (on; 0: every job copied whole, as before): a job's bytes reach the copies only where they
958 // differ from those copied last (src/shadow_keep.h), so a shader's write into a copy of pages copied without a
959 // sign that the title wrote them stays until the title changes those bytes.
960 // shortcut: a title that rewrites the same bytes to reset a GPU-written value is not seen; needs a real write
961 // signal (a write-back to the title's pages) then.
962 static bool keep_gpu_writes() {
963 static const bool on = [] {
964 char value[2] = {};
965 std::size_t length = 0;
966 return getenv_s(&length, value, sizeof(value), "LEONIDA_SHADOW_KEEP") != 0 || length == 0 ||
967 value[0] != '0';
968 }();
969 return on;
970 }
971 static constexpr std::size_t kPieces = kPage / leonida::shadow_keep::kPiece;
972 std::size_t copy_changed(const Job& job) {
973 std::size_t copied = 0;
974 alignas(64) std::uint8_t page[kPage];
975 for (std::size_t at = job.offset, end = job.offset + job.bytes; at < end;) {
976 const std::uintptr_t va = begin_ + at;
977 const std::size_t n = std::min<std::size_t>(end - at, kPage - (va & (kPage - 1)));
978 copy_run(page, reinterpret_cast<const std::uint8_t*>(va), n, job.streaming);
979 leonida::shadow_keep::copy_changed(
980 page, va, n, sums_.data(), first_, [&](std::uintptr_t a, std::uintptr_t b, const std::uint8_t* source) {
981 for_each_target(a, b, [&](const Target& t, std::uintptr_t from, std::uintptr_t to) {
982 std::memcpy(t.shadow + (from - t.begin), source + (from - a), to - from);
983 copied += to - from;
984 });
985 });
986 at += n;
987 }
988 return copied;
989 }
990
947 // The targets sorted by start, the bytes they hold, and reach_[k], the furthest end among targets_[0..k]: the 991 // The targets sorted by start, the bytes they hold, and reach_[k], the furthest end among targets_[0..k]: the
948 // targets over [from, to) are found from the first whose reach passes `from`. 992 // targets over [from, to) are found from the first whose reach passes `from`.
949 void index_targets() { 993 void index_targets() {
@@ -1056,6 +1100,7 @@ private:
1056 std::uint64_t reader_ = 0; 1100 std::uint64_t reader_ = 0;
1057 std::size_t watched_pages_ = 0, hot_pages_ = 0; // covered pages write-watched, and hot 1101 std::size_t watched_pages_ = 0, hot_pages_ = 0; // covered pages write-watched, and hot
1058 Vector<std::uint8_t> idle_; // per 4 KiB page: refreshes a hot page went without a write (kCool) 1102 Vector<std::uint8_t> idle_; // per 4 KiB page: refreshes a hot page went without a write (kCool)
1103 Vector<std::uint64_t> sums_; // per 256-byte piece from first_: sum of the bytes copied last, 0: not known
1059 bool runs_stale_ = false; // a page became hot or cold: watch_runs_ is rebuilt at the next refresh 1104 bool runs_stale_ = false; // a page became hot or cold: watch_runs_ is rebuilt at the next refresh
1060 std::uint64_t refresh_asks_ = 0; 1105 std::uint64_t refresh_asks_ = 0;
1061 std::uint64_t refresh_written_ = 0; 1106 std::uint64_t refresh_written_ = 0;
diff --git a/runtime/src/shadow_keep.h b/runtime/src/shadow_keep.h
new file mode 100644
index 000000000..a59752b49
--- /dev/null
+++ b/runtime/src/shadow_keep.h
@@ -0,0 +1,72 @@
1// What a shadow copy of the title's pages keeps of the GPU's writes (LEONIDA_SHADOW_KEEP, shims/
2// d3d12_vulkan_device.cpp ShadowPages). Some pages are copied at every refresh without a sign that the title wrote
3// them (mapped at two addresses, unguarded, reopened with the 64 KiB block around a written page, write-watched or
4// pinned): copied whole, their unchanged bytes overwrote what a shader had stored in the copy since. Here the title's
5// bytes are compared, per 256-byte piece of the title's address space, with a 64-bit sum of those copied last, and
6// only a piece that differs is copied. Portable: no Windows headers, no Vulkan.
7#pragma once
8
9#include <algorithm>
10#include <cstddef>
11#include <cstdint>
12#include <cstring>
13
14namespace leonida::shadow_keep {
15
16inline constexpr std::size_t kPiece = 256;
17
18// The sum of `n` bytes, never 0 (0 is "not known": the piece is copied at its next look).
19// Four independent lanes over 32 bytes a step, so the multiplies do not wait on each other: about the speed of a
20// copy (one chained lane read about 3.6 GB/s on an RTX 5080 machine's CPU, a copy about 18 GB/s).
21inline std::uint64_t sum_of(const std::uint8_t* bytes, std::size_t n) {
22 constexpr std::uint64_t k = 0xff51afd7ed558ccdull;
23 const auto rotl = [](std::uint64_t x, int r) { return (x << r) | (x >> (64 - r)); };
24 std::uint64_t a0 = 0x9e3779b97f4a7c15ull ^ n, a1 = 0xc2b2ae3d27d4eb4full, a2 = 0x165667b19e3779f9ull,
25 a3 = 0x27d4eb2f165667c5ull;
26 std::size_t i = 0;
27 for (; i + 32 <= n; i += 32) {
28 std::uint64_t v[4];
29 std::memcpy(v, bytes + i, 32);
30 a0 = rotl(a0 ^ v[0], 31) * k;
31 a1 = rotl(a1 ^ v[1], 31) * k;
32 a2 = rotl(a2 ^ v[2], 31) * k;
33 a3 = rotl(a3 ^ v[3], 31) * k;
34 }
35 for (; i < n; i += 8) {
36 std::uint64_t v = 0;
37 std::memcpy(&v, bytes + i, n - i < 8 ? n - i : 8);
38 a0 = rotl(a0 ^ v, 31) * k;
39 }
40 std::uint64_t h = a0 ^ rotl(a1, 17) ^ rotl(a2, 29) ^ rotl(a3, 47);
41 h ^= h >> 33;
42 h *= 0xc4ceb9fe1a85ec53ull;
43 h ^= h >> 29;
44 return h | 1; // 0: not known
45}
46
47// `bytes` holds the title's bytes [va, va + n) as read now. sums[k] is the sum of the piece at base + k * kPiece
48// (base kPiece-aligned) as last copied. Each piece, cut at kPiece boundaries of the address (the first and last may be
49// partial), whose bytes differ from its sum takes the new sum and is handed to copy(from, to, source).
50template <class Copy>
51void copy_changed(const std::uint8_t* bytes, std::uintptr_t va, std::size_t n, std::uint64_t* sums,
52 std::uintptr_t base, Copy&& copy) {
53 for (std::size_t off = 0; off < n;) {
54 const std::size_t piece = std::min<std::size_t>(n - off, kPiece - ((va + off) & (kPiece - 1)));
55 std::uint64_t& known = sums[(va + off - base) / kPiece];
56 const std::uint64_t sum = sum_of(bytes + off, piece);
57 if (sum != known) {
58 known = sum;
59 copy(va + off, va + off + piece, bytes + off);
60 }
61 off += piece;
62 }
63}
64
65// The pieces over [from, to) are not known any more (the copies were changed another way, as zeroed): each is copied
66// at its next look.
67inline void forget(std::uint64_t* sums, std::uintptr_t base, std::uintptr_t from, std::uintptr_t to) {
68 if (from >= to) return;
69 std::fill(sums + (from - base) / kPiece, sums + (to - base + kPiece - 1) / kPiece, std::uint64_t(0));
70}
71
72} // namespace leonida::shadow_keep
diff --git a/runtime/test/shadow_keep_test.cpp b/runtime/test/shadow_keep_test.cpp
new file mode 100644
index 000000000..87960c0a2
--- /dev/null
+++ b/runtime/test/shadow_keep_test.cpp
@@ -0,0 +1,141 @@
1// src/shadow_keep.h: a shadow copy keeps a GPU write until the title's bytes under it change. No Windows headers, no
2// GPU, no game data: the "title" and its "copy" are arrays here, and the values are made up.
3#include "../src/shadow_keep.h"
4
5#include <cstdint>
6#include <cstdio>
7#include <cstring>
8#include <utility>
9#include <vector>
10
11namespace {
12
13int failures = 0;
14#define EXPECT(condition) \
15 do { \
16 if (!(condition)) { \
17 std::fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #condition); \
18 ++failures; \
19 } \
20 } while (0)
21
22using leonida::shadow_keep::kPiece;
23
24// A title range and its copy, as ShadowPages has them: the copy of the title byte at address a is copy[a - base].
25struct Pages {
26 static constexpr std::uintptr_t base = 0x10000; // kPiece-aligned, like a tracker's first page
27 std::vector<std::uint8_t> title, copy;
28 std::vector<std::uint64_t> sums;
29 std::vector<std::pair<std::uintptr_t, std::uintptr_t>> copied; // the ranges the last refresh copied
30
31 explicit Pages(std::size_t bytes) : title(bytes), copy(bytes), sums(bytes / kPiece) {
32 for (std::size_t i = 0; i < bytes; ++i) title[i] = std::uint8_t(i * 7 + 3);
33 }
34 // A refresh of [va, va + n): what ShadowPages::copy_changed does for one page.
35 std::size_t refresh(std::uintptr_t va, std::size_t n) {
36 copied.clear();
37 std::size_t bytes = 0;
38 leonida::shadow_keep::copy_changed(
39 title.data() + (va - base), va, n, sums.data(), base,
40 [&](std::uintptr_t from, std::uintptr_t to, const std::uint8_t* source) {
41 std::memcpy(copy.data() + (from - base), source, to - from);
42 copied.emplace_back(from, to);
43 bytes += to - from;
44 });
45 return bytes;
46 }
47 std::size_t refresh() { return refresh(base, title.size()); }
48 bool same(std::size_t from, std::size_t to) const {
49 return !std::memcmp(title.data() + from, copy.data() + from, to - from);
50 }
51};
52
53void unchanged_title_keeps_gpu_write() {
54 Pages p(4096);
55 EXPECT(p.refresh() == 4096); // nothing known yet: all of it
56 EXPECT(p.same(0, 4096));
57 EXPECT(p.refresh() == 0); // nothing changed
58 // A shader stores 16 bytes in the copy; the title's bytes there stay as they were.
59 const std::uint8_t gpu[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
60 std::memcpy(p.copy.data() + 0x340, gpu, sizeof(gpu));
61 EXPECT(p.refresh() == 0);
62 EXPECT(!std::memcmp(p.copy.data() + 0x340, gpu, sizeof(gpu))); // kept: the old code overwrote it here
63 EXPECT(p.same(0, 0x340) && p.same(0x350, 4096));
64}
65
66void changed_title_piece_is_copied() {
67 Pages p(4096);
68 p.refresh();
69 const std::uint8_t gpu[16] = {0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA,
70 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA};
71 std::memcpy(p.copy.data() + 0x340, gpu, sizeof(gpu)); // GPU write in piece 3
72 std::memcpy(p.copy.data() + 0x800, gpu, sizeof(gpu)); // and in piece 8
73 p.title[0x810] ^= 0x5A; // the title writes piece 8
74 EXPECT(p.refresh() == kPiece);
75 EXPECT(p.copied.size() == 1 && p.copied[0].first == Pages::base + 0x800 &&
76 p.copied[0].second == Pages::base + 0x900);
77 EXPECT(p.same(0x800, 0x900)); // the title's new bytes win there
78 EXPECT(!std::memcmp(p.copy.data() + 0x340, gpu, sizeof(gpu))); // the other GPU write stays
79 EXPECT(p.refresh() == 0);
80}
81
82void partial_first_and_last_pieces() {
83 Pages p(4096);
84 // A target that starts and ends inside pieces: [base + 100, base + 1000).
85 const std::uintptr_t va = Pages::base + 100;
86 const std::size_t n = 900;
87 EXPECT(p.refresh(va, n) == n);
88 EXPECT(p.copied.size() == 4);
89 EXPECT(p.copied.front().first == va && p.copied.front().second == Pages::base + kPiece);
90 EXPECT(p.copied.back().first == Pages::base + 3 * kPiece && p.copied.back().second == va + n);
91 EXPECT(p.same(100, 1000));
92 EXPECT(p.copy[99] == 0 && p.copy[1000] == 0); // nothing outside the range
93 EXPECT(p.refresh(va, n) == 0);
94 p.title[999] ^= 1; // last byte of the last, partial piece
95 EXPECT(p.refresh(va, n) == 1000 - 3 * kPiece);
96 p.title[100] ^= 1; // first byte of the first, partial piece
97 EXPECT(p.refresh(va, n) == kPiece - 100);
98 EXPECT(p.same(100, 1000));
99}
100
101void forgotten_sums_copy_once() {
102 Pages p(4096);
103 p.refresh();
104 // The pages were not committed for a refresh: the copies were zeroed and their sums forgotten.
105 std::memset(p.copy.data() + 0x400, 0, 0x200);
106 leonida::shadow_keep::forget(p.sums.data(), Pages::base, Pages::base + 0x400, Pages::base + 0x600);
107 EXPECT(p.refresh() == 0x200); // the same title bytes back: copied once all the same
108 EXPECT(p.same(0, 4096));
109 EXPECT(p.refresh() == 0);
110 // A partial range forgets every piece it touches.
111 leonida::shadow_keep::forget(p.sums.data(), Pages::base, Pages::base + 0x410, Pages::base + 0x501);
112 EXPECT(p.refresh() == 0x200);
113}
114
115void sums_tell_bytes_apart() {
116 std::uint8_t a[kPiece] = {}, b[kPiece] = {};
117 EXPECT(leonida::shadow_keep::sum_of(a, kPiece) != 0);
118 EXPECT(leonida::shadow_keep::sum_of(a, kPiece) == leonida::shadow_keep::sum_of(b, kPiece));
119 for (std::size_t i = 0; i < kPiece; ++i) {
120 b[i] = 1;
121 EXPECT(leonida::shadow_keep::sum_of(a, kPiece) != leonida::shadow_keep::sum_of(b, kPiece));
122 b[i] = 0;
123 }
124 EXPECT(leonida::shadow_keep::sum_of(a, 16) != leonida::shadow_keep::sum_of(a, 17)); // the length counts
125}
126
127} // namespace
128
129int main() {
130 unchanged_title_keeps_gpu_write();
131 changed_title_piece_is_copied();
132 partial_first_and_last_pieces();
133 forgotten_sums_copy_once();
134 sums_tell_bytes_apart();
135 if (failures) {
136 std::fprintf(stderr, "shadow_keep: %d check(s) failed\n", failures);
137 return 1;
138 }
139 std::puts("shadow_keep: OK");
140 return 0;
141}