diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index d2681ad6c4..e707b1abea 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -10127,6 +10127,14 @@ struct TitleTexture { std::uint64_t full_hash = 0; bool full_hashed = false; bool every_byte() const { return mapped && layout.layout.size <= (4u << 20); } + bool rolling_hash() const { return mapped && !every_byte(); } + leonida::TitleTextureChunkHashes chunk_hashes; + std::uint64_t source_revision = 0; // Map, written Unmap or a replacement texture layout + void layout_changed() { + ++source_revision; + hashed = false; + chunk_hashes = {}; + } std::uint64_t fills = 0; }; @@ -10163,6 +10171,7 @@ void DeviceState::title_texture_mapped(const void* resource, std::uint64_t addre if (it == title_textures.end() || it->second->resource != resource) return; TitleTexture& t = *it->second; t.mapped = true; + ++t.source_revision; t.memory.retry(); // The title computes the layout of what it writes right before it maps: take it when no view gave one. if (!t.gpu_written && (t.layout_guessed || !t.layout_known) && @@ -10170,7 +10179,7 @@ void DeviceState::title_texture_mapped(const void* resource, std::uint64_t addre t.layout_known = true; t.layout_guessed = false; t.layout_from_xg = true; - t.hashed = false; + t.layout_changed(); } static std::atomic logged{0}; if (logged.fetch_add(1, std::memory_order_relaxed) < 48) { @@ -10196,6 +10205,7 @@ void DeviceState::title_texture_unmapped(const void* resource, std::uint64_t add std::lock_guard lock(title_texture_mutex); const auto it = title_textures.find(address); if (it != title_textures.end() && it->second->resource == resource) { + ++it->second->source_revision; it->second->stale = true; it->second->memory.retry(); } @@ -11938,6 +11948,8 @@ class Device final const auto entries = leonida::title_texture_snapshot(state_.title_textures); title_pass_ = true; std::uint64_t checked = 0, filled = 0, fill_pass_ns = 0; + TitleTexture* first_rolling = nullptr; + TitleTexture* next_rolling = nullptr; const auto visit = [&](TitleTexture& t) { // A slot-133 texture's guessed layout (no slot-70 view yet) is only used once the title maps it. if (t.gpu_written || !t.layout_known || !t.resource || @@ -11970,7 +11982,14 @@ class Device final t.memory.defer(); return; } - if (t.hashed && hash == t.hash && !t.stale) { + const bool rolling = t.rolling_hash(); + if (t.hashed && hash == t.hash && !t.stale && (!rolling || t.chunk_hashes.ready())) { + if (rolling) { + // A single exhaustive chunk across all large mapped textures, after the usual checks. + if (!first_rolling) first_rolling = &t; + if (!next_rolling && t.address >= title_rolling_cursor_) next_rolling = &t; + return; + } if (!t.every_byte() || stats.passes % 6) return; std::uint64_t full = 0; checked += span; @@ -12035,6 +12054,12 @@ class Device final ++stats.every_pass_visits; visit(*entry.second); } + if (TitleTexture* t = next_rolling ? next_rolling : first_rolling) { + title_rolling_cursor_ = t->address + 1; + const auto start = clock::now(); + checked += check_title_chunk(*t); + stats.hash_ns += std::chrono::duration_cast(clock::now() - start).count(); + } stats.every_pass_ns += std::chrono::duration_cast(clock::now() - every_start).count(); // The budget is the round robin's: mapped and stale textures above are checked every pass whatever it is. const auto first_bytes = checked, first_hash_ns = stats.hash_ns; @@ -12162,8 +12187,8 @@ class Device final // still has that resource. Others (host copies, unbound memory) are filled under the lock as before. Resource* r = nullptr; rt::xg_xs::Texture layout{}; - std::uint64_t cpu = 0, fills = 0; - bool every_byte = false; + std::uint64_t cpu = 0; + TitleFillVersion version; { std::lock_guard lock(state_.title_texture_mutex); const InTitleTextures inside; @@ -12178,8 +12203,8 @@ class Device final r->AddRef(); layout = t.layout; cpu = t.cpu; - fills = t.fills; - every_byte = t.every_byte(); + version = {t.fills, t.source_revision, leonida::title_memory_map::generation(), + t.every_byte(), t.rolling_hash()}; } else { filled = fill_title_texture(t, true) != 0; } @@ -12187,7 +12212,7 @@ class Device final } } if (r) { - filled = fill_unlocked(address, *r, layout, cpu, fills, every_byte, f); + filled = fill_unlocked(address, *r, layout, cpu, version, f); r->Release(); } std::size_t left = 0; @@ -12208,20 +12233,35 @@ class Device final } } + struct TitleFillVersion { + std::uint64_t fills = 0, source_revision = 0, map_generation = 0; + bool every_byte = false, rolling = false; + }; + + static bool title_mapping_unchanged(std::uint64_t generation, std::uint64_t base, std::uint64_t span) { + if (generation == leonida::title_memory_map::generation()) return true; + std::uint64_t now = 0; + bool overlaps = false; + return leonida::title_memory_map::changes_since(generation, now, base, base + span, + [&](auto, auto) { overlaps = true; }) && !overlaps; + } + // The fill worker's fill of a staged texture: copy, hash and upload without the registry lock, then the result // under it, if the registry still names `r` at `address` and nobody filled it meanwhile. bool fill_unlocked(std::uint64_t address, Resource& r, const rt::xg_xs::Texture& layout, std::uint64_t cpu, - std::uint64_t fills, bool every_byte, TitleFiller& f) { + TitleFillVersion version, TitleFiller& f) { const std::uint64_t span = layout.layout.size; f.tiled.resize(std::size_t(span)); const bool copied = copy_guarded(f.tiled.data(), reinterpret_cast(cpu), std::size_t(span), title_memory_write_combined(cpu)); std::uint64_t hash = 0, full = 0; bool full_hashed = false, ok = false, nonzero = false; + leonida::TitleTextureChunkHashes chunk_hashes; std::uint64_t staged_ns = 0; if (copied) { hash_guarded(f.tiled.data(), f.tiled.size(), hash); - full_hashed = every_byte && hash_guarded(f.tiled.data(), f.tiled.size(), full, true); + full_hashed = version.every_byte && hash_guarded(f.tiled.data(), f.tiled.size(), full, true); + if (version.rolling) snapshot_title_chunks(chunk_hashes, f.tiled); const auto start = std::chrono::steady_clock::now(); ok = r.upload_staged_title(layout, f.tiled.data(), f.columns, false, nonzero); staged_ns = std::chrono::duration_cast(std::chrono::steady_clock::now() - start) @@ -12245,12 +12285,21 @@ class Device final return false; } ++title_stats_.staged_fills; - if (t.fills != fills) return true; // another fill recorded itself in between: its hash is as good + if ((version.rolling || t.rolling_hash()) && + (t.fills != version.fills || t.source_revision != version.source_revision || + !title_mapping_unchanged(version.map_generation, cpu, span))) { + // This upload may have become visible after the intervening one. Refill from the current layout + // rather than trusting a digest from a different upload or from before the first large Map. + t.stale = true; + return true; + } + if (t.fills != version.fills) return true; // another fill recorded itself in between: its hash is as good if (t.owned && !t.fills) r.publish_streamed_texture(); t.hash = hash; t.hashed = true; t.full_hash = full; t.full_hashed = full_hashed; + t.chunk_hashes = std::move(chunk_hashes); ++t.fills; ++title_stats_.fills; title_stats_.fill_bytes += span; @@ -12297,6 +12346,7 @@ class Device final geometry_refresher_->wake.notify_one(); } std::uint64_t title_refresh_cursor_ = 0; // under title_texture_mutex + std::uint64_t title_rolling_cursor_ = 0; // likewise std::uint64_t title_map_generation_ = 0; // likewise: the map changes the passes have seen std::chrono::steady_clock::time_point title_retry_all_{}; // likewise leonida::TitleWriteRanges title_map_changes_; // likewise, scratch @@ -12392,7 +12442,7 @@ class Device final t->desc = words; t->layout_known = true; t->layout_guessed = t->layout_from_xg = false; - t->hashed = false; + t->layout_changed(); } else { refuse_title_view(why, d, address); // counted; the view of its image is still written } @@ -12607,6 +12657,32 @@ class Device final if (!t.hashed || hash != t.hash || t.stale) fill_title_texture(t, true); } + static void snapshot_title_chunks(leonida::TitleTextureChunkHashes& chunks, + const std::vector& snapshot) { + chunks.snapshot(snapshot.size(), [&](std::size_t offset, std::size_t bytes) { + return hash_bytes(snapshot.data() + offset, bytes, true); + }); + } + + std::size_t check_title_chunk(TitleTexture& t) { + const auto chunk = t.chunk_hashes.next(); + const auto address = t.cpu + chunk.offset; + const auto* bytes = reinterpret_cast(static_cast(address)); + std::uint64_t hash = 0; + bool ok = false; + // Stream from WC pages into cached scratch before hashing, just as the upload copy does. + if (title_memory_write_combined(address)) { + if (title_tiled_.size() < chunk.bytes) title_tiled_.resize(chunk.bytes); + ok = copy_guarded(title_tiled_.data(), bytes, chunk.bytes, true); + if (ok) hash = hash_bytes(title_tiled_.data(), chunk.bytes, true); + } else { + ok = hash_guarded(bytes, chunk.bytes, hash, true); + } + if (!ok) t.memory.defer(); + else if (hash != chunk.hash) t.stale = true; // Use the next pass's normal priority upload. + return chunk.bytes; + } + // Snapshot the whole footprint before uploading any subresource. A concurrent unmap defers the fill. // Private title staging bypasses the D3D12 submit callbacks. Generic staged copies require an outer fill. std::uint64_t fill_title_texture(TitleTexture& t, bool staged) { @@ -12620,6 +12696,8 @@ class Device final } const std::uint64_t span = layout.layout.size; if (!title_texture_readable(t)) return 0; + const bool rolling = t.rolling_hash(); + const auto map_generation = rolling ? leonida::title_memory_map::generation() : 0; title_tiled_.resize(std::size_t(span)); if (!copy_guarded(title_tiled_.data(), reinterpret_cast(t.cpu), std::size_t(span), title_memory_write_combined(t.cpu))) { @@ -12687,9 +12765,14 @@ class Device final static_cast(t.cpu), static_cast(span), int(staged), int(nonzero)); if (t.owned && !t.fills) t.resource->publish_streamed_texture(); - t.hash = hash; - t.hashed = true; - t.stale = false; + if (rolling && !title_mapping_unchanged(map_generation, t.cpu, span)) { + t.stale = true; + } else { + if (rolling) snapshot_title_chunks(t.chunk_hashes, title_tiled_); + t.hash = hash; + t.hashed = true; + t.stale = false; + } ++t.fills; ++title_stats_.fills; title_stats_.fill_bytes += span; diff --git a/runtime/src/title_texture_refresh.h b/runtime/src/title_texture_refresh.h index ed7c0f2b67..8dc8be0c40 100644 --- a/runtime/src/title_texture_refresh.h +++ b/runtime/src/title_texture_refresh.h @@ -1,5 +1,6 @@ #pragma once #include +#include #include #include #include @@ -28,6 +29,42 @@ inline bool title_write_overlaps(const TitleWriteRanges& writes, std::uintptr_t return begin < end && it != writes.end() && it->first < end; } +// Each digest describes a chunk of the last successful upload, never a subsequently observed CPU snapshot. +class TitleTextureChunkHashes { +public: + static constexpr std::size_t chunk_bytes = 256u << 10; + + struct Chunk { + std::size_t offset, bytes; + std::uint64_t hash; + }; + + bool ready() const { return !hashes_.empty(); } + + template + void snapshot(std::size_t bytes, Hash hash) { + bytes_ = bytes; + next_ = 0; + hashes_.resize(bytes / chunk_bytes + (bytes % chunk_bytes != 0)); + for (std::size_t i = 0; i < hashes_.size(); ++i) { + const auto offset = i * chunk_bytes; + hashes_[i] = hash(offset, std::min(chunk_bytes, bytes - offset)); + } + } + + // The caller checks ready() first. A failed read still advances so later chunks get their turn. + Chunk next() { + const auto index = next_; + next_ = index + 1 == hashes_.size() ? 0 : index + 1; + const auto offset = index * chunk_bytes; + return {offset, std::min(chunk_bytes, bytes_ - offset), hashes_[index]}; + } + +private: + std::vector hashes_; + std::size_t bytes_ = 0, next_ = 0; +}; + // The registry's entries as one pass will visit them, in placement order. A pass cannot walk the registry itself: a // fill it makes can submit, a submission destroys a retired image, and that image's destructor erases its entry // (DeviceState::title_texture_gone). Windows' mutex is recursive for its owner, so the erase lands inside the pass and diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index 3d65fc7409..d739e7216c 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -1402,6 +1402,55 @@ int check_mapped_plane(ID3D12Device* device) { return 0; } +// The last chunk contains a texel outside the periodic hash's two per-page samples and final 64 bytes. +int check_large_mapped_texture(ID3D12Device* device) { + const char* who = "large persistent slot-133 texture"; + constexpr UINT width = 2048, height = 1024, pitch = width * 4, size = pitch * height; + constexpr UINT missed = size - pitch + 128; + const auto release_pages = [](void* p) { VirtualFree(p, 0, MEM_RELEASE); }; + std::unique_ptr pages( + VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE), release_pages); + EXPECT(pages); + GpuReader gpu; + EXPECT(!gpu.init(device, size)); + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = width; + desc.Height = height; + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.SampleDesc.Count = desc.DepthOrArraySize = desc.MipLevels = 1; + leonida::title_xg_layouts::note({UINT(desc.Dimension), UINT(desc.Format), height, 1, 1, width}, 1); + Ref texture; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages.get(), desc, 6, IID_PPV_ARGS(&texture.p)), S_OK); + void* mapped = nullptr; + EXPECT_HR(texture->Map(0, nullptr, &mapped), S_OK); + EXPECT(mapped == pages.get()); + auto* pixels = static_cast(mapped); + std::memset(pixels, 0x18, size); + ID3D12CommandList* lists[]{gpu.list.p}; + auto submit = [&](UINT64 fence) { + gpu.queue->ExecuteCommandLists(1, lists); + return SUCCEEDED(gpu.queue->Signal(gpu.fence.p, fence)) && + SUCCEEDED(gpu.fence->SetEventOnCompletion(fence, gpu.done)) && + WaitForSingleObject(gpu.done, 30000) == WAIT_OBJECT_0; + }; + std::vector readback(size); + EXPECT(submit(1)); + EXPECT_HR(texture->ReadFromSubresource(readback.data(), pitch, size, 0, nullptr), S_OK); + EXPECT(readback[missed] == 0x18); + pixels[missed] = 0x41; // Leave the original Map open and send no write notification. + // Here there is one large mapped texture. 32 chunks cover its 8 MiB, then the next pass uploads it. + for (UINT64 fence = 2; fence <= 34; ++fence) EXPECT(submit(fence)); + EXPECT_HR(texture->ReadFromSubresource(readback.data(), pitch, size, 0, nullptr), S_OK); + EXPECT(readback[missed] == 0x41); + pixels[0] = 0x52; // A sampled change still refreshes on the very next pass. + EXPECT(submit(35)); + EXPECT_HR(texture->ReadFromSubresource(readback.data(), pitch, size, 0, nullptr), S_OK); + EXPECT(readback[0] == 0x52); + texture->Unmap(0, nullptr); + return 0; +} + // Several threads write the same watched pages while submissions keep making them read-only again. Two threads that // fault on one page race: the first fault reopens it, a submission can protect it again before the second fault is // handled, and the second write must still be retried, not refused (refused, the process ends: seen natively). After @@ -1990,7 +2039,8 @@ void print_cases(const std::vector& cases, const char* who) { int main(int argc, char** argv) { const bool prefix_only = argc == 2 && std::strcmp(argv[1], "--host-prefix-only") == 0; - if (argc != 1 && !prefix_only) return 2; + const bool large_mapped_only = argc == 2 && std::strcmp(argv[1], "--large-mapped-only") == 0; + if (argc != 1 && !prefix_only && !large_mapped_only) return 2; _putenv_s("LEONIDA_TITLE_TEXTURE_PERIOD_MS", "0"); _putenv_s("LEONIDA_TITLE_TEXTURE_CHECK_KB", "0"); vktest::Device vk; @@ -2018,6 +2068,18 @@ int main(int argc, char** argv) { const int result = check_host_prefix_buffers(ours.p); return result || vk.validation_errors() ? 1 : 0; } + if (large_mapped_only) { + if (vk.host_image_copy) { + std::puts("large persistent slot-133 texture: host copies available"); + failures += check_large_mapped_texture(ours.p); + } + info.host_image_copy = false; + Ref staged; + if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&staged.p)))) return 1; + std::puts("large persistent slot-133 texture: forced staged copies"); + failures += check_large_mapped_texture(staged.p); + return failures || vk.validation_errors() ? 1 : 0; + } failures += check(ours.p, "vulkan"); const std::vector vulkan_cases = open_cases(ours.p); print_cases(vulkan_cases, "vulkan"); @@ -2028,6 +2090,7 @@ int main(int argc, char** argv) { failures += check_pending_stream_views(ours.p); failures += check_shared_bc_placements(ours.p); failures += check_mapped_plane(ours.p); + failures += check_large_mapped_texture(ours.p); failures += check_mapped_bc_array(ours.p); } { @@ -2037,6 +2100,7 @@ int main(int argc, char** argv) { Ref staged; if (FAILED(rt::d3d12::create_vulkan_device(no_host_copy, IID_PPV_ARGS(&staged.p)))) return 1; failures += check_mapped_plane(staged.p); + failures += check_large_mapped_texture(staged.p); failures += check_mapped_bc_array(staged.p); } failures += check_written_pages_all(ours.p); diff --git a/runtime/test/title_memory_map_test.cpp b/runtime/test/title_memory_map_test.cpp index ba5a518a1d..b9e4f175be 100644 --- a/runtime/test/title_memory_map_test.cpp +++ b/runtime/test/title_memory_map_test.cpp @@ -142,6 +142,27 @@ int main() { check(pass() == 4 && probes == 0, "a pass with no change probes nothing"); } + { + leonida::TitleTextureChunkHashes hashes; + const auto chunk_bytes = leonida::TitleTextureChunkHashes::chunk_bytes; + check(!hashes.ready(), "a texture with no accepted snapshot has no audit baseline"); + const auto hash = [](std::size_t offset, std::size_t bytes) { return std::uint64_t(offset + bytes); }; + hashes.snapshot(2 * chunk_bytes + 31, hash); + check(hashes.ready(), "an accepted snapshot installs the audit baseline"); + const auto first = hashes.next(), second = hashes.next(), tail = hashes.next(), wrapped = hashes.next(); + check(first.offset == 0 && first.bytes == chunk_bytes && first.hash == chunk_bytes, + "first audit chunk covers the start of the footprint"); + check(second.offset == chunk_bytes && second.bytes == chunk_bytes && second.hash == 2 * chunk_bytes, + "second audit chunk follows without depending on the first read succeeding"); + check(tail.offset == 2 * chunk_bytes && tail.bytes == 31 && tail.hash == 2 * chunk_bytes + 31, + "partial tail hashes exactly the remaining bytes"); + check(wrapped.offset == 0 && wrapped.hash == first.hash, "the audit wraps without modifying the baseline"); + hashes.snapshot(17, hash); + const auto replacement = hashes.next(); + check(replacement.offset == 0 && replacement.bytes == 17 && replacement.hash == 17, + "a new accepted upload resets the cursor and replaces the old footprint"); + } + std::printf("%d checks, %d failures\n", g_checks, g_failures); return g_failures ? 1 : 0; }