Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions runtime/shims/d3d12_vulkan_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<const UnalignedWord64*>(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));
Expand Down Expand Up @@ -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<std::uintptr_t>(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
Expand Down
8 changes: 5 additions & 3 deletions runtime/shims/xmem.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -1594,7 +1594,8 @@ LONG CALLBACK physical_page_fault(EXCEPTION_POINTERS* info) {
if (where != kNoReservation || access == 1)
queried = VirtualQuery(reinterpret_cast<const void*>(accessed), &seen, sizeof(seen)) != 0;
const auto pc = reinterpret_cast<uintptr_t>(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<const void*>(accessed), &seen, sizeof(seen)) != 0;
read_note_size = describe_read(read_note, pc, accessed, seen);
plant_read = where == kInWindow && g_pool_zero_pages;
Expand Down Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion runtime/shims/xmem.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
28 changes: 26 additions & 2 deletions runtime/src/title_texture_memory.h
Original file line number Diff line number Diff line change
@@ -1,31 +1,55 @@
#pragma once
#include <windows.h>
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <limits>

#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<class Probe>
bool check(std::uint64_t generation, bool cache_failure, Probe probe, bool cache_success = false) {
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<std::uintptr_t>::max)() - cpu
? (std::numeric_limits<std::uintptr_t>::max)()
: cpu + static_cast<std::uintptr_t>(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;
};

Expand Down
137 changes: 137 additions & 0 deletions runtime/test/d3d12_existing_heap_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1359,6 +1359,141 @@ int check_pending_stream_views(ID3D12Device* device) {
return 0;
}

namespace {
std::atomic<DWORD> g_view_av_thread{0};
std::atomic<unsigned> 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<std::uint8_t*>(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<UINT, 14> resource{};
std::array<UINT, 16> 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<UINT64>(pages),
{reinterpret_cast<SIZE_T>(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<ID3D12Resource> 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<UINT, 14> resource{};
std::array<UINT, 16> 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<UINT64>(pages),
{reinterpret_cast<SIZE_T>(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<ID3D12Resource> 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";
Expand Down Expand Up @@ -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);
Expand All @@ -2099,6 +2235,7 @@ int main(int argc, char** argv) {
no_host_copy.host_image_copy = false;
Ref<ID3D12Device> 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);
}
Expand Down
45 changes: 44 additions & 1 deletion runtime/test/title_memory_map_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 <windows.h>

#include <cstdint>
Expand Down Expand Up @@ -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;
}
Loading