Skip to content
Open
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
15 changes: 15 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,9 @@ if(EXISTS "${INTAKE_PYTHON}")
# and section count the DirectStorage heartbeat reports from it.
add_test(NAME xmem_page_stats COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_SOURCE_DIR}/tests/xmem_page_stats_check.py" "$<TARGET_FILE:xmem_shim>")
# Readability checks ask the page registry instead of touching unmapped pages.
add_test(NAME xmem_mapped_bytes COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_SOURCE_DIR}/tests/xmem_mapped_bytes_check.py" "$<TARGET_FILE:xmem_shim>")
# A page-token write names granted pages only: no section outside a grant, and a fresh grant reads zero.
add_test(NAME xmem_physical_write_owner COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_SOURCE_DIR}/tests/xmem_physical_write_owner_check.py" "$<TARGET_FILE:xmem_shim>")
Expand Down Expand Up @@ -1417,6 +1420,18 @@ set_tests_properties(startup_queue_page_batch_warp PROPERTIES RUN_SERIAL TRUE TI
set_tests_properties(startup_queue_page_batch_runs_warp PROPERTIES RUN_SERIAL TRUE TIMEOUT 90 SKIP_RETURN_CODE 77
ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_DEBUG=0;X2W_XMEM_PERMISSIVE=1;X2W_XMEM_GPU_MIRROR=0;X2W_XMEM_LAZY_COMMIT=0;X2W_XMEM_SHARED_VIEWS=1")

# Unknown queue slots do not fault on every call for a reserved, unmapped argument address.
add_executable(startup_queue_probe tests/startup_queue_probe.cpp)
target_compile_features(startup_queue_probe PRIVATE cxx_std_17)
target_link_libraries(startup_queue_probe PRIVATE d3d12_xs_shim d3d12 dxgi)
add_dependencies(startup_queue_probe xmem_shim)
foreach(backend IN ITEMS warp hardware)
add_test(NAME startup_queue_probe_reserved_${backend} COMMAND startup_queue_probe ${backend} reserved)
add_test(NAME startup_queue_probe_xmem_${backend} COMMAND startup_queue_probe ${backend} xmem "$<TARGET_FILE:xmem_shim>")
set_tests_properties(startup_queue_probe_reserved_${backend} startup_queue_probe_xmem_${backend} PROPERTIES
TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "X2W_D3D12_PERMISSIVE=1")
endforeach()

# Closed lists stay submittable, also after their allocator's Reset (#1352).
add_executable(startup_list_resubmit tests/startup_list_resubmit.cpp)
target_compile_features(startup_list_resubmit PRIVATE cxx_std_17)
Expand Down
38 changes: 37 additions & 1 deletion src/startup_stubs/d3d12_draw.inl
Original file line number Diff line number Diff line change
Expand Up @@ -1620,6 +1620,34 @@ void buffer_view(D3D12_CPU_DESCRIPTOR_HANDLE dest, ID3D12Resource* buffer, u64 o
// Recheck single-mip R8 and A8 planes on their first bind each frame and other textures every 15 frames.
// Targets and UAVs are GPU-written and never uploaded.
LONG textures_uploaded, texture_bytes_uploaded, textures_unreadable;

// Texel addresses of by-address textures whose first page a probe found unreadable, with the frame of
// the probe. Outside xmem's page reservations the probe touches one byte per page, and an unmapped page
// costs a first-chance access violation (under the debug launcher one debugger round trip each). Such an
// address is not probed again for unreadable_retry_frames frames; after that it is, since the title maps
// its pages while it loads.
constexpr LONG unreadable_retry_frames = 30;
std::mutex unreadable_mutex;
std::unordered_map<u64, LONG> unreadable_addresses;
LONG address_probe_skipped;

bool recently_unreadable(u64 address)
{
const std::lock_guard guard(unreadable_mutex);
const auto it = unreadable_addresses.find(address);
if (it == unreadable_addresses.end()) return false;
if (frame_number - it->second <= unreadable_retry_frames) return true;
unreadable_addresses.erase(it);
return false;
}

void note_unreadable(u64 address)
{
const std::lock_guard guard(unreadable_mutex);
if (unreadable_addresses.size() > 65536) unreadable_addresses.clear();
unreadable_addresses[address] = frame_number;
}

u64 hash_memory(const unsigned char* data, std::size_t bytes)
{
u64 h = 0xcbf29ce484222325ull;
Expand Down Expand Up @@ -1730,7 +1758,15 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture)
: x2w_startup::recheck_cpu_texture(desc, total, elapsed));
const bool reusable = state.done && (!state.pending_list || state.pending_list == list);
if (reusable && !announced && !recheck) return true;
if (readable_window(reinterpret_cast<u64>(memory), static_cast<std::size_t>(total)) < total) {
// An address a probe found unmapped is not probed again for 30 frames, unless a write was announced.
bool skipped_probe = false;
if (tiled_address && !announced && recently_unreadable(reinterpret_cast<u64>(memory))) {
skipped_probe = true;
InterlockedIncrement(&address_probe_skipped);
}
std::size_t window = 0;
if (skipped_probe || (window = readable_window(reinterpret_cast<u64>(memory), static_cast<std::size_t>(total))) < total) {
if (tiled_address && !skipped_probe && !window) note_unreadable(reinterpret_cast<u64>(memory));
if (!state.done) InterlockedIncrement(&textures_unreadable);
if (console) return false;
state.done = true;
Expand Down
14 changes: 13 additions & 1 deletion src/startup_stubs/d3d12_memory_srv.inl
Original file line number Diff line number Diff line change
Expand Up @@ -555,7 +555,19 @@ Wrapper* publish_tiled_texture(Wrapper* device, u64 address, const D3D12_RESOURC
{
const auto bytes = address_texture_bytes(device, desc);
// The transient upload ring accepts individual copies up to 64 MiB.
if (bytes > x2w_startup::max_published_texture_bytes || !x2w_local::readable(reinterpret_cast<const void*>(address), bytes)) return nullptr;
if (bytes > x2w_startup::max_published_texture_bytes || !bytes || address < 0x10000) return nullptr;
// The texels must be readable. The test goes through xmem's page registry (readable_window), so an
// unmapped page inside a title page reservation is not touched; an address found unmapped is not
// probed again for 30 frames (recently_unreadable).
if (recently_unreadable(address)) {
InterlockedIncrement(&address_probe_skipped);
return nullptr;
}
const std::size_t readable_bytes = readable_window(address, static_cast<std::size_t>(bytes));
if (readable_bytes != bytes) {
if (!readable_bytes) note_unreadable(address);
return nullptr;
}
std::lock_guard lock(tiled_srv_mutex);
const auto [first, last] = tiled_srv_addresses.equal_range(address);
for (auto it = first; it != last; ++it) {
Expand Down
52 changes: 47 additions & 5 deletions src/startup_stubs/d3d12_xs_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
#include "startup_stubs/address_texture.h"
#include "startup_stubs/list_upload_pages.h"
#include "startup_stubs/resource_budget.h"
#include <atomic>
#include "startup_stubs/upload_reservation.h"
#include <optional>
#include "startup_stubs/derived_blend.h"
Expand Down Expand Up @@ -413,10 +414,11 @@ void guid_text(const GUID* g, char* out, std::size_t size)
g->Data4[7]);
}

std::size_t readable_window(u64 address, std::size_t wanted);
void hex_text(const void* data, std::size_t bytes, char* out, std::size_t size)
{
out[0] = 0;
if (!data || !x2w_local::readable(data, bytes)) return;
if (!data || readable_window(reinterpret_cast<u64>(data), bytes) < bytes) return;
const auto* p = static_cast<const unsigned char*>(data);
std::size_t used = 0;
for (std::size_t i = 0; i < bytes && used + 4 < size; ++i) used += std::snprintf(out + used, size - used, "%02x ", p[i]);
Expand Down Expand Up @@ -583,9 +585,14 @@ void fill_all_traps(std::index_sequence<K...>)

// A call that passes a known interface IID is a creation or query call: a no-op that returned 0
// would hand the title "success" with no object. Such calls trap instead of being ignored.
// The readability test goes through xmem's page registry first (readable_window): a value that is an
// address inside a title page reservation with nothing mapped there, such as the base of a physical-page
// pool whose mapping failed, is answered without touching it. Probing it cost one first-chance access
// violation per call (423 for one such pool base passed to queue slot 31 in one run, before slot 31 was
// mapped to queue_page_mappings).
bool names_known_iid(u64 value)
{
if (value < 0x10000 || !x2w_local::readable(reinterpret_cast<const void*>(value), sizeof(GUID))) return false;
if (value < 0x10000 || readable_window(value, sizeof(GUID)) < sizeof(GUID)) return false;
return kind_for(*reinterpret_cast<const GUID*>(value)) != other_kind;
}
bool create_shaped(u64 a, u64 b, u64 c, u64 d, u64 e, u64 f, u64 g)
Expand Down Expand Up @@ -2818,9 +2825,38 @@ D3D12_GPU_VIRTUAL_ADDRESS upload_from_title(Wrapper* list, u64 title_address, st
return ring_copy(list, title_address, bytes, &offset, &resource) && resource ? resource->GetGPUVirtualAddress() + offset : 0;
}

// Number of contiguous readable bytes at address, up to wanted.
// xmem's page registry (x2w_xmem_mapped_bytes) answers for addresses in the title's mapped-page
// reservations without touching them. Probing an unmapped page there costs a first-chance access
// violation each, and under the debug launcher a debugger round trip each (about 21000 in one
// loading screen, almost all from by-address textures whose pages were not mapped yet).
using XmemMappedBytes = BOOL(WINAPI*)(ULONG_PTR, SIZE_T, SIZE_T*);
XmemMappedBytes xmem_mapped_bytes() noexcept
{
static std::atomic<XmemMappedBytes> found{nullptr};
static std::atomic<LONG> lookups{0};
if (const auto f = found.load(std::memory_order_acquire)) return f;
if (lookups.fetch_add(1, std::memory_order_relaxed) >= 256) return nullptr; // xmem.dll not loaded or an older one
const HMODULE xmem = GetModuleHandleW(L"xmem.dll");
const auto f = xmem ? reinterpret_cast<XmemMappedBytes>(GetProcAddress(xmem, "x2w_xmem_mapped_bytes")) : nullptr;
if (f) found.store(f, std::memory_order_release);
return f;
}
LONG xmem_answered_unmapped;

// Number of contiguous readable bytes at address, up to wanted. Where xmem knows the pages, only its
// mapped prefix is touched (no fault in the common case); elsewhere one byte per page is touched.
std::size_t readable_window(u64 address, std::size_t wanted)
{
if (const auto query = wanted ? xmem_mapped_bytes() : nullptr) {
SIZE_T mapped = 0;
if (query(static_cast<ULONG_PTR>(address), wanted, &mapped)) {
if (!mapped) {
InterlockedIncrement(&xmem_answered_unmapped);
return 0;
}
return x2w_local::probe_readable(static_cast<std::uintptr_t>(address), mapped);
}
}
return x2w_local::probe_readable(static_cast<std::uintptr_t>(address), wanted);
}

Expand Down Expand Up @@ -4735,7 +4771,7 @@ __declspec(noinline) u64 queue_dynamic(Wrapper* self, u64 rdx, u64 r8, u64 r9)
static_cast<unsigned long>(hr));
return static_cast<u64>(hr);
}
if (rdx >= 1 && rdx <= 64 && r8 >= 0x10000 && x2w_local::readable(reinterpret_cast<void*>(r8), rdx * sizeof(void*))) {
if (rdx >= 1 && rdx <= 64 && r8 >= 0x10000 && readable_window(r8, rdx * sizeof(void*)) >= rdx * sizeof(void*)) {
auto* const* lists = reinterpret_cast<void* const*>(r8);
bool all_lists = true;
for (u64 i = 0; i < rdx; ++i) {
Expand All @@ -4748,7 +4784,11 @@ __declspec(noinline) u64 queue_dynamic(Wrapper* self, u64 rdx, u64 r8, u64 r9)
return 0;
}
}
if (create_shaped(rdx, r8, r9, 0, 0, 0, 0)) {
// As in noop_slot, only the first calls of a slot are checked for an IID: the check reads its
// arguments, and an unchecked slot called every frame with a pointer-shaped non-pointer (slot 31's
// r9, before slot 31 was mapped to queue_page_mappings) paid a first-chance access violation per call.
static LONG shape_checks;
if (shape_checks < 32 && InterlockedIncrement(&shape_checks) <= 32 && create_shaped(rdx, r8, r9, 0, 0, 0, 0)) {
char name[64];
std::snprintf(name, sizeof(name), "CommandQueue::slot%d(passes an IID)", N);
x2w_trap::fire(X2W_TRAP_MODULE, X2W_TRAP_MODULE_ID, name, N & 0xFF, reinterpret_cast<u64>(self), rdx, r8, r9,
Expand Down Expand Up @@ -7474,6 +7514,8 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa
"(region-information proofs %lld, region queries %lld)", views_noted, views_distinct, descriptors_copied,
static_cast<u64>(heap_infos().size()), static_cast<long long>(placed_buffer_calls),
static_cast<long long>(placed_buffer_region_info), static_cast<long long>(placed_buffer_queries));
log("x2w-d3d12 readability: unmapped by xmem's page registry %ld, unreadable probes skipped %ld",
InterlockedCompareExchange(&xmem_answered_unmapped, 0, 0), InterlockedCompareExchange(&address_probe_skipped, 0, 0));
{
char line[640];
if (view_census_line(line, sizeof(line))) log("%s", line);
Expand Down
41 changes: 41 additions & 0 deletions src/xmem_mapped_pages.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ struct PhysicalMemory {
ULONG64 stamp = 0;
};
std::map<ULONG_PTR, Run> runs;
// Ordinary commits the caller placed at an address (XMemVirtualAlloc "commit at address"): memory that
// x2w_xmem_mapped_bytes cannot judge from the page registry.
std::map<ULONG_PTR, SIZE_T> commits;
// The slabs and their 64 KiB slots; released slots are reused lowest first, so that pages reused together
// are adjacent slots again.
x2w_xmem::SlabSlots<HANDLE> slots{era_physical::page_bytes};
Expand Down Expand Up @@ -1071,6 +1074,10 @@ void* local_virtual_alloc(void* address, SIZE_T bytes, DWORD type, ULONGLONG att
result = VirtualAlloc2(GetCurrentProcess(), address, bytes,
MEM_RESERVE | MEM_COMMIT | MEM_REPLACE_PLACEHOLDER, protect, nullptr, 0);
}
if (result) {
const std::lock_guard guard(memory.mutex);
memory.commits.insert_or_assign(reinterpret_cast<ULONG_PTR>(result), bytes);
}
how = "commit at address";
}
} else {
Expand Down Expand Up @@ -2273,6 +2280,40 @@ const int file_io_wrapped = [] {
}();
} // namespace

// Experimental export: whether [address, address + bytes) is mapped, answered from the page registry
// without touching the memory. A probe that touches an unmapped page costs one first-chance access
// violation (under the debug launcher, one debugger round trip each). Answers only for addresses inside
// a placeholder reservation that pages are mapped into (the reservations recorded for page mapping):
// *mapped receives the number of bytes from address on whose 64 KiB pages have a view, up to bytes.
// Returns FALSE (no answer; the caller probes instead) for any other address, for one that a commit at
// address may cover, for a range that runs past its reservation, and for an unmapped answer that Windows
// does not confirm (a released reservation the registry still names).
extern "C" BOOL WINAPI x2w_xmem_mapped_bytes(ULONG_PTR address, SIZE_T bytes, SIZE_T* mapped)
{
if (!mapped || !bytes || address > std::numeric_limits<ULONG_PTR>::max() - bytes) return FALSE;
const ULONG_PTR end = address + bytes;
ULONG_PTR at = address & ~(ULONG_PTR{page_bytes} - 1);
{
const std::lock_guard guard(memory.mutex);
const auto reservation = owned_reservation(address);
if (reservation == memory.reservations.end()) return FALSE;
const ULONG_PTR reservation_end = reservation->first + reservation->second;
if (end > reservation_end) return FALSE;
if (!memory.commits.empty()) {
auto commit = memory.commits.lower_bound(end);
if (commit != memory.commits.begin() && std::prev(commit)->first + std::prev(commit)->second > address) return FALSE;
}
while (at < end && memory.views.count(at)) at += page_bytes;
}
*mapped = at <= address ? 0 : static_cast<SIZE_T>((at < end ? at : end) - address);
if (*mapped == 0) {
MEMORY_BASIC_INFORMATION info{};
if (!VirtualQuery(reinterpret_cast<const void*>(address), &info, sizeof(info)) || info.State != MEM_RESERVE)
return FALSE;
}
return TRUE;
}

// Experimental export: writes bytes into physical pages named by the title's
// page tokens (page number << 4, as XMemMapPhysicalPages takes them), starting offset bytes into the
// first page. DirectStorage requests can name such pages as their destination. A token that names
Expand Down
1 change: 1 addition & 0 deletions src/xmem_shim.def
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,4 @@ EXPORTS
x2w_xmem_map_counts @25
x2w_xmem_stable_call @26
x2w_xmem_alias_counts @27
x2w_xmem_mapped_bytes @28
Loading
Loading