diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 80807b58db..c6803e5d91 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -3801,7 +3801,8 @@ to be recovered from call sites (or the NDA GDK headers, if a developer has acce | Device slot 61 | The retail title's boot under `gta6rt --run` (stop 20 of the RT-5 measurements in #6910): called as `(desc, dest handle)` once per sampler | `d3d12_xs_device.cpp` routes it to the PC `CreateSampler` (slot 22) with the description's PC `D3D12_SAMPLER_DESC` prefix, for a caller in an image the guest loader mapped; the PC slot 61 is `CreateMetaCommand`, which any other caller (a host test driving the device through the proxy) still gets. The layout of the description beyond the PC fields is **Open**. | | Device slot 74 | The retail title's boot under `gta6rt --run`: called as `(pointer, u32, pointer)` | **Stand-in.** `d3d12_xs_device.cpp` answers `S_OK` and does nothing, for a caller in an image the guest loader mapped; the PC slot 74 is `ShaderCacheControl`, which the call does not fit and which any other caller still gets. What the console method is, and what it should do, is **Open**. | | Command-allocator slot 9 | The retail title's boot under `gta6rt --run`: called past the 9-slot PC allocator, as `(function pointer, context, ...)`; `SetAllocatorCallbackX` is the name the commit that added it uses | **Stand-in.** The allocator proxy records the callback and its context (`allocator_proxy_callback`, `allocator_proxy_callback_context`) and answers `S_OK`. **Nothing calls the callback**: the Vulkan layer backs command buffers itself. Whether the title depends on being called back is **Open**. | -| Device slot 81, queue `PresentX`/`SuspendX`/`ResumeX` | XCL (GPL-2.0-only, third-party): `GetFrameStatisticsX` at device slot 81, `PresentX` at queue slot 30 (older runtime layout) or 32 (newer); `SuspendX`/`ResumeX` slots unmeasured | `set_presentation_handler` forwards 78-81 and the queue routes to a presenter (`attach_xbox_presentation`). Without one, slot 81 answers `S_OK` with a zero count (no statistics yet; the answer the retail boot through the story load was measured with, where the public samples' "not available yet" is `S_FALSE`; a null count, or a count above zero with no array, is `E_POINTER`); `PresentX` goes to the presentation the device proxy builds itself on the first call (`queue_present_x`: in the title's window or one of the runtime's, `LEONIDA_PRESENT_WINDOW`), which takes its frame tokens from the same source as the device's `WaitFrameEventX`; every other queue slot past the PC table answers `S_OK` and does nothing. `PresentX` is slot 30 on a queue in the older layout and slot 32 on a queue detected as the newer one (a fence reaching slot 16 or 17, or `SignalX` at 25), never both: in the newer layout slot 30 is another method. Slot 81 moves with `LEONIDA_XS_FRAME_STATISTICS_SLOT` (3..127); `LEONIDA_XS_PRESENT_X_SLOT` pins `PresentX` to one slot whatever the layout; `SuspendX` and `ResumeX` are routed only when `LEONIDA_XS_SUSPEND_X_SLOT` / `LEONIDA_XS_RESUME_X_SLOT` are set (queue slots 19..127; two routes on one slot are refused with a log). | +| Device slot 81, queue `PresentX`/`SuspendX`/`ResumeX` | XCL (GPL-2.0-only, third-party): `GetFrameStatisticsX` at device slot 81, `PresentX` at queue slot 30 (older runtime layout) or 32 (newer); `SuspendX`/`ResumeX` slots unmeasured | `set_presentation_handler` forwards 78-81 and the queue routes to a presenter (`attach_xbox_presentation`). Without one, slot 81 answers `S_OK` with a zero count (no statistics yet; the answer the retail boot through the story load was measured with, where the public samples' "not available yet" is `S_FALSE`; a null count, or a count above zero with no array, is `E_POINTER`); `PresentX` goes to the presentation the device proxy builds itself on the first call (`queue_present_x`: in the title's window or one of the runtime's, `LEONIDA_PRESENT_WINDOW`), which takes its frame tokens from the same source as the device's `WaitFrameEventX`; every other queue slot past the PC table answers `S_OK` and does nothing, except slot 31 (next row). `PresentX` is slot 30 on a queue in the older layout and slot 32 on a queue detected as the newer one (a fence reaching slot 16 or 17, or `SignalX` at 25), never both: in the newer layout slot 30 is another method. Slot 81 moves with `LEONIDA_XS_FRAME_STATISTICS_SLOT` (3..127); `LEONIDA_XS_PRESENT_X_SLOT` pins `PresentX` to one slot whatever the layout; `SuspendX` and `ResumeX` are routed only when `LEONIDA_XS_SUSPEND_X_SLOT` / `LEONIDA_XS_RESUME_X_SLOT` are set (queue slots 19..127; two routes on one slot are refused with a log). | +| Queue slot 31, `CopyPageMappingsBatchX` | Arguments `(count, batches, pool, pool pages, flags)`, a 24-byte batch `{UINT64 destination; UINT32 range count; const range* ranges}` and a 12-byte range `{UINT32 kind, start, count}`: read statically from the retail executable's call site and the code that fills the batches (#968), corroborated by the same call shape in a public project's queue (VIctory, `copy_page_mappings`, where the newer layout puts it at 29), and the pool-size argument equalled the page count of the title's own `XMemAllocatePhysicalPages` call in a boot | Every range goes to xmem's `copy_page_mappings_fn` (`d3d12_xs_device.cpp`, `queue_copy_page_mappings`): kind 0 maps pool pages `start, start + 1, ...` at the destination, 1 maps pool page `start` at every destination page, 2 unmaps, 3 leaves the destination as it is; each range moves the destination on by `count` pages. A destination page gets a second view of the physical page mapped at its source page, and the same view at the paired CPU range when the destination is a GPU-only reservation (`title_gpu_views`), where the layer reads that memory. `S_OK` when every range was applied, `E_INVALIDARG` (logged once) for a range past the pool, an unknown kind or one xmem refuses; without xmem linked (tests of the proxy alone) the slot answers `S_OK` like the other console-only slots. Tested by `xmem_test` and `xs_proxy_mock_test`. **Known gap:** the mappings change when the call is made, not when the queue reaches the batch, as on the console; whether earlier queued work still reads a destination page then is not measured. | | VRS | Public `D3D12_SHADING_RATE` / `D3D12_AXIS_SHADING_RATE` | `VK_KHR_fragment_shading_rate`; `RSSetShadingRate`/image-based rate map to `vkCmdSetFragmentShadingRateKHR`. | | Mesh shader tier | Public `D3D12_MESH_SHADER_TIER` | `VK_EXT_mesh_shader`; the 9,282 translated mesh shaders make this a hard requirement for any content that uses them. | | Wave MMA | Public `D3D12_WAVE_MMA_TIER` | Not used: no shader sets `WAVE_MMA` in SFI0 and none contains `v_mfma`/`v_wmma` (all 26,503, `tools/feature_scan.py`). Answer the tier query truthfully; no cooperative-matrix mapping is needed. | diff --git a/docs/linux_proton.md b/docs/linux_proton.md index 30107cfeb3..f98aacf149 100644 --- a/docs/linux_proton.md +++ b/docs/linux_proton.md @@ -101,11 +101,15 @@ Each item was a stop on at least one of the machines. Tests named in the pull re ## Where it stops -- **Streamed memory that never reaches its destination.** The title calls queue slot 31 (`CopyPageMappingsBatchX`) - about 300 times per boot and this branch still ignores it; tens of thousands of streamed views wait for memory - that never becomes readable. An open pull request in this repository implements it. -- **Culling compute at world start** reads buffers named by descriptors in the directly indexed heap; with the - point above unfixed those reads leave mapped memory and the device is lost (NVIDIA Xid 13/109 on Linux). +- **Streamed memory that reaches its destination late or not at all.** The title calls queue slot 31 + (`CopyPageMappingsBatchX`) about 300 times per boot. With #968 this branch maps each batch's pool pages at the + destination and at the paired CPU view the layer reads (`docs/d3d12_vulkan.md`, section 4.9), so most streamed + views find readable memory; before it, tens of thousands of them waited for memory that never became readable. Two gaps + remain: the mappings change when the call is made, not in queue order, and a run with the CPU-view fix still had + views waiting after 420 s, apparently for ranges no mapping call had reached yet. +- **Culling compute at world start** reads buffers named by descriptors in the directly indexed heap; where the + memory behind them is not mapped, those reads leave mapped memory and the device is lost (NVIDIA Xid 13/109 on + Linux). - **Mesh stages** do not get the heap offset yet. - **16 GB of RAM:** at the end of the load the process holds ~14.6 GB (RAM plus swap) on the Linux machine after the cuts above. zram made this worse (compressed pages still occupy RAM); a swap file on disk is the better choice. diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 23b0e05a05..264b32a489 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -28,6 +28,7 @@ #include "d3d12_com.h" // rt::d3d12::create_console_descriptor_heap for slot 14 #endif #include "d3d12_trace.h" +#include "xmem.h" // rt::xmem::copy_page_mappings_fn for queue slot 31 #include "d3d12_xs_alloc_size.h" #include "d3d12_xs_desc_clean.h" #include "../src/frame_pacer.h" @@ -894,6 +895,8 @@ bool is_console_caller(const void* address); // defined with the device proxy constexpr unsigned kQueueExecuteCommandListsX = 35; // console ExecuteCommandLists(count, lists) variant static_assert(kQueueExecuteCommandLists < kQueuePublicSlots && kQueueExecuteCommandListsX < kQueueSlots, "queue execution slots must stay within their respective tables"); +// CopyPageMappingsBatchX(count, batches, pool, pool pages, flags), past the public chain (queue_copy_page_mappings). +constexpr unsigned kQueueCopyPageMappingsBatchX = 31; constexpr unsigned kFenceSignal = 10; // ID3D12Fence::Signal(UINT64), from the CPU constexpr unsigned kFenceCompletedValueSlot = 12; // one past ID3D12Fence1: the completed value's address static_assert(kFenceCompletedValueSlot >= kFence1PublicSlots && kFenceCompletedValueSlot < kFenceSlots, @@ -1537,6 +1540,82 @@ std::uint64_t queue_execute_command_lists(ChildProxy* self, std::uint64_t count_ return 0; } +// ---- Queue slot 31: CopyPageMappingsBatchX ---- +// +// Measured on the retail executable (static): game_scarlett_master.exe+0xf2cc7f calls the queue's slot 31 +// (`call [vtable + 0xf8]`) with EDX the batch count, R8 the batches, R9 the base of its physical-page pool, the pool's +// size in 64 KiB pages as the fifth argument and 0 as the sixth; the result is not tested. It fills a batch at +0xf2ca74 +// as {UINT64 destination; UINT32 range count; const range* ranges} (24 bytes) and a range as {UINT32 kind, start, +// count} (12 bytes). The kinds: 0 maps pool pages start, start + 1, ... at the destination; 1 maps pool page `start` at +// every destination page; 2 leaves the destination unmapped; 3 leaves it as it is. Each range moves the destination on +// by count pages, whatever its kind. The same call shape is in VIctory's queue (copy_page_mappings, "newer" layout, +// where every slot from 14 on is two later than in older titles). In a boot the pool size matched the title's own +// XMemAllocatePhysicalPages count exactly. The console maps GPU page tables; here each range becomes xmem's +// copy_page_mappings_fn, which maps the physical page behind each pool page at its destination, the aliasing two +// XMemMapPhysicalPages calls with one page give. +// +// Without xmem (tests that compile this proxy alone) the slot is refused as before. A range outside the pool, of an +// unknown kind, or that xmem refuses is skipped and logged once; the call then returns E_INVALIDARG. +struct ConsolePageRange { + std::uint32_t kind, start, count; +}; +struct ConsolePageBatch { + std::uint64_t destination; + std::uint32_t count; + const ConsolePageRange* ranges; +}; +static_assert(sizeof(ConsolePageRange) == 12 && sizeof(ConsolePageBatch) == 24, "the title's page batch layout"); + +constexpr std::uint64_t kConsolePageSize = 0x10000; + +bool copy_console_page_range(const ConsolePageRange& range, std::uint64_t destination, std::uint64_t pool, + std::uint32_t pool_pages) { + void* const at = reinterpret_cast(destination); + const void* const from = reinterpret_cast(pool + std::uint64_t{range.start} * kConsolePageSize); + switch (range.kind) { + case 0: + return std::uint64_t{range.start} + range.count <= pool_pages && + rt::xmem::copy_page_mappings_fn(at, from, range.count, false); + case 1: + return range.start < pool_pages && rt::xmem::copy_page_mappings_fn(at, from, range.count, true); + case 2: + return rt::xmem::copy_page_mappings_fn(at, nullptr, range.count, false); + case 3: + return true; + default: + return false; + } +} + +HRESULT queue_copy_page_mappings(std::uint64_t count_word, std::uint64_t batches_word, std::uint64_t pool, + std::uint64_t pool_pages_word) { + const auto count = static_cast(count_word); + const auto pool_pages = static_cast(pool_pages_word); + const auto* const batches = reinterpret_cast(batches_word); + if (count && !batches) return E_INVALIDARG; + static std::atomic first_call{true}, first_refusal{true}; + if (first_call.exchange(false, std::memory_order_relaxed)) + std::fprintf(stderr, "[rt] d3d12_xs: queue slot 31 (CopyPageMappingsBatchX) first call: %u batch(es), pool " + "0x%llx of %u pages\n", count, static_cast(pool), pool_pages); + bool all = true; + for (std::uint32_t b = 0; b < count; ++b) { + if (!batches[b].ranges) continue; + std::uint64_t at = batches[b].destination; + for (std::uint32_t r = 0; r < batches[b].count; ++r) { + const ConsolePageRange& range = batches[b].ranges[r]; + if (!copy_console_page_range(range, at, pool, pool_pages)) { + all = false; + if (first_refusal.exchange(false, std::memory_order_relaxed)) + std::fprintf(stderr, "[rt] d3d12_xs: queue slot 31: range kind %u, pool pages %u+%u at 0x%llx not " + "mapped (pool of %u pages, error %lu); logged once\n", range.kind, range.start, + range.count, static_cast(at), pool_pages, GetLastError()); + } + at += std::uint64_t{range.count} * kConsolePageSize; + } + } + return all ? S_OK : E_INVALIDARG; +} + // PresentX is at queue slot 30 in an older runtime layout and 32 in a newer one (public corroboration, XCL; see // docs/d3d12_vulkan.md). 30 is the default and LEONIDA_XS_PRESENT_X_SLOT sets the other. SuspendX and ResumeX have no // default: 0 means not routed, so they answer only when their variable is set. @@ -1693,6 +1772,14 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_ } return hr_to_u64(S_OK); } + // CopyPageMappingsBatchX (queue_copy_page_mappings), ahead of the presentation routes and the + // console-only S_OK below; without xmem linked it stays with the console-only answer. + if constexpr (Slot == kQueueCopyPageMappingsBatchX) { + if (Slot >= self->slot_count && rt::xmem::copy_page_mappings_fn) { + d3d12_trace::record(child_trace_name(Slot)); + return hr_to_u64(queue_copy_page_mappings(a1, a2, a3, a4)); + } + } // PresentX, SuspendX and ResumeX at their routed slots (xbox_queue_slot_routes). The default PresentX // slot is the older layout's; the newer layout has it two slots later unless the variable names it. A // presentation attached with set_presentation_handler answers first; without one PresentX goes to the diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index 82d8142d0f..c8cbbd8da3 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp @@ -983,6 +983,62 @@ BOOL WINAPI XMemMapPhysicalPagesScatter(void* const* addresses, uint32_t page_co return TRUE; } +// rt::xmem::copy_page_mappings_fn (xmem.h), for the console queue's CopyPageMappingsBatchX: each destination page gets +// a view of the physical page mapped at its source page, so both addresses are one memory, as two XMemMapPhysicalPages +// calls with the same page make them. Every source page is looked up before any destination page changes, so a source +// range that overlaps the destination maps what was there before the call. A destination in a GPU-only range is mapped +// at its paired CPU range too (title_gpu_views), and a source page missing at a GPU-only address is looked up there. +bool copy_page_mappings(void* destination, const void* source, uint64_t pages, bool repeat_first) { + const uintptr_t to = reinterpret_cast(destination); + const uintptr_t from = reinterpret_cast(source); + constexpr uintptr_t kMax = (std::numeric_limits::max)(); + if (!aligned_page_address(to) || !aligned_page_address(from) || pages > kMax / kPhysicalPageSize || + to > kMax - pages * kPhysicalPageSize || (!repeat_first && from > kMax - pages * kPhysicalPageSize)) { + SetLastError(ERROR_INVALID_PARAMETER); + return false; + } + if (!placeholder_api().available()) { + SetLastError(ERROR_NOT_SUPPORTED); + return false; + } + const std::lock_guard lock(g_phys_mutex); + // The destination is usually a GPU-only reservation, which the D3D12 layer reads at its paired CPU view + // (title_gpu_views::to_cpu); that view gets the same pages, or it would stay reserved and never readable. + const uintptr_t cpu_to = leonida::title_gpu_views::to_cpu(to, pages * kPhysicalPageSize); + const Window* const cpu_window = cpu_to != to ? find_window(cpu_to, pages * kPhysicalPageSize) : nullptr; + if (!source) { + for (uint64_t i = 0; i < pages; ++i) { + if (!unmap_page(to + i * kPhysicalPageSize)) return false; + if (cpu_window && !unmap_page(cpu_to + i * kPhysicalPageSize)) return false; + } + return true; + } + const Window* const window = find_window(to, pages * kPhysicalPageSize); + if (!window) { + SetLastError(ERROR_INVALID_ADDRESS); + return false; + } + std::vector found(static_cast(pages), 0); + for (uint64_t i = 0; i < pages; ++i) { + const uintptr_t src_va = from + (repeat_first ? 0 : i) * kPhysicalPageSize; + auto it = g_mapped.find(src_va); + if (it == g_mapped.end()) { // a GPU-only source whose pages were mapped at its CPU view + const uintptr_t cpu_src = leonida::title_gpu_views::to_cpu(src_va, kPhysicalPageSize); + if (cpu_src != src_va) it = g_mapped.find(cpu_src); + } + if (it != g_mapped.end()) found[static_cast(i)] = it->second; + } + const DWORD protect = view_protect(*window); + const DWORD cpu_protect = cpu_window ? view_protect(*cpu_window) : 0; + for (uint64_t i = 0; i < pages; ++i) { + const uint64_t page = found[static_cast(i)]; + if (!map_page(to + i * kPhysicalPageSize, page, protect)) return false; + if (cpu_window && !map_page(cpu_to + i * kPhysicalPageSize, page, cpu_protect)) return false; + } + return true; +} +[[maybe_unused]] const bool g_copy_page_mappings_set =(rt::xmem::copy_page_mappings_fn = ©_page_mappings, true); + // The title's write watching, on reservations it made with MEM_WRITE_WATCH. One xmem write-watched for the shadows // (reserve_watched) is refused as the host refuses a region that is not write-watched ((UINT)-1, // ERROR_INVALID_PARAMETER), as the console would: it isn't write-watched there, and a reset here would clear the bits diff --git a/runtime/shims/xmem.h b/runtime/shims/xmem.h index c60ccf5d30..22bb365a2e 100644 --- a/runtime/shims/xmem.h +++ b/runtime/shims/xmem.h @@ -16,4 +16,12 @@ bool commit_physical_pages(const std::uint64_t* page_array, std::size_t count); bool transfer_physical(std::span pages, std::uint16_t offset, std::span staging, bool write); +// Console queue slot 31, CopyPageMappingsBatchX (d3d12_xs_device.cpp): maps at `destination` the physical pages that +// are mapped at `source` now, `pages` 64 KiB pages one after another, or the one page at `source` every time with +// `repeat_first`. A source page with nothing mapped leaves its destination page unmapped; a null `source` unmaps them +// all. False, with the last error set, for an unaligned address or a destination outside a physical-page window. +// Set by xmem.cpp when it is linked: the command-object proxy is also compiled into tests without it. +using CopyPageMappingsFn = bool (*)(void* destination, const void* source, std::uint64_t pages, bool repeat_first); +inline CopyPageMappingsFn copy_page_mappings_fn = nullptr; + } diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp index f7d766d4e3..c457a9a2a6 100644 --- a/runtime/test/xmem_test.cpp +++ b/runtime/test/xmem_test.cpp @@ -556,6 +556,128 @@ void test_physical_pages(const PhysicalApi& api) { // The windows were split into one placeholder per page; the process exit releases them. } +// rt::xmem::copy_page_mappings_fn, behind console queue slot 31 (CopyPageMappingsBatchX): a destination page maps the +// physical page that is mapped at the source page, so both addresses are one memory, as two XMemMapPhysicalPages calls +// with the same page would make them. +void test_copy_page_mappings(const PhysicalApi& api) { + const auto copy = rt::xmem::copy_page_mappings_fn; + check(copy != nullptr, "xmem.cpp sets the copy_page_mappings hook"); + if (!copy) return; + constexpr uint64_t kPool = 4, kHeap = 8; + auto* const pool = static_cast(api.virtual_alloc( + nullptr, kPool * kPage64k, MEM_RESERVE | kXmem64kPages, 0x23, PAGE_READWRITE | PAGE_GRAPHICS_READWRITE)); + auto* const heap = static_cast(api.virtual_alloc( + nullptr, kHeap * kPage64k, MEM_RESERVE | kXmem64kPages, 0x23, PAGE_READWRITE | PAGE_GRAPHICS_READWRITE)); + check(pool && heap, "XMemVirtualAlloc reserves a pool window and a heap window"); + if (!pool || !heap) return; + uint64_t pages[kPool]{}; + uint64_t count = kPool; + check(api.allocate(0x280, &count, pages) == TRUE && count == kPool, "pages for the pool"); + // Pool pages 0..2 mapped, pool page 3 left unmapped. + check(api.map(pool, 3, pages) == pool, "the pool maps three pages"); + for (uint64_t i = 0; i < 3; ++i) fill_page(pool + i * kPage64k, 0x7100u + static_cast(i)); + + // A run: heap pages 0 and 1 show pool pages 1 and 2, and are the same memory. + check(copy(heap, pool + kPage64k, 2, false), "a run of pool pages maps into the heap"); + check(page_holds(heap, 0x7101u) && page_holds(heap + kPage64k, 0x7102u), "the heap pages show pool pages 1 and 2"); + static_cast(static_cast(heap + kPage64k))[1] = 0xc0ffee31; + check(read_u32(pool + 2 * kPage64k, 4) == 0xc0ffee31, "a write through the heap is seen in the pool: one memory"); + + // One page repeated. + check(copy(heap + 2 * kPage64k, pool, 3, true), "one pool page maps at three heap pages"); + check(page_holds(heap + 2 * kPage64k, 0x7100u) && page_holds(heap + 4 * kPage64k, 0x7100u), + "every repeated page shows pool page 0"); + + // A pool page with nothing mapped leaves its destination unmapped; so does the null source. + check(copy(heap + 5 * kPage64k, pool + 2 * kPage64k, 2, false), "a run that ends in an unmapped pool page maps"); + check(page_holds(heap + 5 * kPage64k, 0x7102u) && reserved_only(heap + 6 * kPage64k), + "the unmapped pool page leaves its heap page unmapped"); + check(copy(heap, nullptr, 2, false), "a null source unmaps"); + check(reserved_only(heap) && reserved_only(heap + kPage64k), "the heap pages are reserved again"); + check(page_holds(pool + kPage64k, 0x7101u), "unmapping the heap leaves the pool's own mapping"); + + // Overlapping source and destination: every source page is read before any destination page changes. + check(copy(pool + kPage64k, pool, 2, false), "a run maps over an overlapping range"); + check(page_holds(pool + kPage64k, 0x7100u) && page_holds(pool + 2 * kPage64k, 0x7101u), + "the overlapping run shows the pages from before it"); + + uint8_t outside = 0; + const auto outside_page = + reinterpret_cast((reinterpret_cast(&outside) + 0xffff) & ~uintptr_t{0xffff}); + check(!copy(outside_page, pool, 1, false), "a destination outside any window fails"); + SetLastError(ERROR_SUCCESS); + check(!copy(heap + 1, pool, 1, false) && GetLastError() == ERROR_INVALID_PARAMETER, + "a destination that is not 64 KiB-aligned fails"); + check(!copy(heap, pool + 1, 1, false) && GetLastError() == ERROR_INVALID_PARAMETER, + "a source that is not 64 KiB-aligned fails"); + + api.map(heap, kHeap, nullptr); + api.map(pool, kPool, nullptr); + check(api.free_pages(kPool, pages) == TRUE, "the pool's pages are freed"); +} + +bool access_faults(volatile uint32_t* address, bool write); + +// The same hook on a GPU-only destination: the title reserves a CPU-mappable range and a GPU-only one of the same size +// right after it (title_gpu_views), and the D3D12 layer reads the GPU-only range's memory at the CPU range's address. +// A batch copy onto the GPU-only range maps the same pages at the CPU range too, so that memory becomes readable there. +void test_copy_page_mappings_cpu_view(const PhysicalApi& api) { + const auto copy = rt::xmem::copy_page_mappings_fn; + if (!copy) return; // test_copy_page_mappings reports it + constexpr uint64_t kPool = 2, kPair = 3; + auto* const pool = static_cast(api.virtual_alloc( + nullptr, kPool * kPage64k, MEM_RESERVE | kXmem64kPages, 0x23, PAGE_READWRITE | PAGE_GRAPHICS_READWRITE)); + auto* const other = static_cast(api.virtual_alloc( + nullptr, kPage64k, MEM_RESERVE | kXmem64kPages, 0x23, PAGE_READWRITE | PAGE_GRAPHICS_READWRITE)); + // The pair: the CPU-mappable range, then the GPU-only one (PAGE_GRAPHICS_NOACCESS | PAGE_NOACCESS) of its size. + auto* const cpu = static_cast(api.virtual_alloc( + nullptr, kPair * kPage64k, MEM_RESERVE | kXmem64kPages, 0x23, PAGE_READWRITE | PAGE_GRAPHICS_READWRITE)); + auto* const gpu = static_cast( + api.virtual_alloc(nullptr, kPair * kPage64k, MEM_RESERVE | kXmem64kPages, 0x3, 0x801)); + check(pool && other && cpu && gpu, "XMemVirtualAlloc reserves a pool, a window and a CPU + GPU-only pair"); + if (!pool || !other || !cpu || !gpu) return; + check(leonida::title_gpu_views::to_cpu(reinterpret_cast(gpu)) == reinterpret_cast(cpu), + "the GPU-only range reads at the CPU range reserved just before it"); + uint64_t pages[kPool]{}; + uint64_t count = kPool; + check(api.allocate(0x280, &count, pages) == TRUE && count == kPool, "pages for the pool"); + check(api.map(pool, kPool, pages) == pool, "the pool maps its pages"); + for (uint64_t i = 0; i < kPool; ++i) fill_page(pool + i * kPage64k, 0x7300u + static_cast(i)); + + // A run onto the GPU-only range: its CPU range shows the same bytes. Each page is read under a guard first, so a + // page left reserved fails its check instead of faulting the test (Wine's VirtualQuery does not report a view + // mapped into a placeholder as committed, so the state is not asked for). + const auto readable = [](const uint8_t* page) { + return !access_faults(reinterpret_cast(const_cast(page)), false); + }; + check(copy(gpu, pool, kPool, false), "a run of pool pages maps onto the GPU-only range"); + check(readable(gpu) && page_holds(gpu, 0x7300u), "the GPU-only range shows the pool pages"); + check(readable(cpu) && readable(cpu + kPage64k), "the paired CPU range is readable after the copy"); + check(readable(cpu) && readable(cpu + kPage64k) && page_holds(cpu, 0x7300u) && page_holds(cpu + kPage64k, 0x7301u), + "the paired CPU range shows the same bytes as the pool"); + check(!readable(cpu + 2 * kPage64k), "a CPU page past the copied run stays unmapped"); + if (readable(cpu + kPage64k)) { + static_cast(static_cast(cpu + kPage64k))[1] = 0xc0ffee32; + check(read_u32(pool + kPage64k, 4) == 0xc0ffee32 && read_u32(gpu + kPage64k, 4) == 0xc0ffee32, + "a write at the CPU range is seen in the pool and the GPU-only range: one memory"); + } + + // A GPU-only source whose page is mapped only at its CPU range is found there. + check(api.map(cpu + 2 * kPage64k, 1, &pages[0]) == cpu + 2 * kPage64k, "a page maps at the CPU range alone"); + check(copy(other, gpu + 2 * kPage64k, 1, false), "a copy from the GPU-only range maps"); + check(readable(other) && page_holds(other, 0x7300u), + "a GPU-only source page unmapped there is looked up at its CPU range"); + + // A null source unmaps both ranges. + check(copy(gpu, nullptr, kPool, false), "a null source unmaps the GPU-only range"); + check(!readable(gpu) && !readable(cpu) && !readable(cpu + kPage64k), "the paired CPU range is unmapped with it"); + + api.map(other, 1, nullptr); + api.map(cpu, kPair, nullptr); + api.map(pool, kPool, nullptr); + check(api.free_pages(kPool, pages) == TRUE, "the pool's pages are freed"); +} + bool access_faults(volatile uint32_t* address, bool write) { __try { if (write) { @@ -1530,6 +1652,8 @@ int main() { if (tools_mem) check(tools_mem() == FALSE, "XMemIsToolsMemAvailable returns FALSE (no devkit tools memory)"); if (virtual_alloc && physical.allocate && physical.free_pages && physical.map && physical.scatter) { test_physical_pages(physical); + test_copy_page_mappings(physical); + test_copy_page_mappings_cpu_view(physical); test_physical_pages_commit_on_touch(physical); test_commit_physical_pages(physical); test_first_touch_during_remap(physical); diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 17ed015c0d..eb6373fd38 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -15,6 +15,7 @@ // patching this executable's own import table before the first proxy table is built (one process each). // Every device, queue, fence and resource here is a mock that records the calls it gets. No game data, no Xbox DLLs. #include "../shims/d3d12_xs_device.h" +#include "../shims/xmem.h" #include "../src/d3d12_xs_frame_events.h" #include @@ -3098,6 +3099,88 @@ int check_list_cpu_handles() { return 0; } +// ---- 9b. Queue slot 31: CopyPageMappingsBatchX(count, batches, pool, pool pages, flags) ---- +// +// The batches as the retail title fills them (game_scarlett_master.exe+0xf2ca74): a 24-byte batch {destination, range +// count, ranges}, 12-byte ranges {kind, start, count}. Each range reaches xmem's hook once; xmem is not linked here, so +// a recording stand-in takes its place. + +struct PageRange31 { + std::uint32_t kind, start, count; +}; +struct PageBatch31 { + std::uint64_t destination; + std::uint32_t count; + const PageRange31* ranges; +}; +static_assert(sizeof(PageRange31) == 12 && sizeof(PageBatch31) == 24, "the title's batch layout"); + +struct CopyCall { + std::uint64_t destination, source, pages; + bool repeat; +}; +CopyCall g_copy_calls[8]; +unsigned g_copy_count = 0; +bool g_copy_result = true; + +bool record_copy(void* destination, const void* source, std::uint64_t pages, bool repeat_first) { + if (g_copy_count < std::size(g_copy_calls)) + g_copy_calls[g_copy_count] = {word(destination), word(source), pages, repeat_first}; + ++g_copy_count; + return g_copy_result; +} + +int check_queue_copy_page_mappings() { + Mock* mock = nullptr; + void* device = make_device(mock, 9, true); + EXPECT(device); + void* queue = make_queue(device); + EXPECT(queue); + Mock* const queue_mock = reinterpret_cast(xs::queue_proxy_real_queue(queue)); + constexpr std::uint64_t kPage = 0x10000, kPool = 0x7000000000, kHeap = 0x9000000000; + const PageRange31 first[3] = {{0, 4, 2}, {3, 0, 5}, {1, 7, 3}}; // a run, left as is, one page repeated + const PageRange31 second[1] = {{2, 0, 6}}; // unmapped + const PageBatch31 batches[3] = {{kHeap, 3, first}, {kHeap + 0x100 * kPage, 1, second}, {kHeap, 0, nullptr}}; + + // Without xmem the slot keeps the console-only answer every unmodelled queue slot gets. + rt::xmem::copy_page_mappings_fn = nullptr; + EXPECT(hr_of(raw(queue, 31, 3, word(batches), kPool, 16, 0)) == S_OK); + + rt::xmem::copy_page_mappings_fn = &record_copy; + g_copy_count = 0; + EXPECT(hr_of(raw(queue, 31, 3, word(batches), kPool, 16, 0)) == S_OK && g_copy_count == 3); + EXPECT(g_copy_calls[0].destination == kHeap && g_copy_calls[0].source == kPool + 4 * kPage && + g_copy_calls[0].pages == 2 && !g_copy_calls[0].repeat); + EXPECT(g_copy_calls[1].destination == kHeap + 7 * kPage && g_copy_calls[1].source == kPool + 7 * kPage && + g_copy_calls[1].pages == 3 && g_copy_calls[1].repeat); + // Kind 3 maps nothing but still moves the destination on (5 pages, so the repeat lands at page 7); kind 2 unmaps. + EXPECT(g_copy_calls[2].destination == kHeap + 0x100 * kPage && g_copy_calls[2].source == 0 && + g_copy_calls[2].pages == 6); + EXPECT(queue_mock->calls[31] == 0); // never forwarded to the PC queue + + // A range past the pool, or of an unknown kind, is refused on its own; the others still map. + const PageRange31 bad[3] = {{0, 15, 2}, {7, 0, 1}, {1, 15, 4}}; // 15 + 2 > 16 pages; kind 7; page 15 is inside + const PageBatch31 bad_batch[1] = {{kHeap, 3, bad}}; + g_copy_count = 0; + EXPECT(hr_of(raw(queue, 31, 1, word(bad_batch), kPool, 16, 0)) == E_INVALIDARG && g_copy_count == 1); + EXPECT(g_copy_calls[0].destination == kHeap + 3 * kPage && g_copy_calls[0].source == kPool + 15 * kPage && + g_copy_calls[0].repeat); + + // xmem refusing a range (no window there) makes the call fail too; no batches at all is fine. + g_copy_result = false; + EXPECT(hr_of(raw(queue, 31, 1, word(batches), kPool, 16, 0)) == E_INVALIDARG); + g_copy_result = true; + EXPECT(hr_of(raw(queue, 31, 0, 0, kPool, 16, 0)) == S_OK); + EXPECT(hr_of(raw(queue, 31, 2, 0, kPool, 16, 0)) == E_INVALIDARG); + + rt::xmem::copy_page_mappings_fn = nullptr; + EXPECT(release(queue) == 0 && release(device) == 0 && mock->refs == 0); + std::printf("xs_proxy_mock: queue slot 31 (CopyPageMappingsBatchX) sends each range to xmem's hook (a run, one page " + "repeated, unmapped, left as is), refuses a range past the pool or of an unknown kind, and answers " + "console-only S_OK without xmem\n"); + return 0; +} + // ---- Guard-region setup failures: this executable's import table, patched before the first proxy table ---- std::atomic g_injected{0}; @@ -3727,7 +3810,7 @@ int main(int argc, char** argv) { check_slot74() || check_xbox_queue_slots() || check_list_cpu_handles() || - check_presentation_wiring()) + check_presentation_wiring() || check_queue_copy_page_mappings()) return 1; if (check_placed_resource_x()) return 1; std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news);