diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 1fb36401e3..3be1d88c08 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -225,18 +225,24 @@ bool copy_guarded(std::uint8_t* to, const std::uint8_t* from, std::size_t bytes, // (streaming, file reads, XG copies) or whole planes (video), never a few bytes inside a page. The same sampling as // OpenScarlett's texture hash before submission (src/gpu/d3d12_xs/device_x.cpp, f8e24d4, MIT), with more samples. // False when a page faults (the title unmapped it). No C++ objects here: it is a __try frame. -inline std::uint64_t mix_words(std::uint64_t h, const std::uint8_t* at, std::size_t n) { +#pragma pack(push, 1) +struct UnalignedWord64 { + std::uint64_t value; +}; +#pragma pack(pop) + +LEONIDA_GUARDED_NO_BUILTIN inline std::uint64_t mix_words(std::uint64_t h, const std::uint8_t* at, std::size_t n) { for (std::size_t i = 0; i + 8 <= n; i += 8) { - std::uint64_t w; - std::memcpy(&w, at + i, 8); + const std::uint64_t w = reinterpret_cast(at + i)->value; h = (h ^ w) * 0x100000001b3ull; h ^= h >> 29; } return h; } // The reads of hash_guarded, in a frame of its own: an inline load inside the __try is not covered by clang-cl -// without /EHa (src/guarded_copy.h). -__declspec(noinline) std::uint64_t hash_bytes(const std::uint8_t* p, std::size_t bytes, bool every_byte) { +// without /EHa, and a CRT memcpy call is not covered under Wine (src/guarded_copy.h). +__declspec(noinline) LEONIDA_GUARDED_NO_BUILTIN std::uint64_t hash_bytes(const std::uint8_t* p, std::size_t bytes, + bool every_byte) { std::uint64_t h = 0x9e3779b97f4a7c15ull ^ bytes; if (bytes <= (256u << 10) || every_byte) { h = mix_words(h, p, bytes & ~std::size_t(7)); @@ -15508,6 +15514,8 @@ class Device final const bool guard = check_pages_before_read(); if (!guard && !t.memory.pending()) return true; const bool mapped = t.mapped && refresh_mapped_pages(); + if (!title_pass_ && guard && !mapped) + t.memory.sync_map(title_map_generation_, static_cast(t.cpu), t.layout.layout.size); const auto commit = mapped ? leonida::kernel_writes::state().committer.load(std::memory_order_acquire) : nullptr; const bool waited = t.memory.pending(); // The answer is kept (generation 0) until a map change over the texture, a write into it or the periodic diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index 384f7bd278..964cc92160 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp @@ -1575,7 +1575,7 @@ LONG CALLBACK physical_page_fault(EXCEPTION_POINTERS* info) { MEMORY_BASIC_INFORMATION seen{}; // the page as the decision saw it char read_note[1024]; DWORD read_note_size = 0; - bool plant_read = false, promote = false; + bool plant_read = false, promote = false, from_title = false; bool queried = false; { const FaultLockShared lock; @@ -1594,7 +1594,8 @@ LONG CALLBACK physical_page_fault(EXCEPTION_POINTERS* info) { if (where != kNoReservation || access == 1) queried = VirtualQuery(reinterpret_cast(accessed), &seen, sizeof(seen)) != 0; const auto pc = reinterpret_cast(record->ExceptionAddress); - if (access == 0 && result == PageCommit::not_ours && title_code(pc)) { + from_title = access == 0 && result == PageCommit::not_ours && title_code(pc); + if (from_title) { if (!queried) queried = VirtualQuery(reinterpret_cast(accessed), &seen, sizeof(seen)) != 0; read_note_size = describe_read(read_note, pc, accessed, seen); plant_read = where == kInWindow && g_pool_zero_pages; @@ -1670,7 +1671,8 @@ LONG CALLBACK physical_page_fault(EXCEPTION_POINTERS* info) { exit = FaultExit::committed; } else if (answered) { exit = FaultExit::answered; - } else if (result == PageCommit::committed_before && !escalated) { + } else if ((result == PageCommit::committed_before && !escalated) || + (title_page && access == 0 && result == PageCommit::not_ours && !from_title)) { exit = FaultExit::passed_guarded; // a guard's (the D3D12 layer's), routine: not noted } else if (title_page || reserved_write) { note_fault(kRefused, accessed, access, result, where, seen); diff --git a/runtime/shims/xmem.h b/runtime/shims/xmem.h index 96fb89e7ea..6e0017f2ba 100644 --- a/runtime/shims/xmem.h +++ b/runtime/shims/xmem.h @@ -55,7 +55,7 @@ enum class FaultExit : int { answered, // a mapped page committed, or found committed and allowed (another thread's map or commit) planted, // a window page the title never mapped, backed by a zero page committed, // a section page in the title's reservation with no view of xmem's, committed - passed_guarded, // a committed page of xmem's views whose protection refuses the access: its guard's to answer + passed_guarded, // a committed page whose protection refuses the access, or a host guarded read of an unmapped page passed_foreign, // memory that is not the title's reservation and not only reserved: someone else's fault left_to_title, // the title's reservation, or a write into memory that is only reserved: noted (FaultNote) count diff --git a/runtime/src/title_texture_memory.h b/runtime/src/title_texture_memory.h index a97e5bed66..ff9f004e07 100644 --- a/runtime/src/title_texture_memory.h +++ b/runtime/src/title_texture_memory.h @@ -1,14 +1,17 @@ #pragma once #include +#include #include #include #include +#include "title_page_watch.h" + namespace leonida { // Keep negative probes until the title changes the map or a writer reports this footprint. With cache_success, -// positive ones too: a caller that is told of every map change over the footprint (retry) and reads it under a guard -// (a page gone since faults into a defer) need not walk the pages before every read. +// positive ones too: a caller that is told of every map change over the footprint (retry or sync_map) and reads it +// under a guard (a page gone since faults into a defer) need not walk the pages before every read. class TextureReadability { public: template @@ -16,16 +19,37 @@ class TextureReadability { if (cache_failure && pending_ && !retry_ && generation_ == generation) return false; if (cache_success && probed_ && !pending_ && !retry_ && generation_ == generation) return true; generation_ = generation; // snapshot before the probe so a concurrent map change is noticed + map_generation_ = title_memory_map::generation(); retry_ = false; probed_ = true; pending_ = !probe(); return !pending_; } + // Between refresh passes, check whether the map journal recorded a change over [cpu, cpu + size) since both + // this texture's last probe and the last pass's sweep. + void sync_map(std::uint64_t pass_generation, std::uintptr_t cpu, std::uint64_t size) { + if (!probed_ || retry_) return; + const std::uint64_t since = (std::max)(map_generation_, pass_generation); + if (title_memory_map::generation() == since) return; + const std::uintptr_t end = size > (std::numeric_limits::max)() - cpu + ? (std::numeric_limits::max)() + : cpu + static_cast(size); + std::uint64_t now = 0; + bool overlapped = false; + if (!title_memory_map::changes_since( + since, now, cpu, end, [&](std::uintptr_t, std::uintptr_t) { overlapped = true; }) || + overlapped) { + retry_ = true; + } else { + map_generation_ = now; + } + } void defer() { pending_ = true; } // mapping disappeared between the probe and the read void retry() { retry_ = true; } bool pending() const { return pending_; } private: std::uint64_t generation_ = 0; + std::uint64_t map_generation_ = 0; bool pending_ = false, retry_ = false, probed_ = false; }; diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index 25fa1f6544..546c760555 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -1359,6 +1359,141 @@ int check_pending_stream_views(ID3D12Device* device) { return 0; } +namespace { +std::atomic g_view_av_thread{0}; +std::atomic g_view_avs{0}; + +LONG CALLBACK count_view_av(PEXCEPTION_POINTERS info) { + if (info && info->ExceptionRecord && info->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && + GetCurrentThreadId() == g_view_av_thread.load(std::memory_order_relaxed)) { + g_view_avs.fetch_add(1, std::memory_order_relaxed); + } + return EXCEPTION_CONTINUE_SEARCH; +} +} // namespace + +// Map changes reported to title_memory_map between submissions must both retire a cached readable answer before a +// synchronous slot-70 view hashes decommitted pages, and wake a pending slot-70 view without waiting for a submission. +int check_placed_view_map_changes(ID3D12Device* device) { + const char* who = "slot-70 view map changes"; + if (!rt::d3d12::bindless_set_layout(device)) return 0; + GpuReader gpu; + EXPECT(!gpu.init(device, 4096)); + auto env_is = [](const char* name, const char* want) { + char buf[16]{}; + const DWORD n = GetEnvironmentVariableA(name, buf, sizeof(buf)); + return n > 0 && n < sizeof(buf) && std::strcmp(buf, want) == 0; + }; + auto index = [&](const leonida::gfx10::ImageWords& descriptor) { + std::uint32_t key[8]; + std::memcpy(key, descriptor.data(), sizeof(key)); + return rt::d3d12::bindless_hash_lookup(device, key); + }; + + // 1. Committed >256 KiB texture -> decommit interior 64 KiB + map::changed -> synchronous view takes zero AVs. + { + constexpr SIZE_T bytes = 512 * 1024; + auto* pages = static_cast(VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + EXPECT(pages); + std::memset(pages, 0x5a, bytes); + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = 512; + desc.Height = 1024; + desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Format = DXGI_FORMAT_R8_UNORM; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = desc.Format; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Texture2D.MipLevels = 1; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + leonida::gfx10::ImageWords slot{}; + auto write_view = [&](UINT mapping) { + srv.Shader4ComponentMapping = mapping; + std::array resource{}; + std::array words{}; + std::memcpy(resource.data(), &desc, sizeof(desc)); + std::memcpy(words.data(), &srv, sizeof(srv)); + return rt::d3d12::write_placed_texture_view(device, false, resource.data(), words.data(), + reinterpret_cast(pages), + {reinterpret_cast(slot.data())}); + }; + EXPECT(write_view(D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING)); + EXPECT(index(slot) != 0); + + EXPECT(VirtualFree(pages + 65536, 65536, MEM_DECOMMIT) != FALSE); + leonida::title_memory_map::changed(pages + 65536, 65536); + + g_view_avs.store(0, std::memory_order_relaxed); + g_view_av_thread.store(GetCurrentThreadId(), std::memory_order_relaxed); + PVOID veh = AddVectoredExceptionHandler(1, &count_view_av); + EXPECT(veh != nullptr); + const bool wrote_after_unmap = write_view(D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(0, 0, 0, 0)); + RemoveVectoredExceptionHandler(veh); + g_view_av_thread.store(0, std::memory_order_relaxed); + EXPECT(wrote_after_unmap); + EXPECT(g_view_avs.load(std::memory_order_relaxed) == 0); + + EXPECT(VirtualAlloc(pages + 65536, 65536, MEM_COMMIT, PAGE_READWRITE) == pages + 65536); + leonida::title_memory_map::changed(pages + 65536, 65536); + Ref placement; + desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 6, IID_PPV_ARGS(&placement.p)), S_OK); + placement.p->Release(); + placement.p = nullptr; + VirtualFree(pages, 0, MEM_RELEASE); + } + + // 2. Reserved texture -> commit + map::changed (no texel write note, no submission) -> synchronous view publishes. + { + constexpr SIZE_T bytes = 65536; + void* pages = VirtualAlloc(nullptr, bytes, MEM_RESERVE, PAGE_NOACCESS); + EXPECT(pages); + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = 32; + desc.Height = 8; + desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Format = DXGI_FORMAT_R8_UNORM; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = desc.Format; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Texture2D.MipLevels = 1; + leonida::gfx10::ImageWords first{}, second{}; + auto write_view = [&](UINT mapping, leonida::gfx10::ImageWords& out) { + srv.Shader4ComponentMapping = mapping; + std::array resource{}; + std::array words{}; + std::memcpy(resource.data(), &desc, sizeof(desc)); + std::memcpy(words.data(), &srv, sizeof(srv)); + return rt::d3d12::write_placed_texture_view(device, false, resource.data(), words.data(), + reinterpret_cast(pages), + {reinterpret_cast(out.data())}); + }; + EXPECT(write_view(D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, first)); + if (!env_is("LEONIDA_TITLE_IMAGE_DEFER", "0")) EXPECT(!index(first)); + + EXPECT(VirtualAlloc(pages, bytes, MEM_COMMIT, PAGE_READWRITE) == pages); + std::memset(pages, 0x33, bytes); + leonida::title_memory_map::changed(pages, bytes); + + EXPECT(write_view(D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(0, 0, 0, 0), second)); + if (!env_is("LEONIDA_TITLE_FILL_ASYNC", "1")) EXPECT(index(first) && index(second)); + + Ref placement; + desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 6, IID_PPV_ARGS(&placement.p)), S_OK); + placement.p->Release(); + placement.p = nullptr; + VirtualFree(pages, 0, MEM_RELEASE); + } + return 0; +} + // A persistent Map can become readable without notifying xmem or calling Map a second time. int check_mapped_plane(ID3D12Device* device) { const char* who = "persistent slot-133 plane"; @@ -2089,6 +2224,7 @@ int main(int argc, char** argv) { if (vk.host_pointer_alignment) failures += check_title_placed_all(ours.p); if (vk.host_image_copy) { failures += check_pending_stream_views(ours.p); + failures += check_placed_view_map_changes(ours.p); failures += check_shared_bc_placements(ours.p); failures += check_mapped_plane(ours.p); failures += check_mapped_bc_array(ours.p); @@ -2099,6 +2235,7 @@ int main(int argc, char** argv) { no_host_copy.host_image_copy = false; Ref staged; if (FAILED(rt::d3d12::create_vulkan_device(no_host_copy, IID_PPV_ARGS(&staged.p)))) return 1; + failures += check_placed_view_map_changes(staged.p); failures += check_mapped_plane(staged.p); failures += check_mapped_bc_array(staged.p); } diff --git a/runtime/test/title_memory_map_test.cpp b/runtime/test/title_memory_map_test.cpp index ba5a518a1d..ff226d6481 100644 --- a/runtime/test/title_memory_map_test.cpp +++ b/runtime/test/title_memory_map_test.cpp @@ -7,7 +7,8 @@ // 3. a reader further behind than the journal holds is told so (it then looks at everything); // 4. a change with no range overlaps every reader; // 5. TextureReadability keeps a positive answer, when asked to, until a retry; -// 6. a pass over 20,000 waiting textures probes only those under the one mapped block. +// 6. a pass over 20,000 waiting textures probes only those under the one mapped block; +// 7. between passes, sync_map retries only when a map change overlaps the texture's footprint. #include #include @@ -142,6 +143,48 @@ int main() { check(pass() == 4 && probes == 0, "a pass with no change probes nothing"); } + // 7. Synchronous view checks between passes (sync_map): unrelated map changes cost no probe, an overlapping unmap + // defers without reading, and an overlapping map wakes a waiting texture before the next pass. + { + constexpr std::uintptr_t cpu = kBase + 0x20000000; + constexpr std::uint64_t size = 512 * 1024; + const std::uint64_t pass_generation = map::generation(); + bool mapped = true; + unsigned probes = 0; + leonida::TextureReadability r; + const auto probe = [&] { + ++probes; + return mapped; + }; + check(r.check(0, true, probe, true) && probes == 1 && !r.pending(), + "sync_map: initial probe caches a readable answer"); + for (std::uintptr_t i = 0; i < 32; ++i) + map::changed(cpu + size + i * 0x10000, cpu + size + (i + 1) * 0x10000); + r.sync_map(pass_generation, cpu, size); + check(r.check(0, true, probe, true) && probes == 1, + "sync_map: map changes outside the footprint keep the cached answer"); + r.sync_map(pass_generation, cpu, size); + check(r.check(0, true, probe, true) && probes == 1, + "sync_map: a second check at the same generation does nothing"); + + mapped = false; + map::changed(cpu + 0x10000, cpu + 0x20000); + r.sync_map(pass_generation, cpu, size); + check(!r.check(0, true, probe, true) && r.pending() && probes == 2, + "sync_map: an overlapping unmap between passes reprobes and defers"); + + map::changed(cpu - 0x10000, cpu); + r.sync_map(pass_generation, cpu, size); + check(!r.check(0, true, probe, true) && r.pending() && probes == 2, + "sync_map: an adjacent non-overlapping change leaves a pending texture waiting"); + + mapped = true; + map::changed(cpu, cpu + size); + r.sync_map(pass_generation, cpu, size); + check(r.check(0, true, probe, true) && !r.pending() && probes == 3, + "sync_map: an overlapping map between passes wakes a pending texture at once"); + } + std::printf("%d checks, %d failures\n", g_checks, g_failures); return g_failures ? 1 : 0; } diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp index 991388c7f5..fca830bf0f 100644 --- a/runtime/test/xmem_test.cpp +++ b/runtime/test/xmem_test.cpp @@ -1544,6 +1544,38 @@ void test_physical_pages_commit_on_touch(const PhysicalApi& api) { check(read_ok, "ReadFile fills a page that commit_physical_range committed"); check(api.map(second, 2, nullptr) == second && api.map(window, kMapped, nullptr) == window, "they unmap"); + { + // A host guarded read (outside the title image at 0x140000000) of an unmapped window page exits as + // passed_guarded without counting as left_to_title; a title read still counts as left_to_title. + void* const stub_page = VirtualAlloc(nullptr, 4096, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + const uint8_t mov_eax_rcx_ret[] = {0x8b, 0x01, 0xc3}; + DWORD stub_old = 0; + bool stub_ready = false; + if (stub_page) { + std::memcpy(stub_page, mov_eax_rcx_ret, sizeof(mov_eax_rcx_ret)); + stub_ready = VirtualProtect(stub_page, 4096, PAGE_EXECUTE_READ, &stub_old) != FALSE; + FlushInstructionCache(GetCurrentProcess(), stub_page, sizeof(mov_eax_rcx_ret)); + } + const auto host_read_faults = [&](const void* p) { + __try { + reinterpret_cast(stub_page)(p); + return false; + } __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER + : EXCEPTION_CONTINUE_SEARCH) { + return true; + } + }; + const uint64_t guarded_before = rt::xmem::fault_exits(rt::xmem::FaultExit::passed_guarded); + const uint64_t left_before = rt::xmem::fault_exits(rt::xmem::FaultExit::left_to_title); + check(stub_ready && host_read_faults(second) && + rt::xmem::fault_exits(rt::xmem::FaultExit::passed_guarded) == guarded_before + 1 && + rt::xmem::fault_exits(rt::xmem::FaultExit::left_to_title) == left_before, + "a host guarded read of an unmapped window page exits as passed_guarded"); + check(access_faults(reinterpret_cast(second), false) && + rt::xmem::fault_exits(rt::xmem::FaultExit::left_to_title) == left_before + 1, + "a title read of an unmapped window page still exits as left_to_title"); + if (stub_page) VirtualFree(stub_page, 0, MEM_RELEASE); + } check(api.free_pages(count, pages.data()) == TRUE, "XMemFreePhysicalPages frees them"); }