diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 22515184a0..7abd1e0649 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1756,6 +1756,15 @@ The copies: write-fault handler waits for the trackers' locks while the faulting thread may hold the process heap's lock (the title's `XMemAlloc` blocks are `_aligned_malloc`'s), so the state changed under those locks allocates from a heap of the runtime's own (`leonida::host_heap`), never the process heap. +- **What the GPU wrote into a copy stays** until the title changes the bytes under it. Some pages are copied at + every refresh without a sign that the title wrote them (mapped at two addresses, left writable, reopened with the + 64 KiB around a written page, write-watched or pinned); copied whole, they overwrote a value a compute program had + stored in the copy for the next frame with the title's unchanged bytes, so it read back as the title's old value + every other frame. `ShadowPages` 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; a piece zeroed because its page + went away is copied again in full once it comes back. Limit: a title that writes the same bytes again to reset a + value the GPU changed is not seen (that needs the GPU's writes to reach the title's pages). `LEONIDA_SHADOW_KEEP=0` + copies every page as before. - **Only the title's memory** gets a copy: the blocks and ranges the xmem shims hand the title (`XMemAlloc`, `XMemAllocDefault`, `XMemVirtualAlloc`, the title's `VirtualAlloc`). An address anywhere else, the runtime's or a host DLL's memory included, is left as it was and counted, as is an arena VA or a buffer the layer made. diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index f037b2326c..ddf3681a28 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -3907,6 +3907,12 @@ if(TARGET Vulkan::Headers) # The same return copy for a slot-133 buffer's shadow (the write-back of a compute result the title reads again). add_test(NAME d3d12_placed_write_back COMMAND d3d12_title_va_test --placed-writeback) set_tests_properties(d3d12_placed_write_back PROPERTIES SKIP_RETURN_CODE 77) + # Two shadows over one page share their sums: a newly filled one must still follow the title's bytes, with + # LEONIDA_SHADOW_KEEP on and off (review by lixonik). + add_test(NAME d3d12_shadow_keep_refill COMMAND d3d12_title_va_test --shadow-keep-refill) + set_tests_properties(d3d12_shadow_keep_refill PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_SHADOW_KEEP=1") + add_test(NAME d3d12_shadow_keep_refill_off COMMAND d3d12_title_va_test --shadow-keep-refill) + set_tests_properties(d3d12_shadow_keep_refill_off PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_SHADOW_KEEP=0") add_test(NAME d3d12_api_descriptor_copy COMMAND d3d12_title_va_test --api-descriptor-copy) set_tests_properties(d3d12_api_descriptor_copy PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_DESC_MIRROR=1") add_test(NAME d3d12_api_descriptor_copy_off COMMAND d3d12_title_va_test --api-descriptor-copy-off) @@ -4684,6 +4690,12 @@ if(TARGET Vulkan::Headers) target_compile_options(console_heap_vsharp_slots_test PRIVATE /W4 /permissive- /utf-8) endif() add_test(NAME console_heap_vsharp_slots COMMAND console_heap_vsharp_slots_test) + # A slot-133 shadow keeps a GPU write until the title's bytes under it change (src/shadow_keep.h). + add_executable(shadow_keep_test test/shadow_keep_test.cpp) + if(WIN32 AND MSVC) + target_compile_options(shadow_keep_test PRIVATE /W4 /permissive- /utf-8) + endif() + add_test(NAME shadow_keep COMMAND shadow_keep_test) # Queue construction cleans its Vulkan handles if holder registration runs out of host memory. add_executable(vk_host_texture_order_test test/vk_host_texture_order_test.cpp) 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 7f02f41e05..e3b430416e 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -379,6 +379,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `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. | | `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. | | `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. | +| `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. | | `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. | | `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. | | `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 93f92a132c..16b814589e 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -57,6 +57,7 @@ #include "../src/resource_detile.h" #include "../src/console_texture_layout.h" #include "../src/shader_library.h" +#include "../src/shadow_keep.h" #include "../src/dstorage_trace.h" #include "../src/title_page_watch.h" #include "../src/guarded_copy.h" @@ -378,6 +379,7 @@ class ShadowPages { last_ = (end_ + kPage - 1) & ~(kPage - 1); state_.assign((last_ - first_) / kPage, 0); idle_.assign(state_.size(), 0); + sums_.assign(state_.size() * kPieces, 0); cover_.assign(state_.size(), 1); targets_.push_back({begin_, end_, shadow}); index_targets(); @@ -593,6 +595,7 @@ class ShadowPages { if (state_[i] & kZero) continue; const auto [offset, bytes] = span_of(i, i + 1); zero_targets(offset, bytes); + leonida::shadow_keep::forget(sums_.data(), first_, begin_ + offset, begin_ + offset + bytes); if (!zeroed_.empty() && zeroed_.back().offset + zeroed_.back().bytes == offset) zeroed_.back().bytes += bytes; else @@ -660,6 +663,10 @@ class ShadowPages { pieces_.walk_ms = std::chrono::duration(copy_start - walk_start).count(); std::size_t copied = 0; for (const Job& job : jobs_) { + if (keep_gpu_writes()) { // only the pieces whose title bytes changed (src/shadow_keep.h) + copied += copy_changed(job); + continue; + } std::uint8_t* run_dst = nullptr; const std::uint8_t* run_src = nullptr; std::size_t run_bytes = 0; @@ -710,12 +717,14 @@ class ShadowPages { const std::size_t n = (first_ - first) / kPage; state_.insert(state_.begin(), n, std::uint8_t(0)); idle_.insert(idle_.begin(), n, std::uint8_t(0)); + sums_.insert(sums_.begin(), n * kPieces, std::uint64_t(0)); cover_.insert(cover_.begin(), n, 0u); first_ = first; } if (last > last_) { state_.resize((last - first_) / kPage, 0); idle_.resize(state_.size(), 0); + sums_.resize(state_.size() * kPieces, 0); cover_.resize(state_.size(), 0); last_ = last; } @@ -735,6 +744,8 @@ class ShadowPages { state_[at + i] |= other.state_[i]; cover_[at + i] += other.cover_[i]; idle_[at + i] = other.idle_[i]; + std::copy_n(other.sums_.begin() + std::ptrdiff_t(i * kPieces), kPieces, + sums_.begin() + std::ptrdiff_t((at + i) * kPieces)); } targets_.insert(targets_.end(), other.targets_.begin(), other.targets_.end()); if (other.map_generation_ != map_generation_) map_generation_ = ~std::uint64_t(0); @@ -779,15 +790,42 @@ class ShadowPages { kind = classify(region); } const std::uintptr_t from = std::max(at, begin), to = std::min(next, end); - if (kind == Kind::zero) + if (kind == Kind::zero) { std::memset(shadow + (from - begin), 0, to - from); - else - copy_run(shadow + (from - begin), reinterpret_cast(from), to - from, - (region.Protect & PAGE_WRITECOMBINE) != 0); + } else { + const bool streaming = (region.Protect & PAGE_WRITECOMBINE) != 0; + copy_run(shadow + (from - begin), reinterpret_cast(from), to - from, streaming); + // The sums stand for what every target holds. The new target now holds the title's current bytes, so + // the pieces where those differ from the sums are brought to the other targets too, and the sums + // follow; otherwise a title that later writes the old bytes back would leave the new target behind. + // Whole pieces (inside this page, so this region) up to the targets' ends, as a refresh sums them: a + // piece cut at the new target's edge would be summed short and copied again at the next refresh. + constexpr std::uintptr_t kPiece = leonida::shadow_keep::kPiece; + if (keep_gpu_writes()) + reconcile(std::max(from & ~(kPiece - 1), begin_), std::min((to + kPiece - 1) & ~(kPiece - 1), end_), + streaming); + } at = next; } } + // [from, to), readable title pages: the pieces whose bytes differ from the sums are copied to every target over + // them and their sums updated, as a refresh does. + void reconcile(std::uintptr_t from, std::uintptr_t to, bool streaming) { + alignas(64) std::uint8_t page[kPage]; + for (std::uintptr_t va = from; va < to;) { + const std::size_t n = std::min(to - va, kPage - (va & (kPage - 1))); + copy_run(page, reinterpret_cast(va), n, streaming); + leonida::shadow_keep::copy_changed( + page, va, n, sums_.data(), first_, [&](std::uintptr_t a, std::uintptr_t b, const std::uint8_t* source) { + for_each_target(a, b, [&](const Target& t, std::uintptr_t lo, std::uintptr_t hi) { + std::memcpy(t.shadow + (lo - t.begin), source + (lo - a), hi - lo); + }); + }); + va += n; + } + } + // Under shadow_mutex: `shadow` is no longer a target. Pages no other target covers are made writable again and // passed over from now on. False when it isn't one of this tracker's. bool remove_target(const std::uint8_t* shadow) { @@ -1082,6 +1120,40 @@ class ShadowPages { jobs_.push_back({offset, bytes, streaming, aliased}); } + // LEONIDA_SHADOW_KEEP (on; 0: every job copied whole, as before): a job's bytes reach the copies only where they + // differ from those copied last (src/shadow_keep.h), so a shader's write into a copy of pages copied without a + // sign that the title wrote them stays until the title changes those bytes. + // shortcut: a title that rewrites the same bytes to reset a GPU-written value is not seen; needs a real write + // signal (a write-back to the title's pages) then. + static bool keep_gpu_writes() { + static const bool on = [] { + char value[2] = {}; + std::size_t length = 0; + return getenv_s(&length, value, sizeof(value), "LEONIDA_SHADOW_KEEP") != 0 || length == 0 || + value[0] != '0'; + }(); + return on; + } + static constexpr std::size_t kPieces = kPage / leonida::shadow_keep::kPiece; + std::size_t copy_changed(const Job& job) { + std::size_t copied = 0; + alignas(64) std::uint8_t page[kPage]; + for (std::size_t at = job.offset, end = job.offset + job.bytes; at < end;) { + const std::uintptr_t va = begin_ + at; + const std::size_t n = std::min(end - at, kPage - (va & (kPage - 1))); + copy_run(page, reinterpret_cast(va), n, job.streaming); + leonida::shadow_keep::copy_changed( + page, va, n, sums_.data(), first_, [&](std::uintptr_t a, std::uintptr_t b, const std::uint8_t* source) { + for_each_target(a, b, [&](const Target& t, std::uintptr_t from, std::uintptr_t to) { + std::memcpy(t.shadow + (from - t.begin), source + (from - a), to - from); + copied += to - from; + }); + }); + at += n; + } + return copied; + } + // The targets sorted by start, the bytes they hold, and reach_[k], the furthest end among targets_[0..k]: the // targets over [from, to) are found from the first whose reach passes `from`. void index_targets() { @@ -1208,6 +1280,7 @@ class ShadowPages { std::uint64_t reader_ = 0; std::size_t watched_pages_ = 0, hot_pages_ = 0; // covered pages write-watched, and hot Vector idle_; // per 4 KiB page: refreshes a hot page went without a write (kCool) + Vector sums_; // per 256-byte piece from first_: sum of the bytes copied last, 0: not known bool runs_stale_ = false; // a page became hot or cold: watch_runs_ is rebuilt at the next refresh std::uint64_t refresh_asks_ = 0; 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 0000000000..a59752b494 --- /dev/null +++ b/runtime/src/shadow_keep.h @@ -0,0 +1,72 @@ +// What a shadow copy of the title's pages keeps of the GPU's writes (LEONIDA_SHADOW_KEEP, shims/ +// d3d12_vulkan_device.cpp ShadowPages). Some pages are copied at every refresh without a sign that the title wrote +// them (mapped at two addresses, unguarded, reopened with the 64 KiB block around a written page, write-watched or +// pinned): copied whole, their unchanged bytes overwrote what a shader had stored in the copy since. Here the title's +// bytes are compared, per 256-byte piece of the title's address space, with a 64-bit sum of those copied last, and +// only a piece that differs is copied. Portable: no Windows headers, no Vulkan. +#pragma once + +#include +#include +#include +#include + +namespace leonida::shadow_keep { + +inline constexpr std::size_t kPiece = 256; + +// The sum of `n` bytes, never 0 (0 is "not known": the piece is copied at its next look). +// Four independent lanes over 32 bytes a step, so the multiplies do not wait on each other: about the speed of a +// copy (one chained lane read about 3.6 GB/s on an RTX 5080 machine's CPU, a copy about 18 GB/s). +inline std::uint64_t sum_of(const std::uint8_t* bytes, std::size_t n) { + constexpr std::uint64_t k = 0xff51afd7ed558ccdull; + const auto rotl = [](std::uint64_t x, int r) { return (x << r) | (x >> (64 - r)); }; + std::uint64_t a0 = 0x9e3779b97f4a7c15ull ^ n, a1 = 0xc2b2ae3d27d4eb4full, a2 = 0x165667b19e3779f9ull, + a3 = 0x27d4eb2f165667c5ull; + std::size_t i = 0; + for (; i + 32 <= n; i += 32) { + std::uint64_t v[4]; + std::memcpy(v, bytes + i, 32); + a0 = rotl(a0 ^ v[0], 31) * k; + a1 = rotl(a1 ^ v[1], 31) * k; + a2 = rotl(a2 ^ v[2], 31) * k; + a3 = rotl(a3 ^ v[3], 31) * k; + } + for (; i < n; i += 8) { + std::uint64_t v = 0; + std::memcpy(&v, bytes + i, n - i < 8 ? n - i : 8); + a0 = rotl(a0 ^ v, 31) * k; + } + std::uint64_t h = a0 ^ rotl(a1, 17) ^ rotl(a2, 29) ^ rotl(a3, 47); + h ^= h >> 33; + h *= 0xc4ceb9fe1a85ec53ull; + h ^= h >> 29; + return h | 1; // 0: not known +} + +// `bytes` holds the title's bytes [va, va + n) as read now. sums[k] is the sum of the piece at base + k * kPiece +// (base kPiece-aligned) as last copied. Each piece, cut at kPiece boundaries of the address (the first and last may be +// partial), whose bytes differ from its sum takes the new sum and is handed to copy(from, to, source). +template +void copy_changed(const std::uint8_t* bytes, std::uintptr_t va, std::size_t n, std::uint64_t* sums, + std::uintptr_t base, Copy&& copy) { + for (std::size_t off = 0; off < n;) { + const std::size_t piece = std::min(n - off, kPiece - ((va + off) & (kPiece - 1))); + std::uint64_t& known = sums[(va + off - base) / kPiece]; + const std::uint64_t sum = sum_of(bytes + off, piece); + if (sum != known) { + known = sum; + copy(va + off, va + off + piece, bytes + off); + } + off += piece; + } +} + +// The pieces over [from, to) are not known any more (the copies were changed another way, as zeroed): each is copied +// at its next look. +inline void forget(std::uint64_t* sums, std::uintptr_t base, std::uintptr_t from, std::uintptr_t to) { + if (from >= to) return; + std::fill(sums + (from - base) / kPiece, sums + (to - base + kPiece - 1) / kPiece, std::uint64_t(0)); +} + +} // namespace leonida::shadow_keep diff --git a/runtime/test/d3d12_title_va_test.cpp b/runtime/test/d3d12_title_va_test.cpp index bf0f14f1ea..90eddc66a6 100644 --- a/runtime/test/d3d12_title_va_test.cpp +++ b/runtime/test/d3d12_title_va_test.cpp @@ -1165,6 +1165,59 @@ int check_rebound_tables(Context& c, ID3D12RootSignature* narrow, bool mirror, b return 0; } +// Two slot-133 shadows over the same title page share one tracker and its sums (LEONIDA_SHADOW_KEEP, src/ +// shadow_keep.h). A is copied with the title's byte at 1; the byte becomes 2 and B is made over the page, so B's first +// copy holds 2; the byte goes back to 1 and a submission refreshes both. Both copies must hold 1, with the flag on or +// off: B's first copy brings its pieces to the sums, or the sums still read 1 and B keeps 2 (found by lixonik). +int check_shadow_keep_refill(Context& c) { + constexpr UINT64 kPage = 4096, kAt = 16; // the byte: page 1 of A, page 0 of B + auto* pages = static_cast( + VirtualAlloc(nullptr, kPages, MEM_TOP_DOWN | MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + EXPECT(pages); + pages[kPage + kAt] = 1; + const D3D12_RESOURCE_DESC desc = buffer_desc(2 * kPage); + Ref a, b, readback; + EXPECT(SUCCEEDED(rt::d3d12::create_buffer_at_host_address(c.inner, pages, desc, 0xFFFFFFFFu, + IID_PPV_ARGS(&a.p)))); + EXPECT(rt::d3d12::title_shadow_buffer(a.p)); + pages[kPage + kAt] = 2; + EXPECT(SUCCEEDED(rt::d3d12::create_buffer_at_host_address(c.inner, pages + kPage, desc, 0xFFFFFFFFu, + IID_PPV_ARGS(&b.p)))); + EXPECT(rt::d3d12::title_shadow_buffer(b.p)); + pages[kPage + kAt] = 1; + + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + const auto readback_desc = buffer_desc(2 * kBytes); + EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + Ref allocator; + Ref list; + EXPECT(SUCCEEDED(c.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(c.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list.p)))); + list->CopyBufferRegion(readback.p, 0, a.p, kPage, kBytes); + list->CopyBufferRegion(readback.p, kBytes, b.p, 0, kBytes); + EXPECT(list->Close() == S_OK); + ID3D12CommandList* lists[] = {list.p}; + c.queue->ExecuteCommandLists(1, lists); // the refresh, then the copies + EXPECT(rt::d3d12::last_execute_result(c.queue) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(c.queue->Signal(c.fence, ++c.fence_value))); + EXPECT(SUCCEEDED(c.fence->SetEventOnCompletion(c.fence_value, nullptr))); + void* mapped = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + const std::uint8_t got_a = static_cast(mapped)[kAt]; + const std::uint8_t got_b = static_cast(mapped)[kBytes + kAt]; + readback->Unmap(0, nullptr); + std::printf("shadow keep refill: A holds %u, B holds %u (the title's byte is 1)\n", got_a, got_b); + EXPECT(got_a == 1); + EXPECT(got_b == 1); + a.reset(); + b.reset(); + VirtualFree(pages, 0, MEM_RELEASE); + return 0; +} + } // namespace int main(int argc, char** argv) { @@ -1176,6 +1229,7 @@ int main(int argc, char** argv) { const bool window_cap = argc == 2 && std::strcmp(argv[1], "--window-cap") == 0; const bool window_write_back = argc == 2 && std::strcmp(argv[1], "--window-writeback") == 0; const bool placed_write_back = argc == 2 && std::strcmp(argv[1], "--placed-writeback") == 0; + const bool keep_refill = argc == 2 && std::strcmp(argv[1], "--shadow-keep-refill") == 0; if (window_cap) { const char* cap = std::getenv("LEONIDA_TITLE_WINDOWS_MB"); if (!cap || std::strcmp(cap, "0")) { @@ -1299,6 +1353,14 @@ int main(int argc, char** argv) { std::printf("title-placed buffer write back: the GPU's writes reached the title's pages\n"); return 0; } + if (keep_refill) { + if (check_shadow_keep_refill(c)) return 1; + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + return 0; + } if (window_write_back) { if (check_window_write_back(c, geometry)) return 1; if (d.validation_errors()) { diff --git a/runtime/test/shadow_keep_test.cpp b/runtime/test/shadow_keep_test.cpp new file mode 100644 index 0000000000..87960c0a29 --- /dev/null +++ b/runtime/test/shadow_keep_test.cpp @@ -0,0 +1,141 @@ +// src/shadow_keep.h: a shadow copy keeps a GPU write until the title's bytes under it change. No Windows headers, no +// GPU, no game data: the "title" and its "copy" are arrays here, and the values are made up. +#include "../src/shadow_keep.h" + +#include +#include +#include +#include +#include + +namespace { + +int failures = 0; +#define EXPECT(condition) \ + do { \ + if (!(condition)) { \ + std::fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #condition); \ + ++failures; \ + } \ + } while (0) + +using leonida::shadow_keep::kPiece; + +// A title range and its copy, as ShadowPages has them: the copy of the title byte at address a is copy[a - base]. +struct Pages { + static constexpr std::uintptr_t base = 0x10000; // kPiece-aligned, like a tracker's first page + std::vector title, copy; + std::vector sums; + std::vector> copied; // the ranges the last refresh copied + + explicit Pages(std::size_t bytes) : title(bytes), copy(bytes), sums(bytes / kPiece) { + for (std::size_t i = 0; i < bytes; ++i) title[i] = std::uint8_t(i * 7 + 3); + } + // A refresh of [va, va + n): what ShadowPages::copy_changed does for one page. + std::size_t refresh(std::uintptr_t va, std::size_t n) { + copied.clear(); + std::size_t bytes = 0; + leonida::shadow_keep::copy_changed( + title.data() + (va - base), va, n, sums.data(), base, + [&](std::uintptr_t from, std::uintptr_t to, const std::uint8_t* source) { + std::memcpy(copy.data() + (from - base), source, to - from); + copied.emplace_back(from, to); + bytes += to - from; + }); + return bytes; + } + std::size_t refresh() { return refresh(base, title.size()); } + bool same(std::size_t from, std::size_t to) const { + return !std::memcmp(title.data() + from, copy.data() + from, to - from); + } +}; + +void unchanged_title_keeps_gpu_write() { + Pages p(4096); + EXPECT(p.refresh() == 4096); // nothing known yet: all of it + EXPECT(p.same(0, 4096)); + EXPECT(p.refresh() == 0); // nothing changed + // A shader stores 16 bytes in the copy; the title's bytes there stay as they were. + const std::uint8_t gpu[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; + std::memcpy(p.copy.data() + 0x340, gpu, sizeof(gpu)); + EXPECT(p.refresh() == 0); + EXPECT(!std::memcmp(p.copy.data() + 0x340, gpu, sizeof(gpu))); // kept: the old code overwrote it here + EXPECT(p.same(0, 0x340) && p.same(0x350, 4096)); +} + +void changed_title_piece_is_copied() { + Pages p(4096); + p.refresh(); + const std::uint8_t gpu[16] = {0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, + 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA}; + std::memcpy(p.copy.data() + 0x340, gpu, sizeof(gpu)); // GPU write in piece 3 + std::memcpy(p.copy.data() + 0x800, gpu, sizeof(gpu)); // and in piece 8 + p.title[0x810] ^= 0x5A; // the title writes piece 8 + EXPECT(p.refresh() == kPiece); + EXPECT(p.copied.size() == 1 && p.copied[0].first == Pages::base + 0x800 && + p.copied[0].second == Pages::base + 0x900); + EXPECT(p.same(0x800, 0x900)); // the title's new bytes win there + EXPECT(!std::memcmp(p.copy.data() + 0x340, gpu, sizeof(gpu))); // the other GPU write stays + EXPECT(p.refresh() == 0); +} + +void partial_first_and_last_pieces() { + Pages p(4096); + // A target that starts and ends inside pieces: [base + 100, base + 1000). + const std::uintptr_t va = Pages::base + 100; + const std::size_t n = 900; + EXPECT(p.refresh(va, n) == n); + EXPECT(p.copied.size() == 4); + EXPECT(p.copied.front().first == va && p.copied.front().second == Pages::base + kPiece); + EXPECT(p.copied.back().first == Pages::base + 3 * kPiece && p.copied.back().second == va + n); + EXPECT(p.same(100, 1000)); + EXPECT(p.copy[99] == 0 && p.copy[1000] == 0); // nothing outside the range + EXPECT(p.refresh(va, n) == 0); + p.title[999] ^= 1; // last byte of the last, partial piece + EXPECT(p.refresh(va, n) == 1000 - 3 * kPiece); + p.title[100] ^= 1; // first byte of the first, partial piece + EXPECT(p.refresh(va, n) == kPiece - 100); + EXPECT(p.same(100, 1000)); +} + +void forgotten_sums_copy_once() { + Pages p(4096); + p.refresh(); + // The pages were not committed for a refresh: the copies were zeroed and their sums forgotten. + std::memset(p.copy.data() + 0x400, 0, 0x200); + leonida::shadow_keep::forget(p.sums.data(), Pages::base, Pages::base + 0x400, Pages::base + 0x600); + EXPECT(p.refresh() == 0x200); // the same title bytes back: copied once all the same + EXPECT(p.same(0, 4096)); + EXPECT(p.refresh() == 0); + // A partial range forgets every piece it touches. + leonida::shadow_keep::forget(p.sums.data(), Pages::base, Pages::base + 0x410, Pages::base + 0x501); + EXPECT(p.refresh() == 0x200); +} + +void sums_tell_bytes_apart() { + std::uint8_t a[kPiece] = {}, b[kPiece] = {}; + EXPECT(leonida::shadow_keep::sum_of(a, kPiece) != 0); + EXPECT(leonida::shadow_keep::sum_of(a, kPiece) == leonida::shadow_keep::sum_of(b, kPiece)); + for (std::size_t i = 0; i < kPiece; ++i) { + b[i] = 1; + EXPECT(leonida::shadow_keep::sum_of(a, kPiece) != leonida::shadow_keep::sum_of(b, kPiece)); + b[i] = 0; + } + EXPECT(leonida::shadow_keep::sum_of(a, 16) != leonida::shadow_keep::sum_of(a, 17)); // the length counts +} + +} // namespace + +int main() { + unchanged_title_keeps_gpu_write(); + changed_title_piece_is_copied(); + partial_first_and_last_pieces(); + forgotten_sums_copy_once(); + sums_tell_bytes_apart(); + if (failures) { + std::fprintf(stderr, "shadow_keep: %d check(s) failed\n", failures); + return 1; + } + std::puts("shadow_keep: OK"); + return 0; +}