diff --git a/docs/d3d12_command_objects.md b/docs/d3d12_command_objects.md index 1aef122066..36a02e8749 100644 --- a/docs/d3d12_command_objects.md +++ b/docs/d3d12_command_objects.md @@ -565,6 +565,10 @@ shape and the shift around them, but the shape alone does not single the method | 55 (`+0x1b8`) | **51** | `DiscardResource` | `(resource, null)` at `0x6dcb`, after the pending barriers are flushed through slot 26 | | 59 (`+0x1d8`) | — | console only (shape) | four calls, two shapes: `(1, blob, size)` at `0x6b5a` and `0x6d53`, the blob a run of qwords whose first is `0xf3080 \| (qword count & 0x7f)`; and `(0, &qword, 8)` with the qword 1 at `0x6e52` and `0x6eb8`, only when a profiling bit of the context is set (`0x6e2a`). The first argument is set as a byte (`mov dl, 1` / `xor edx, edx`). It looks like one slot for both ends of a GPU event; no public method takes a bool first. With 55 at +4 and 61 at +2, the two slots the console lacks are among 56–60 | | 61 (`+0x1e8`) | **59** | `ExecuteIndirect` | `(signature, 1, argument buffer, offset, null, 0)` at `0x59a0` | +| 71 (`+0x238`) | — | console only | `Write32BitValueBottomOfPipeX(address, u32 value, flush, flags)`: the 32-bit value, written into the title's memory once the list's work has run (the list values, [d3d12_xs_console_abi.md §5.5](d3d12_xs_console_abi.md)) | +| 72 (`+0x240`) | — | console only | `Write64BitValueBottomOfPipeX(address, u64 value, flush, flags)`: the 64-bit value; flags 1 ask for a GPU timestamp and 2 for a system timestamp instead of the value the call carried | +| 73 (`+0x248`) | — | console only | `Wait32BitValueX`: a wait on the 32-bit value; the list values hold the queue until it compares true or times out (§5.5 there) | +| 74 (`+0x250`) | — | console only | `Wait64BitValueX`: the same on the 64-bit value | | 85 (`+0x2a8`) | — | `CopyTextureRegion` shape (inferred) | run: `(stack pointer, 0, 0)`, twice per dispatch. Statically six arguments, `(&dst, 0, 0, 0, &src, null)`: the public `CopyTextureRegion` (PC 16) with two `D3D12_TEXTURE_COPY_LOCATION`s, not one pointer. At `0x7147` dst is `{texture, SUBRESOURCE_INDEX, 0}` and src `{buffer, PLACED_FOOTPRINT, footprint}`, the footprint from device slot 38 (`GetCopyableFootprints`, `0x708b`); at `0x7191` both are subresource 0 (texture to texture). The caller also clears the next stack argument (`0x70e7`); whether the method takes a seventh is open, as is what console slot 16 is | | 141 (`+0x468`) | — | console only | `(2, GPU VA, size, n)` at `0x65f8`: binds a buffer the DLL names `FFX_XBox_ComputeScratch`; `n` is the bound pipeline's scratch value from pipeline slot 11 (see above) | @@ -573,6 +577,20 @@ So the console list has four more methods than the PC list between `ResourceBarr Mapping the console list as "PC plus a constant" is wrong. The BVH builder adds 37, 39, 43 and 45 (the rest of the +4 root group) and the console-only 71, 73, 80, 146 (`Barrier`) and 148 (sections 3.3 and 3.3a). +**The two value-write slots.** Slots 71 and 72 are the console's value writes and 73 and 74 the waits that go with +them. The slot numbers are measured, not read: the retail title's own trace calls slot 71 with a title address and +a value, slot 72 with a title address and the flags word and slot 74 with a wait's arguments, and the value writes +are at 71/72 rather than at 69/70; and `XboxBvhBuilder.dll` reads a 32-bit value write at `+0x238` (slot 71) and a masked wait at `+0x248` +(slot 73). The call shapes are xcl's (crates/xcl/src/hle/d3d12x/list_x.rs, GPL-2.0) and the deferred +bottom-of-pipe write model is VIctory's (crates/victory-gpu/src/list.rs, GPL-3.0): the write is not a GPU command, +it is a CPU write into the title's memory, made after the submission that recorded it has run. Both projects are +cited for facts and for the model only, no code copied. The runtime has two writers for them, one per list: the list +values (`runtime/shims/d3d12_xs_list_values.h`, on by default) for the lists they track, with the waits of slots 73 +and 74; and the GPU-label path (`runtime/src/vulkan_gpu_labels.h`, `LEONIDA_GPU_LABELS=1`) for the others. Both +land a write whose address is a GPU address arena offset in the arena, never at that number in host memory, and one +on a page of xmem's that the title's view keeps `PAGE_NOACCESS` through xmem's own mapping of the physical page +(`runtime/src/value_write_sink.h`). + **The list object is wider than its vtable, and this is what that width is for.** Before a root-argument or dispatch call the DLL checks a write cursor at `+0x18` against a limit (`+0x30` for root arguments, `+0x28` for a dispatch). While there is room, it writes the command into that buffer itself instead of calling: a root argument is a header word from the diff --git a/docs/d3d12_xs_console_abi.md b/docs/d3d12_xs_console_abi.md index b14410c431..986acf6802 100644 --- a/docs/d3d12_xs_console_abi.md +++ b/docs/d3d12_xs_console_abi.md @@ -231,6 +231,12 @@ The runtime's model: reads half of it, and pinned like any host write, so the slot-133 shadows see it). Later than the console, never earlier. Writes land in submission order across queues: the pump reads the fences newest write first, so a write whose work waited for an older one is never seen done before it. +- Two targets that store cannot reach (`runtime/src/value_write_sink.h`). An address in the GPU address arena's + range is an arena offset, a default-heap buffer, not a host address: it is asked before any host store and lands + in the arena's own mapping (one in the arena's reserved start or a sparse buffer is dropped). A page of xmem's that + the title's view keeps `PAGE_NOACCESS` (a GPU-only window), where the store faults, lands through xmem's own + mapping of the physical page. Counted as `writes_arena` and `writes_title_pages`. In the boots to the story load no + write failed the host store (0 of 63 219), so both are a safety net. - `write64` flags 1 and 2 take the GPU's timestamp at the write's place in the list: an `EndQuery(TIMESTAMP)` on the real list (the Vulkan layer writes it at the bottom of the pipe) and a `ResolveQueryData` of that one slot into a readback ring of the device's, read when the write lands. Flag 1 lands those ticks, which count at the queue's diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index a3da490790..e9cb8d4345 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -3086,6 +3086,15 @@ if(TARGET Vulkan::Headers) target_compile_definitions(xbox_gpu_label_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_VULKAN_DEVICE) add_test(NAME xbox_gpu_label_completion COMMAND xbox_gpu_label_test) set_tests_properties(xbox_gpu_label_completion PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 20) + # The list values' write fallbacks (src/value_write_sink.h): an arena offset lands in the arena, a PAGE_NOACCESS + # page of xmem's through xmem's own mapping. xmem.cpp and registry.cpp are compiled in for the xmem.dll exports. + add_executable(xbox_list_value_fallback_test test/xbox_list_value_fallback_test.cpp shims/d3d12_xs_device.cpp + shims/d3d12_xs_pso_stream.cpp shims/xmem.cpp shims/registry.cpp) + target_link_libraries(xbox_list_value_fallback_test PRIVATE gta6rt_d3d12_com psapi) + target_compile_definitions(xbox_list_value_fallback_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_VULKAN_DEVICE) + target_link_options(xbox_list_value_fallback_test PRIVATE /OPT:NOREF) + add_test(NAME xbox_list_value_fallback COMMAND xbox_list_value_fallback_test) + set_tests_properties(xbox_list_value_fallback PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30) add_executable(d3d12_present_test test/d3d12_present_test.cpp) target_link_libraries(d3d12_present_test PRIVATE gta6rt_d3d12_com user32 gdi32 dxgi) target_compile_definitions(d3d12_present_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) diff --git a/runtime/README.md b/runtime/README.md index d25b0470da..1573b8883c 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -352,7 +352,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_PIPELINE_COMPILE` | unset | `on-demand` (the `--first-run-ui` profile sets it) prepares pipeline-state streams and sampled views at bind time: a placed 2D texture then waits for its memory until a command or a view first uses it. `cache-only` makes an eager build (`LEONIDA_LAZY_PIPELINES=0`) ask the driver's cache first and leaves what would have to be compiled to the first draw. `first-use` is accepted and means the default. When a pipeline is compiled is `LEONIDA_LAZY_PIPELINES`. | | `LEONIDA_GRAPHICS_STAGE_LAYOUT` | on | Graphics root arguments are laid out as the console does for the vertex, pixel and geometry stages (from `s8`, a descriptor table in one dword). `0` keeps `rt::rootsig::pack()` (from `s0`, two dwords per address) for every graphics signature. | | `LEONIDA_FRAME_PACING` | unset | `1` (the `--first-run-ui` profile sets it) hands device slots 78 to 81 (`SetFrameIntervalX`, `ScheduleFrameEventX`, `WaitFrameEventX`, `GetFrameStatisticsX`) to the device's own presentation once the first `PresentX` has built it, with the title's interval and origin event replayed to its pacer. Unset, the slots answer from the device's token counter with no wait. | -| `LEONIDA_GPU_LABELS` | unset | `1` records the labels of console list slots 71 and 72 and stores each into the title's memory when the GPU has finished the command buffer that carries it (`src/vulkan_gpu_labels.h`), for lists the list values (`LEONIDA_LIST_VALUES`, on by default) do not track: those land their slot 71 to 74 writes themselves, and a second writer could rewind a counter. Unset, the two slots of an untracked list do nothing. | +| `LEONIDA_GPU_LABELS` | unset | `1` records the labels of console list slots 71 and 72 and stores each into the title's memory when the GPU has finished the command buffer that carries it (`src/vulkan_gpu_labels.h`), for lists the list values (`LEONIDA_LIST_VALUES`, on by default) do not track: those land their slot 71 to 74 writes themselves, and a second writer could rewind a counter. Unset, the two slots of an untracked list do nothing. Both writers land a value at a GPU address arena offset in the arena and one on an xmem page the title sees as `PAGE_NOACCESS` through xmem's own mapping (`src/value_write_sink.h`). | | `LEONIDA_LINEAR_MAP_FIRST` | unset | `Map` of a slot 133 texture leased as linear answers with the placement address and the title texture registry fills the image. `1` gives it the linear mapping instead: pinned pages, with a GPU-written texture read back into them, and a refusal when the pages are gone. | | `LEONIDA_CONSOLE_D16S8` | by GPU | The console's `D16_UNORM_S8_UINT` family (DXGI 118 to 120) is made as the D24S8 family where the GPU has `D24_UNORM_S8_UINT` as a depth-stencil attachment and keeps its own D16/S8 path where it has none (AMD). `native` or `d24` chooses for every GPU. The device logs which it took. | | `LEONIDA_RGBA4_COPY_REFUSE` | unset | `1` refuses a footprint copy to or from a `B4G4R4A4_UNORM` render target stored as RGBA8 (its texels are four bytes there, not two). Unset, the copy is made. | diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 22d5f1f419..49743d0c1d 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -29,6 +29,7 @@ #include "d3d12_xs_native_pso.h" #include "dxgi_com.h" #include "../src/arena_size.h" +#include "../src/value_write_sink.h" #include "../src/arena_blocks.h" #include "../src/gfx10_descriptors.h" #include "../src/depth24_fragment.h" @@ -2720,6 +2721,33 @@ struct DeviceState { return true; } + // The console's value writes (list slots 71 and 72) whose address is an arena offset: a default-heap buffer. + // The arena is host-visible, so its host mapping holds the bytes the GPU reads. As in resolve_title_memory, an + // address below the arena's size is an arena address unless the title's own memory is there (arena_allocate + // keeps out of those ranges); an arena address is never stored to as a host address, so it is the arena's + // whether or not it can be written here (src/value_write_sink.h). Below the first offset the arena hands out are + // the null region, the zero page and the quad indices, which shaders read: a value there is refused, as is one + // past the end. + leonida::value_sink::Landing write_arena_value(std::uint64_t va, const void* bytes, unsigned size) { + using leonida::value_sink::Landing; + if (!arena.mapped || va >= arena.size) return Landing::elsewhere; + std::uint64_t title_lo = 0, title_hi = 0; + if (leonida::title_va_aliases().title_memory(va, title_lo, title_hi)) return Landing::elsewhere; + if (!bytes || !size || va < arena.first || size > arena.size - va) return Landing::refused; + // A sparse resource's memory is bound by the sparse pass, not by the arena's mapping. + if (context && context->is_sparse_va(va)) return Landing::refused; + // An aligned value in one store, so a reader never sees half of it. + if (size == 4 && !(va & 3)) + std::atomic_ref(*reinterpret_cast(arena.mapped + va)) + .store(*static_cast(bytes), std::memory_order_relaxed); + else if (size == 8 && !(va & 7)) + std::atomic_ref(*reinterpret_cast(arena.mapped + va)) + .store(*static_cast(bytes), std::memory_order_relaxed); + else + std::memcpy(arena.mapped + va, bytes, size); + return Landing::landed; + } + struct ShaderVisibleHeap { VkDeviceSize end; D3D12_DESCRIPTOR_HEAP_TYPE type; @@ -2933,6 +2961,7 @@ struct DeviceState { std::uint8_t* mapped = nullptr; VkDeviceAddress address = 0; VkDeviceSize size = 0; + VkDeviceSize first = 0; // the first offset handed out: below it are the null region and kArenaReserved std::uint32_t memory_type = 0; std::mutex mutex; leonida::ArenaBlocks blocks; // offset -> size, guarded by mutex (src/arena_blocks.h) @@ -10883,6 +10912,13 @@ class Device final } #endif state_.context->set_depth_range_unrestricted(info.depth_range_unrestricted); + // The console's value writes (list slots 71 and 72) at an arena offset land in the arena + // (src/value_write_sink.h): the list values' pump and the GPU-label path ask this device before any host store. + leonida::value_sink::set_arena( + [](void* device, std::uint64_t address, const void* bytes, unsigned size) { + return static_cast(device)->write_arena_value(address, bytes, size); + }, + &state_); if (info.physical && state_.format_properties) { state_.context->set_color_attachment_format( [physical = info.physical, get_props = state_.format_properties](VkFormat format) { @@ -11375,11 +11411,17 @@ class Device final address.buffer = arena.buffer; arena.address = vk.vkGetBufferDeviceAddress(state_.info.device, &address); arena.size = info.size; + // The GPU address arena is the console's address space: the title names it by offset, so the label path + // has to find it (src/gpu_label_memory.h). Its address space starts at 0. + if (arena.mapped) + leonida::label::memory().track(0, static_cast(arena.size), + reinterpret_cast(arena.mapped), true); { // Under the arena's lock: an insert rebalances the tree and rewrites child links, which a walk on // another thread must not see half done. std::lock_guard lock(arena.mutex); arena.blocks.reset(null_bytes + kArenaReserved, arena.size); + arena.first = null_bytes + kArenaReserved; char check[2] = {}; size_t check_length = 0; arena.check_all = getenv_s(&check_length, check, "LEONIDA_ARENA_CHECK") == 0 && check_length > 1 && @@ -11427,6 +11469,7 @@ class Device final } ~Device() override { + leonida::value_sink::clear_arena(&state_); // first: it waits for a value write into the arena in progress raw_images_.clear(); geometry_refresher_.reset(); // its refresh uses state_.geometry title_filler_.reset(); // its fills use the title-texture registry diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 7ff788c61a..90dcc61136 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -3214,6 +3214,12 @@ std::uint64_t WINAPI list_slot(ListProxy* self, std::uint64_t a1, std::uint64_t const unsigned width = Slot == 71 ? 4u : 8u; const unsigned clock = Slot == 72 ? ((a4 & 1) ? 1u : ((a4 & 2) ? 2u : 0u)) : 0u; auto target = leonida::label::memory().capture(a1, width); + if (!target.owner.lock() && rt::xmem::label_target_fn) { + // The pages the title maps are the title's memory too, and the xmem shim owns their page + // tables (runtime/shims/xmem.h). + leonida::label::Target mapped; + if (rt::xmem::label_target_fn(a1, width, mapped)) target = std::move(mapped); + } if (target.owner.lock()) rt::d3d12::record_gpu_label(reinterpret_cast(self->real), {std::move(target), a2, clock}); @@ -6526,7 +6532,7 @@ const char* list_tail_slot_name(unsigned slot, unsigned char console_layout) { X(waits_relayed) X(gates_held) X(gates_met) X(gates_timed_out) X(cuts) X(cuts_deferred) X(cut_failures) \ X(gates_short) X(demotions) X(late_met) X(bundle_ops) X(releases) X(release_us) X(release_us_max) \ X(pass_us_max) X(release_stalls) X(remaps_now) X(remaps_deferred) X(remaps_failed) X(remap_wait_us_max) \ - X(stamps_gpu) X(stamps_cpu) X(labels_handed) + X(stamps_gpu) X(stamps_cpu) X(labels_handed) X(writes_arena) X(writes_title_pages) ListValueStats list_value_stats() { const list_values::Counters& c = list_values::counters(); diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index 8ad512bc98..67097a7d4a 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -58,6 +58,14 @@ // CreateCommandList(0, type, allocator, initialState). The type is the first word of the Xbox desc; there // is no node-mask argument in the console call (public HLE; the PC six-argument form differs). An riid the // proxy does not answer (the console's own list IID) is answered with the proxy. +// slots 71/72 Write32BitValueBottomOfPipeX and Write64BitValueBottomOfPipeX: the console's value writes, with +// slots 73/74 (Wait32BitValueX, Wait64BitValueX) the waits that go with them. A list the list values +// track (d3d12_xs_list_values.h, LEONIDA_LIST_VALUES, on by default) records all four, lands each write +// once its part has run and holds its queue at a wait. Only for a list they do not track +// (LEONIDA_LIST_VALUES=0, bundles) does LEONIDA_GPU_LABELS=1 record slots 71/72 as GPU completion labels +// (runtime/src/vulkan_gpu_labels.h): one writer per list. Either writer lands a value at an arena offset +// in the arena, and one on a page of xmem's that the title's view keeps PAGE_NOACCESS through xmem's own +// mapping (runtime/src/value_write_sink.h). // slots 78/79/80/81 SetFrameIntervalX, ScheduleFrameEventX, WaitFrameEventX, GetFrameStatisticsX. A presentation // attached with set_presentation_handler (below) answers them; without one a per-device token state // machine does, before the PC vtable is indexed: WaitFrameEventX returns at once with a fresh non-zero @@ -476,6 +484,7 @@ struct ListValueStats { std::uint64_t remaps_now, remaps_deferred, remaps_failed, remap_wait_us_max; // queue slot 31 std::uint64_t stamps_gpu, stamps_cpu; // write64 flags 1/2 landed with the GPU's timestamp, the CPU's clock std::uint64_t labels_handed; // slot 71/72 writes given to LEONIDA_GPU_LABELS (lists not tracked here) + std::uint64_t writes_arena, writes_title_pages; // landed in the arena, through xmem's mapping (in writes_landed) }; ListValueStats list_value_stats(); void reset_list_value_stats(); diff --git a/runtime/shims/d3d12_xs_list_values.h b/runtime/shims/d3d12_xs_list_values.h index d6baab5bd4..2a30b4b964 100644 --- a/runtime/shims/d3d12_xs_list_values.h +++ b/runtime/shims/d3d12_xs_list_values.h @@ -17,7 +17,8 @@ // - A part's writes land after the part has run: the queue proxy signals the queue's `written` fence behind the // lists of a group and the pump, a thread of its own, stores the values with the CPU once that fence is reached // (kernel_writes::store: one locked access for an aligned value, as any host write into title memory, so the -// slot-133 shadows see it). Later than the console, never earlier: a write in the middle of a part lands when the +// slot-133 shadows see it; an arena offset and a page xmem keeps PAGE_NOACCESS land through src/value_write_sink.h, +// see land()). Later than the console, never earlier: a write in the middle of a part lands when the // whole part is done. Writes land in the order they were submitted, across queues too: the fences are read newest // first, so a write whose work waited for an older one (a relay, a title fence) is never seen done before it. // A timestamp write (write64 flags 1 and 2) lands the GPU's timestamp for its place in the list (Timestamps). @@ -60,6 +61,7 @@ #include "d3d12_xs_device.h" // console_value_met, ListValueStats #include "../src/title_page_watch.h" // leonida::kernel_writes::store +#include "../src/value_write_sink.h" // leonida::value_sink: the arena and xmem's PAGE_NOACCESS pages namespace rt::d3d12_xs::list_values { @@ -171,6 +173,10 @@ struct Counters { std::atomic stamps_gpu{0}, stamps_cpu{0}; // List slot 71/72 writes handed to the GPU-label path (LEONIDA_GPU_LABELS) of a list these values do not track. std::atomic labels_handed{0}; + // Writes landed through the fallbacks (src/value_write_sink.h): in the GPU address arena (an arena offset is never + // stored to as a host address), and through xmem's own mapping of a page the title's view keeps PAGE_NOACCESS. + // Both are also counted in writes_landed. + std::atomic writes_arena{0}, writes_title_pages{0}; }; inline Counters& counters() { @@ -860,12 +866,29 @@ class Pump { previous && first >= previous ? static_cast(first - previous) * ms_per_tick : 0.0); } + // A write's target, in this order (src/value_write_sink.h): + // - an offset in the GPU address arena (a default-heap buffer): the device writes its own mapping. Asked before + // any host store, since a host store at an arena offset would write whatever host memory is at that number. + // One the arena refuses (its reserved start, a sparse buffer) is dropped. + // - the title's memory: kernel_writes::store, as before. + // - a page of xmem's that the title's view keeps PAGE_NOACCESS, where that store faults: xmem writes its own + // mapping of the physical page. void land(const WriteGroup& group) { note_stamps(*group.queue, group); for (const Write& write : group.writes) { const std::uint64_t value = write.kind == WriteKind::value ? write.value : stamp(*group.queue, write); - if (leonida::kernel_writes::store(reinterpret_cast(static_cast(write.address)), - value, write.bytes)) { + void* const target = reinterpret_cast(static_cast(write.address)); + const leonida::value_sink::Landing arena = leonida::value_sink::arena(write.address, &value, write.bytes); + bool landed = arena == leonida::value_sink::Landing::landed; + if (landed) bump(counters().writes_arena); + if (arena == leonida::value_sink::Landing::elsewhere) { + landed = leonida::kernel_writes::store(target, value, write.bytes); + if (!landed && leonida::value_sink::title_pages(target, &value, write.bytes)) { + landed = true; + bump(counters().writes_title_pages); + } + } + if (landed) { bump(counters().writes_landed); continue; } diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index 299ac6da79..40bc28f2a9 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp @@ -48,6 +48,7 @@ #include "../src/title_page_watch.h" #include "../src/title_geometry_watch.h" #include "../src/title_va_alias.h" +#include "../src/value_write_sink.h" namespace { @@ -2271,6 +2272,28 @@ BOOL WINAPI TitleVirtualProtect(LPVOID address, SIZE_T size, DWORD protect, PDWO } // namespace +// The host bytes of the 64 KiB page at `address` (the 64 KiB-aligned address of the page), with the section kept +// alive so that the bytes stay mapped after the lock is released. False when the page is not one of xmem's +// physical pages. The section's own mapping of a page is the host's copy of those bytes, which the CPU may write +// even where the title's own view of the page is PAGE_NOACCESS. +namespace { +struct HostPage { + std::shared_ptr
section; + std::uint64_t offset = 0; +}; + +bool host_page(std::uintptr_t address, HostPage& out) { + const std::lock_guard lock(g_phys_mutex); + const auto mapped = g_mapped.find(address); + if (mapped == g_mapped.end()) return false; + const auto page = g_pages.find(mapped->second); + if (page == g_pages.end() || !page->second.section || !page->second.section->scratch) return false; + out.section = page->second.section; + out.offset = page->second.offset; + return true; +} +} // namespace + namespace rt::xmem { void note_stream_reservation(uintptr_t base, size_t size, uintptr_t caller_rva) { @@ -2628,6 +2651,81 @@ std::shared_ptr pin_mapped_data(const void* address, std::size_t s return {section,static_cast(section->scratch)+offset+(start-first)}; } +// Writes `size` bytes at `address` in the title's memory, through the host pages xmem manages: the section's own +// mapping of the physical page, which the CPU may write even where the title's own view of the page is +// PAGE_NOACCESS (the GPU memory windows are). False when the range is not one of xmem's pages, or when the pages +// cannot be committed. +bool write_title_bytes(const void* address, const void* bytes, std::size_t size) { + if (!size) return true; + if (!address || !bytes) return false; + if (size > 2 * kPhysicalPageSize) return false; // a value write is four or eight bytes + if (!commit_physical_range(address, size)) return false; + const auto start = reinterpret_cast(address); + const std::uintptr_t mask = ~static_cast(kPhysicalPageSize - 1); + // Every page of the range is resolved before anything is written, so a range that is not entirely xmem's leaves + // no half-written value behind. The section is kept alive by the handle, so the bytes stay mapped while they + // are written. + HostPage pages[2]; + std::size_t count = 0; + for (std::size_t done = 0; done < size;) { + const std::uintptr_t at = start + done; + const std::uintptr_t page = at & mask; + if (count == 2 || !host_page(page, pages[count])) return false; + ++count; + done += kPhysicalPageSize - static_cast(at - page); + } + std::size_t done = 0; + for (std::size_t index = 0; done < size; ++index) { + const std::uintptr_t at = start + done; + const std::uintptr_t page = at & mask; + const std::size_t offset = static_cast(at - page); + std::size_t chunk = kPhysicalPageSize - offset; + if (chunk > size - done) chunk = size - done; + std::uint8_t* const host = static_cast(pages[index].section->scratch) + pages[index].offset; + // An aligned value in one store, as kernel_writes::store makes it: a title thread polling the same physical + // page through another view never reads half of it. + if (chunk == size && size == 4 && !(offset & 3)) + std::atomic_ref(*reinterpret_cast(host + offset)) + .store(*static_cast(bytes), std::memory_order_relaxed); + else if (chunk == size && size == 8 && !(offset & 7)) + std::atomic_ref(*reinterpret_cast(host + offset)) + .store(*static_cast(bytes), std::memory_order_relaxed); + else + std::memcpy(host + offset, static_cast(bytes) + done, chunk); + done += chunk; + } + return true; +} + +// The D3D12 layer calls this through leonida::value_sink (src/value_write_sink.h), so that the D3D12 library does not +// have to link the xmem shim into every consumer of that library. A process that links the shim gets the write; one +// that does not drops a value write that its host store could not land. +[[maybe_unused]] const bool g_title_write_set = (leonida::value_sink::set_title_pages(&write_title_bytes), true); + +// The label target of an address in the pages the title maps: those pages are the title's memory, and the +// console's value writes name them (src/gpu_label_memory.h). The region is tracked on demand, one per page, so +// the label path finds a page by its address. The page tables are read under g_phys_mutex, and the region is +// tracked after that lock is released: the label path takes the two locks the other way round. +bool label_target(std::uintptr_t address, unsigned bytes, leonida::label::Target& out) { + if (!bytes || (bytes != 4 && bytes != 8) || (address & (bytes - 1))) return false; + const auto page = address & ~static_cast(kPhysicalPageSize - 1); + { + const std::lock_guard lock(g_phys_mutex); + const auto mapped = g_mapped.find(page); + if (mapped == g_mapped.end()) return false; + const auto entry = g_pages.find(mapped->second); + if (entry == g_pages.end() || !entry->second.section || !entry->second.section->scratch) return false; + } + // The region is tracked on demand, one per page. A region that is already there is kept: a target that is + // still in flight keeps the region it was captured from, and a replaced region would drop it. + if (!leonida::label::memory().capture(page, 4).owner.lock()) + leonida::label::memory().track(page, kPhysicalPageSize, page, false); + out = leonida::label::memory().capture(address, bytes); + return static_cast(out.owner.lock()); +} + +[[maybe_unused]] const bool g_label_target_set = (rt::xmem::label_target_fn = &label_target, true); + static bool commit_pages_locked(const uint64_t* page_array, size_t count) { if (count == 0) return true; if (!page_array) { diff --git a/runtime/shims/xmem.h b/runtime/shims/xmem.h index 329766f6b2..9a7df46c5b 100644 --- a/runtime/shims/xmem.h +++ b/runtime/shims/xmem.h @@ -6,6 +6,8 @@ #include #include +#include "../src/gpu_label_memory.h" // leonida::label::Target: the console's value writes (list slots 71 and 72) + namespace rt::xmem { // CopyPageMappingsBatchX, Xbox queue slot 31. Measured x64 layout (also documented by VIctory). @@ -76,4 +78,16 @@ bool transfer_physical(std::span pages, std::uint16_t offse using CopyPageMappingsFn = bool (*)(void* destination, const void* source, std::uint64_t pages, bool repeat_first); inline CopyPageMappingsFn copy_page_mappings_fn = nullptr; +// Writes `size` bytes at `address` in the title's memory, through the host pages xmem manages: its own mapping of the +// physical page, which the CPU may write where the title's view of the page is PAGE_NOACCESS. False when the range is +// not xmem's pages. Registered with leonida::value_sink (src/value_write_sink.h) as the fallback of the console's +// value writes (list slots 71 and 72), so that the D3D12 layer reaches it without linking this shim. +bool write_title_bytes(const void* address, const void* bytes, std::size_t size); + +// The label target of an address in the pages the title maps: those pages are the title's memory too, and the +// console's value writes name them (runtime/src/vulkan_gpu_labels.h). The shim owns the page tables, so it answers +// the question. False when the address is not in one of the title's mapped pages. +using LabelTargetFn = bool (*)(std::uintptr_t address, unsigned bytes, leonida::label::Target& out); +inline LabelTargetFn label_target_fn = nullptr; + } diff --git a/runtime/src/gpu_label_memory.h b/runtime/src/gpu_label_memory.h index 7446220873..ac0c535913 100644 --- a/runtime/src/gpu_label_memory.h +++ b/runtime/src/gpu_label_memory.h @@ -28,7 +28,8 @@ class Memory { public: void track(std::uintptr_t base, std::uintptr_t bytes, std::uintptr_t allocation_base, bool heap) { - if (!base || !bytes || !allocation_base || bytes > std::numeric_limits::max() - base) return; + // A base of 0 is the GPU address arena: its address space starts at 0 (runtime/shims/d3d12_vulkan_device.cpp). + if (!bytes || !allocation_base || bytes > std::numeric_limits::max() - base) return; const auto end = base + bytes; std::lock_guard lock(mutex_); auto previous = regions_.upper_bound(base); diff --git a/runtime/src/value_write_sink.h b/runtime/src/value_write_sink.h new file mode 100644 index 0000000000..d6db3989bb --- /dev/null +++ b/runtime/src/value_write_sink.h @@ -0,0 +1,77 @@ +#pragma once +// Where a console value write (list slots 71 and 72) lands when its target is not memory a plain host store reaches: +// - the GPU address arena: the title names a default-heap buffer by its arena offset, which is not a host address, so +// a host store at that number would write whatever host memory is there. The D3D12 device that owns the arena +// answers for its range (set_arena) and writes through its own mapping. +// - a page of the title's memory that xmem maps PAGE_NOACCESS (a GPU-only window): the title's view refuses the CPU, +// and xmem writes through its own mapping of the physical page (set_title_pages, rt::xmem::write_title_bytes). +// Two writers use it: the list values' pump (shims/d3d12_xs_list_values.h), which lands the writes of the lists it +// tracks, and the GPU-label path (vulkan_gpu_labels.h, LEONIDA_GPU_LABELS=1), for lists it does not track. +// Portable: no Windows or Vulkan headers, so both sides and the tests without a GPU can include it. + +#include +#include +#include +#include + +namespace leonida::value_sink { + +enum class Landing { + elsewhere, // not the arena's: the caller stores it as before + landed, // the arena took it + refused, // the arena's, but its bytes cannot be written there (reserved, sparse, past the end): dropped +}; + +// `device` is the context set_arena was given; `address` the title's address of the value, `size` 4 or 8. +using ArenaWrite = Landing (*)(void* device, std::uint64_t address, const void* bytes, unsigned size); +// True when the bytes were written; false when the range is not one of the shim's pages. +using TitlePagesWrite = bool (*)(const void* address, const void* bytes, std::size_t size); + +struct State { + // Held across an arena write, so a device that goes away (clear_arena) waits for one in progress. + std::mutex mutex; + ArenaWrite arena = nullptr; + void* device = nullptr; + std::atomic title_pages{nullptr}; +}; + +inline State& state() { + static State s; + return s; +} + +// The device that owns the arena. The last device to set it answers; clear_arena(device) ends its turn. +inline void set_arena(ArenaWrite write, void* device) { + State& s = state(); + const std::lock_guard lock(s.mutex); + s.arena = write; + s.device = device; +} + +inline void clear_arena(void* device) { + State& s = state(); + const std::lock_guard lock(s.mutex); + if (s.device != device) return; + s.arena = nullptr; + s.device = nullptr; +} + +// Asked before any host store of a value write: an arena offset must never reach one. +inline Landing arena(std::uint64_t address, const void* bytes, unsigned size) { + State& s = state(); + const std::lock_guard lock(s.mutex); + if (!s.arena) return Landing::elsewhere; + return s.arena(s.device, address, bytes, size); +} + +// xmem sets it when it is linked into the process (shims/xmem.cpp). +inline void set_title_pages(TitlePagesWrite write) { state().title_pages.store(write, std::memory_order_release); } + +// The fallback after a host store into the title's memory failed: the page may be one of xmem's that the title's view +// keeps PAGE_NOACCESS. False without xmem, or when the page is not xmem's. +inline bool title_pages(const void* address, const void* bytes, std::size_t size) { + const TitlePagesWrite write = state().title_pages.load(std::memory_order_acquire); + return write && write(address, bytes, size); +} + +} // namespace leonida::value_sink diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 00a93f34a3..145fa11ee5 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -1909,6 +1909,16 @@ class VulkanContext { deletion_queue_.drain(current_ticket, device_, vk); } + // True when the VA names a sparse resource: the sparse pass binds its memory, not the arena's mapping, so the + // host's bytes at that offset are not the resource's. The console's value writes skip those. + bool is_sparse_va(std::uint64_t va) { + const std::shared_lock lock(resource_mutex_); + BufferVaIndex::Hit hit{}; + if (!buffer_vas_.find(va, hit)) return false; + const ResourceBinding* const b = resolve(hit.id); + return b && b->sparse_buffer; + } + // Both methods are called with submit_mutex_ held. A queue's own progress timeline is // monotonic even when another queue completes first; global tickets are retired in order. void record_submit_locked(VkSemaphore progress, std::uint64_t value) { diff --git a/runtime/src/vulkan_gpu_labels.h b/runtime/src/vulkan_gpu_labels.h index 32590cc392..60953417f0 100644 --- a/runtime/src/vulkan_gpu_labels.h +++ b/runtime/src/vulkan_gpu_labels.h @@ -1,5 +1,6 @@ #pragma once #include "gpu_label_memory.h" +#include "value_write_sink.h" #include #include #include @@ -22,6 +23,8 @@ #endif namespace leonida::label { +// LEONIDA_GPU_LABELS=1 records list slots 71 and 72 here, for the lists the list values (shims/d3d12_xs_list_values.h, +// LEONIDA_LIST_VALUES) do not track: those land their writes themselves, and one address has one writer. inline bool enabled() { static const bool active = [] { const char *v = std::getenv("LEONIDA_GPU_LABELS"); @@ -37,6 +40,25 @@ inline bool enabled() { // (kernel_writes::begin_write), so the label reaches it and the layer copies the page again; a page that stays // read-only after that is the title's own doing and the label is dropped, as before. Called with no shadow lock held. inline bool store_value(const Target &target, std::uint64_t value) { + // The runtime's own memory first (src/value_write_sink.h): an arena offset is not a host address, so it goes to the + // arena and never to the store below; a page xmem maps PAGE_NOACCESS is written through xmem's own mapping. The + // value is written little-endian, the way the console's x64 writes it: the low 'width' bytes of the word. A + // target neither takes - the title's own private pages - is left to the path below, which opens a read-only page + // the way a kernel write does. + { + const std::uint64_t word = value; + bool refused = false; + if (memory().publish(target, [&](std::uintptr_t address, unsigned width, std::uintptr_t) { + const value_sink::Landing landing = value_sink::arena(address, &word, width); + if (landing != value_sink::Landing::elsewhere) { + refused = landing == value_sink::Landing::refused; + return !refused; + } + return value_sink::title_pages(reinterpret_cast(address), &word, width); + })) + return true; + if (refused) return false; + } #ifdef _WIN32 return memory().publish(target, [&](std::uintptr_t address, unsigned width, std::uintptr_t allocation_base) { MEMORY_BASIC_INFORMATION mbi{}; diff --git a/runtime/test/xbox_list_value_fallback_test.cpp b/runtime/test/xbox_list_value_fallback_test.cpp new file mode 100644 index 0000000000..fe5718c522 --- /dev/null +++ b/runtime/test/xbox_list_value_fallback_test.cpp @@ -0,0 +1,222 @@ +// The list values' write fallbacks (runtime/src/value_write_sink.h), on a Vulkan device and the queue and list proxies, +// with xmem linked in as in gta6rt. No game data. +// - A write whose address is a GPU address arena offset (a default-heap buffer) lands in the arena, read back by a GPU +// copy; one in the arena's reserved start is dropped, never stored at that number in host memory. +// - A write to a page of xmem's that the title made PAGE_NOACCESS (its VirtualProtect, which xmem's fault handler and +// kernel_writes' reopen leave as the title set it), where the host store faults, lands through xmem's own mapping +// of the physical page. +// - A write to ordinary title memory lands as before, through neither fallback. +// LEONIDA_GPU_LABELS=1 throughout: the arena and xmem's pages are label targets too, and the lists here are tracked by +// the list values, so no write may be handed to the label path (one writer per list). +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../shims/shims.h" +#include "../shims/xmem.h" +#include "../src/title_page_watch.h" + +#include +#include +#include +#include + +#define CHECK(x) \ + do { \ + if (!(x)) { \ + std::fprintf(stderr, "line %d: %s\n", __LINE__, #x); \ + return 1; \ + } \ + } while (0) + +using namespace d3d12test; +namespace xs = rt::d3d12_xs; + +namespace { +using Create = HRESULT(WINAPI *)(void *, const void *, ID3D12CommandAllocator *, ID3D12PipelineState *, const IID *, + void **); +using Put = void(WINAPI *)(void *, std::uintptr_t, std::uint64_t, std::uint32_t, std::uint32_t); +using XMemVirtualAllocFn = void *(WINAPI *)(void *, SIZE_T, DWORD, ULONGLONG, DWORD); +using XMemAllocatePhysicalPagesFn = BOOL(WINAPI *)(std::uint64_t, std::uint64_t *, std::uint64_t *); +using XMemFreePhysicalPagesFn = BOOL(WINAPI *)(std::uint64_t, const std::uint64_t *); +using XMemMapPhysicalPagesFn = void *(WINAPI *)(void *, std::uint64_t, const std::uint64_t *); +constexpr DWORD kXmem64kPages = 0x20400000; +constexpr SIZE_T kPage64k = 0x10000; + +struct Writes { + std::uintptr_t address; + std::uint64_t value; + bool wide; +}; + +// One tracked list with the writes, submitted through the queue proxy; true once every write has landed or failed. +bool submit(ID3D12Device *device, ID3D12CommandQueue *queue, ID3D12CommandAllocator *allocator, + std::initializer_list writes) { + std::uint64_t desc[4]{}; + Ref list; + if (FAILED(reinterpret_cast(slot(device, 73))(device, desc, allocator, nullptr, + &__uuidof(ID3D12GraphicsCommandList), + reinterpret_cast(&list.p))) || + !xs::is_list_proxy(list.p)) + return false; + for (const Writes &w : writes) + reinterpret_cast(slot(list.p, w.wide ? 72 : 71))(list.p, w.address, w.value, 0, 0); + if (FAILED(list->Close())) return false; + ID3D12CommandList *submitted[1] = {list.p}; + queue->ExecuteCommandLists(1, submitted); + Ref done; + return SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&done.p))) && + SUCCEEDED(queue->Signal(done.p, 1)) && SUCCEEDED(done->SetEventOnCompletion(1, nullptr)) && + xs::list_values_idle(4000); +} + +// The first `bytes` of a default-heap buffer, through a GPU copy into a readback buffer. +bool read_back(ID3D12Device *real, ID3D12Resource *buffer, void *out, UINT64 bytes) { + D3D12_RESOURCE_DESC desc = buffer->GetDesc(); + D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + Ref readback; + D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + if (FAILED(real->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readback.p))) || + FAILED(real->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p))) || + FAILED(real->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))) || + FAILED(real->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list.p))) || + FAILED(real->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))) + return false; + list->CopyBufferRegion(readback.p, 0, buffer, 0, bytes); + if (FAILED(list->Close())) return false; + ID3D12CommandList *lists[1] = {list.p}; + queue->ExecuteCommandLists(1, lists); + if (FAILED(queue->Signal(fence.p, 1)) || FAILED(fence->SetEventOnCompletion(1, nullptr))) return false; + void *mapped = nullptr; + D3D12_RANGE range{0, static_cast(bytes)}; + if (FAILED(readback->Map(0, &range, &mapped)) || !mapped) return false; + std::memcpy(out, mapped, static_cast(bytes)); + readback->Unmap(0, nullptr); + return true; +} +} // namespace + +int main() { + _putenv_s("LEONIDA_GPU_LABELS", "1"); + xs::set_list_values_enabled(true); + vktest::Device gpu; + auto status = gpu.initialize(); + if (status == vktest::DeviceStatus::unavailable) return 77; + CHECK(status == vktest::DeviceStatus::ready); + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = gpu.instance_proc; + info.instance = gpu.instance; + info.physical = gpu.physical; + info.device = gpu.device; + info.queue = gpu.queue; + info.queue_family = gpu.family; + info.buffer_device_address = true; + ID3D12Device *inner = nullptr; + CHECK(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); + Ref device; + CHECK( + SUCCEEDED(xs::create_device_proxy(inner, __uuidof(ID3D12Device), reinterpret_cast(&device.p), true))); + rt::d3d12::set_device_outer(inner, device.p); + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + Ref queue; + CHECK(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + Ref allocator; + CHECK(SUCCEEDED(inner->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + + // 1. Ordinary title memory: the host store, as before; neither fallback. + auto *plain = static_cast(VirtualAlloc(nullptr, 4096, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + CHECK(plain); + // The title's memory, as xmem registers it in gta6rt: an address below the arena's size is the title's there. + leonida::title_va_aliases().add_title_memory(reinterpret_cast(plain), 4096); + xs::reset_list_value_stats(); + CHECK(submit(device.p, queue.p, allocator.p, + {{reinterpret_cast(plain), 11, false}, + {reinterpret_cast(plain + 1), 0x500000006ull, true}})); + auto stats = xs::list_value_stats(); + CHECK(stats.writes_landed == 2 && stats.writes_failed == 0); + CHECK(stats.writes_arena == 0 && stats.writes_title_pages == 0 && stats.labels_handed == 0); + CHECK(InterlockedCompareExchange64(plain, 0, 0) == 11 && InterlockedCompareExchange64(plain + 1, 0, 0) == + 0x500000006ll); + VirtualFree(const_cast(plain), 0, MEM_RELEASE); + std::puts("a write to the title's own memory lands through the host store"); + + // 2. An arena offset: a default-heap buffer's VA. The value lands in the arena, where the GPU reads it. + D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + D3D12_RESOURCE_DESC buffer_desc{}; + buffer_desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer_desc.Width = kPage64k; + buffer_desc.Height = 1; + buffer_desc.DepthOrArraySize = 1; + buffer_desc.MipLevels = 1; + buffer_desc.SampleDesc.Count = 1; + buffer_desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + Ref buffer; + CHECK(SUCCEEDED(inner->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &buffer_desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&buffer.p)))); + const std::uint64_t va = buffer->GetGPUVirtualAddress(); + CHECK(va && va < (std::uint64_t{1} << 32)); // an arena offset, not a host address + xs::reset_list_value_stats(); + CHECK(submit(device.p, queue.p, allocator.p, {{va, 41, false}, {va + 8, 0x300000004ull, true}})); + stats = xs::list_value_stats(); + CHECK(stats.labels_handed == 0); + CHECK(stats.writes_landed == 2 && stats.writes_arena == 2 && stats.writes_failed == 0); + std::uint64_t words[2]{}; + CHECK(read_back(inner, buffer.p, words, sizeof(words))); + CHECK(static_cast(words[0]) == 41 && words[1] == 0x300000004ull); + // The arena's reserved start (null region, zero page, quad indices) is the arena's, and shaders read it: a write + // there is dropped, and never stored at that number in host memory. + xs::reset_list_value_stats(); + CHECK(submit(device.p, queue.p, allocator.p, {{0x100, 99, false}})); + stats = xs::list_value_stats(); + CHECK(stats.writes_landed == 0 && stats.writes_failed == 1 && stats.writes_arena == 0); + std::puts("a write to an arena offset lands in the arena; one in its reserved start is dropped"); + + // 3. A page of xmem's that the title made PAGE_NOACCESS through its VirtualProtect: the host store faults there + // (xmem's fault handler and reopen_unowned leave a page the title protected), and the value lands through xmem's + // own mapping of the page. + auto reserve = reinterpret_cast(rt::shims::find("xmem.dll", "XMemVirtualAlloc")); + auto allocate = + reinterpret_cast(rt::shims::find("xmem.dll", "XMemAllocatePhysicalPages")); + auto map = reinterpret_cast(rt::shims::find("xmem.dll", "XMemMapPhysicalPages")); + auto free_pages = reinterpret_cast(rt::shims::find("xmem.dll", "XMemFreePhysicalPages")); + using ProtectFn = BOOL(WINAPI *)(void *, SIZE_T, DWORD, PDWORD); + auto title_protect = reinterpret_cast(rt::shims::find("kernel32.dll", "VirtualProtect")); + CHECK(reserve && allocate && map && free_pages && title_protect); + auto *window = + static_cast(reserve(nullptr, kPage64k, MEM_RESERVE | kXmem64kPages, 0, PAGE_READWRITE)); + CHECK(window); + std::uint64_t page = 0, count = 1; + CHECK(allocate(0x280, &count, &page) && count == 1); + CHECK(map(window, 1, &page) == window); + window[0] = 1; // committed, as a page the title used + DWORD old = 0; + CHECK(title_protect(window, kPage64k, PAGE_NOACCESS, &old)); + // What the list values did before the fallback: the host store into the title's view, which refuses it. + CHECK(!leonida::kernel_writes::store(window + 0x80, 1, 4)); + xs::reset_list_value_stats(); + CHECK(submit(device.p, queue.p, allocator.p, + {{reinterpret_cast(window) + 0x40, 0x5151, false}, + {reinterpret_cast(window) + 0x48, 0x700000008ull, true}})); + stats = xs::list_value_stats(); + CHECK(stats.labels_handed == 0); + CHECK(stats.writes_landed == 2 && stats.writes_title_pages == 2 && stats.writes_failed == 0); + const std::uintptr_t host = rt::xmem::physical_page_scratch(page); + CHECK(host); + std::uint32_t low = 0; + std::uint64_t wide = 0; + std::memcpy(&low, reinterpret_cast(host + 0x40), sizeof(low)); + std::memcpy(&wide, reinterpret_cast(host + 0x48), sizeof(wide)); + CHECK(low == 0x5151 && wide == 0x700000008ull); + map(window, 1, nullptr); + CHECK(free_pages(1, &page)); + std::puts("a write to a PAGE_NOACCESS page of xmem's lands through xmem's own mapping"); + + CHECK(gpu.validation_errors() == 0); + return 0; +}